gamedebug

package
v0.4.0-rc.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 4, 2026 License: Apache-2.0 Imports: 44 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package gamedebug is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/.

Package gamedebug holds development-only tooling and overlays for NSGo games: a frame-time graph, collision and sprite-bounds wireframes, a live scene inspector, a behavior tree and state machine inspector with steering guides, an interactive dev console with typed tunables, named timing scopes with Chrome/Perfetto trace export, an asset memory tracker with budgets, a GC/allocation monitor, and a fixed-step visual log of entity messages, category snapshots and debug shapes saved as JSON Lines.

In default builds every feature is compiled in and Enabled reports true. Building with -tags release swaps the implementation for empty no-ops where Enabled reports false and Overlay.View returns nil, so release binaries link none of the overlay UI, graph, AI inspector, steering guides, console, profiler, memory tracker, GC monitor, visual log, or wireframe code.

Index

Examples

Constants

View Source
const (
	// MonitorNameEntitiesAlive counts live entities in an entities.World.
	MonitorNameEntitiesAlive = "entities/alive"

	// MonitorNameParticlesActive counts live particles across monitored particles.Emitter values.
	MonitorNameParticlesActive = "particles/active"
	// MonitorNameParticlesEmitters counts non-nil particles.Emitter values returned by the emitter callback.
	MonitorNameParticlesEmitters = "particles/emitters"

	// MonitorNamePhysicsBodies counts bodies in a 2D physics.World.
	MonitorNamePhysicsBodies = "physics/bodies"
	// MonitorNamePhysicsTriggers counts triggers in a 2D physics.World.
	MonitorNamePhysicsTriggers = "physics/triggers"

	// MonitorNamePhysicsRigidBodies counts bodies in a 2D physics.RigidWorld.
	MonitorNamePhysicsRigidBodies = "physics/rigid_bodies"
	// MonitorNamePhysicsRigidAwake counts awake bodies in a 2D physics.RigidWorld.
	MonitorNamePhysicsRigidAwake = "physics/rigid_awake"
	// MonitorNamePhysicsJoints counts joints in a 2D physics.RigidWorld.
	MonitorNamePhysicsJoints = "physics/joints"

	// MonitorNamePhysics3DBodies counts bodies in a 3D physics3d.World.
	MonitorNamePhysics3DBodies = "physics3d/bodies"
	// MonitorNamePhysics3DAwake counts awake dynamic bodies in a 3D physics3d.World.
	MonitorNamePhysics3DAwake = "physics3d/awake"

	// MonitorNameNetBytesSent counts cumulative replicated snapshot bytes sent by netplay.ServerWorld.
	MonitorNameNetBytesSent = "net/bytes_sent"
	// MonitorNameNetBytesPerTick measures average replicated bytes per tick from netplay.ServerWorld.
	MonitorNameNetBytesPerTick = "net/bytes_per_tick"
	// MonitorNameNetPacketsSent counts cumulative replicated packets sent by netplay.ServerWorld.
	MonitorNameNetPacketsSent = "net/packets_sent"
	// MonitorNameNetSnapshotsSent counts cumulative snapshots sent by netplay.ServerWorld.
	MonitorNameNetSnapshotsSent = "net/snapshots_sent"
	// MonitorNameNetSnapshotsDeferred counts snapshots deferred due to peer bandwidth budgets.
	MonitorNameNetSnapshotsDeferred = "net/snapshots_deferred"

	// MonitorNameNetBytesOut measures aggregate outbound transport throughput in bytes/s from NetMonitor.
	MonitorNameNetBytesOut = "net/bytes_out"
	// MonitorNameNetBytesIn measures aggregate inbound transport throughput in bytes/s from NetMonitor.
	MonitorNameNetBytesIn = "net/bytes_in"
	// MonitorNameNetPacketsOut measures aggregate outbound transport throughput in packets/s from NetMonitor.
	MonitorNameNetPacketsOut = "net/packets_out"
	// MonitorNameNetPacketsIn measures aggregate inbound transport throughput in packets/s from NetMonitor.
	MonitorNameNetPacketsIn = "net/packets_in"

	// MonitorNameNetRollbacks counts cumulative rollbacks from netplay.RollbackSession.
	MonitorNameNetRollbacks = "net/rollbacks"
	// MonitorNameNetRollbackDepth tracks the maximum rollback depth in frames from netplay.RollbackSession.
	MonitorNameNetRollbackDepth = "net/rollback_depth"
	// MonitorNameNetMispredictions counts cumulative input mispredictions from netplay.RollbackSession.
	MonitorNameNetMispredictions = "net/mispredictions"
	// MonitorNameNetDesyncs counts cumulative checksum desyncs from netplay.RollbackSession.
	MonitorNameNetDesyncs = "net/desyncs"
)

Stable monitor names registered by the built-in Monitor* helpers. Playtests, benchmarks, and MCP agents can rely on these names across builds.

View Source
const (
	MovieDirEnv    = "NSGO_GAME_MOVIE_DIR"
	MovieFPSEnv    = "NSGO_GAME_MOVIE_FPS"
	MovieFramesEnv = "NSGO_GAME_MOVIE_FRAMES"
	MovieReplayEnv = "NSGO_GAME_MOVIE_REPLAY"
)

Environment variables set by `game dev -movie` so a running development game can start deterministic movie capture automatically via DevMovieOptions.

View Source
const (
	// MovieAudioVideoOnly is recorded in movie.yaml when no offline audio
	// callback was supplied and only PNG frames were written.
	MovieAudioVideoOnly = "video-only"
	// MovieAudioWAVFile is the file name written beside the image sequence and
	// recorded in movie.yaml when offline audio samples are captured.
	MovieAudioWAVFile = "audio.wav"
)
View Source
const (
	VLogFormat  = "gamedebug.vlog"
	VLogVersion = 1
)

VLogFormat and VLogVersion identify the JSON Lines header WriteJSONL writes first and ReadVLog requires.

View Source
const (
	VLogShapeLine   = "line"
	VLogShapeArrow  = "arrow"
	VLogShapeCircle = "circle"
	VLogShapeBox    = "box"
	VLogShapePath   = "path"
	VLogShapeText   = "text"
)

Standard shape kinds recorded by VLog's shape helpers and drawn by ShapeOverlay and the editor's Visual Log viewport overlay.

View Source
const DefaultVLogCapacity = 4096

DefaultVLogCapacity is the number of entries, and separately of shapes, a VLog keeps when NewVLog is given a capacity of 0 or less.

View Source
const FrameHistory = 120

FrameHistory is the number of frames retained in a FrameStats ring buffer.

View Source
const MovieManifestVersion = 1

MovieManifestVersion is the movie.yaml schema version written and read by this package.

Variables

View Source
var (
	// ErrCPUProfileActive reports calling StartCPUProfile or ProfileCPU while another CPU profile is already running.
	ErrCPUProfileActive = errors.New("gamedebug: CPU profile is already running")
	// ErrCPUProfileUnsupported reports requesting a CPU profile on a target where runtime CPU sampling is unavailable, such as WebAssembly.
	ErrCPUProfileUnsupported = errors.New("gamedebug: CPU profiling is unavailable in WebAssembly")
)

Functions

func AssertZeroAllocs

func AssertZeroAllocs(t testing.TB, runs int, fn func())

AssertZeroAllocs fails t if fn allocates on the heap during runs iterations, for use in CI hot-path regression tests.

func ClearPanic

func ClearPanic()

ClearPanic removes the stored last panic record.

func ConsoleView

func ConsoleView(cx *core.Scope, c *Console) core.View

ConsoleView returns a native NSGo view bound to c, composable inside Overlay or any game view tree.

func Enabled

func Enabled() bool

Enabled reports whether debug overlays are compiled into this build. It is true in default builds and false with -tags release.

func EncodeMovieManifest

func EncodeMovieManifest(m MovieManifest) ([]byte, error)

EncodeMovieManifest validates m and encodes it as canonical deterministic YAML for movie.yaml.

func EstimateImageBytes

func EstimateImageBytes(w, h int) int64

EstimateImageBytes returns the uncompressed RGBA8 memory footprint (w * h * 4) for an image of size w by h, or 0 if either dimension is non-positive.

func EstimatePCMBytes

func EstimatePCMBytes(samples, channels, bytesPerSample int) int64

EstimatePCMBytes returns the uncompressed PCM memory footprint (samples * channels * bytesPerSample), or 0 if any parameter is non-positive.

func MarkPlayable

func MarkPlayable()

MarkPlayable records when the game first accepts play. It has no effect in release builds.

func MeasureAllocs

func MeasureAllocs(runs int, fn func()) float64

MeasureAllocs wraps testing.AllocsPerRun and returns the average heap allocations per execution of fn over runs iterations (defaulting to 100 when runs <= 0).

func MonitorEntities

func MonitorEntities(m *Monitors, w *entities.World)

MonitorEntities registers the built-in entity count monitor ("entities/alive") for w.

func MonitorNet

func MonitorNet(m *Monitors, stats func() netplay.ReplicationStats)

MonitorNet registers built-in netplay replication monitors ("net/bytes_sent", "net/bytes_per_tick", "net/packets_sent", "net/snapshots_sent", and "net/snapshots_deferred") sampled from stats.

func MonitorNetBandwidth

func MonitorNetBandwidth(m *Monitors, nm *NetMonitor)

MonitorNetBandwidth registers built-in transport bandwidth monitors ("net/bytes_out", "net/bytes_in", "net/packets_out", and "net/packets_in") sampled from nm's zero-allocation snapshot.

func MonitorParticles

func MonitorParticles(m *Monitors, emitters func() []*particles.Emitter)

MonitorParticles registers built-in particle monitors ("particles/active" and "particles/emitters") sampled from the emitters slice returned by emitters.

func MonitorPhysics

func MonitorPhysics(m *Monitors, w *physics.World)

MonitorPhysics registers built-in 2D physics monitors ("physics/bodies" and "physics/triggers") for w.

func MonitorPhysics3D

func MonitorPhysics3D(m *Monitors, w *physics3d.World)

MonitorPhysics3D registers built-in 3D physics monitors ("physics3d/bodies" and "physics3d/awake") for w.

func MonitorRigidPhysics

func MonitorRigidPhysics(m *Monitors, w *physics.RigidWorld)

MonitorRigidPhysics registers built-in 2D rigid-body physics monitors ("physics/rigid_bodies", "physics/rigid_awake", and "physics/joints") for w.

