Skip to content Search Apps Documentation Source Content Run Reset Eval Playground File Folder Download Copy Actions State String Boolean Number Struct Map Slice Pointer Function Closure Reference Nil Package Type Interface Unknown

Community realm. Read the code first. Community realm, deployed by its author. Read the code before you interact or send coins.

Playground

course.gno

// Package course is what golf and a hole agree on: a hole as data (Simple,
// GG1), its weather, and how a stroke is launched and drops.
package course

import (
	"math"
	"strconv"

	"gno.land/p/nym-alexiscolin000/gnogolf/physics"
)

// BoardW and BoardH are the board author.Fit gives a hole declared without W
// and H, in board units (nothing deployed reads them: Decode holds W and H to
// 1..MaxBoard).
const BoardW, BoardH = 32, 16

// WearW and WearH are the wear grid, stretched over any board: 128 counters.
const WearW, WearH = 16, 8

// MaxBoard is the longest side a board may have: it bounds the text board
// and the flood a client runs.
const MaxBoard = 96

// WearIndexOn maps a position on a w x h board to its wear cell, clamped.
func WearIndexOn(p physics.Vec2, w, h int) int {
	x := int(p.X * WearW / float64(w))
	y := int(p.Y * WearH / float64(h))
	if x < 0 {
		x = 0
	}
	if x >= WearW {
		x = WearW - 1
	}
	if y < 0 {
		y = 0
	}
	if y >= WearH {
		y = WearH - 1
	}
	return y*WearW + x
}

// Pulse is pieces that come and go: present on the strokes where
// (stroke+Phase) % Every < On, a timed wall's rule (physics.There) applied per
// stroke. The clock is the stroke number in the player's own round (0 is the
// first shot), never shared between players: previewing shot N and
// committing it meet the same course.
type Pulse struct {
	Every, On, Phase int
	Walls            []physics.Wall
	Posts            []physics.Post
	Zones            []physics.Zone
}

// The weather kinds. Each but Clear is also the skin of its whole-board zones.
const (
	Clear = ""      // Clear is no weather at all
	Wind  = "wind"  // Wind is a Slope: a steady push, Vec per substep
	Rain  = "rain"  // Rain is a Surface a little quicker than dry grass
	Fog   = "fog"   // Fog is a Surface of scale 1: it only hides the far end
	Storm = "storm" // Storm is rain and wind in gusts, and lightning to look at
	Snow  = "snow"  // Snow is a Surface a little slower
)

// chance is one kind of weather in a climate, out of 100.
type chance struct {
	percent int
	kind    string
}

// climates is each world's chance of each kind, out of 100; a world not
// listed has the garden's. Unexported so nothing can change it.
var climates = map[string][]chance{
	"garden":   {{55, Clear}, {20, Wind}, {15, Rain}, {10, Fog}},
	"island":   {{50, Clear}, {25, Wind}, {15, Rain}, {10, Storm}},
	"town":     {{50, Clear}, {20, Rain}, {15, Fog}, {15, Wind}},
	"mountain": {{40, Clear}, {25, Snow}, {20, Wind}, {15, Fog}},
}

// The weather's strengths.
const (
	// WindMin is the weakest wind, per substep.
	WindMin = 0.08
	// WindMax is the strongest wind, per substep.
	WindMax = 0.15
	// RainScale is how much quicker the green is in the rain: a touch, not
	// ice (much more and every board turns to pinball).
	RainScale = 1.025
	// WetIce is how much quicker again the rain makes ice.
	WetIce = 1.06
	// SnowScale is how much slower the green is in the snow.
	SnowScale = 0.9
)

// Forecast is one hole's weather for one period. Whole-board zones lie under
// the hole's own; the rest (puddles, wet ice) lie over it.
type Forecast struct {
	Period int64
	Kind   string
	Wind   physics.Vec2
	Zones  []physics.Zone
	// Work is what drawing it cost, in physics.MaxWork's units (about a
	// thousand gas); golf counts it in a commit's budget.
	Work int
}

// hash is 64-bit FNV-1a: small, deterministic, the same on every validator.
func hash(s string) uint64 {
	h := uint64(14695981039346656037)
	for i := 0; i < len(s); i++ {
		h ^= uint64(s[i])
		h *= 1099511628211
	}
	return h
}

// ForecastFor is the weather of hole id (in world) for a period: a hash of
// the two looked up in the world's climate. Nobody picks it.
func ForecastFor(id, world string, h *Simple, period int64) Forecast {
	seed := hash(id + "#" + strconv.FormatInt(period, 10))
	table, ok := climates[world]
	if !ok {
		table = climates["garden"]
	}
	roll, kind := int(seed%100), Clear
	for _, c := range table {
		if roll < c.percent {
			kind = c.kind
			break
		}
		roll -= c.percent
	}
	f := Forecast{Period: period, Kind: kind, Work: forecastWork}
	f.Wind, f.Zones = weatherFor(kind, h, seed, &f.Work)
	return f
}

// rng is a tiny deterministic generator from a seed (Knuth's LCG).
type rng struct{ s uint64 }

func (r *rng) next() uint64 {
	r.s = r.s*6364136223846793005 + 1442695040888963407
	return r.s >> 11
}

func (r *rng) unit() float64 { return float64(r.next()%1000000) / 1000000 }

// WeatherFor is the wind and zones of one kind of weather on a hole, drawn
// from seed: the wind's side and strength, where the rain leaves its puddles.
func WeatherFor(kind string, h *Simple, seed uint64) (physics.Vec2, []physics.Zone) {
	var work int
	return weatherFor(kind, h, seed, &work)
}

