GitHubComeçar

A referência da API é gerada a partir dos comentários de documentação Go no código-fonte e está escrita em inglês.

package devstate

import "github.com/nsgo-dev/game/pkg/tooling/devstate"

Visão geral

Package devstate saves and restores the running game scene, fixed-step loop clock, and serialized state across Go rebuilds during development.

In release builds (-tags release), the package compiles to zero-cost no-op stubs so production binaries link none of the reflection, serialization, or file I/O logic.

Índice

Funções

func ComputeSchemaHash(sample any) string

ComputeSchemaHash reflects the deterministic structural schema of sample (field names, tags, and types recursively) and returns its SHA-256 hex digest.

Top-level pointer indirection is unwrapped so ComputeSchemaHash(T{}) and ComputeSchemaHash(&T{}) yield the exact same hash. Any added, removed, renamed, reordered, or retyped field changes the digest.

Tipos

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

Hook binds a Snapshotter to a core.Scope so state is saved automatically on exit, scope disposal, or an optional periodic interval.

func Attach(cx *core.Scope, store *Store, target Snapshotter, opts HookOptions) *Hook

Attach wires target into cx so that session snapshots are saved automatically when cx exits or is disposed, and periodically when opts.SaveInterval > 0.

func (h *Hook) RestoreInto(state any) (RestoreResult, error)

RestoreInto loads a saved snapshot into state (a non-nil pointer) and, when successfully restored, forwards it to the attached Snapshotter's Restore method.

func (h *Hook) SaveNow() error

SaveNow captures a snapshot from the attached Snapshotter and persists it immediately.

func (h *Hook) Stop()

Stop halts periodic checkpointing and prevents automatic save on scope cleanup.

type HookOptions struct {
	// SceneID returns the identifier of the currently active scene.
	// If nil, "default" is recorded.
	SceneID func() string
	// LoopTick returns the current fixed-step simulation tick count.
	LoopTick func() uint64
	// LoopElapsed returns the total elapsed simulation time.
	LoopElapsed func() time.Duration
	// SaveInterval periodically checkpoints state while running when > 0.
	SaveInterval time.Duration
	// Logf receives diagnostic messages such as schema mismatch notifications.
	// When nil, the store's logger is used.
	Logf func(format string, args ...any)
}

HookOptions configures how Attach captures scene metadata and checkpoints state.

type RestoreResult struct {
	Restored    bool
	SceneID     string
	LoopTick    uint64
	LoopElapsed time.Duration
	SkipReason  string
}

RestoreResult describes the outcome of Store.Restore.

When a saved snapshot cannot be applied because its state struct schema changed across a rebuild, Restored is false, SkipReason explains why, and Restore returns a nil error so the game starts fresh cleanly.

type SessionSnapshot struct {
	SceneID     string        `json:"scene_id"`
	SchemaHash  string        `json:"schema_hash"`
	LoopTick    uint64        `json:"loop_tick"`
	LoopElapsed time.Duration `json:"loop_elapsed"`
	Payload     []byte        `json:"payload"`
	SavedAt     time.Time     `json:"saved_at"`
}

SessionSnapshot is the persisted state of a running development session.

type Snapshotter interface {
	Snapshot() (any, error)
	Restore(state any) error
}

Snapshotter is implemented by scenes or game controllers that participate in automatic dev-session capture and restore via Hook.

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

Store persists and restores SessionSnapshots either on disk or in core.Storage.

func NewStorageStore(st core.Storage, key string) *Store

NewStorageStore creates a core.Storage-backed dev session store under key.

func NewStore(path string) *Store

NewStore creates a file-backed dev session store at path.

func (s *Store) Clear() error

Clear removes any persisted session snapshot.

func (s *Store) LoadSnapshot() (snap SessionSnapshot, ok bool, err error)

LoadSnapshot reads the stored SessionSnapshot without decoding its payload. If no snapshot exists, ok is false and err is nil. A snapshot that does not decode returns a *loaderr.Error that names the snapshot's file (or storage key) and line.

func (s *Store) Restore(state any) (RestoreResult, error)

Restore loads the saved session snapshot into state (which must be a non-nil pointer).

If no snapshot exists, or if the saved schema hash does not match state's current schema, Restore logs a diagnostic notice and returns Restored: false with a clear SkipReason and a nil error so the app starts fresh without crashing.

func (s *Store) Save(sceneID string, loopTick uint64, elapsed time.Duration, state any) error

Save marshals state together with its schema hash and loop clock, writing the snapshot atomically.

func (s *Store) SetLogger(logf func(format string, args ...any))

SetLogger sets the logger used for non-fatal restore notices such as schema mismatches. Passing nil restores the default log.Printf behavior.