func MonitorRollback

func MonitorRollback(m *Monitors, stats func() netplay.RollbackStats)

MonitorRollback registers built-in rollback netcode monitors ("net/rollbacks", "net/rollback_depth", "net/mispredictions", and "net/desyncs") sampled from stats.

func ProfileCPU

func ProfileCPU(duration time.Duration) ([]byte, error)

ProfileCPU samples the current process for duration and returns a pprof profile.

func ProfileHeap

func ProfileHeap() ([]byte, error)

ProfileHeap runs a garbage collection and returns the current heap profile in pprof format.

func ReadVLog

func ReadVLog(r io.Reader) ([]VLogEntry, []VLogShape, error)

ReadVLog reads a log written by WriteJSONL. It refuses a missing or unknown header, an unknown record type or level, unknown fields, malformed JSON Lines, and lines larger than 4 MiB.

func RecordMovie

func RecordMovie(cx *core.Scope, l *game.Loop, opts MovieOptions) (stop func() error, err error)

RecordMovie pauses l's real-time clock and captures deterministic frames at opts.FPS into opts.Dir (through os.Root) until opts.Frames have been written or stop is called. Each frame steps l by Loop.StepRate()/opts.FPS fixed updates, waits for capture and disk write to finish before starting the next frame, writes frame-000001.png (and audio.wav when opts.Audio is set), and writes movie.yaml when finished.

When cx is non-nil, call RecordMovie on the engine goroutine; simulation steps and default cx.Capture calls run on the engine goroutine while PNG encoding and disk writes run off-thread so slow captures never drop frames or freeze the UI. When cx is nil, opts.Capture is required and frames run in a dedicated goroutine.

func StartCPUProfile

func StartCPUProfile(w io.Writer) error

StartCPUProfile starts Go CPU sampling into w until StopCPUProfile is called, for a start and stop control in an editor or MCP client. It returns ErrCPUProfileActive while another CPU profile, including one started by ProfileCPU, is running.

func StopCPUProfile

func StopCPUProfile()

StopCPUProfile stops the CPU profile started by StartCPUProfile and flushes it to its writer. It does nothing when no profile is running.

func WriteHeapProfile

func WriteHeapProfile(w io.Writer) error

WriteHeapProfile runs runtime.GC so live in-use counts are up to date, then writes the heap profile (inuse and alloc samples) to w in pprof format.

Types

type AISnapshot

type AISnapshot struct {
	// Agent identifies the inspected agent (for example, "guard-1" or "boss").
	Agent string
	// Tree holds the behavior tree's pre-order node traces (for example, from ai.BTInspector.Walk or WalkInto).
	Tree []ai.BTNodeTrace
	// Machine holds a flow.Machine's current state and bounded transition history (for example, from m.Inspect()).
	Machine *flow.MachineInspection
}

AISnapshot describes a chosen agent's live AI state for the debug overlay panel. Set Tree to inspect a behavior tree, Machine to inspect a flow.Machine, or both.

func BehaviorTreeSnapshot

func BehaviorTreeSnapshot(agent string, ins *ai.BTInspector) AISnapshot

BehaviorTreeSnapshot builds an AISnapshot for agent by walking ins. Under -tags release, BehaviorTreeSnapshot returns a zero AISnapshot without walking ins.

func StateMachineSnapshot

func StateMachineSnapshot(agent string, m flow.MachineInspector) AISnapshot

StateMachineSnapshot builds an AISnapshot for agent from m's current state and transition history. Under -tags release, StateMachineSnapshot returns a zero AISnapshot without snapshotting m.

type AssetKind

type AssetKind uint8

AssetKind classifies tracked asset memory in a MemoryTracker.

const (
	// AssetImage identifies standalone decoded images and textures.
	AssetImage AssetKind = iota
	// AssetAtlas identifies sprite atlases and sheets.
	AssetAtlas
	// AssetAudio identifies decoded audio buffers and sound banks.
	AssetAudio
	// AssetOther identifies any other asset category.
	AssetOther
)

func (AssetKind) String

func (k AssetKind) String() string

String returns a lowercase label for k.

type Category

type Category interface {
	Name() string
	Snapshot(entity string) []Field
}

Category is a gameplay system that can describe one entity, such as its abilities, stats, perception or navigation state. VLog.Snapshot records what a Category reports for an entity at a fixed step, and Overlay displays registered categories for the picked entity.

type CategoryDrawer

type CategoryDrawer interface {
	Category
	Draw(entity string, d *core.Drawing)
}

CategoryDrawer is optionally implemented by a Category that can also draw world-space debug overlays for an entity into a core.Drawing.

type CategorySnapshot

type CategorySnapshot struct {
	Name   string
	Fields []Field
}

CategorySnapshot is one named Category's captured fields for the picked entity.

type CommandInfo

type CommandInfo struct {
	// Name is the command name as typed on the console.
	Name string
	// Help is the command's usage or description text.
	Help string
	// Builtin reports whether the command is built into Console.
	Builtin bool
}

CommandInfo describes one command available on a Console.

type Console

type Console struct {
	// contains filtered or unexported fields
}

Console is an interactive development console supporting custom commands, range-checked typed tunables, history navigation, tab completion, and Storage persistence.

Example

A Console runs commands typed by the developer and tunes registered variables within their ranges.

package main

import (
	"fmt"

	"github.com/nsgo-dev/game/pkg/tooling/gamedebug"
)

func main() {
	c := gamedebug.NewConsole()
	gravity := 9.8
	c.RegisterFloat("gravity", 0, 50, &gravity)
	c.RegisterCommand("spawn", "spawn <kind>: add an enemy", func(args []string) (string, error) {
		return "spawned " + args[0], nil
	})

	out, err := c.Exec("set gravity 24.5")
	fmt.Println(out, err, gravity)
	out, err = c.Exec("spawn slime")
	fmt.Println(out, err)
	_, err = c.Exec("set gravity 99")
	fmt.Println(err != nil, gravity)
	fmt.Println(c.Complete("sp"))
}
Output:
gravity = 24.5 <nil> 24.5
spawned slime <nil>
true 24.5
[spawn]

func NewConsole

func NewConsole() *Console

NewConsole returns an empty development Console with built-in commands enabled.

func (*Console) AttachLoop

func (c *Console) AttachLoop(l *game.Loop)

AttachLoop makes the console's pause, step and timescale built-in commands drive l, replacing the loop attached before. Attaching the same loop again does nothing; before any loop is attached, Exec reports those commands as unknown.

func (*Console) Commands

func (c *Console) Commands() []CommandInfo

Commands returns all built-in and registered console commands sorted by name.

func (*Console) Complete

func (c *Console) Complete(prefix string) []string

Complete returns sorted completion candidates for prefix, completing command names and tunable names for get/set/help.

func (*Console) Entries

func (c *Console) Entries() []ConsoleEntry

Entries returns a copy of the current console output log.

func (*Console) Exec

func (c *Console) Exec(line string) (string, error)

Exec parses and executes one command line, updating history and output entries.

func (*Console) History

func (c *Console) History() []string

History returns a copy of executed command lines, oldest first.

func (*Console) HistoryNext

func (c *Console) HistoryNext() string

HistoryNext steps forward through command history, returning "" once past the most recent entry.

func (*Console) HistoryPrev

func (c *Console) HistoryPrev() string

HistoryPrev steps backward through command history and returns the selected command line.

func (*Console) LoadTunables

func (c *Console) LoadTunables(st core.Storage, key string) error

LoadTunables restores registered tunables from st under key. Missing entries are a no-op; unknown keys are ignored; out-of-range values return an error without mutating the tunable.

Its errors are *loaderr.Error values that name key as the file, with the line of the tunable at fault and how to fix it.

func (*Console) RegisterBool

func (c *Console) RegisterBool(name string, ptr *bool)

RegisterBool registers a bool tunable bound to ptr.

func (*Console) RegisterCommand

func (c *Console) RegisterCommand(name, help string, fn func(args []string) (string, error))

RegisterCommand registers a named console command and its help text.

func (*Console) RegisterFloat

func (c *Console) RegisterFloat(name string, minVal, maxVal float64, ptr *float64)

RegisterFloat registers a range-checked float64 tunable bound to ptr.

func (*Console) RegisterFunc

func (c *Console) RegisterFunc(name string, fn expr.Func)

RegisterFunc registers a named expression function callable from eval and set commands.

func (*Console) RegisterInt

func (c *Console) RegisterInt(name string, minVal, maxVal int, ptr *int)

RegisterInt registers a range-checked int tunable bound to ptr.

func (*Console) RegisterString

func (c *Console) RegisterString(name string, ptr *string)

RegisterString registers a string tunable bound to ptr.

func (*Console) SaveTunables

func (c *Console) SaveTunables(st core.Storage, key string) error

SaveTunables persists all registered tunables into st under key as JSON.

func (*Console) SetTunable

func (c *Console) SetTunable(name string, value any, clamp bool) (TunableChange, error)

SetTunable updates the named tunable to value after checking its type and numeric range, and returns the previous value with a snapshot of the tunable after the change, both taken under the same lock as the write. A float tunable takes any Go integer or float; an int tunable takes any Go integer. With clamp, a number outside the tunable's range, including an integer beyond int's range, is stored as the nearest bound and TunableChange.Clamped is set; without clamp it is refused. On error the tunable is left unchanged.

func (*Console) Tunable

func (c *Console) Tunable(name string) (TunableInfo, bool)

Tunable returns a snapshot of the named tunable and reports whether it is registered.

func (*Console) Tunables

func (c *Console) Tunables() []TunableInfo

Tunables returns a snapshot of all registered tunables sorted by name.

type ConsoleEntry

type ConsoleEntry struct {
	// Input is the raw command line that was executed.
	Input string
	// Output is the returned text or error message.
	Output string
	// IsError reports whether the command returned an error.
	IsError bool
}

ConsoleEntry is one recorded command execution in a dev Console log.

type DrawCounter

type DrawCounter = sprite.DrawCounter

DrawCounter is an alias for sprite.DrawCounter so games can create one from gamedebug and attach it directly to sprite.Batch, tilemap.Tilemap, particles.Emitter, scene.Scene, Options.DrawCounter, and mcp.Config.DrawCounter without conversions. Under -tags release, all recording methods compile to no-ops.

type DrawStats