// weatherFor is WeatherFor, adding what it cost to *work (see wet).
func weatherFor(kind string, h *Simple, seed uint64, work *int) (physics.Vec2, []physics.Zone) {
	W, H := float64(h.W), float64(h.H)
	all := func(k physics.ZoneKind, skin string, scale float64, vec physics.Vec2) physics.Zone {
		// the wind is air, and never speeds the ball up
		air := k == physics.Slope
		return physics.Zone{Kind: k, Min: physics.V(0, 0), Max: physics.V(W, H), Scale: scale, Vec: vec, Skin: skin, Air: air, Capped: air}
	}
	r := &rng{s: seed}
	blow := func() physics.Vec2 {
		s := WindMin + r.unit()*(WindMax-WindMin)
		if h.Shelter > 0 && s > h.Shelter {
			s = h.Shelter
		}
		return physics.FromPolar(r.unit()*2*math.Pi, s)
	}
	switch kind {
	case Wind:
		v := blow()
		return v, []physics.Zone{all(physics.Slope, Wind, 0, v)}
	case Rain:
		return physics.Vec2{}, wet(h, r, []physics.Zone{all(physics.Surface, Rain, RainScale, physics.Vec2{})}, work)
	case Storm:
		// rain, and the wind in two alternating gusts
		*work += stormWork
		v := blow()
		a, s := math.Atan2(v.Y, v.X), v.Len()
		g1, g2 := all(physics.Slope, Wind, 0, physics.FromPolar(a+gustTurn, s)), all(physics.Slope, Wind, 0, physics.FromPolar(a-gustTurn, s))
		g1.Every, g1.On, g1.Phase = gustEvery, gustEvery/2, 0
		g2.Every, g2.On, g2.Phase = gustEvery, gustEvery/2, gustEvery/2
		zs := []physics.Zone{all(physics.Surface, Storm, 1, physics.Vec2{}), all(physics.Surface, Rain, RainScale, physics.Vec2{}), g1, g2}
		return v, wet(h, r, zs, work)
	case Fog:
		return physics.Vec2{}, []physics.Zone{all(physics.Surface, Fog, 1, physics.Vec2{})}
	case Snow:
		return physics.Vec2{}, []physics.Zone{all(physics.Surface, Snow, SnowScale, physics.Vec2{})}
	}
	return physics.Vec2{}, nil
}

// A storm's gusts turn gustTurn radians (about 40°) off its wind, one way
// then the other, each for half of gustEvery substeps.
const (
	gustTurn  = 0.7
	gustEvery = 6
)

// Where rain leaves its puddles: minPuddles plus up to morePuddles-1 more,
// in at most puddleTries tries; each puddleR plus up to puddleGrow wide,
// puddleAspect as deep, and puddleScale as quick as the grass, kept
// puddleGap clear of the one before.
const (
	minPuddles   = 2
	morePuddles  = 3
	puddleTries  = 60
	puddleR      = 1.1
	puddleGrow   = 0.7
	puddleAspect = 0.8
	puddleScale  = 0.6
	puddleGap    = 0.5
)

// The work of a forecast, in physics.MaxWork's units, measured on GnoVM gas:
// any forecast, a storm's gusts, a puddle try, and in it each post, zone,
// polygon edge and fixed wall dryLand tests, and each zone wet checks for ice.
const (
	forecastWork = 3000 // drawing any forecast, before the rain's tries
	stormWork    = 5000 // a storm's gusts, on top
	tryWork      = 35
	dryPostWork  = 22
	dryZoneWork  = 20
	dryEdgeWork  = 16
	dryWallWork  = 100
	iceWork      = 5
)

// WorstForecastWork bounds the Work of h's forecast in any period and world:
// a storm's, whose puddle tries all fail, each after dryLand has tested every
// piece (a try that fails sooner costs less, and one that places a puddle
// ends them sooner). Golf refuses a hole whose worst forecast leaves a commit
// no room for its heaviest shot.
func WorstForecastWork(h *Simple) int {
	f := h.Field()
	try := tryWork + dryPostWork*len(f.Posts)
	for _, z := range f.Zones {
		try += dryZoneTest(z)
	}
	for _, wl := range f.Walls {
		if wl.Every <= 0 {
			try += dryWallWork
		}
	}
	return forecastWork + stormWork + iceWork*len(f.Zones) + puddleTries*try
}

// dryZoneTest is the work of dryLand's test of one zone: its polygon's edges
// too for any zone but plain ground (Contains, at its dearest).
func dryZoneTest(z physics.Zone) int {
	if (z.Kind != physics.Surface && z.Kind != physics.Slope) || (z.Kind == physics.Surface && z.Skin != "") {
		return dryZoneWork + dryEdgeWork*len(z.Poly)
	}
	return dryZoneWork
}

