package world

import "math"

type noise uint64

func mix(h uint64) uint64 {
	h ^= h >> 33
	h *= 0xff51afd7ed558ccd
	h ^= h >> 33
	h *= 0xc4ceb9fe1a85ec53
	return h ^ h>>33
}

func (n noise) hash(x, y int) uint64 {
	return mix(uint64(n) ^ mix(uint64(x)*0x9e3779b97f4a7c15^uint64(y)*0xc2b2ae3d27d4eb4f))
}

func (n noise) unit(x, y int) float64 {
	return float64(n.hash(x, y)>>11)/(1<<52) - 1
}

func (n noise) grad(ix, iy int, x, y float64) float64 {
	a := math.Pi * n.unit(ix, iy)
	return math.Cos(a)*(x-float64(ix)) + math.Sin(a)*(y-float64(iy))
}

func (n noise) at(x, y float64) float64 {
	x0, y0 := math.Floor(x), math.Floor(y)
	ix, iy := int(x0), int(y0)
	sx, sy := fade(x-x0), fade(y-y0)
	top := lerp(n.grad(ix, iy, x, y), n.grad(ix+1, iy, x, y), sx)
	bottom := lerp(n.grad(ix, iy+1, x, y), n.grad(ix+1, iy+1, x, y), sx)
	return lerp(top, bottom, sy)
}

func (n noise) fbm(x, y float64, octaves int) float64 {
	sum, weight, total := 0.0, 1.0, 0.0
	for i := range octaves {
		sum += weight * noise(mix(uint64(n)+uint64(i))).at(x, y)
		total += weight
		weight /= 2
		x, y = x*2, y*2
	}
	return sum / total
}

func fade(t float64) float64       { return t * t * t * (t*(t*6-15) + 10) }
func lerp(a, b, t float64) float64 { return a + (b-a)*t }