type DrawStats struct {
	// DrawCalls is the number of draw calls submitted in the frame.
	DrawCalls int
	// Sprites is the number of sprites drawn in the frame.
	Sprites int
	// Batches is the number of sprite or instanced draw batches submitted in the frame.
	Batches int
	// Triangles is the number of triangles submitted in the frame.
	Triangles uint64
	// Vertices is the number of vertices submitted in the frame.
	Vertices uint64
}

DrawStats captures per-frame draw submission counts for overlay display and MCP performance readouts.

type Field

type Field struct {
	Name  string `json:"name"`
	Value string `json:"value"`
}

Field is one named value in a Category snapshot.

type FrameSample

type FrameSample struct {
	// Total is the elapsed time of the frame.
	Total time.Duration
	// Update is the time spent in fixed-step updates during the frame.
	Update time.Duration
	// Draw is the time spent drawing the frame.
	Draw time.Duration
	// GPU is the measured GPU execution time for the frame when available from timestamp queries.
	GPU time.Duration
	// HasGPU reports whether GPU was measured for this frame.
	HasGPU bool
	// GCHitch reports whether a GC pause occurred during this frame.
	GCHitch bool
	// Cause is an optional short explanation of a frame-time spike (such as shader compilation or asset streaming) when known by the game.
	Cause string
}

FrameSample holds the measured durations of one rendered frame.

type FrameStats

type FrameStats struct {
	// contains filtered or unexported fields
}

FrameStats keeps the last FrameHistory frame timings in a fixed-size ring buffer without per-frame heap allocations.

func (*FrameStats) At

func (s *FrameStats) At(i int) FrameSample

At returns sample i in chronological order, where 0 is the oldest retained frame and Len()-1 is the newest. Out-of-range indices return the zero FrameSample.

func (*FrameStats) Average

func (s *FrameStats) Average() FrameSample

Average returns the mean Total, Update, Draw, and GPU durations across the retained samples.

func (*FrameStats) DrawGraph

func (s *FrameStats) DrawGraph(d *core.Drawing, size core.Size, targetFPS float64)

DrawGraph records a stacked update+draw bar graph of the retained frame samples into d, filling size, with a reference line at targetFPS (60 when 0 or less).

func (*FrameStats) FPS

func (s *FrameStats) FPS() float64

FPS returns the average frame rate in frames per second across the retained samples, or 0 when empty.

func (*FrameStats) Latest

func (s *FrameStats) Latest() FrameSample

Latest returns the most recently recorded sample, or the zero FrameSample when empty.

func (*FrameStats) Len

func (s *FrameStats) Len() int

Len returns how many samples are currently stored, up to FrameHistory.

func (*FrameStats) MaxTotal

func (s *FrameStats) MaxTotal() time.Duration

MaxTotal returns the longest Total frame duration among the retained samples.

func (*FrameStats) Record

func (s *FrameStats) Record(total, update, draw time.Duration)

Record appends one frame's timings to the ring buffer, overwriting the oldest sample once full.

Negative durations are clamped to zero. When total is zero and update or draw is positive, total defaults to update+draw.

func (*FrameStats) Reset

func (s *FrameStats) Reset()

Reset clears all recorded samples.

func (*FrameStats) Samples

func (s *FrameStats) Samples(dst []FrameSample) []FrameSample

Samples appends the retained samples in chronological order to dst and returns the resulting slice.

type GCFrameSample

type GCFrameSample struct {
	// FrameDuration is the frame duration passed to SampleFrame.
	FrameDuration time.Duration
	// CyclesDelta is the number of GC cycles completed since the previous sample.
	CyclesDelta uint64
	// Pause is the estimated total GC pause time observed during this frame.
	Pause time.Duration
	// HeapObjectsBytes is the live heap object bytes reported by /memory/classes/heap/objects:bytes.
	HeapObjectsBytes uint64
	// AllocsDelta is the number of heap objects allocated during this frame (/gc/heap/allocs:objects).
	AllocsDelta uint64
	// AllocBytesDelta is the number of heap bytes allocated during this frame (/gc/heap/allocs:bytes).
	AllocBytesDelta uint64
	// Hitched reports whether a GC pause occurred during this frame.
	Hitched bool
}

GCFrameSample records GC metrics sampled for one frame by a GCMonitor.

type GCMonitor

type GCMonitor struct {
	// contains filtered or unexported fields
}

GCMonitor samples Go runtime/metrics GC counters, heap allocations and pause histograms once per frame with zero steady-state allocations, flagging frames hitched by garbage collection.

func NewGCMonitor

func NewGCMonitor(historyLen int) *GCMonitor

NewGCMonitor returns a GCMonitor retaining up to historyLen recent frame samples (defaulting to FrameHistory when <= 0).

func (*GCMonitor) AllocBytesPerFrame

func (m *GCMonitor) AllocBytesPerFrame() float64

AllocBytesPerFrame returns the average number of heap bytes allocated per frame across the retained history window, or 0 when empty.

func (*GCMonitor) AllocsPerFrame

func (m *GCMonitor) AllocsPerFrame() float64

AllocsPerFrame returns the average number of heap objects allocated per frame across the retained history window, or 0 when empty.

func (*GCMonitor) At

func (m *GCMonitor) At(i int) GCFrameSample

At returns sample i in chronological order (0 is oldest, Len()-1 is newest).

func (*GCMonitor) HeapObjectsBytes

func (m *GCMonitor) HeapObjectsBytes() uint64

HeapObjectsBytes returns the most recently sampled /memory/classes/heap/objects:bytes value.

func (*GCMonitor) LastPause

func (m *GCMonitor) LastPause() time.Duration

LastPause returns the most recent non-zero GC pause observed by this monitor.

func (*GCMonitor) Latest

func (m *GCMonitor) Latest() GCFrameSample

Latest returns the most recently sampled GCFrameSample, or the zero value when empty.

func (*GCMonitor) Len

func (m *GCMonitor) Len() int

Len returns how many frame samples are currently retained in history.

func (*GCMonitor) MaxPause

func (m *GCMonitor) MaxPause() time.Duration

MaxPause returns the longest per-frame GC pause observed by this monitor.

func (*GCMonitor) RecentHitches

func (m *GCMonitor) RecentHitches() int

RecentHitches returns how many frames in the retained history ring buffer experienced a GC pause.

func (*GCMonitor) Reset

func (m *GCMonitor) Reset()

Reset clears retained GC frame history, hitch counts and peak pause timings, and re-baselines runtime/metrics counters to the current point in time.

func (*GCMonitor) SampleFrame

func (m *GCMonitor) SampleFrame(frameDur time.Duration) GCFrameSample

SampleFrame reads runtime/metrics for the completed frame and returns its GCFrameSample without heap allocations in steady state.

func (*GCMonitor) TotalCycles

func (m *GCMonitor) TotalCycles() uint64

TotalCycles returns the cumulative GC cycle count reported by /gc/cycles/total:gc-cycles.

type GroupMemory

type GroupMemory struct {
	// Group is the asset group name, such as "level1" or "ui".
	Group string
	// TotalBytes is the total tracked bytes across all assets in the group.
	TotalBytes int64
	// Budget is the configured byte budget for the group, or 0 when unbounded.
	Budget int64
	// OverBudget reports whether Budget > 0 and TotalBytes > Budget.
	OverBudget bool
	// Count is the number of tracked assets currently in the group.
	Count int
	// ByKind maps each AssetKind present in the group to its tracked byte total.
	ByKind map[AssetKind]int64
}

GroupMemory reports the tracked memory for one asset group.

type LayerSnapshot

type LayerSnapshot struct {
	// Name identifies the layer, such as "terrain", "actors" or "hud".
	Name string
	// Space is the coordinate space the layer draws in, such as "world" or "screen".
	Space string
	// Objects is the number of live objects on the layer.
	Objects int
}

LayerSnapshot describes one layer within a SceneSnapshot.

type MemoryTracker

type MemoryTracker struct {

	// OnBudget is called once when a Track operation crosses a group or total budget.
	OnBudget func(GroupMemory)
	// contains filtered or unexported fields
}

MemoryTracker accounts for decoded asset memory grouped by owner (such as level or scene) and validates per-group and total byte budgets.

Example

A MemoryTracker adds up decoded asset sizes per group and checks them against budgets.

package main

import (
	"fmt"

	"github.com/nsgo-dev/game/pkg/tooling/gamedebug"
)

func main() {
	m := gamedebug.NewMemoryTracker()
	m.SetBudget("level-1", 8<<20)
	m.Track("level-1", "tiles.png", gamedebug.AssetImage, gamedebug.EstimateImageBytes(1024, 1024))
	m.Track("level-1", "boss.png", gamedebug.AssetImage, gamedebug.EstimateImageBytes(1024, 1024))
	fmt.Println(m.GroupBytes("level-1"), m.CheckBudget("level-1") == nil)

	m.Track("level-1", "music.pcm", gamedebug.AssetAudio, gamedebug.EstimatePCMBytes(48000*60, 2, 2))
	fmt.Println(m.CheckBudget("level-1") == nil)
	m.ReleaseGroup("level-1")
	fmt.Println(m.TotalBytes())
}
Output:
8388608 true
false
0

func NewMemoryTracker

func NewMemoryTracker() *MemoryTracker

NewMemoryTracker returns an empty asset MemoryTracker.

func (*MemoryTracker) CheckAllBudgets

func (m *MemoryTracker) CheckAllBudgets() error

CheckAllBudgets validates the total budget and every configured per-group budget, returning a joined error if any are exceeded.

func (*MemoryTracker) CheckBudget

func (m *MemoryTracker) CheckBudget(group string) error

CheckBudget returns an error if group has a configured budget and its tracked bytes exceed that budget.

func (*MemoryTracker) GroupBytes

func (m *MemoryTracker) GroupBytes(group string) int64

GroupBytes returns the total tracked bytes currently held by group.

func (*MemoryTracker) Groups

func (m *MemoryTracker) Groups() []GroupMemory

Groups returns a sorted snapshot of all groups with tracked assets and their per-kind byte breakdowns.

func (*MemoryTracker) ReleaseGroup

func (m *MemoryTracker) ReleaseGroup(group string)

ReleaseGroup drops all tracked assets and bytes belonging to group. Any configured budget for group is retained.

func (*MemoryTracker) SetBudget

func (m *MemoryTracker) SetBudget(group string, maxBytes int64)

SetBudget sets the maximum allowed bytes for group. Passing maxBytes <= 0 removes the budget for group.