// wet adds what rain leaves on a hole: its ice quicker still, and two to four
// puddles on the lane, clear of the kerb, the pieces, the tee and the cup.
// What it costs goes in *work.
func wet(h *Simple, r *rng, zs []physics.Zone, work *int) []physics.Zone {
	f := h.Field()
	*work += iceWork * len(f.Zones)
	for _, z := range f.Zones {
		if z.Kind == physics.Surface && z.Skin == "ice" {
			z.Scale *= WetIce
			zs = append(zs, z)
		}
	}
	want, placed := minPuddles+int(r.next()%morePuddles), []physics.Zone{}
	for try := 0; try < puddleTries && len(placed) < want; try++ {
		c := physics.V(r.unit()*float64(h.W), r.unit()*float64(h.H))
		rad := puddleR + r.unit()*puddleGrow
		*work += tryWork
		if !dryLand(h, c, rad, work) {
			continue
		}
		clash := false
		for _, p := range placed {
			if p.Min.Add(p.Max).Scale(0.5).Sub(c).LenCmp(p.Max.X-p.Min.X+puddleGap) < 0 {
				clash = true
			}
		}
		if clash {
			continue
		}
		placed = append(placed, physics.Zone{Kind: physics.Surface, Min: c.Sub(physics.V(rad, rad*puddleAspect)), Max: c.Add(physics.V(rad, rad*puddleAspect)), Scale: puddleScale, Round: true, Skin: "puddle"})
	}
	return append(zs, placed...)
}

// dryLand says whether a puddle of radius rad can lie at c: inside the lane's
// outline (even-odd over the fixed walls, a ray to a far point at a slant no
// grid wall lies along), off any zone but plain ground, dryGap from any piece
// and dryTee from tee and cup. Cheap tests first, no square roots: on a lane
// hole every try fails.
func dryLand(h *Simple, c physics.Vec2, rad float64, work *int) bool {
	f := h.Field()
	if c.Sub(h.Start()).LenCmp(rad+dryTee) < 0 || c.Sub(h.Cup()).LenCmp(rad+dryTee) < 0 {
		return false
	}
	for _, p := range f.Posts {
		*work += dryPostWork
		if p.C.Sub(c).LenCmp(p.R+rad+dryGap) < 0 {
			return false
		}
	}
	for _, z := range f.Zones {
		*work += dryZoneTest(z)
		if z.Kind != physics.Surface && z.Kind != physics.Slope && z.Contains(c) {
			return false
		}
		if z.Kind == physics.Surface && z.Skin != "" && z.Contains(c) {
			return false // not on the sand or the ice: a puddle is on the green
		}
	}
	far, in := c.Add(physics.V(farX, farY)), false
	for _, wl := range f.Walls {
		if wl.Every > 0 {
			continue
		}
		*work += dryWallWork
		if c.Sub(wl.Seg.Closest(c)).LenCmp(rad+dryGap) < 0 {
			return false
		}
		if wl.Seg.Crosses(c, far) {
			in = !in
		}
	}
	return in
}

const (
	dryTee     = 2
	dryGap     = 0.3
	farX, farY = 1e4, 37
)

// WithWeather lays weather over a field: the sky's whole-board zones go under
// its own (the sand stays sand in the rain), puddles and wet ice over them.
// It may return f itself: do not mutate what it returns.
func WithWeather(f *physics.Field, weather []physics.Zone) *physics.Field {
	if len(weather) == 0 {
		return f
	}
	under, over := []physics.Zone{}, []physics.Zone{}
	for _, z := range weather {
		switch z.Skin {
		case Wind, Rain, Fog, Storm, Snow:
			under = append(under, z)
		default:
			over = append(over, z)
		}
	}
	g := *f
	g.Zones = append(append(append(make([]physics.Zone, 0, len(f.Zones)+len(weather)), under...), f.Zones...), over...)
	return &g
}

// WithZones is the field with zones put first (a puddle over the sand is the
// puddle). It may return f itself: do not mutate what it returns.
func WithZones(f *physics.Field, zones []physics.Zone) *physics.Field {
	if len(zones) == 0 {
		return f
	}
	g := *f
	g.Zones = append(append(make([]physics.Zone, 0, len(f.Zones)+len(zones)), zones...), f.Zones...)
	return &g
}

// WithExtras is the field plus one stroke's pieces, the hole's own left as
// is. It may return f itself: do not mutate what it returns.
func WithExtras(f *physics.Field, walls []physics.Wall, posts []physics.Post) *physics.Field {
	if len(walls) == 0 && len(posts) == 0 {
		return f
	}
	g := *f
	g.Walls = append(append(make([]physics.Wall, 0, len(f.Walls)+len(walls)), f.Walls...), walls...)
	g.Posts = append(append(make([]physics.Post, 0, len(f.Posts)+len(posts)), f.Posts...), posts...)
	return &g
}

// Simple is a hole: its geometry, what Decode gives golf. Fields and methods
// pair up (Strokes/Par, Tee/Start, Pin/Cup, Course/Field) because a field and
// a method cannot share a name.
type Simple struct {
	W, H      int // the board, 1 to MaxBoard a side (Decode holds data to it, author.Fit sets it)
	Title     string
	Strokes   int // par: the strokes a good round takes (0 means 3)
	Tee, Pin  physics.Vec2
	Course    *physics.Field
	Pulses    []Pulse // pieces that come and go with the stroke number
	Substeps  int
	CupRadius float64
	// World is the hole's world (1 to MaxWorld letters a-z, as Decode holds
	// it); Order is its place there, 0 to MaxOrder (a course hole 1 or more).
	World string
	Order float64
	// Shelter caps the wind the hole is played in (0: the world's own).
	Shelter float64
}

// ExtraZones is the zones the hole's pulses lay down at a stroke.
func (h *Simple) ExtraZones(stroke int) []physics.Zone {
	var zs []physics.Zone
	for _, p := range h.Pulses {
		if physics.There(stroke, p.Every, p.On, p.Phase) {
			zs = append(zs, p.Zones...)
		}
	}
	return zs
}

// Varies says whether the hole has pulses: pieces that come and go.
func (h *Simple) Varies() bool { return len(h.Pulses) > 0 }

