package main

import "math"

// The piece of a hull under a point, if any. Each piece's own outline decides, and
// where two outlines overlap the nearer centre wins, so a click in the seam between
// two pieces picks the one it is closest to.
func hullPieceAt(p *player, x, y float64) int {
	id, best := 0, math.MaxFloat64
	for _, q := range p.Pieces {
		wx, wy := hullToWorld(p, q.LX, q.LY)
		if d := math.Hypot(wx-x, wy-y); d < best && pieceAt(q.Kind, wx, wy, p.H, x, y) {
			best, id = d, q.ID
		}
	}
	return id
}

func hullToWorld(p *player, lx, ly float64) (float64, float64) {
	c, s := math.Cos(p.H), math.Sin(p.H)
	return p.X + lx*c - ly*s, p.Y + lx*s + ly*c
}

func hullToLocal(p *player, x, y float64) (float64, float64) {
	return inward(p.X, p.Y, p.H, x, y)
}

func wrap(a float64) float64 { return math.Atan2(math.Sin(a), math.Cos(a)) }

func finite(f float64) bool { return !math.IsNaN(f) && !math.IsInf(f, 0) }