func (*MemoryTracker) SetTotalBudget

func (m *MemoryTracker) SetTotalBudget(maxBytes int64)

SetTotalBudget sets the maximum allowed total bytes across all groups. Passing maxBytes <= 0 removes the total budget.

func (*MemoryTracker) TotalBudget

func (m *MemoryTracker) TotalBudget() int64

TotalBudget returns the configured total byte budget, or 0 when none is set.

func (*MemoryTracker) TotalBytes

func (m *MemoryTracker) TotalBytes() int64

TotalBytes returns the total tracked bytes across all asset groups.

func (*MemoryTracker) Track

func (m *MemoryTracker) Track(group, name string, kind AssetKind, bytes int64)

Track records or updates an asset named name in group with its AssetKind and size in bytes. Negative byte counts are clamped to 0.

func (*MemoryTracker) TrackAsset

func (m *MemoryTracker) TrackAsset(group, name, kind string, bytes int64)

TrackAsset records or updates an asset named name in group under kind ("image", "atlas", "audio", or "other") with size in bytes. It implements assets.MemoryTracker so a MemoryTracker can be passed directly to assets.WithMemoryTracker without pkg/assets importing gamedebug.

func (*MemoryTracker) TrackAtlasPage

func (m *MemoryTracker) TrackAtlasPage(group, name string, bytes int64)

TrackAtlasPage records a runtime atlas page in group under AssetAtlas. It implements sprite.MemoryReporter so a MemoryTracker can be passed directly to sprite.DynamicAtlasOptions.Memory.

func (*MemoryTracker) Untrack

func (m *MemoryTracker) Untrack(group, name string)

Untrack removes a previously tracked asset from group.

func (*MemoryTracker) UntrackAtlasPage

func (m *MemoryTracker) UntrackAtlasPage(group, name string)

UntrackAtlasPage removes a previously tracked runtime atlas page from group. It implements sprite.MemoryReporter.

type MonitorSeries

type MonitorSeries struct {
	Name    string
	Unit    string
	Latest  float64
	Samples []float64
}

MonitorSeries is the sampled history of one named runtime monitor.

type Monitors

type Monitors struct {
	// contains filtered or unexported fields
}

Monitors records named numeric samples for the profiler overlay. Sampling reuses its ring buffers and does not allocate after monitors are registered.

func NewMonitors

func NewMonitors(history int) *Monitors

NewMonitors creates a monitor registry retaining history samples per series. A non-positive history uses the profiler frame history.

func (*Monitors) Add

func (m *Monitors) Add(name, unit string, sample func() float64)

Add registers or replaces a named monitor. Empty names and nil callbacks are ignored. Registering an existing name updates its unit and callback while preserving its sampled history.

func (*Monitors) Get

func (m *Monitors) Get(name string) (MonitorSeries, bool)

Get returns a chronological snapshot of the named monitor, or false if not registered.

func (*Monitors) Len

func (m *Monitors) Len() int

Len returns the number of registered monitors.

func (*Monitors) Reset

func (m *Monitors) Reset()

Reset clears all sampled values while retaining registered monitors.

func (*Monitors) Sample

func (m *Monitors) Sample()

Sample records one value from every registered monitor without heap allocations.

func (*Monitors) Series

func (m *Monitors) Series() []MonitorSeries

Series returns monitor snapshots in registration order. Samples are returned chronologically, oldest first.

type MovieManifest

type MovieManifest struct {
	Version         int       `yaml:"version"`
	FPS             int       `yaml:"fps"`
	Rate            int       `yaml:"rate"`
	Frames          int       `yaml:"frames"`
	Steps           int       `yaml:"steps"`
	Size            MovieSize `yaml:"size"`
	Seed            uint64    `yaml:"seed"`
	Replay          string    `yaml:"replay,omitempty"`
	Audio           string    `yaml:"audio"`
	AudioSampleRate int       `yaml:"audioSampleRate,omitempty"`
	AudioChannels   int       `yaml:"audioChannels,omitempty"`
}

MovieManifest is the deterministic YAML manifest written to movie.yaml beside the captured frame-000001.png sequence so a run can be inspected and reproduced.

func LoadMovieManifest

func LoadMovieManifest(dir string) (MovieManifest, error)

LoadMovieManifest reads and parses movie.yaml from dir through os.Root.

func ParseMovieManifest

func ParseMovieManifest(data []byte) (MovieManifest, error)

ParseMovieManifest decodes and validates a movie.yaml document, refusing unknown fields, unsupported versions, inconsistent counts, and trailing YAML documents.

type MovieOptions

type MovieOptions struct {
	// Dir is the output directory where frame-000001.png, movie.yaml, and
	// optional audio.wav are written through os.Root.
	Dir string
	// FPS is the output frame rate in frames per second. Loop.StepRate() must
	// be divisible by FPS; each output frame runs Loop.StepRate()/FPS fixed
	// updates.
	FPS int
	// Frames stops recording automatically after this many frames, or 0 to
	// record until stop() is called (or cx is disposed).
	Frames int
	// Capture optionally returns the rendered frame for each output frame.
	// When nil, RecordMovie captures Target (or the scope's owning surface when
	// Target is nil) via cx.Capture.
	Capture func(ctx context.Context) (*image.RGBA, error)
	// BeforeCapture optionally runs right after Loop.StepNow on the simulation
	// goroutine (the engine goroutine when cx is non-nil) and before Capture
	// runs, allowing callers to snapshot engine-owned state for off-thread
	// rasterization.
	BeforeCapture func() error
	// Target optionally selects the NSGo surface/view captured by cx.Capture
	// when Capture is nil.
	Target *core.Ref
	// Seed records the deterministic RNG seed in movie.yaml.
	Seed uint64
	// Replay records the slash-separated replay file path in movie.yaml.
	Replay string
	// Audio optionally pulls interleaved float32 samples in [-1, 1] for each
	// output frame to write audio.wav beside the image sequence (for example
	// driven by sound.SoftwareMixer). When nil, recording writes video only
	// and movie.yaml records audio: video-only.
	Audio func(dst []float32) error
	// AudioSampleRate sets the sample rate in Hz when Audio is set (default 48000).
	AudioSampleRate int
	// AudioChannels sets the channel count when Audio is set (default 2).
	AudioChannels int
	// OnFrame optionally runs after each frame is written to disk.
	OnFrame func(frame int)
	// OnDone optionally runs once when recording finishes with the final
	// manifest and any error.
	OnDone func(MovieManifest, error)
}

MovieOptions configures fixed-rate deterministic movie capture.

func DevMovieOptions

func DevMovieOptions() (MovieOptions, bool, error)

DevMovieOptions reads MovieOptions from the environment variables set by `game dev -movie` (MovieDirEnv, MovieFPSEnv, MovieFramesEnv, MovieReplayEnv). It returns (MovieOptions{}, false, nil) when MovieDirEnv is unset.

type MovieSession

type MovieSession struct {
	// contains filtered or unexported fields
}

MovieSession controls an active fixed-rate movie recording started by StartMovie.

func StartMovie

func StartMovie(cx *core.Scope, l *game.Loop, opts MovieOptions) (*MovieSession, error)

StartMovie starts a fixed-rate deterministic movie recording session and returns a MovieSession for inspecting progress, waiting for completion, or stopping early.

func (*MovieSession) Done

func (s *MovieSession) Done() <-chan struct{}

Done returns a channel that closes once the session finishes writing all frames, optional audio.wav, and movie.yaml.

func (*MovieSession) Status

func (s *MovieSession) Status() MovieStatus

Status returns a snapshot of the session's live progress.

func (*MovieSession) Stop

func (s *MovieSession) Stop() (MovieManifest, error)

Stop stops the recording cleanly, writes movie.yaml (and audio.wav when audio was captured), restores the loop's prior Paused state, and returns the final MovieManifest and any error. It is safe to call from the engine goroutine or any other goroutine, and safe to call more than once.

func (*MovieSession) Wait

func (s *MovieSession) Wait() (MovieManifest, error)

Wait blocks until the recording finishes (after reaching MovieOptions.Frames, being stopped, or failing) and returns the final MovieManifest and error.

type MovieSize

type MovieSize struct {
	Width  int `yaml:"width"`
	Height int `yaml:"height"`
}

MovieSize records the pixel dimensions of captured movie frames in movie.yaml.

type MovieStatus

type MovieStatus struct {
	Active bool
	Frames int
	Steps  int
	Dir    string
	FPS    int
	Rate   int
	Audio  string
}

MovieStatus describes the live progress of an active or completed MovieSession.

type NetChannelStats

type NetChannelStats struct {
	// Channel is the transport delivery channel (ChannelReliableOrdered or ChannelUnreliable).
	Channel netplay.Channel
	// BytesPerSec is the combined send and receive byte rate on this channel.
	BytesPerSec float64
	// PacketsPerSec is the combined send and receive packet rate on this channel.
	PacketsPerSec float64
	// SendBytesPerSec is the outbound byte rate on this channel.
	SendBytesPerSec float64
	// RecvBytesPerSec is the inbound byte rate on this channel.
	RecvBytesPerSec float64
	// SendPacketsPerSec is the outbound packet rate on this channel.
	SendPacketsPerSec float64
	// RecvPacketsPerSec is the inbound packet rate on this channel.
	RecvPacketsPerSec float64
}

NetChannelStats reports live throughput rates for one netplay.Channel.

type NetMessageEvent

type NetMessageEvent struct {
	// Dir is netplay.CaptureSend ("send") or netplay.CaptureRecv ("recv").
	Dir netplay.CaptureDirection
	// Peer is the remote peer ID.
	Peer netplay.PeerID
	// Channel is the transport delivery channel.
	Channel netplay.Channel
	// Type is the decoded wire message type (such as "replication.delta", "rollback.single_input", "relay.members", or "raw").
	Type string
	// Bytes is the payload size in bytes.
	Bytes int
}

NetMessageEvent records one recently sent or received packet's decoded wire message type.

type NetMonitor

type NetMonitor struct {
	// contains filtered or unexported fields
}

NetMonitor tracks per-channel and per-peer throughput rates, Transport InboxStats, and recent decoded wire message types using reused buffers so per-frame updates perform zero heap allocations in steady state.

func NewNetMonitor

func NewNetMonitor(recentLimit int) *NetMonitor

NewNetMonitor creates a NetMonitor retaining up to recentLimit recent message types (defaulting to 12 when <= 0).