// Extras is the walls and posts the hole's pulses add at a stroke.
func (h *Simple) Extras(stroke int) ([]physics.Wall, []physics.Post) {
	var ws []physics.Wall
	var ps []physics.Post
	for _, p := range h.Pulses {
		if physics.There(stroke, p.Every, p.On, p.Phase) {
			ws = append(ws, p.Walls...)
			ps = append(ps, p.Posts...)
		}
	}
	return ws, ps
}

// PreviewWith plays a stroke of a round in some weather, read-only, the timed
// pieces starting at tick. A pulse piece that came back on the ball pushes it
// out, never across the hole's own walls. A ball left where the next stroke
// brings a hazard back returns to where this stroke started, as under a timed
// hazard (else that hazard would cost a stroke for nothing).
func (h *Simple) PreviewWith(ball physics.Vec2, angle, power float64, stroke, tick int, weather []physics.Zone) (physics.Shot, bool) {
	ws, ps := h.Extras(stroke)
	ball = physics.UnstickIn(ball, ws, ps, h.Course.Radius, h.Course.Walls)
	f := WithZones(WithExtras(h.Course, ws, ps), h.ExtraZones(stroke))
	f = physics.WithTick(WithWeather(f, weather), tick)
	shot, holed := Sink(f.Step(ball, Launch(angle, power), h.Substeps), h.Pin, h.CupRadius, h.Course.Radius)
	if !holed && len(shot.Path) > 0 {
		for _, z := range h.ExtraZones(stroke + 1) {
			if z.Kind == physics.Hazard && z.Contains(shot.Rest()) {
				shot.Path = append(shot.Path, ball)
				shot.Air = append(shot.Air, false)
				shot.Cause = append(shot.Cause, '-')
				break
			}
		}
	}
	return shot, holed
}

// Par is the strokes a good round takes: Strokes, 3 unless it says 1 to 19.
func (h *Simple) Par() int {
	if h.Strokes > 0 && h.Strokes < 20 {
		return h.Strokes
	}
	return 3
}

// Start is the tee.
func (h *Simple) Start() physics.Vec2 { return h.Tee }

// Cup is where the cup is.
func (h *Simple) Cup() physics.Vec2 { return h.Pin }

// Field is the course as the physics sees it.
func (h *Simple) Field() *physics.Field { return h.Course }

// Kick turns a stroke's power (0 to 10) into the ball's speed per substep,
// Kick·p^(3/4), so the roll (v²/2a) grows as p^(3/2). A full stroke rolls 44
// on the usual green, a board's length. Calibrated to keep every hole's par.
const Kick = 0.79

// Launch is the ball's starting velocity for a stroke. Every hole should use
// it, so that the same pull means the same shot on every course.
func Launch(angle, power float64) physics.Vec2 {
	if !(power > 0) {
		return physics.Vec2{}
	}
	return physics.FromPolar(angle, Kick*math.Sqrt(power*math.Sqrt(power)))
}

// minDrop is the least a ball falls to drop: a smaller ball drops as one of
// 0.5, else a point ball would drop into any cup at any speed.
const minDrop = 0.5

// Capture is the fastest a ball of radius ball crossing a cup of radius cup,
// off its centre by off, can go and still drop, in board units per substep;
// 0 when it cannot drop at all. Holmes's criterion (Am. J. Phys. 59, 1991):
// (2·sqrt(R² − b²) − r) · sqrt(G / 2r).
func Capture(cup, ball, off float64) float64 {
	c := cup*cup - off*off
	if !(c > 0) {
		return 0
	}
	if !(ball >= minDrop) {
		ball = minDrop
	}
	chord := 2*math.Sqrt(c) - ball
	if !(chord > 0) {
		return 0
	}
	return chord * math.Sqrt(physics.G/(2*ball))
}

// jumpStep is how much longer than the fastest drop a step must be for the
// one after it to be the rest of a jump, not a slow ball.
const jumpStep = 1.5

// Sink decides whether a shot ends in the cup: it stops within radius of the
// pin, or crosses the cup no faster than Capture allows a ball of radius
// ball. When it drops, the path is cut there and ends on the pin.
func Sink(shot physics.Shot, pin physics.Vec2, radius, ball float64) (physics.Shot, bool) {
	p := shot.Path
	top := Capture(radius, ball, 0) // over the middle: the fastest drop
	for i := 0; i+1 < len(p); i++ {
		a, d := p[i], p[i+1].Sub(p[i])
		if d.LenCmp(top) > 0 {
			continue // too fast, or a tunnel jump
		}
		if airborne(shot, i) || airborne(shot, i+1) {
			continue // flying over the cup is not dropping into it
		}
		// a short step right after a long one is not a slow ball: it is the
		// rest of a substep after a tunnel exit or a bounce
		if i > 0 && p[i].Sub(p[i-1]).LenCmp(top*jumpStep) > 0 {
			continue
		}
		// a step whose box is more than radius from the pin cannot drop
		if b, r := p[i+1], radius+1e-9; (pin.X < a.X-r && pin.X < b.X-r) || (pin.X > a.X+r && pin.X > b.X+r) ||
			(pin.Y < a.Y-r && pin.Y < b.Y-r) || (pin.Y > a.Y+r && pin.Y > b.Y+r) {
			continue
		}
		l := d.Len()
		t := 0.0
		if l > 0 {
			t = pin.Sub(a).Dot(d) / (l * l)
			if t < 0 {
				t = 0
			} else if t > 1 {
				t = 1
			}
		}
		at := a.Add(d.Scale(t))
		// the step's nearest point to the pin is where it crosses the cup
		if off := at.Sub(pin).Len(); off <= radius && l <= Capture(radius, ball, off) {
			cut := make([]physics.Vec2, 0, i+3)
			cut = append(cut, p[:i+1]...)
			shot.Path = append(cut, at, pin)
			if len(shot.Air) > i {
				shot.Air = append(append(make([]bool, 0, i+3), shot.Air[:i+1]...), false, false)
			}
			if len(shot.Cause) > i {
				shot.Cause = append(append(make([]byte, 0, i+3), shot.Cause[:i+1]...), '-', '-')
			}
			return shot, true
		}
	}
	if shot.Rest().Sub(pin).LenCmp(radius) <= 0 {
		shot.Path = append(shot.Path, pin)
		if shot.Air != nil {
			shot.Air = append(shot.Air, false)
		}
		if shot.Cause != nil {
			shot.Cause = append(shot.Cause, '-')
		}
		return shot, true
	}
	return shot, false
}

func airborne(s physics.Shot, i int) bool { return i < len(s.Air) && s.Air[i] }

data.gno

package course

import (
	"errors"
	"math"

	"gno.land/p/nym-alexiscolin000/gnogolf/physics"
)

// Magic starts GG1, a hole as one little-endian binary string, frozen with
// this package: magic, header, field, skin table (str = u8 len + bytes),
// walls (style runs, then segments and, outside pulses, their Lengths),
// posts, zones, pulses; each list a count first. Encode is the layout.
const Magic = "GG1"

// The frozen limits Decode holds a hole to, pulses included.
const (
	MaxWalls     = 160
	MaxPosts     = 32
	MaxZones     = 32
	MaxPoly      = 64  // points in one polygon
	MaxPolyTotal = 512 // points in all of them
	MaxPulses    = 16
	MaxSkins     = 64
	MaxSubsteps  = 60
	MaxTiming    = 4096
	MaxOrder     = 999
	MaxWorld     = 16
)

const (
	flagRound = 1 << iota
	flagOutside
	flagAir
	flagCapped
)

// Encode is the hole as GG1. It stores what it is given: call it on a hole
// after Fit, with its walls prepared.
func Encode(h *Simple) string {
	e := &encoder{}
	f := h.Course
	if f == nil {
		f = &physics.Field{}
	}
	skins := map[string]int{}
	var table []string
	skin := func(s string) {
		if _, ok := skins[s]; !ok {
			skins[s] = len(table)
			table = append(table, s)
		}
	}
	pieces := func(ws []physics.Wall, ps []physics.Post, zs []physics.Zone) {
		for _, w := range ws {
			skin(w.Skin)
		}
		for _, p := range ps {
			skin(p.Skin)
		}
		for _, z := range zs {
			skin(z.Skin)
		}
	}
	pieces(f.Walls, f.Posts, f.Zones)
	for _, p := range h.Pulses {
		pieces(p.Walls, p.Posts, p.Zones)
	}

	e.b = append(e.b, Magic...)
	e.u16(h.W)
	e.u16(h.H)
	e.u8(h.Strokes)
	e.u16(h.Substeps)
	e.str(h.World)
	e.f64(h.Order)
	e.str(h.Title)
	e.vec(h.Tee)
	e.vec(h.Pin)
	e.f64(h.CupRadius)
	e.f64(h.Shelter)
	e.f64(f.Friction)
	e.f64(f.Bounce)
	e.f64(f.Radius)
	e.u16(len(table))
	for _, s := range table {
		e.str(s)
	}
	e.walls(f.Walls, skins, f.Radius, true)
	e.posts(f.Posts, skins)
	e.zones(f.Zones, skins)
	e.u8(len(h.Pulses))
	for _, p := range h.Pulses {
		e.i32(p.Every)
		e.i32(p.On)
		e.i32(p.Phase)
		e.walls(p.Walls, skins, f.Radius, false)
		e.posts(p.Posts, skins)
		e.zones(p.Zones, skins)
	}
	return string(e.b)
}

type encoder struct{ b []byte }

func (e *encoder) u8(n int)  { e.b = append(e.b, byte(n)) }
func (e *encoder) u16(n int) { e.b = append(e.b, byte(n), byte(n>>8)) }
func (e *encoder) i32(n int) {
	u := uint32(int32(n))
	e.b = append(e.b, byte(u), byte(u>>8), byte(u>>16), byte(u>>24))
}

func (e *encoder) f64(x float64) {
	u := math.Float64bits(x)
	e.b = append(e.b, byte(u), byte(u>>8), byte(u>>16), byte(u>>24), byte(u>>32), byte(u>>40), byte(u>>48), byte(u>>56))
}

func (e *encoder) vec(v physics.Vec2) {
	e.f64(v.X)
	e.f64(v.Y)
}

func (e *encoder) str(s string) {
	e.u8(len(s))
	e.b = append(e.b, s[:len(s)&0xff]...)
}

// sameStyle is whether two walls share everything but their segment.
func sameStyle(a, b *physics.Wall) bool {
	return math.Float64bits(a.Bounce) == math.Float64bits(b.Bounce) && a.Mark == b.Mark && a.Skin == b.Skin &&
		a.Every == b.Every && a.On == b.On && a.Phase == b.Phase
}