func (*NetMonitor) ObserveRecv

func (m *NetMonitor) ObserveRecv(pkt netplay.Packet)

ObserveRecv records one inbound packet and decodes its wire message type into reused buffers without steady-state allocations.

func (*NetMonitor) ObserveSend

func (m *NetMonitor) ObserveSend(to netplay.PeerID, ch netplay.Channel, payload []byte)

ObserveSend records one outbound packet and decodes its wire message type into reused buffers without steady-state allocations.

func (*NetMonitor) Reset

func (m *NetMonitor) Reset()

Reset clears all accumulated traffic counters, peer trackers, and recent message history while keeping allocated slice capacities.

func (*NetMonitor) SampleFrame

func (m *NetMonitor) SampleFrame(dt time.Duration)

SampleFrame commits the current frame's packet/byte counts into the sliding rate window, polls InboxStats from any wrapped InboxReporter, and refreshes the cached NetSnapshot without steady-state heap allocations.

func (*NetMonitor) Snapshot

func (m *NetMonitor) Snapshot() NetSnapshot

Snapshot returns the most recent NetSnapshot built by SampleFrame, backed by m's reused buffers so calling it in Options.Net allocates zero bytes.

func (*NetMonitor) Wrap

func (m *NetMonitor) Wrap(inner netplay.Transport) netplay.Transport

Wrap wraps inner so every successful Send and every Recv packet is observed by m with zero steady-state heap allocations. If inner implements netplay.InboxReporter or netplay.LinkReporter, SampleFrame polls their stats automatically and the wrapper forwards both interfaces.

type NetPeerStats

type NetPeerStats struct {
	// Peer identifies the remote peer (or netplay.PeerBroadcast for broadcast sends).
	Peer netplay.PeerID
	// BytesPerSec is the combined send and receive byte rate with this peer.
	BytesPerSec float64
	// PacketsPerSec is the combined send and receive packet rate with this peer.
	PacketsPerSec float64
	// SendBytesPerSec is the outbound byte rate to this peer.
	SendBytesPerSec float64
	// RecvBytesPerSec is the inbound byte rate from this peer.
	RecvBytesPerSec float64
	// SendPacketsPerSec is the outbound packet rate to this peer.
	SendPacketsPerSec float64
	// RecvPacketsPerSec is the inbound packet rate from this peer.
	RecvPacketsPerSec float64
	// Link holds the transport's per-peer RTT, jitter, loss, and cumulative counters when HasLink is true.
	Link netplay.LinkStats
	// HasLink reports whether the wrapped transport reported LinkStats for this peer.
	HasLink bool
}

NetPeerStats reports live throughput rates for one remote peer.

type NetSnapshot

type NetSnapshot struct {
	// Inbox holds the transport's InboxStats counters.
	Inbox netplay.InboxStats
	// Channels holds per-channel throughput rates.
	Channels []NetChannelStats
	// Peers holds per-peer throughput rates.
	Peers []NetPeerStats
	// Recent holds the most recent N decoded message events, oldest to newest.
	Recent []NetMessageEvent
}

NetSnapshot describes live network traffic rates, inbox counters, and recent message types for the debug overlay panel.

type Options

type Options struct {
	// ToggleKey is the key binding that shows and hides the overlay; "F3" when empty.
	ToggleKey string
	// PauseKey toggles the wrapped loop between paused and running; "F8" and "pause" when empty. F8 is named on every target; "pause" is the Pause/Break key's name in a browser.
	PauseKey string
	// StepKey advances the wrapped loop by one fixed update while it is paused; "F10" when empty.
	StepKey string
	// SlowerKey halves the wrapped loop's time scale, down to 1/8; "-" when empty.
	SlowerKey string
	// FasterKey doubles the wrapped loop's time scale, up to 4; "=" and "shift+=" when empty. "=" is named on every target; "shift+=" is Shift+Equal on desktop platforms, which a browser reports as "+" with Shift held.
	FasterKey string
	// Visible sets whether the overlay starts shown.
	Visible bool
	// TargetFPS is the reference frame rate drawn on the frame-time graph; 60 when 0 or less.
	TargetFPS float64
	// LineWidth is the base stroke width, in screen points, for collision and bounds wireframes; 1 when 0 or less.
	LineWidth float32
	// Scenes, when set, supplies the active scenes and layers shown by the scene inspector. If it reads NSGo signals, the inspector updates as those signals change; otherwise it refreshes on recorded frames and RefreshScenes.
	Scenes func() []SceneSnapshot
	// Now is the clock WrapLoop uses to measure Update and Draw durations; time.Now when nil.
	Now func() time.Time
	// Console, when set, renders an interactive dev console alongside the overlay.
	Console *Console
	// Profiler, when set, displays top named timing scopes inside the overlay.
	Profiler *Profiler
	// Monitors, when set, samples named runtime counters once per recorded frame.
	Monitors *Monitors
	// Memory, when set, displays asset memory usage and budget status inside the overlay.
	Memory *MemoryTracker
	// GC, when set, samples GC pauses each frame and highlights GC-hitched frames in the overlay.
	GC *GCMonitor
	// DrawStats, when set, supplies live per-frame draw statistics displayed in the overlay and exposed to MCP performance readouts.
	DrawStats func() DrawStats
	// DrawCounter, when set, supplies live per-frame draw submission counts and batch-break reasons from sprite batches, tilemaps, particle emitters, and scenes directly to the overlay and MCP performance readouts.
	DrawCounter *DrawCounter
	// AI, when set, supplies the chosen agent's behavior tree or state machine snapshot shown in the AI inspector panel.
	// If it reads NSGo signals, the panel updates reactively; otherwise it refreshes on recorded frames and RefreshAI.
	AI func() AISnapshot
	// Net, when set, supplies live network traffic rates, InboxStats counters, and recent decoded message types shown in the network inspector panel.
	// Callers can build NetSnapshot without per-frame allocations using NetMonitor.
	Net func() NetSnapshot
	// Sound, when set, displays live active voice counts, concurrency groups, and bus ducking inside the overlay and exposes them to MCP sound readouts.
	Sound *sound.Mixer
	// Categories registers initial gameplay debugger categories shown for the picked entity.
	Categories []Category
	// PickedEntity, when set, supplies the stable ID of the currently picked entity shown by the gameplay debugger.
	// When nil, SetPickedEntity sets the picked entity.
	PickedEntity func() string
	// VLog, when set, attaches a visual log to the overlay for picked-entity inspection and shape drawing.
	VLog *VLog
}

Options configures an Overlay. Every field is optional and takes a sensible default when zero.

type Overlay

type Overlay struct {
	// contains filtered or unexported fields
}

Overlay coordinates the development debug HUD: a key-toggled panel with a frame-time graph and scene inspector, plus world-space collision and sprite-bounds wireframes.

Example

An Overlay's FrameStats keeps recent frame timings for its graph; RecordFrame adds one, as WrapLoop does for each frame of a game.Loop.

package main

import (
	"fmt"
	"time"

	"github.com/nsgo-dev/game/pkg/tooling/gamedebug"
)

func main() {
	o := gamedebug.New(gamedebug.Options{ToggleKey: "F3"})
	for _, ms := range []time.Duration{16, 17, 18} {
		o.RecordFrame(ms*time.Millisecond, 4*time.Millisecond, 8*time.Millisecond)
	}
	stats := o.Stats()
	fmt.Println(stats.Len(), stats.Average().Total, stats.MaxTotal())
	fmt.Println(o.Visible())
	o.Toggle()
	fmt.Println(o.Visible())
}
Output:
3 17ms 18ms
false
true

func New

func New(opts Options) *Overlay

New returns a configured debug overlay.

func (*Overlay) AISnapshot

func (o *Overlay) AISnapshot() AISnapshot

AISnapshot returns the currently displayed AI snapshot from Options.AI if configured, or the most recent SetAI value.

func (*Overlay) Attach

func (o *Overlay) Attach(cx *core.Scope)

Attach wires the overlay's reactive signals and toggle key onto cx. Calling Attach more than once on the same scope is a no-op; View calls Attach automatically.

func (*Overlay) Categories

func (o *Overlay) Categories() []Category

Categories returns a copy of the registered gameplay debugger categories in registration order.

func (*Overlay) CategorySnapshots

func (o *Overlay) CategorySnapshots() []CategorySnapshot

CategorySnapshots evaluates every registered gameplay debugger category for the currently picked entity.

func (*Overlay) ClearAI

func (o *Overlay) ClearAI()

ClearAI clears the pushed AI snapshot and hides the AI inspector panel when Options.AI is nil.

func (*Overlay) ClearNet

func (o *Overlay) ClearNet()

ClearNet clears the pushed network snapshot and hides the network inspector panel when Options.Net is nil.

func (*Overlay) Console

func (o *Overlay) Console() *Console

Console returns the Console attached to the overlay via Options.Console, or nil.

func (*Overlay) DrawBatchBounds

func (o *Overlay) DrawBatchBounds(d *core.Drawing, batch *sprite.Batch, col core.Color)

DrawBatchBounds draws the untrimmed bounding wireframes of all sprites in batch under d's active transform while the overlay is visible.

func (*Overlay) DrawBox

func (o *Overlay) DrawBox(d *core.Drawing, b core.Bounds, col core.Color)

DrawBox draws a wireframe box under d's active transform while the overlay is visible.

func (*Overlay) DrawBreaks

func (o *Overlay) DrawBreaks() map[string]int

DrawBreaks returns a snapshot of non-zero batch-break reasons recorded on Options.DrawCounter, or nil when no counter is attached or no breaks occurred.

func (*Overlay) DrawCategories

func (o *Overlay) DrawCategories(d *core.Drawing)

DrawCategories invokes Draw(entity, d) on every registered Category that also implements CategoryDrawer while the overlay is visible and a picked entity is active.

func (*Overlay) DrawCircle

func (o *Overlay) DrawCircle(d *core.Drawing, x, y, r float32, col core.Color)

DrawCircle draws a wireframe circle under d's active transform while the overlay is visible.

func (*Overlay) DrawCounter

func (o *Overlay) DrawCounter() *DrawCounter

DrawCounter returns the DrawCounter attached to the overlay via Options.DrawCounter, or nil.

func (*Overlay) DrawFighterBoxes

func (o *Overlay) DrawFighterBoxes(d *core.Drawing, f *framedata.Fighter, hurt, hit core.Color)