func (e *encoder) walls(ws []physics.Wall, skins map[string]int, r float64, lengths bool) {
	e.u16(len(ws))
	for i := 0; i < len(ws); {
		j := i + 1
		for j < len(ws) && sameStyle(&ws[i], &ws[j]) {
			j++
		}
		w := &ws[i]
		e.u16(j - i)
		e.f64(w.Bounce)
		e.i32(int(w.Mark))
		e.u16(skins[w.Skin])
		e.i32(w.Every)
		e.i32(w.On)
		e.i32(w.Phase)
		i = j
	}
	for _, w := range ws {
		e.vec(w.Seg.A)
		e.vec(w.Seg.B)
		if lengths {
			l, lp, lm := physics.Lengths(w.Seg, r)
			e.f64(l)
			e.f64(lp)
			e.f64(lm)
		}
	}
}

func (e *encoder) posts(ps []physics.Post, skins map[string]int) {
	e.u16(len(ps))
	for _, p := range ps {
		e.vec(p.C)
		e.f64(p.R)
		e.f64(p.Bounce)
		e.i32(int(p.Mark))
		e.u16(skins[p.Skin])
	}
}

func (e *encoder) zones(zs []physics.Zone, skins map[string]int) {
	e.u16(len(zs))
	for _, z := range zs {
		e.u8(int(z.Kind))
		flags := 0
		if z.Round {
			flags |= flagRound
		}
		if z.Outside {
			flags |= flagOutside
		}
		if z.Air {
			flags |= flagAir
		}
		if z.Capped {
			flags |= flagCapped
		}
		e.u8(flags)
		e.vec(z.Min)
		e.vec(z.Max)
		e.vec(z.Vec)
		e.f64(z.Scale)
		e.i32(int(z.Mark))
		e.u16(skins[z.Skin])
		e.i32(z.Every)
		e.i32(z.On)
		e.i32(z.Phase)
		e.u16(len(z.Poly))
		for _, p := range z.Poly {
			e.vec(p)
		}
	}
}

// Decode reads a GG1 hole; anything outside the format, its limits or its
// value bounds is an error, with nothing returned. It prepares the walls from
// the stored lengths (physics.PrepareWith) and trusts them: check them once
// with Exact, or use DecodeChecked, before accepting data from anyone.
func Decode(s string) (*Simple, error) {
	d := &decoder{s: s}
	if len(s) < len(Magic) || s[:len(Magic)] != Magic {
		return nil, errors.New("course: not GG1 data")
	}
	d.i = len(Magic)
	h := &Simple{}
	h.W, h.H = d.u16(), d.u16()
	h.Strokes = d.u8()
	h.Substeps = d.u16()
	h.World = d.str()
	h.Order = d.f64()
	h.Title = d.str()
	if d.err != "" {
		return nil, errors.New(d.err)
	}
	if h.W < 1 || h.W > MaxBoard || h.H < 1 || h.H > MaxBoard {
		return nil, errors.New("course: the board is 1 to 96 a side")
	}
	if h.Strokes > 19 {
		return nil, errors.New("course: par is at most 19")
	}
	if h.Substeps < 1 || h.Substeps > MaxSubsteps {
		return nil, errors.New("course: substeps are 1 to 60")
	}
	if !IsWorld(h.World) {
		return nil, errors.New("course: a world is 1 to 16 letters a-z")
	}
	if !(h.Order >= 0 && h.Order <= MaxOrder) {
		return nil, errors.New("course: order is 0 to 999")
	}
	d.w, d.h = float64(h.W), float64(h.H)
	h.Tee, h.Pin = d.point(), d.point()
	h.CupRadius, h.Shelter = d.f64(), d.f64()
	f := &physics.Field{}
	f.Friction, f.Bounce, f.Radius = d.f64(), d.f64(), d.f64()
	if d.err == "" {
		switch {
		case !(h.CupRadius > 0 && h.CupRadius <= 2):
			d.fail("the cup's radius is above 0 and at most 2")
		case !(h.Shelter >= 0 && h.Shelter <= 1):
			d.fail("shelter is 0 to 1")
		case !(f.Friction >= 0 && f.Friction < 1):
			d.fail("friction is 0 to below 1")
		case !bounce(f.Bounce):
			d.fail("a bounce is 0 to 1.5")
		case !(f.Radius >= 0 && f.Radius <= 1):
			d.fail("the ball's radius is 0 to 1")
		}
	}
	n := d.u16()
	if n > MaxSkins {
		d.fail("too many skins")
	}
	if d.err != "" {
		return nil, errors.New(d.err)
	}
	d.skins = make([]string, n)
	for i := range d.skins {
		d.skins[i] = d.str()
	}
	var lens []float64
	f.Walls, lens = d.walls(true)
	f.Posts = d.posts()
	f.Zones = d.zones()
	np := d.u8()
	if np > MaxPulses {
		d.fail("too many pulses")
	}
	if d.err != "" {
		return nil, errors.New(d.err)
	}
	if np > 0 {
		h.Pulses = make([]Pulse, np)
	}
	for i := range h.Pulses {
		p := &h.Pulses[i]
		p.Every, p.On, p.Phase = d.i32(), d.i32(), d.i32()
		if !timing(p.Every, p.On, p.Phase) {
			d.fail("a pulse's timing is out of bounds")
		}
		p.Walls, _ = d.walls(false)
		p.Posts = d.posts()
		p.Zones = d.zones()
		if d.err != "" {
			return nil, errors.New(d.err)
		}
	}
	if d.err != "" {
		return nil, errors.New(d.err)
	}
	if d.i != len(s) {
		return nil, errors.New("course: trailing bytes after the hole")
	}
	physics.PrepareWith(f, lens)
	h.Course = f
	return h, nil
}

// DecodeChecked is Decode, then Exact: for data anyone wrote. It costs a
// Prepare more; data once checked can be read back with Decode.
func DecodeChecked(s string) (*Simple, error) {
	h, err := Decode(s)
	if err != nil {
		return nil, err
	}
	if !Exact(h) {
		return nil, errors.New("course: the stored wall lengths are not the walls' own")
	}
	return h, nil
}

// Exact reports whether a decoded hole's stored lengths are its walls' own,
// its prep bit for bit the one Prepare works out. Use it on a value fresh from
// Decode: it prepares a copy of the field, which can panic on a hole stored in
// another realm (the copy keeps that realm's read-only mark).
func Exact(h *Simple) bool {
	if h.Course == nil {
		return false
	}
	got := physics.Prepared(h.Course)
	g := *h.Course
	physics.Prepare(&g)
	want := physics.Prepared(&g)
	if len(got) != len(want) {
		return false
	}
	for i := range want {
		if math.Float64bits(got[i]) != math.Float64bits(want[i]) {
			return false
		}
	}
	return true
}

// decoder reads GG1 with every read bounds-checked: past the end it records
// the error and reads zeros. Counts are checked against the limits before
// anything is allocated for them.
type decoder struct {
	s                               string
	i                               int
	err                             string
	w, h                            float64 // the board, for the coordinate bounds
	skins                           []string
	nWalls, nPosts, nZones, nPoints int // running totals, pulses included
}

func (d *decoder) fail(why string) {
	if d.err == "" {
		d.err = "course: " + why
	}
}

func (d *decoder) need(n int) bool {
	if d.i+n > len(d.s) {
		d.fail("truncated data")
		d.i = len(d.s)
		return false
	}
	return true
}

func (d *decoder) u8() int {
	if !d.need(1) {
		return 0
	}
	d.i++
	return int(d.s[d.i-1])
}

func (d *decoder) u16() int {
	if !d.need(2) {
		return 0
	}
	s, i := d.s, d.i
	d.i += 2
	return int(s[i]) | int(s[i+1])<<8
}

func (d *decoder) i32() int {
	if !d.need(4) {
		return 0
	}
	s, i := d.s, d.i
	d.i += 4
	return int(int32(uint32(s[i]) | uint32(s[i+1])<<8 | uint32(s[i+2])<<16 | uint32(s[i+3])<<24))
}

// f64 reads a float and refuses NaN and the infinities; -0 is kept.
func (d *decoder) f64() float64 {
	s, i := d.s, d.i
	if i+8 > len(s) {
		d.need(8)
		return 0
	}
	d.i = i + 8
	x := math.Float64frombits(uint64(s[i]) | uint64(s[i+1])<<8 | uint64(s[i+2])<<16 | uint64(s[i+3])<<24 |
		uint64(s[i+4])<<32 | uint64(s[i+5])<<40 | uint64(s[i+6])<<48 | uint64(s[i+7])<<56)
	if x-x != 0 { // NaN or an infinity
		d.fail("a number is not finite")
		return 0
	}
	return x
}

func (d *decoder) str() string {
	n := d.u8()
	if !d.need(n) {
		return ""
	}
	d.i += n
	return d.s[d.i-n : d.i]
}

// point reads a position, which must lie on the board or within 1 of it.
func (d *decoder) point() physics.Vec2 {
	x, y := d.f64(), d.f64()
	if !(x >= -1 && x <= d.w+1 && y >= -1 && y <= d.h+1) {
		d.fail("a point lies off the board")
	}
	return physics.Vec2{X: x, Y: y}
}

// corner reads a corner of a zone's box, which may lie up to MaxBoard off the
// board: Fit keeps a round or polygon zone's box whole.
func (d *decoder) corner() physics.Vec2 {
	x, y := d.f64(), d.f64()
	if !(x >= -MaxBoard && x <= d.w+MaxBoard && y >= -MaxBoard && y <= d.h+MaxBoard) {
		d.fail("a zone's box lies far off the board")
	}
	return physics.Vec2{X: x, Y: y}
}

func (d *decoder) skin() string {
	k := d.u16()
	if k >= len(d.skins) {
		d.fail("a skin index is out of range")
		return ""
	}
	return d.skins[k]
}

func bounce(b float64) bool { return b >= 0 && b <= 1.5 }

// timing is the bounds of Every/On/Phase: untimed is all zeros; timed, on at
// most every and phase below it.
func timing(every, on, phase int) bool {
	if every == 0 {
		return on == 0 && phase == 0
	}
	return every > 0 && every <= MaxTiming && on >= 0 && on <= every && phase >= 0 && phase < every
}

// IsWorld is whether w can name a world: 1 to MaxWorld letters a-z, as Decode
// holds data to.
func IsWorld(w string) bool {
	if len(w) < 1 || len(w) > MaxWorld {
		return false
	}
	for i := 0; i < len(w); i++ {
		if w[i] < 'a' || w[i] > 'z' {
			return false
		}
	}
	return true
}