DrawFighterBoxes draws f's active hurtboxes and hitboxes as wireframes under d's active transform while the overlay is visible.

func (*Overlay) DrawPath

func (o *Overlay) DrawPath(d *core.Drawing, path []core.Point, col core.Color)

DrawPath draws a waypoint polyline under d's active transform while the overlay is visible.

func (*Overlay) DrawShapes

func (o *Overlay) DrawShapes(d *core.Drawing, fn func(*ShapeOverlay))

DrawShapes calls fn with the overlay's ShapeOverlay only while the overlay is visible. When called inside a core.Canvas.Draw callback, toggling the overlay automatically redraws the canvas.

func (*Overlay) DrawSpriteBounds

func (o *Overlay) DrawSpriteBounds(d *core.Drawing, s *sprite.Sprite, col core.Color)

DrawSpriteBounds draws the untrimmed bounding wireframe of s under d's active transform while the overlay is visible.

func (*Overlay) DrawStats

func (o *Overlay) DrawStats() DrawStats

DrawStats returns the current per-frame draw statistics from Options.DrawStats if configured, otherwise from Options.DrawCounter if configured, or the most recent SetDrawStats value.

func (*Overlay) DrawSteering

func (o *Overlay) DrawSteering(d *core.Drawing, info SteeringDebug)

DrawSteering draws steering agent guides (velocity, desired velocity, target, path) under d's active transform while the overlay is visible.

func (*Overlay) DrawTarget

func (o *Overlay) DrawTarget(d *core.Drawing, target core.Point, col core.Color)

DrawTarget draws a target reticle under d's active transform while the overlay is visible.

func (*Overlay) DrawVLog

func (o *Overlay) DrawVLog(d *core.Drawing, entity string, step uint64, col core.Color)

DrawVLog draws recorded visual-log shapes from Options.VLog for entity at step (or at the latest recorded step when step == 0) into d while the overlay is visible.

func (*Overlay) DrawVector

func (o *Overlay) DrawVector(d *core.Drawing, origin, vec core.Point, col core.Color)

DrawVector draws a directional vector arrow under d's active transform while the overlay is visible.

func (*Overlay) GC

func (o *Overlay) GC() *GCMonitor

GC returns the GCMonitor attached to the overlay via Options.GC, or nil.

func (*Overlay) HandleTouch

func (o *Overlay) HandleTouch(ev core.TouchEvent) bool

HandleTouch feeds a touch event into the overlay's three-finger tap recognizer and toggles the overlay when a clean three-finger tap completes. It returns true when the event triggered a toggle.

func (*Overlay) HasDrawStats

func (o *Overlay) HasDrawStats() bool

HasDrawStats reports whether draw statistics have been configured via Options.DrawStats, Options.DrawCounter, or pushed via SetDrawStats.

func (*Overlay) Memory

func (o *Overlay) Memory() *MemoryTracker

Memory returns the MemoryTracker attached to the overlay via Options.Memory, or nil.

func (*Overlay) Monitors

func (o *Overlay) Monitors() *Monitors

Monitors returns the monitor registry owned by or attached to the overlay.

func (*Overlay) NetSnapshot

func (o *Overlay) NetSnapshot() NetSnapshot

NetSnapshot returns the currently displayed network snapshot from Options.Net if configured, or the most recent SetNet value.

func (*Overlay) NoteFrameCause

func (o *Overlay) NoteFrameCause(cause string)

NoteFrameCause attaches a short explanation (for example "first use of torch_glow compiled its shader") to the next frame recorded by RecordFrame. Calling it with an empty string is a no-op; calling it again before RecordFrame replaces the pending cause.

func (*Overlay) NoteFrameGPU

func (o *Overlay) NoteFrameGPU(d time.Duration)

NoteFrameGPU attaches the measured GPU execution duration (for example from render3d.GPUTimer.TotalDuration) to the next frame recorded by RecordFrame. Negative durations are clamped to zero; calling it again before RecordFrame replaces the pending GPU duration.

func (*Overlay) Paused

func (o *Overlay) Paused() bool

Paused reports whether the wrapped loop is paused, and false when no loop is wrapped.

func (*Overlay) PickedEntity

func (o *Overlay) PickedEntity() string

PickedEntity returns the currently picked entity ID from Options.PickedEntity if set, otherwise the value set via SetPickedEntity.

func (*Overlay) Profiler

func (o *Overlay) Profiler() *Profiler

Profiler returns the Profiler attached to the overlay via Options.Profiler, or nil.

func (*Overlay) RecordFrame

func (o *Overlay) RecordFrame(total, update, draw time.Duration)

RecordFrame records one frame's total, update and draw durations into the ring buffer, samples the attached GCMonitor (if any), and refreshes the visible overlay graph.

func (*Overlay) RefreshAI

func (o *Overlay) RefreshAI()

RefreshAI tells the AI inspector panel to re-read Options.AI immediately.

func (*Overlay) RefreshCategories

func (o *Overlay) RefreshCategories()

RefreshCategories re-reads the picked entity and every registered category immediately.

func (*Overlay) RefreshNet

func (o *Overlay) RefreshNet()

RefreshNet tells the network inspector panel to re-read Options.Net immediately.

func (*Overlay) RefreshScenes

func (o *Overlay) RefreshScenes()

RefreshScenes tells the scene inspector to re-read Options.Scenes immediately.

func (*Overlay) RegisterCategory

func (o *Overlay) RegisterCategory(c Category)

RegisterCategory adds a gameplay debugger Category to the overlay, replacing any existing category with the same Name.

func (*Overlay) ResetStats

func (o *Overlay) ResetStats()

ResetStats clears the overlay's recorded frame timings, pushed draw statistics, and attached DrawCounter, and refreshes the visible overlay.

func (*Overlay) SetAI

func (o *Overlay) SetAI(snap AISnapshot)

SetAI updates the AI inspector panel's pushed snapshot and immediately refreshes the panel. It is used when Options.AI is nil.

func (*Overlay) SetDrawStats

func (o *Overlay) SetDrawStats(s DrawStats)

SetDrawStats updates the overlay's pushed per-frame draw statistics and refreshes the visible overlay. It is used when Options.DrawStats is nil.

func (*Overlay) SetNet

func (o *Overlay) SetNet(snap NetSnapshot)

SetNet updates the network inspector panel's pushed snapshot and immediately refreshes the panel. It is used when Options.Net is nil.

func (*Overlay) SetPaused

func (o *Overlay) SetPaused(paused bool)

SetPaused pauses or resumes the loop wrapped by the overlay.

func (*Overlay) SetPickedEntity

func (o *Overlay) SetPickedEntity(entity string)

SetPickedEntity sets the entity inspected by the overlay's gameplay debugger when Options.PickedEntity is nil, and immediately refreshes category views.

func (*Overlay) SetScenes

func (o *Overlay) SetScenes(scenes []SceneSnapshot)

SetScenes updates the scene inspector's snapshot list and immediately refreshes the inspector view. It is used when Options.Scenes is nil.

func (*Overlay) SetTimeScale

func (o *Overlay) SetTimeScale(scale float64)

SetTimeScale changes the simulation speed of the wrapped loop.

func (*Overlay) SetVisible

func (o *Overlay) SetVisible(v bool)

SetVisible shows or hides the overlay and its world-space wireframes.

func (*Overlay) Sound

func (o *Overlay) Sound() *sound.Mixer

Sound returns the sound.Mixer attached to the overlay via Options.Sound, or nil.

func (*Overlay) Stats

func (o *Overlay) Stats() *FrameStats

Stats returns the overlay's frame-time ring buffer.

func (*Overlay) Step

func (o *Overlay) Step()

Step advances one fixed update while the wrapped loop is paused.

func (*Overlay) Toggle

func (o *Overlay) Toggle()

Toggle flips the overlay's visibility.

func (*Overlay) TogglePause

func (o *Overlay) TogglePause()

TogglePause pauses the wrapped loop when it runs and resumes it when paused. It does nothing when no loop is wrapped.

func (*Overlay) UnregisterCategory

func (o *Overlay) UnregisterCategory(name string) bool

UnregisterCategory removes the gameplay debugger Category with the given name and reports whether one was removed.

func (*Overlay) VLog

func (o *Overlay) VLog() *VLog

VLog returns the visual log attached to the overlay via Options.VLog, or nil.

func (*Overlay) View

func (o *Overlay) View(cx *core.Scope) core.Node

View attaches the overlay to cx and returns a non-intrusive native NSGo overlay node positioned over the game view.

func (*Overlay) Visible

func (o *Overlay) Visible() bool

Visible reports whether the overlay is currently shown. Read inside a reactive NSGo view or drawing, it subscribes to visibility toggles.

func (*Overlay) WrapLoop

func (o *Overlay) WrapLoop(l *game.Loop)

WrapLoop wraps l.Update and l.Draw so every frame automatically times Update and Draw and calls RecordFrame. It also gives the console attached through Options the loop, so its pause, step and timescale commands drive it.

func (*Overlay) WrapView

func (o *Overlay) WrapView(cx *core.Scope, child core.Node) core.Node

WrapView wraps child and the overlay's View inside a full-size container whose OnTouch listens for a three-finger tap to toggle the overlay on touch devices without intercepting single-finger game input. Under -tags release, WrapView returns child directly.

type PanicRecord

type PanicRecord struct {
	// Time is when the panic was recorded (UTC).
	Time time.Time `json:"time"`
	// Value is the formatted panic value (fmt.Sprint(r)).
	Value string `json:"value"`
	// Stack is the goroutine stack trace captured when the panic was recorded.
	Stack string `json:"stack"`
	// Context optionally names where the panic was recovered (such as "loop.Update" or "scene.Draw").
	Context string `json:"context,omitempty"`
}

PanicRecord holds a recovered panic recorded by gamedebug.RecordPanic, gamedebug.Recover or gamedebug.RecoverFunc.

func LastPanic

func LastPanic() (PanicRecord, bool)

LastPanic returns the most recent panic recorded by RecordPanic, Recover or RecoverFunc.

func RecordPanic

func RecordPanic(recovered any, stack []byte, context ...string) PanicRecord

RecordPanic stores a recovered panic value and its stack trace so development tools such as game_log_read can surface the most recent crash or recovered panic. If recovered is nil, RecordPanic does nothing and returns the zero PanicRecord. If stack is empty, runtime/debug.Stack is captured automatically.

func Recover

func Recover(context ...string) (PanicRecord, bool)

Recover calls recover() directly and records any panic via RecordPanic. Call it directly as a deferred function (`defer gamedebug.Recover("loop.Update")`); calling it indirectly from another function will not catch panics per Go's recover rules.

func RecoverFunc

func RecoverFunc(context string, fn func()) (rec PanicRecord, panicked bool)

RecoverFunc executes fn and recovers any panic, recording it via RecordPanic. It reports the captured PanicRecord and whether fn panicked.

type ProfileEntry

type ProfileEntry struct {
	Function      string  `json:"function"`
	File          string  `json:"file,omitempty"`
	Line          int     `json:"line,omitempty"`
	Location      string  `json:"location,omitempty"`
	Flat          int64   `json:"flat"`
	FlatPct       float64 `json:"flat_pct"`
	Cum           int64   `json:"cum"`
	CumPct        float64 `json:"cum_pct"`
	InuseBytes    int64   `json:"inuse_bytes,omitempty"`
	InusePct      float64 `json:"inuse_pct,omitempty"`
	InuseCumBytes int64   `json:"inuse_cum_bytes,omitempty"`
	InuseCumPct   float64 `json:"inuse_cum_pct,omitempty"`
	AllocBytes    int64   `json:"alloc_bytes,omitempty"`
	AllocPct      float64 `json:"alloc_pct,omitempty"`
	AllocCumBytes int64   `json:"alloc_cum_bytes,omitempty"`
	AllocCumPct   float64 `json:"alloc_cum_pct,omitempty"`
}

ProfileEntry summarizes one function's flat and cumulative cost in a pprof CPU or heap profile.

type ProfileKind

type ProfileKind string

ProfileKind identifies the kind of Go pprof profile summarized by ProfileSummary.

const (
	// ProfileKindCPU identifies a sampled CPU profile.
	ProfileKindCPU ProfileKind = "cpu"
	// ProfileKindHeap identifies a heap allocation / in-use memory profile.
	ProfileKindHeap ProfileKind = "heap"
	// ProfileKindUnknown identifies any other valid pprof profile kind.
	ProfileKindUnknown ProfileKind = "unknown"
)

type ProfileSummary

type ProfileSummary struct {
	Kind           ProfileKind    `json:"kind"`
	SampleType     string         `json:"sample_type,omitempty"`
	Unit           string         `json:"unit,omitempty"`
	DurationNanos  int64          `json:"duration_nanos,omitempty"`
	Total          int64          `json:"total"`
	TotalInuse     int64          `json:"total_inuse_bytes,omitempty"`
	TotalAlloc     int64          `json:"total_alloc_bytes,omitempty"`
	TotalFunctions int            `json:"total_functions"`
	Entries        []ProfileEntry `json:"entries"`
}

ProfileSummary is a structured function-level summary produced by Summarize from a Go pprof profile.

func Summarize

func Summarize(data []byte, top int) (ProfileSummary, error)

Summarize parses a Go pprof profile (CPU or heap) and returns a deterministic flat/cumulative breakdown by function. When top > 0, Entries is capped at top functions; top == 0 returns all functions with non-zero cost.

type Profiler

type Profiler struct {
	// contains filtered or unexported fields
}

Profiler records named timing scopes per frame with zero steady-state allocations, produces top-scope summaries for Overlay, emits optional runtime/trace regions, and exports Chrome/Perfetto Trace Event Format JSON.

Example

A Profiler times named scopes per frame and reports the costliest ones; SetNow gives it a clock, here one that advances by hand.

package main

import (
	"fmt"
	"time"

	"github.com/nsgo-dev/game/pkg/tooling/gamedebug"
)

func main() {
	now := time.Unix(0, 0)
	p := gamedebug.NewProfiler(0)
	p.SetNow(func() time.Time { return now })

	p.BeginFrame()
	physics := p.Begin("physics")
	now = now.Add(3 * time.Millisecond)
	p.End(physics)
	for range 2 {
		ai := p.Begin("ai")
		now = now.Add(time.Millisecond)
		p.End(ai)
	}
	p.EndFrame()

	for _, s := range p.TopScopes(2) {
		fmt.Println(s.Name, s.Total, s.Calls)
	}
}
Output:
physics 3ms 1
ai 2ms 2

func NewProfiler

func NewProfiler(maxRecordedFrames int) *Profiler

NewProfiler returns a Profiler capable of recording up to maxRecordedFrames frames (defaulting to 300 when <= 0).

func (*Profiler) Begin

func (p *Profiler) Begin(name string) ScopeToken

Begin opens a named timing scope and returns a ScopeToken to pass to End.

func (*Profiler) BeginFrame

func (p *Profiler) BeginFrame()

BeginFrame resets per-frame scope accumulators for the next frame.

func (*Profiler) End

func (p *Profiler) End(tok ScopeToken)

End closes a timing scope started by Begin or Scope.

func (*Profiler) EndFrame

func (p *Profiler) EndFrame()

EndFrame finalizes the current frame's scope timings and advances active recording if enabled.

func (*Profiler) RecordCounter

func (p *Profiler) RecordCounter(name, unit string, value float64)

RecordCounter appends one counter sample for Chrome/Perfetto trace export while recording is active. Once a counter name has been seen and the recording buffer is sized, RecordCounter allocates nothing.

func (*Profiler) RecordGPUPass

func (p *Profiler) RecordGPUPass(label string, dur time.Duration)

RecordGPUPass appends one GPU render pass timing span for the dedicated "GPU" track in Chrome/Perfetto trace export while recording is active. Once a pass label has been seen and the recording buffer is sized, RecordGPUPass allocates nothing.

func (*Profiler) RecordedFrames

func (p *Profiler) RecordedFrames() int

RecordedFrames returns the number of completed frames captured in the current or most recent recording.

func (*Profiler) Recording

func (p *Profiler) Recording() bool

Recording reports whether trace recording is currently active.

func (*Profiler) Reset

func (p *Profiler) Reset()

Reset clears every scope's accumulated timings and frame history, so TopScopes reports nothing until scopes run again. Scope names keep their IDs, so a ScopeToken opened before Reset and ended after it is still charged to its own scope, and an active or finished trace recording (StartRecording, WriteChromeTrace) is left as it is.

func (*Profiler) Scope

func (p *Profiler) Scope(name string) ScopeToken

Scope opens a named timing scope for use with defer: `defer p.Scope("physics").End()`.

func (*Profiler) SetNow

func (p *Profiler) SetNow(fn func() time.Time)

SetNow overrides the clock used to timestamp scopes, primarily for deterministic tests. Passing nil restores time.Now.

func (*Profiler) SetTraceContext

func (p *Profiler) SetTraceContext(ctx context.Context)

SetTraceContext sets the context passed to runtime/trace.StartRegion when Go execution tracing is active.

func (*Profiler) StartRecording

func (p *Profiler) StartRecording(frames int)

StartRecording begins recording scope and counter events for up to frames frames (capped by maxRecordedFrames).

func (*Profiler) StopRecording

func (p *Profiler) StopRecording()

StopRecording ends an active trace recording early, keeping already recorded frames.

func (*Profiler) TopScopes

func (p *Profiler) TopScopes(limit int) []ScopeSummary

TopScopes returns up to limit scope summaries sorted descending by per-frame Total duration (then Avg, then Name). If limit <= 0, all scopes are returned.

func (*Profiler) WriteChromeTrace

func (p *Profiler) WriteChromeTrace(w io.Writer) error

WriteChromeTrace writes recorded scope and counter events in Chrome/Perfetto Trace Event Format JSON to w. Each distinct scope name is assigned its own tid track and thread_name metadata event so Perfetto displays one track per scope, and recorded monitor/counter samples are emitted as counter ("C") events.

type SceneSnapshot

type SceneSnapshot struct {
	// Name identifies the scene, such as "title" or "world".
	Name string
	// Layers are the scene's layers in draw order.
	Layers []LayerSnapshot
}

SceneSnapshot describes one active scene for the scene inspector.

type ScopeSummary

type ScopeSummary struct {
	// Name is the scope identifier passed to Begin or Scope.
	Name string
	// Total is the total duration spent in this scope during the most recent frame.
	Total time.Duration
	// Avg is the rolling average per-frame duration across recent frames.
	Avg time.Duration
	// Max is the longest per-frame duration observed across recent frames.
	Max time.Duration
	// Calls is the number of times this scope ran during the most recent frame.
	Calls int
}

ScopeSummary summarizes a named timing scope's cost for overlay display.

type ScopeToken

type ScopeToken struct {
	// contains filtered or unexported fields
}

ScopeToken is returned by Profiler.Begin or Profiler.Scope and passed to End to close a timing scope without heap allocations.

func (ScopeToken) End

func (t ScopeToken) End()

End closes the timing scope associated with t. It is safe to call on a zero ScopeToken.

type ShapeOverlay

type ShapeOverlay struct {
	// LineWidth is the desired stroke width in screen points; 1 when 0 or less.
	LineWidth float32
}

ShapeOverlay draws collision shapes and sprite bounds as wireframes into a core.Drawing under whatever camera or viewport transform is already active on it.

Stroke widths are automatically divided by the drawing's active scale so wireframes keep a steady thickness at any camera zoom.

func (*ShapeOverlay) DrawBatchBounds

func (s *ShapeOverlay) DrawBatchBounds(d *core.Drawing, batch *sprite.Batch, col core.Color)

DrawBatchBounds strokes the untrimmed bounding box of every visible sprite in batch in col under d's active transform.

func (*ShapeOverlay) DrawBox

func (s *ShapeOverlay) DrawBox(d *core.Drawing, b core.Bounds, col core.Color)

DrawBox strokes the axis-aligned rectangle b in col under d's active transform, leaving d's state unchanged.

func (*ShapeOverlay) DrawCircle

func (s *ShapeOverlay) DrawCircle(d *core.Drawing, x, y, r float32, col core.Color)

DrawCircle strokes a circle centered at (x, y) with radius r in col under d's active transform, leaving d's state unchanged.

func (*ShapeOverlay) DrawFighterBoxes

func (s *ShapeOverlay) DrawFighterBoxes(d *core.Drawing, f *framedata.Fighter, hurt, hit core.Color)

DrawFighterBoxes strokes the boxes f's current move has active on its current frame under d's active transform: hurtboxes in hurt, then hitboxes in hit on top, mirrored as the fighter faces.

func (*ShapeOverlay) DrawPath

func (s *ShapeOverlay) DrawPath(d *core.Drawing, path []core.Point, col core.Color)