// walls reads a wall list: its style runs, then its segments (and, with
// lengths, each wall's three Lengths).
func (d *decoder) walls(lengths bool) ([]physics.Wall, []float64) {
	n := d.u16()
	if d.nWalls += n; d.nWalls > MaxWalls {
		d.fail("too many walls")
	}
	if d.err != "" {
		return nil, nil
	}
	ws := make([]physics.Wall, n)
	for i := 0; i < n && d.err == ""; {
		count := d.u16()
		if count < 1 || count > n-i {
			d.fail("a wall style run does not fit the walls")
			break
		}
		w := physics.Wall{Bounce: d.f64(), Mark: rune(d.i32()), Skin: d.skin(), Every: d.i32(), On: d.i32(), Phase: d.i32()}
		if !bounce(w.Bounce) {
			d.fail("a bounce is 0 to 1.5")
		}
		if !timing(w.Every, w.On, w.Phase) {
			d.fail("a wall's timing is out of bounds")
		}
		for k := 0; k < count; k++ {
			ws[i+k] = w
		}
		i += count
	}
	// one bounds check, then le per float: most of a hole's floats are here
	size := 32
	if lengths {
		size = 56
	}
	if d.err != "" || !d.need(n*size) {
		return nil, nil
	}
	var lens []float64
	if lengths {
		lens = make([]float64, 3*n)
	}
	s, i := d.s, d.i
	for k := range ws {
		ax, ay, bx, by := le(s, i), le(s, i+8), le(s, i+16), le(s, i+24)
		if !(ax >= -1 && ax <= d.w+1 && ay >= -1 && ay <= d.h+1 && bx >= -1 && bx <= d.w+1 && by >= -1 && by <= d.h+1) {
			d.fail("a point lies off the board")
			return nil, nil
		}
		ws[k].Seg = physics.Segment{A: physics.Vec2{X: ax, Y: ay}, B: physics.Vec2{X: bx, Y: by}}
		if lengths {
			l, lp, lm := le(s, i+32), le(s, i+40), le(s, i+48)
			if l-l != 0 || lp-lp != 0 || lm-lm != 0 {
				d.fail("a number is not finite")
				return nil, nil
			}
			lens[3*k], lens[3*k+1], lens[3*k+2] = l, lp, lm
		}
		i += size
	}
	d.i = i
	return ws, lens
}

// le is the little-endian float at s[i:i+8]; the caller checked the length.
// f64 has it inline: a call more per float is gas on every decode.
func le(s string, i int) float64 {
	return math.Float64frombits(uint64(s[i]) | uint64(s[i+1])<<8 | uint64(s[i+2])<<16 | uint64(s[i+3])<<24 |
		uint64(s[i+4])<<32 | uint64(s[i+5])<<40 | uint64(s[i+6])<<48 | uint64(s[i+7])<<56)
}

func (d *decoder) posts() []physics.Post {
	n := d.u16()
	if d.nPosts += n; d.nPosts > MaxPosts {
		d.fail("too many posts")
	}
	if d.err != "" {
		return nil
	}
	ps := make([]physics.Post, n)
	for i := 0; i < n && d.err == ""; i++ {
		p := &ps[i]
		p.C = d.point()
		p.R, p.Bounce = d.f64(), d.f64()
		p.Mark, p.Skin = rune(d.i32()), d.skin()
		if !(p.R > 0 && p.R <= 8) {
			d.fail("a post's radius is above 0 and at most 8")
		}
		if !bounce(p.Bounce) {
			d.fail("a bounce is 0 to 1.5")
		}
	}
	return ps
}

func (d *decoder) zones() []physics.Zone {
	n := d.u16()
	if d.nZones += n; d.nZones > MaxZones {
		d.fail("too many zones")
	}
	if d.err != "" {
		return nil
	}
	zs := make([]physics.Zone, n)
	for i := 0; i < n && d.err == ""; i++ {
		z := &zs[i]
		kind, flags := d.u8(), d.u8()
		if kind > int(physics.Loop) {
			d.fail("a zone's kind is unknown")
		}
		if flags&^(flagRound|flagOutside|flagAir|flagCapped) != 0 {
			d.fail("a zone has unknown flags")
		}
		z.Kind = physics.ZoneKind(kind)
		z.Round, z.Outside, z.Air, z.Capped = flags&flagRound != 0, flags&flagOutside != 0, flags&flagAir != 0, flags&flagCapped != 0
		z.Min, z.Max = d.corner(), d.corner()
		switch z.Kind {
		case physics.Tunnel, physics.Hazard, physics.Loop:
			z.Vec = d.point() // a place on the board
		default:
			z.Vec = physics.Vec2{X: d.f64(), Y: d.f64()} // a push
			// no steeper than MaxSin (squared: no root; a NaN fails it)
			if max := physics.G * physics.MaxSin; !(z.Vec.X*z.Vec.X+z.Vec.Y*z.Vec.Y <= max*max) {
				d.fail("a slope pushes at most G·MaxSin (0.95)")
			}
		}
		z.Scale = d.f64()
		if !(z.Scale >= 0 && z.Scale <= 8) {
			d.fail("a zone's scale is 0 to 8")
		}
		z.Mark, z.Skin = rune(d.i32()), d.skin()
		z.Every, z.On, z.Phase = d.i32(), d.i32(), d.i32()
		if !timing(z.Every, z.On, z.Phase) {
			d.fail("a zone's timing is out of bounds")
		}
		np := d.u16()
		if np == 1 || np == 2 || np > MaxPoly {
			d.fail("a polygon has 3 to 64 points")
		}
		if d.nPoints += np; d.nPoints > MaxPolyTotal {
			d.fail("too many polygon points")
		}
		if d.err != "" {
			break
		}
		if np > 0 {
			z.Poly = make([]physics.Vec2, np)
			for k := range z.Poly {
				z.Poly[k] = d.point()
			}
		}
	}
	return zs
}

gnomod.toml

module = "gno.land/p/nym-alexiscolin000/gnogolf/course"
gno = "0.9"

[addpkg]
  creator = "g1mpkp5lm8lwpm0pym4388836d009zfe4maxlqsq"
  height = 65066
  max_deposit = "7000000ugnot"