DrawPath strokes a waypoint polyline and small waypoint markers in col under d's active transform.

func (*ShapeOverlay) DrawSpriteBounds

func (s *ShapeOverlay) DrawSpriteBounds(d *core.Drawing, sp *sprite.Sprite, col core.Color)

DrawSpriteBounds strokes the untrimmed bounding box of sp in col, respecting its origin, scale, flip and rotation, under d's active transform.

func (*ShapeOverlay) DrawSteering

func (s *ShapeOverlay) DrawSteering(d *core.Drawing, info SteeringDebug)

DrawSteering draws world-space debug guides for a 2D steering agent under d's active transform: its waypoint path, target reticle and sightline, body radius, desired velocity arrow, and current velocity arrow.

func (*ShapeOverlay) DrawTarget

func (s *ShapeOverlay) DrawTarget(d *core.Drawing, target core.Point, col core.Color)

DrawTarget strokes a crosshair reticle at target in col under d's active transform.

func (*ShapeOverlay) DrawVLogShapes

func (s *ShapeOverlay) DrawVLogShapes(d *core.Drawing, shapes []VLogShape, col core.Color)

DrawVLogShapes draws recorded VLogShape wireframes into d under its active transform, using col when a shape does not specify its own Color.

func (*ShapeOverlay) DrawVector

func (s *ShapeOverlay) DrawVector(d *core.Drawing, origin, vec core.Point, col core.Color)

DrawVector strokes a directional arrow from origin to origin+vec in col under d's active transform, keeping line width and arrowhead size steady in screen points across camera zooms.

type Startup

type Startup = startuptime.Snapshot

Startup contains the first update, first draw, and first playable milestones for the process.

func StartupTimings

func StartupTimings() Startup

StartupTimings returns timings from Go package initialization in this process. In a release build every mark is unset.

type StartupMark

type StartupMark = startuptime.Mark

StartupMark is the elapsed time to one startup milestone. Recorded is false until the milestone occurs.

type SteeringColors

type SteeringColors struct {
	// Agent colors the agent's collision-radius wireframe (default: 0xE2E8F0).
	Agent core.Color
	// Velocity colors the current velocity vector arrow (default: 0x22C55E).
	Velocity core.Color
	// Desired colors the desired velocity vector arrow (default: 0x38BDF8).
	Desired core.Color
	// Target colors the target reticle and sightline (default: 0xF59E0B).
	Target core.Color
	// Path colors the waypoint polyline and waypoint markers (default: 0xA78BFA).
	Path core.Color
}

SteeringColors customizes the colors used by DrawSteering. Zero fields take high-contrast defaults.

type SteeringDebug

type SteeringDebug struct {
	// Agent is the steering agent whose position, radius, and current velocity are drawn.
	Agent ai.Agent
	// DesiredVelocity is the agent's desired velocity vector (drawn when non-zero).
	DesiredVelocity core.Point
	// Target is the agent's current target position (drawn when HasTarget is true).
	Target core.Point
	// HasTarget reports whether Target should be drawn, allowing (0, 0) as a valid target.
	HasTarget bool
	// Path is an optional sequence of world-space waypoints being followed.
	Path []core.Point
	// WaypointIndex highlights Path[WaypointIndex] as the active waypoint when in [0, len(Path)); set negative to omit active highlighting.
	WaypointIndex int
	// VelocityScale scales Velocity and DesiredVelocity into world drawing units (1 when 0 or less).
	VelocityScale float32
	// Colors overrides default colors for any non-zero color field.
	Colors SteeringColors
}

SteeringDebug holds the debug visualization inputs for one 2D steering agent.

type TunableChange

type TunableChange struct {
	// Old is the tunable's value before the change.
	Old any
	// Tunable describes the tunable after the change; its Value is the value stored.
	Tunable TunableInfo
	// Clamped reports whether the requested value lay outside the tunable's range and was stored as the nearest bound.
	Clamped bool
}

TunableChange is the result of Console.SetTunable.

type TunableInfo

type TunableInfo struct {
	// Name is the tunable's registered name.
	Name string
	// Type is "float", "int", "bool" or "string".
	Type string
	// Value is the tunable's current value (float64, int, bool or string).
	Value any
	// Default is the value captured when the tunable was registered.
	Default any
	// Min is the inclusive lower bound for numeric tunables ("float" or "int"), or nil for other types.
	Min any
	// Max is the inclusive upper bound for numeric tunables ("float" or "int"), or nil for other types.
	Max any
}

TunableInfo describes one registered tunable variable on a Console.

type VLog

type VLog struct {
	// contains filtered or unexported fields
}

VLog is a bounded visual log of entity messages, Category snapshots and debug shapes, each tagged with the fixed step it was recorded at. Once full, recording a new entry drops the oldest entry, and likewise for shapes. A VLog is safe for concurrent use, and every method on a nil *VLog is a no-op.

func NewVLog

func NewVLog(capacity int) *VLog

NewVLog returns a VLog keeping at most capacity entries and capacity shapes; DefaultVLogCapacity when capacity is 0 or less.

func (*VLog) Arrow

func (l *VLog) Arrow(step uint64, entity string, from, to [3]float32)

Arrow records a directed arrow from from to to for entity at step.

func (*VLog) Box

func (l *VLog) Box(step uint64, entity string, minPt, maxPt [3]float32)

Box records an axis-aligned box from minPt to maxPt for entity at step.

func (*VLog) Categories

func (l *VLog) Categories() []string

Categories returns the sorted distinct non-empty category names currently present in entries or shapes.

func (*VLog) Circle

func (l *VLog) Circle(step uint64, entity string, center [3]float32, radius float32)

Circle records a circle (or 3D sphere) centered at center with radius for entity at step.

func (*VLog) Clear

func (l *VLog) Clear()

Clear removes every recorded entry and shape from the log.

func (*VLog) Entities

func (l *VLog) Entities() []string

Entities returns the sorted distinct non-empty entity names currently present in entries or shapes.

func (*VLog) Entries

func (l *VLog) Entries(entity, category string, from, to uint64) []VLogEntry

Entries returns, in recorded order, the entries whose step is in [from, to] and that match entity and category. An empty entity or category matches any, and a to of 0 means no upper bound.

func (*VLog) FilterEntries

func (l *VLog) FilterEntries(entity, category string, level VLogLevel, from, to uint64) []VLogEntry

FilterEntries returns, in recorded order, the entries whose step is in [from, to] and that match entity, category and level. An empty entity, category or level matches any, and a to of 0 means no upper bound.

func (*VLog) Len

func (l *VLog) Len() (entries, shapes int)

Len reports how many entries and shapes the log holds.

func (*VLog) Line

func (l *VLog) Line(step uint64, entity string, a, b [3]float32)

Line records a line segment from a to b for entity at step.

func (*VLog) LoadJSONL

func (l *VLog) LoadJSONL(r io.Reader) error

LoadJSONL reads a JSON Lines visual log via ReadVLog and replaces the log's retained entries and shapes with its contents (respecting the log's capacity).

func (*VLog) Log

func (l *VLog) Log(step uint64, entity, category string, level VLogLevel, message string)

Log records a message for entity under category at step.

func (*VLog) Logf

func (l *VLog) Logf(step uint64, entity, category string, level VLogLevel, format string, args ...any)

Logf formats and records a message for entity under category at step. Under -tags release, Logf is a no-op and does not format its arguments.

func (*VLog) Path

func (l *VLog) Path(step uint64, entity string, points [][3]float32)

Path records a waypoint polyline for entity at step. The points are copied.

func (*VLog) Shape

func (l *VLog) Shape(step uint64, entity, kind string, points [][3]float32)

Shape records a debug shape of kind for entity at step. The points are copied.

func (*VLog) ShapeWith

func (l *VLog) ShapeWith(s VLogShape)

ShapeWith records a full VLogShape, copying its points slice. Shapes containing non-finite (NaN or Inf) coordinates or radii are ignored.

func (*VLog) Shapes

func (l *VLog) Shapes(entity string, from, to uint64) []VLogShape

Shapes returns, in recorded order, the shapes whose step is in [from, to] and that match entity. An empty entity matches any, and a to of 0 means no upper bound.

func (*VLog) Snapshot

func (l *VLog) Snapshot(step uint64, entity string, c Category)

Snapshot records what c reports for entity at step as an info entry under c's name.

func (*VLog) StepRange

func (l *VLog) StepRange() (minStep, maxStep uint64, ok bool)

StepRange returns the inclusive minimum and maximum fixed step retained in the log, or ok == false when the log is empty.

func (*VLog) String

func (l *VLog) String() string

String summarizes the log's size.

func (*VLog) Text

func (l *VLog) Text(step uint64, entity string, pos [3]float32, text string)

Text records a world-space text label at pos for entity at step.

func (*VLog) WriteJSONL

func (l *VLog) WriteJSONL(w io.Writer) error

WriteJSONL writes the log as JSON Lines: a header line naming VLogFormat and VLogVersion, then every entry and then every shape in recorded order, each tagged with "type": "entry" or "shape".

type VLogEntry

type VLogEntry struct {
	Step     uint64    `json:"step"`
	Entity   string    `json:"entity"`
	Category string    `json:"category"`
	Level    VLogLevel `json:"level"`
	Message  string    `json:"message,omitempty"`
	Fields   []Field   `json:"fields,omitempty"`
}

VLogEntry is one message, or one Category snapshot, recorded for an entity at a fixed step.

type VLogLevel

type VLogLevel string

VLogLevel is the severity of a VLogEntry.

const (
	VLogInfo  VLogLevel = "info"
	VLogWarn  VLogLevel = "warn"
	VLogError VLogLevel = "error"
)

The levels a VLogEntry may carry; ReadVLog refuses any other.

type VLogShape

type VLogShape struct {
	Step     uint64       `json:"step"`
	Entity   string       `json:"entity"`
	Category string       `json:"category,omitempty"`
	Kind     string       `json:"kind"`
	Points   [][3]float32 `json:"points,omitempty"`
	Radius   float32      `json:"radius,omitempty"`
	Text     string       `json:"text,omitempty"`
	Color    uint32       `json:"color,omitempty"`
}

VLogShape is one debug shape, such as a path, circle, arrow, box, line or text label, recorded for an entity at a fixed step. Kind names the shape and Points holds its world-space points.

Directories

Path Synopsis
Package categories is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/.
Package categories is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL