inventory

package
v0.4.0-rc.3 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: 21 Imported by: 2 modules, 1 package

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 inventory is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/.

Package inventory holds gameplay items: item definitions with optional per-stack data fields read from versioned YAML, slot-based containers of item stacks, typed equipment slots, atomic multi-container exchanges, versioned crafting recipe books, timed crafting queues (fixed-loop or real-time offline via pkg/idle), and snapshots that round-trip through a game/save Store.

Item definitions

A Catalog is the set of ItemDef values a game knows, parsed from a version 1 or version 2 YAML document with Parse (unknown fields, duplicate IDs and trailing documents are refused) or built in code with NewCatalog. Catalog.Encode writes deterministic 2-space YAML that Parse reads back unchanged. Each definition names its maximum stack size (1 when omitted), the equipment kind it fits, free-form tags, numeric stats, and optional per-stack Data fields (such as durability, quality or custom names) with optional type, bounds and default values. A version 2 catalog also declares the items a release renamed or retired in its renamed and retired sections; RestoreContent applies them so an older save holding a removed ID still loads.

Containers and per-stack data

A Container is a fixed number of slots, each empty or holding one Stack{Item, Count, Data} no larger than that item's maximum stack. Add and AddWithData top up existing stacks of the item with equal Data in slot order before filling empty slots in slot order, and return what did not fit; AddAll and AddAllWithData add everything or nothing. Stacks with different Data never merge. Remove takes items from the last matching slot backwards. MoveTo moves a whole stack into an empty slot, merges it into a stack of the same item and equal Data as far as that stack has room, or swaps it otherwise; SplitTo copies Data when splitting into an empty slot; Transfer quick-moves a stack into another container preserving its Data. SetData and SetDataField update a slot's per-stack data with schema validation. Every operation that returns an error leaves all containers unchanged.

Equipment

Equipment is a set of named slots, each accepting items whose ItemDef.Equip equals the slot's kind (two "ring" slots can share one kind). Equip takes one item (with its per-stack Data) from a container slot and returns the item it replaces (with its Data) to the container; Unequip returns the equipped item and its Data to a container. Both are all-or-nothing.

Atomic exchanges, recipes and crafting queues

Exchange removes inputs (by item ID or by tag, with optional CompareSlots preference) from one or more From containers and places outputs into To containers (defaulting to From) all or nothing. Exchange.Plan dry-runs the transaction and reports exact missing inputs and outputs that do not fit without mutating any container.

Book holds versioned YAML crafting recipes (RecipeFormatVersion = 1, parsed with ParseRecipes and written byte-identically with Book.Encode), supporting item or tag inputs, multiple outputs with optional per-stack data, station tags, craft times and unlock keys. Book.Craftable lists matching recipes and how many times each can be made.

Queue tracks timed crafting orders stepped deterministically on the fixed loop (NewQueue + Step), or driven on the wall clock across app absences by idle.Jobs (NewRealtimeQueue / NewQueueWithJobs + Sync), with atomic input consumption, input refund on Cancel, atomic output delivery on Collect, and versioned snapshots (QueueStateVersion = 1).

Saving

Container.Snapshot, Equipment.Snapshot and Queue.Snapshot return plain JSON-tagged values to store in a save slot alongside the rest of a game's state; Restore validates snapshots against the catalog and recipe book before replacing anything. RestoreContent applies a catalog's declared renames and retirements and returns a RestoreReport, and SavePart / SavePartContent wire into save.Game.

Unless configured with an idle.Jobs wall clock on a real-time Queue, nothing in inventory reads the clock, spawns goroutines or keeps package-level state, so it is deterministic and safe to run on a headless server. A Container, Equipment or Queue is not safe for concurrent use.

Index

Examples

Constants

View Source
const (
	// MinVersion is the oldest item catalog version this package reads: items only, with no content update declarations.
	MinVersion = 1
	// CurrentVersion is the newest item catalog version this package reads and writes. Version 2 adds the renamed and retired sections that keep saves holding item IDs a release removed loadable.
	CurrentVersion = 2
)
View Source
const MaxContainerSize = 1 << 16

MaxContainerSize is the largest number of slots a Container may have.

View Source
const MaxStackLimit = 1 << 30

MaxStackLimit is the largest MaxStack an item definition may declare.

View Source
const QueueStateVersion = 1

QueueStateVersion is the QueueState format version written by Queue.Snapshot and accepted by Queue.Restore and strict JSON/YAML decoding.

View Source
const RecipeFormatVersion = 1

RecipeFormatVersion is the recipe book YAML format version read by ParseRecipes and written by Book.Encode.

View Source
const RecipeSchemaURL = "https://nsgo.games/schemas/recipes.v1.json"

RecipeSchemaURL is the published draft-07 JSON Schema URL for version 1 recipe books.

View Source
const SchemaURLV1 = "https://nsgo.games/schemas/inventory.v1.json"

SchemaURLV1 is where the JSON Schema of version 1 item catalogs (items only) is published. Catalog.Encode names it in a yaml-language-server comment on a version 1 catalog's first line.

View Source
const SchemaURLV2 = "https://nsgo.games/schemas/inventory.v2.json"

SchemaURLV2 is where the JSON Schema of version 2 item catalogs, which add renamed and retired sections, is published. Catalog.Encode names it in a yaml-language-server comment on a version 2 catalog's first line.

Variables

View Source
var (
	// ErrUnknownItem reports an item ID the catalog does not define.
	ErrUnknownItem = errors.New("inventory: unknown item")
	// ErrInvalidCount reports a non-positive count, or a count larger than a stack holds.
	ErrInvalidCount = errors.New("inventory: invalid count")
	// ErrSlotOutOfRange reports a container slot index outside [0, Len).
	ErrSlotOutOfRange = errors.New("inventory: slot out of range")
	// ErrEmptySlot reports an operation that needs an item in a slot that holds none.
	ErrEmptySlot = errors.New("inventory: slot is empty")
	// ErrSlotOccupied reports a destination slot holding a different item, or one without room for the items being moved.
	ErrSlotOccupied = errors.New("inventory: slot is occupied")
	// ErrFull reports that a container has no room for all of the items asked for.
	ErrFull = errors.New("inventory: container is full")
	// ErrNotEnough reports a container holding fewer of an item than asked for.
	ErrNotEnough = errors.New("inventory: not enough items")
	// ErrCatalogMismatch reports an operation across containers or equipment built from different catalogs.
	ErrCatalogMismatch = errors.New("inventory: different catalogs")
)
View Source
var (
	// ErrUnknownEquipSlot reports an equipment slot name the Equipment does not have.
	ErrUnknownEquipSlot = errors.New("inventory: unknown equipment slot")
	// ErrNotEquippable reports an item whose equipment kind does not match the slot's kind.
	ErrNotEquippable = errors.New("inventory: item does not fit equipment slot")
)
View Source
var (
	// ErrUnknownOrder reports a craft order ID not found in a Queue.
	ErrUnknownOrder = errors.New("inventory: unknown craft order")
	// ErrInvalidQueueState reports a malformed, unsupported-version, or inconsistent QueueState.
	ErrInvalidQueueState = errors.New("inventory: invalid craft queue state")
)
View Source
var (
	// ErrUnknownRecipe reports a recipe ID a Book does not define.
	ErrUnknownRecipe = errors.New("inventory: unknown recipe")
	// ErrWrongStation reports a craft attempted at a station that does not satisfy the recipe's Station tag.
	ErrWrongStation = errors.New("inventory: recipe requires a different station")
)
View Source
var ErrInvalidData = errors.New("inventory: invalid stack data")

ErrInvalidData reports per-stack data that names an undeclared field, uses the wrong value type, is non-finite, or falls outside a field's declared bounds.

Functions

func Craft

func Craft(c *Container, r Recipe) error

Craft validates and applies one recipe to c atomically. On any error the container remains unchanged, including when outputs do not fit after inputs are removed.

func RecipeSchema

func RecipeSchema(opts jsonschema.Options) (*jsonschema.Schema, error)

RecipeSchema returns the draft-07 JSON Schema for a version 1 crafting recipe book (RecipeBookDoc). The schema requires version 1 and rejects unknown top-level, recipe, input and output fields.

func Schema

func Schema(opts jsonschema.Options) (*jsonschema.Schema, error)

Schema returns the draft-07 JSON Schema for an item catalog. The schema requires version 1 or 2 and rejects unknown top-level, item, data field, retired and refund fields.

func SchemaComment

func SchemaComment(version int) string

SchemaComment returns the first line Catalog.Encode writes for a catalog of the given version: a YAML comment that points a YAML language server at SchemaURL. Parse ignores it like any other comment.

func SchemaForVersion

func SchemaForVersion(version int, opts jsonschema.Options) (*jsonschema.Schema, error)

SchemaForVersion returns the draft-07 JSON Schema for an item catalog of the given version, the format Catalog.Encode writes and Parse reads. A version 1 schema has no renamed or retired sections, which Parse refuses in a version 1 catalog, and each version is the only value the schema allows.

func SchemaURL

func SchemaURL(version int) string

SchemaURL returns the schema URL of a catalog of the given version, SchemaURLV1 for version 1 and SchemaURLV2 otherwise.

Types

type Book

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

Book is an immutable, validated collection of crafting recipes parsed from versioned YAML with ParseRecipes or built in code with NewBook.

func NewBook

func NewBook(defs ...RecipeDef) (*Book, error)

NewBook validates defs and returns a Book holding copies of them in the given order.

func ParseRecipes

func ParseRecipes(data []byte) (*Book, error)

ParseRecipes decodes a version 1 YAML recipe book and validates it. Unknown fields, duplicate recipe IDs, invalid inputs/outputs, explicit zero counts or durations, and trailing YAML documents are refused.

func (*Book) Craft

func (b *Book) Craft(id string, from, to []*Container) (Plan, error)

Craft applies recipe id once atomically across from and to (defaulting to from when to is empty).

func (*Book) Craftable

func (b *Book) Craftable(containers []*Container, station string) []CraftableRecipe

Craftable lists every recipe in b matching station that can be crafted at least once using containers (for both inputs and outputs), together with how many times each recipe can be made, in book order. Recipes with an Unlock key are included so the caller can inspect Recipe.Unlock; use CraftableUnlocked to filter locked recipes directly.

func (*Book) CraftableUnlocked

func (b *Book) CraftableUnlocked(containers []*Container, station string, unlocked func(key string) bool) []CraftableRecipe

CraftableUnlocked behaves like Craftable, except recipes with a non-empty Unlock key are included only when unlocked != nil and unlocked(recipe.Unlock) returns true.

func (*Book) Encode

func (b *Book) Encode() ([]byte, error)

Encode writes the recipe book as deterministic 2-space YAML (recipes in book order, data keys sorted) that ParseRecipes reads back byte-identically.

func (*Book) Exchange

func (b *Book) Exchange(id string, times int, from, to []*Container) (Exchange, error)

Exchange builds an Exchange that crafts recipe id times times, consuming inputs from from and placing outputs into to (or from when to is empty).

func (*Book) Has

func (b *Book) Has(id string) bool

Has reports whether the book defines id.

func (*Book) Len

func (b *Book) Len() int

Len returns the number of recipes in the book.

func (*Book) MaxCrafts

func (b *Book) MaxCrafts(id string, from, to []*Container) (int, error)

MaxCrafts returns how many times recipe id can be crafted with inputs from from and outputs placed into to (or from when to is empty).

func (*Book) Plan

func (b *Book) Plan(id string, from, to []*Container) (Plan, error)

Plan dry-runs crafting recipe id once across from and to (defaulting to from when to is empty).

func (*Book) Recipe

func (b *Book) Recipe(id string) (RecipeDef, bool)

Recipe returns a copy of the recipe definition with the given ID.

func (*Book) Recipes

func (b *Book) Recipes() []RecipeDef

Recipes returns copies of every recipe definition in book order.

func (*Book) ValidateCatalog

func (b *Book) ValidateCatalog(cat *Catalog) error

ValidateCatalog checks that every item ID referenced by inputs and outputs exists in cat, and that every output's per-stack data conforms to that item's declared ItemDef.Data fields.

func (*Book) ValidateTags

func (b *Book) ValidateTags(reg *tags.Registry) error

ValidateTags checks that every station tag and tag input in b is declared in reg (or is an implied parent of a declared tag), returning a *loaderr.Error with a nearest-name suggestion on the first undeclared tag.

type Catalog

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

Catalog is an immutable, validated set of item definitions and the content update declarations a release made, built with Parse or NewCatalog.

func NewCatalog

func NewCatalog(defs ...ItemDef) (*Catalog, error)

NewCatalog validates defs and returns a version 2 catalog holding copies of them in the given order, with no content update declarations.

func Parse

func Parse(data []byte) (*Catalog, error)

Parse decodes a version 1 or version 2 YAML item catalog and validates it. Unknown fields, duplicate item IDs, invalid definitions, content update declarations that do not resolve to a current item, and trailing YAML documents are refused.

func (*Catalog) Encode

func (c *Catalog) Encode() ([]byte, error)

Encode writes the catalog as deterministic 2-space YAML, SchemaComment for its version on the first line (definitions in catalog order, stats keys sorted, retired entries in catalog order) that Parse reads back unchanged. A version 1 catalog is written as version 1; a version 2 catalog adds its renamed and retired sections.

func (*Catalog) Has

func (c *Catalog) Has(id string) bool

Has reports whether the catalog defines id.

func (*Catalog) Item

func (c *Catalog) Item(id string) (ItemDef, bool)

Item returns a copy of the definition with the given ID.

func (*Catalog) Items

func (c *Catalog) Items() []ItemDef

Items returns copies of every definition in catalog order.

func (*Catalog) Len

func (c *Catalog) Len() int

Len returns the number of definitions in the catalog.

func (*Catalog) Renamed

func (c *Catalog) Renamed() map[string]string

Renamed returns a copy of the catalog's rename map with chains followed, so every old ID maps to the item that defines it now.

func (*Catalog) Retired

func (c *Catalog) Retired() []Retirement

Retired returns copies of the catalog's retirement entries in catalog order.

func (*Catalog) ValidateTags

func (c *Catalog) ValidateTags(reg *tags.Registry) error

ValidateTags checks that every tag on every item in c is declared in reg (or is an implied parent of a declared tag), returning a *loaderr.Error with the item's field path and a nearest-name suggestion on the first undeclared tag.

func (*Catalog) Version

func (c *Catalog) Version() int

Version returns the catalog's format version, from MinVersion (1) to CurrentVersion (2).

type Container

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

Container is a fixed number of slots holding item stacks from one Catalog. The zero Container is not usable; create one with NewContainer.

func NewContainer

func NewContainer(catalog *Catalog, size int) (*Container, error)

NewContainer returns an empty container with size slots, in [1, MaxContainerSize], holding items from catalog.

func (*Container) Add

func (c *Container) Add(item string, count int) (remaining int, err error)

Add puts up to count of item (with any declared default data) into the container and returns how many did not fit. It first tops up existing stacks of item with matching data in slot order, then fills empty slots in slot order. It returns ErrUnknownItem or ErrInvalidCount, adding nothing, when item is not in the catalog or count is not positive.

Example
package main

import (
	"fmt"

	"github.com/nsgo-dev/game/pkg/inventory"
)

func main() {
	cat, _ := inventory.Parse([]byte("version: 1\nitems:\n  - id: arrow\n    maxStack: 99\n"))
	quiver, _ := inventory.NewContainer(cat, 2)
	left, _ := quiver.Add("arrow", 250)
	fmt.Println(quiver.Slot(0).Item, quiver.Slot(0).Count, quiver.Slot(1).Count, left)
}
Output:
arrow 99 99 52

func (*Container) AddAll

func (c *Container) AddAll(item string, count int) error

AddAll puts all count of item into the container the way Add does, or returns ErrFull and adds nothing when they do not all fit.

func (*Container) AddAllWithData

func (c *Container) AddAllWithData(item string, count int, data StackData) error

AddAllWithData puts all count of item carrying data into the container the way AddWithData does, or returns ErrFull and adds nothing when they do not all fit.

func (*Container) AddWithData

func (c *Container) AddWithData(item string, count int, data StackData) (remaining int, err error)

AddWithData puts up to count of item carrying data (validated against ItemDef.Data with defaults applied) into the container and returns how many did not fit. Stacks only merge when their items and data are equal.

func (*Container) Catalog

func (c *Container) Catalog() *Catalog

Catalog returns the catalog the container's items come from.

func (*Container) Clear

func (c *Container) Clear()

Clear empties every slot.

func (*Container) Count

func (c *Container) Count(item string) int

Count returns how many of item the container holds across all slots, regardless of per-stack data.

func (*Container) CountTag

func (c *Container) CountTag(tag string) int

CountTag returns how many items carrying tag (or a child tag under it) the container holds across all slots.

func (*Container) IsEmpty

func (c *Container) IsEmpty() bool

IsEmpty reports whether every slot is empty.

func (*Container) Len

func (c *Container) Len() int

Len returns the number of slots.

func (*Container) Move

func (c *Container) Move(from, to int) error

Move moves the stack in slot from to slot to within the container, as MoveTo does.

func (*Container) MoveTo

func (c *Container) MoveTo(from int, dst *Container, to int) error

MoveTo moves the whole stack in slot from into slot to of dst, which may be c itself:

  • into an empty slot, the stack moves there, keeping its per-stack data;
  • onto a stack of the same item with equal per-stack data, as many as that stack has room for merge into it and the rest stay in from;
  • onto a different item, or onto the same item with different per-stack data, the two stacks swap.

Moving a slot onto itself does nothing. It returns ErrEmptySlot when slot from is empty and ErrCatalogMismatch when dst uses a different catalog.

func (*Container) Remove

func (c *Container) Remove(item string, count int) error

Remove takes count of item out of the container, from the last slot holding it backwards, or returns ErrNotEnough and removes nothing when the container holds fewer.

func (*Container) RemoveAt

func (c *Container) RemoveAt(i, count int) (Stack, error)

RemoveAt takes count items out of slot i and returns them as a Stack. It returns ErrEmptySlot for an empty slot and ErrInvalidCount when count is not in [1, the slot's count].

func (*Container) Restore

func (c *Container) Restore(st ContainerState) error

Restore replaces the container's contents with st after checking every entry: the slot must be in range and listed once, the item defined by the catalog, the count in [1, the item's maximum stack], and any per-stack data valid for the item's declared fields. On error the container is left unchanged. Use RestoreContent to apply the catalog's declared renames and retirements instead.

func (*Container) RestoreContent

func (c *Container) RestoreContent(st ContainerState) (RestoreReport, error)

RestoreContent restores a snapshot through the content updates its catalog declares: old item IDs are renamed or replaced and retired items without a replacement are dropped, as RestoreMigrated does with the maps passed in. It returns the changes it applied so the game can grant the declared refunds or show a notice. Restore stays strict for games without a migration policy.

func (*Container) RestoreMigrated

func (c *Container) RestoreMigrated(st ContainerState, renamed map[string]string, retired map[string]struct{}) (RestoreReport, error)

RestoreMigrated restores a snapshot while applying declared ID changes. A rename maps an old ID to a current ID. A retired ID is dropped. Counts are split into slots the snapshot leaves empty when the replacement's max stack is lower; the slots of the snapshot's other stacks are never used for a split.

func (*Container) Room

func (c *Container) Room(item string) int

Room returns how many more of item (with its default per-stack data) the container can hold: the free space in its stacks of item with matching data plus a full stack per empty slot. It returns 0 for an item the catalog does not define.

func (*Container) RoomWithData

func (c *Container) RoomWithData(item string, data StackData) int

RoomWithData returns how many more of item carrying data (with declared defaults applied) the container can hold. It returns 0 for an unknown item or invalid data.

func (*Container) SavePart

func (c *Container) SavePart() save.Part

SavePart returns a save.Part (implementing save.StagedPart and save.Resetter) that saves and restores c through save.Game. Loading validates every slot before mutating c, and resets c to empty when loading an older save slot that omits this part.

func (*Container) SavePartContent

func (c *Container) SavePartContent(onRestore func(RestoreReport)) save.Part

SavePartContent returns a save.Part like SavePart whose restores apply the catalog's declared renames and retirements, so a save holding an item ID a release removed still loads. onRestore, when non-nil, receives the changes each restore applied, so the game can grant the declared refunds or show a notice after loading. Use SavePart for a strict restore that refuses such a save.

func (*Container) SetData

func (c *Container) SetData(i int, data StackData) error

SetData replaces the per-stack data of slot i after validating data against the item's declared ItemDef.Data fields (applying declared defaults for omitted fields). On any error the slot is left unchanged.

func (*Container) SetDataField

func (c *Container) SetDataField(i int, field string, value DataValue) error

SetDataField updates one declared per-stack data field on slot i, keeping the stack's other fields intact. On any error the slot is left unchanged.

func (*Container) Slot

func (c *Container) Slot(i int) Stack

Slot returns a copy of the stack in slot i, or an empty Stack when i is out of range.

func (*Container) Slots

func (c *Container) Slots() []Stack

Slots returns a copy of every slot in order.

func (*Container) Snapshot

func (c *Container) Snapshot() ContainerState

Snapshot returns the container's non-empty slots in ascending order.

func (*Container) Split

func (c *Container) Split(from, to, count int) error

Split moves count items from slot from to slot to within the container, as SplitTo does.

func (*Container) SplitTo

func (c *Container) SplitTo(from int, dst *Container, to int, count int) error

SplitTo moves count items, in [1, the stack's count], from slot from into slot to of dst, which must be empty or hold the same item with equal per-stack data and room for all count. Splitting into an empty slot copies per-stack data. It returns ErrSlotOccupied, moving nothing, when slot to holds a different item, different data, or lacks the room, and does nothing when from and to are the same slot.

func (*Container) Transfer

func (c *Container) Transfer(from int, dst *Container) (moved int, err error)

Transfer quick-moves the stack in slot from into dst the way AddWithData does (topping up dst's stacks of the item with equal data, then filling its empty slots) and returns how many moved; what does not fit stays in slot from. dst must be a different container from the same catalog.

type ContainerState

type ContainerState struct {
	// Slots lists the non-empty slots in ascending slot order.
	Slots []SlotState `json:"slots"`
}

ContainerState is a container's contents in a form encoding/json writes deterministically, for storing in a save slot.

type CraftOrder

type CraftOrder struct {
	// ID is the deterministic sequential order identifier within its Queue (such as "craft-1").
	ID string `json:"id" yaml:"id"`
	// Recipe is the RecipeDef.ID being crafted.
	Recipe string `json:"recipe" yaml:"recipe"`
	// Duration is the total craft time declared by the recipe when the order started; 0 for instant crafts.
	Duration time.Duration `json:"duration,omitempty" yaml:"duration,omitempty"`
	// Remaining is how much craft time remains; 0 when the order is completed.
	Remaining time.Duration `json:"remaining,omitempty" yaml:"remaining,omitempty"`
	// Refund holds the exact stacks consumed when the order started (including resolved items and per-stack data for tag inputs), returned if the order is cancelled.
	Refund []Stack `json:"refund,omitempty" yaml:"refund,omitempty"`
	// Outputs holds the item stacks this order produces upon collection.
	Outputs []Stack `json:"outputs" yaml:"outputs"`
}

CraftOrder is one pending or completed crafting order managed by a Queue.

func (CraftOrder) MarshalJSON

func (o CraftOrder) MarshalJSON() ([]byte, error)

MarshalJSON encodes o with human-readable duration strings.

func (CraftOrder) MarshalYAML

func (o CraftOrder) MarshalYAML() (any, error)

MarshalYAML encodes o deterministically with fixed field order and human-readable duration strings.

func (*CraftOrder) UnmarshalJSON

func (o *CraftOrder) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes o strictly from JSON, refusing unknown fields, null values and invalid durations.

func (*CraftOrder) UnmarshalYAML

func (o *CraftOrder) UnmarshalYAML(n *yaml.Node) error

UnmarshalYAML decodes o strictly from YAML, refusing unknown fields, null values and invalid durations.

func (CraftOrder) Validate

func (o CraftOrder) Validate() error

Validate reports whether o has valid identifiers, non-negative durations, and valid stacks.

type CraftableRecipe

type CraftableRecipe struct {
	// Recipe is a copy of the craftable recipe definition.
	Recipe RecipeDef
	// Times is how many times the recipe can be crafted with the current containers (always >= 1).
	Times int
}

CraftableRecipe is one recipe returned by Book.Craftable alongside how many times it can be made.

type DataField

type DataField struct {
	// Type is "number" (default when omitted) or "string".
	Type DataKind `yaml:"type,omitempty"`
	// Min is an optional finite lower bound for numeric fields.
	Min *float64 `yaml:"min,omitempty"`
	// Max is an optional finite upper bound for numeric fields.
	Max *float64 `yaml:"max,omitempty"`
	// Default is an optional default value applied when a stack is created without an explicit value for this field.
	Default *DataValue `yaml:"default,omitempty"`
}

DataField declares one per-stack data field on an ItemDef, such as durability, quality or a custom name. When Type is omitted, the field holds a finite number ("number").

func (DataField) EffectiveType

func (f DataField) EffectiveType() DataKind

EffectiveType returns Type, or DataNumber when Type is empty.

type DataKind

type DataKind string

DataKind names the value type of a per-stack data field declared on an ItemDef.

const (
	// DataNumber is a finite numeric field (the default when DataField.Type is omitted).
	DataNumber DataKind = "number"
	// DataString is a UTF-8 string field.
	DataString DataKind = "string"
)

type DataValue

type DataValue struct {
	// Kind is DataNumber or DataString.
	Kind DataKind
	// Number holds the numeric value when Kind is DataNumber.
	Number float64
	// String holds the string value when Kind is DataString.
	String string
}

DataValue is one numeric or string value stored in a stack's per-instance Data map.

func NumberData

func NumberData(n float64) DataValue

NumberData returns a numeric DataValue.

func StringData

func StringData(s string) DataValue

StringData returns a string DataValue.

func (DataValue) Equal

func (v DataValue) Equal(other DataValue) bool

Equal reports whether v and other hold the same kind and value.

func (DataValue) MarshalJSON

func (v DataValue) MarshalJSON() ([]byte, error)

MarshalJSON encodes v as a JSON number or string.

func (DataValue) MarshalYAML

func (v DataValue) MarshalYAML() (any, error)

MarshalYAML encodes v deterministically as a YAML number (integer scalar when an exact safe integer, float otherwise) or string.

func (*DataValue) UnmarshalJSON

func (v *DataValue) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes a finite JSON number or JSON string into v, refusing null, booleans, arrays and objects.

func (*DataValue) UnmarshalYAML

func (v *DataValue) UnmarshalYAML(n *yaml.Node) error

UnmarshalYAML decodes a YAML number or string scalar into v, refusing null, booleans, sequences and mappings.

func (DataValue) Validate

func (v DataValue) Validate() error

Validate reports whether v is a valid finite DataNumber or a DataString.

type EquipSlot

type EquipSlot struct {
	// Name identifies the slot, such as "head" or "ring-left"; unique within an Equipment.
	Name string
	// Kind is the equipment kind the slot accepts, matched against ItemDef.Equip; several slots may share a kind.
	Kind string
}

EquipSlot is one named equipment slot.

type Equipment

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

Equipment is a set of typed slots, each holding at most one item (with its optional per-stack data). The zero Equipment is not usable; create one with NewEquipment.

func NewEquipment

func NewEquipment(catalog *Catalog, slots ...EquipSlot) (*Equipment, error)

NewEquipment returns empty equipment with the given slots, in order, holding items from catalog. Slot names must be unique and, like kinds, non-empty without whitespace or control characters.

func (*Equipment) CanEquip

func (e *Equipment) CanEquip(slot, item string) bool

CanEquip reports whether item is in the catalog and fits slot's kind.

func (*Equipment) Catalog

func (e *Equipment) Catalog() *Catalog

Catalog returns the catalog the equipment's items come from.

func (*Equipment) Clear

func (e *Equipment) Clear()

Clear empties every equipment slot.

func (*Equipment) Equip

func (e *Equipment) Equip(slot string, src *Container, from int) error

Equip takes one item (with its per-stack data) from slot from of src and puts it in the equipment slot. An item already in the slot goes back to src with its data: into slot from when taking the item emptied it, otherwise wherever src.AddAllWithData would put it. It returns ErrNotEquippable when the item's kind does not match the slot, ErrFull when src has no room for the replaced item, and ErrCatalogMismatch when src uses a different catalog; on any error nothing changes. Equipping the same item with equal data that is already in the slot does nothing.

func (*Equipment) Equipped

func (e *Equipment) Equipped(slot string) (string, bool)

Equipped returns the item in slot, and false when slot is empty or unknown.

func (*Equipment) EquippedStack

func (e *Equipment) EquippedStack(slot string) (Stack, bool)

EquippedStack returns a copy of the equipped item as a Stack (Count 1, including its per-stack Data), and false when slot is empty or unknown.

func (*Equipment) Restore

func (e *Equipment) Restore(st EquipmentState) error

Restore replaces the equipped items with st after checking every entry: the slot must exist and be listed once, the item must be in the catalog and fit the slot's kind, and any per-stack data must be valid for the item's declared fields. On error the equipment is left unchanged. Use RestoreContent to apply the catalog's declared renames and retirements instead.

func (*Equipment) RestoreContent

func (e *Equipment) RestoreContent(st EquipmentState) (RestoreReport, error)

RestoreContent restores an equipment snapshot through the content updates its catalog declares, as RestoreMigrated does with the maps passed in, and returns the changes it applied so the game can grant the declared refunds or show a notice. Restore stays strict for games without a migration policy.

func (*Equipment) RestoreMigrated

func (e *Equipment) RestoreMigrated(st EquipmentState, renamed map[string]string, retired map[string]struct{}) (RestoreReport, error)

RestoreMigrated restores an equipment snapshot while applying declared ID changes. A rename maps an old ID to a current ID. A retired ID is dropped. It returns the changes it applied.

func (*Equipment) SavePart

func (e *Equipment) SavePart() save.Part

SavePart returns a save.Part (implementing save.StagedPart and save.Resetter) that saves and restores e through save.Game. Loading validates every slot before mutating e, and resets e to empty when loading an older save slot that omits this part.

func (*Equipment) SavePartContent

func (e *Equipment) SavePartContent(onRestore func(RestoreReport)) save.Part

SavePartContent returns a save.Part like SavePart whose restores apply the catalog's declared renames and retirements, so a save holding an item ID a release removed still loads. onRestore, when non-nil, receives the changes each restore applied, so the game can grant the declared refunds or show a notice after loading. Use SavePart for a strict restore that refuses such a save.

func (*Equipment) SetData

func (e *Equipment) SetData(slot string, data StackData) error

SetData replaces the per-stack data of the item in equipment slot after validating it against the item's declared ItemDef.Data fields.

func (*Equipment) SetDataField

func (e *Equipment) SetDataField(slot, field string, value DataValue) error

SetDataField updates one declared per-stack data field on the item in equipment slot.

func (*Equipment) Slots

func (e *Equipment) Slots() []EquipSlot

Slots returns a copy of the equipment's slots in order.

func (*Equipment) Snapshot

func (e *Equipment) Snapshot() EquipmentState

Snapshot returns the occupied slots in slot order.

func (*Equipment) Unequip

func (e *Equipment) Unequip(slot string, dst *Container) error

Unequip moves the item in slot (with its per-stack data) into dst the way dst.AddAllWithData does. It returns ErrEmptySlot when slot holds nothing and ErrFull, leaving the item equipped, when dst has no room.

type EquipmentState

type EquipmentState struct {
	// Slots lists the occupied equipment slots in the Equipment's slot order.
	Slots []EquippedState `json:"slots"`
}

EquipmentState is the equipped items in a form encoding/json writes deterministically, for storing in a save slot.

type EquippedState

type EquippedState struct {
	// Slot is the equipment slot's name.
	Slot string `json:"slot"`
	// Item is the equipped item's ID.
	Item string `json:"item"`
	// Data holds optional per-stack instance fields declared on the item's ItemDef.
	Data StackData `json:"data,omitempty"`
}

EquippedState is one occupied equipment slot in an EquipmentState.

type Exchange

type Exchange struct {
	// From lists the containers to consume Take inputs from, in order.
	From []*Container
	// To lists the containers to place Give outputs into, in order; when empty, From is used.
	To []*Container
	// Take lists the required inputs (by item ID or by tag).
	Take []Ingredient
	// Give lists the output stacks to add after Take inputs are removed.
	Give []Stack
	// CompareSlots, when non-nil, orders candidate slots to consume for each input (returning < 0 to consume a before b).
	// When nil, slots are consumed in From container order and from the last slot backwards within each container, matching Container.Remove.
	CompareSlots func(a, b SlotRef) int
}

Exchange is an atomic multi-container transaction that removes Take inputs from From containers and adds Give outputs into To containers all or nothing. When To is empty, outputs are placed into From in order.

func (Exchange) Apply

func (e Exchange) Apply() (Plan, error)

Apply validates and executes e atomically across all involved containers. If any input is missing it returns the Plan and ErrNotEnough; if any output does not fit it returns the Plan and ErrFull. On any error every container is left unchanged.

func (Exchange) Plan

func (e Exchange) Plan() (Plan, error)

Plan validates e and simulates it on shadow copies without mutating any container, reporting exact missing inputs and outputs that do not fit. Structural errors (nil containers, catalog mismatches, unknown items, negative counts or invalid output data) are returned as a non-nil error.

type Grant

type Grant struct {
	// Item is the granted item's ID.
	Item string `yaml:"item"`
	// Count is how many are granted; 0 means 1.
	Count int `yaml:"count,omitempty"`
}

Grant is an item and how many of it someone is granted; Count 0 means 1 and is written by omitting the field.

func (Grant) Quantity

func (g Grant) Quantity() int

Quantity returns how many the grant is for: Count, or 1 when Count is 0.

type Ingredient

type Ingredient struct {
	// Item matches one specific item ID in the catalog; mutually exclusive with Tag.
	Item string `yaml:"item,omitempty"`
	// Tag matches any catalog item carrying this tag or a child tag under it; mutually exclusive with Item.
	Tag string `yaml:"tag,omitempty"`
	// Count is how many matching items are required; 0 means 1.
	Count int `yaml:"count,omitempty" schema:"minimum=1"`
}

Ingredient describes one required input for an Exchange or RecipeDef, matching either one specific item ID or any catalog item carrying Tag (or a child tag under it). Exactly one of Item or Tag must be non-empty. Count 0 means 1 (and is written by omitting count in YAML).

func (Ingredient) Quantity

func (in Ingredient) Quantity() int

Quantity returns Count, or 1 when Count is 0.

type ItemDef

type ItemDef struct {
	// ID uniquely identifies the item within its catalog and is what stacks, snapshots and saves refer to. It must be non-empty and contain no whitespace or control characters.
	ID string `yaml:"id" schema:"required"`
	// Name is the item's display name or localization key.
	Name string `yaml:"name,omitempty"`
	// Description is optional longer display text or a localization key.
	Description string `yaml:"description,omitempty"`
	// Icon is an optional asset URI for the item's icon, such as "asset:icons/potion.png".
	Icon string `yaml:"icon,omitempty"`
	// MaxStack is how many of the item one slot holds, in [1, MaxStackLimit]; 0 means 1 and is written by omitting the field, since Parse refuses an explicit "maxStack: 0".
	MaxStack int `yaml:"maxStack,omitempty"`
	// Equip is the equipment kind the item fits, matched against EquipSlot.Kind; empty means the item cannot be equipped.
	Equip string `yaml:"equip,omitempty"`
	// Tags are free-form labels such as "consumable" or "quest", unique within the item.
	Tags []string `yaml:"tags,omitempty,flow"`
	// Stats holds finite numeric values such as damage, armor, weight or price, keyed by non-empty names.
	Stats map[string]float64 `yaml:"stats,omitempty"`
	// Data declares optional per-stack instance fields (such as durability, quality or a custom name) stored on Stack.Data.
	Data map[string]DataField `yaml:"data,omitempty"`
}

ItemDef defines one kind of item.

func (ItemDef) EffectiveMaxStack

func (d ItemDef) EffectiveMaxStack() int

EffectiveMaxStack returns MaxStack, or 1 when MaxStack is 0.

func (ItemDef) HasExactTag

func (d ItemDef) HasExactTag(tag string) bool

HasExactTag reports whether the item carries tag literally without parent matching.

func (ItemDef) HasTag

func (d ItemDef) HasTag(tag string) bool

HasTag reports whether the item carries tag or a child tag under it (for example, an item tagged "item.consumable.healing" matches "item.consumable" and "item").

func (ItemDef) TagContainer

func (d ItemDef) TagContainer(reg *tags.Registry) (*tags.Container, error)

TagContainer resolves d.Tags against reg into a new tags.Container. It returns a *loaderr.Error if reg is nil or any tag on d is not registered in reg.

type MissingInput

type MissingInput struct {
	// Index is the input's position in Exchange.Take.
	Index int
	// Input is the requested Ingredient.
	Input Ingredient
	// Have is how many matching items were available.
	Have int
	// Want is how many were required.
	Want int
	// Missing is Want - Have.
	Missing int
}

MissingInput reports one Exchange.Take entry that could not be satisfied.

type Plan

type Plan struct {
	// Missing lists unsatisfied inputs in Exchange.Take order.
	Missing []MissingInput
	// Unfit lists outputs that do not fit in Exchange.Give order.
	Unfit []UnfitOutput
	// Taken lists the exact stacks consumed from From containers (including resolved items and per-stack data for tag inputs).
	Taken []TakenStack
}

Plan is the dry-run outcome of an Exchange, reporting exactly what inputs are missing, what outputs do not fit, and which stacks would be consumed.

func (Plan) OK

func (p Plan) OK() bool

OK reports whether every input is present and every output fits.

type Queue

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

Queue manages timed crafting orders from one Book against one Catalog.

Created with NewQueue, it advances deterministically on the fixed loop via Step(dt). Created with NewRealtimeQueue or NewQueueWithJobs, its pending orders are tracked in an idle.Jobs schedule so crafting continues on the wall clock while the app is closed, completing orders in finish order via Sync(now).

A real-time Queue owns its idle.Jobs schedule exclusively: Sync collects every finished job in it, and Snapshot, Restore and SavePart save and replace the whole schedule, so do not share that schedule with other subsystems.

func NewQueue

func NewQueue(catalog *Catalog, book *Book) (*Queue, error)

NewQueue returns an empty fixed-loop crafting queue for catalog and book.

func NewQueueWithJobs

func NewQueueWithJobs(catalog *Catalog, book *Book, jobs *idle.Jobs) (*Queue, error)

NewQueueWithJobs returns an empty crafting queue backed by jobs (allocating a fresh idle.Jobs when jobs is nil). The queue owns jobs exclusively; see Queue.

func NewRealtimeQueue

func NewRealtimeQueue(catalog *Catalog, book *Book, clock idle.TimeSource) (*Queue, error)

NewRealtimeQueue returns an empty crafting queue backed by its own idle.Jobs schedule (using optional clock as a trusted time source) so crafts finish on the wall clock while the app is closed.

func (*Queue) Book

func (q *Queue) Book() *Book

Book returns the recipe book used by q.

func (*Queue) Cancel

func (q *Queue) Cancel(orderID string, refundTo ...*Container) (CraftOrder, error)

Cancel removes pending order id from q and, when refundTo is non-empty, atomically returns its consumed input stacks into refundTo. If refundTo lacks room, Cancel returns ErrFull and leaves both refundTo and q unchanged.

func (*Queue) Catalog

func (q *Queue) Catalog() *Catalog

Catalog returns the item catalog used by q.

func (*Queue) Collect

func (q *Queue) Collect(to ...*Container) ([]CraftOrder, error)

Collect delivers completed orders' outputs into to in FIFO order, removing each delivered order from Completed. Each order is delivered atomically; if an order does not fit, it and all later completed orders remain in Completed and Collect returns the already-collected orders together with ErrFull.

func (*Queue) CollectOne

func (q *Queue) CollectOne(orderID string, to ...*Container) (CraftOrder, error)

CollectOne delivers one completed order's outputs into to atomically and removes it from Completed. On any error (unknown order, ErrFull), containers and q remain unchanged.

func (*Queue) CompleteJob

func (q *Queue) CompleteJob(orderID string) (CraftOrder, bool)

CompleteJob marks pending order id as completed immediately, moves it to Completed and, in a real-time queue, removes its job from the backing idle.Jobs schedule.

func (*Queue) Completed

func (q *Queue) Completed() []CraftOrder

Completed returns copies of all completed orders waiting to be collected, in completion order.

func (*Queue) Enqueue

func (q *Queue) Enqueue(recipeID string, from ...*Container) (CraftOrder, Plan, error)

Enqueue consumes recipeID's inputs atomically from from and adds a new craft order to q. For a fixed-loop queue (NewQueue), time advances via Step(dt). For a real-time queue with a configured idle.Jobs.Clock, Enqueue reads Clock; otherwise call EnqueueAt with an explicit timestamp.

func (*Queue) EnqueueAt

func (q *Queue) EnqueueAt(recipeID string, now time.Time, from ...*Container) (CraftOrder, Plan, error)

EnqueueAt consumes recipeID's inputs atomically from from and adds a new craft order at wall-clock timestamp now (ignored by fixed-loop queues). On any error (unknown recipe, missing inputs, invalid timestamp, catalog mismatch), both containers and q are left unchanged.

func (*Queue) Jobs

func (q *Queue) Jobs() *idle.Jobs

Jobs returns the backing idle.Jobs schedule, or nil for a fixed-loop Queue.

func (*Queue) Pending

func (q *Queue) Pending() []CraftOrder

Pending returns copies of all pending (in-progress and waiting) orders in FIFO order.

func (*Queue) Remaining

func (q *Queue) Remaining(orderID string, now time.Time) time.Duration

Remaining reports how much time remains until order id completes (including any orders queued ahead of it). For a real-time queue, it queries the backing idle.Jobs at now; for a fixed-loop queue, it sums remaining durations up through order id.

func (*Queue) Restore

func (q *Queue) Restore(st QueueState) error

Restore replaces q's pending and completed orders (and backing idle.Jobs when present) from st after validating every order against q's catalog and book. On any error q is left unchanged.

func (*Queue) SavePart

func (q *Queue) SavePart() save.Part

SavePart returns a save.Part (implementing save.StagedPart and save.Resetter) that saves and restores q through save.Game. Loading validates the entire QueueState before mutating q, and resets q to empty when loading an older save slot that omits this part.

func (*Queue) Snapshot

func (q *Queue) Snapshot() QueueState

Snapshot returns q's versioned persisted state (including backing idle.JobsState when running in real-time mode).

func (*Queue) SpeedUp

func (q *Queue) SpeedUp(orderID string, d time.Duration) bool

SpeedUp reduces pending order id's remaining duration by d and reports whether the order was shortened. In a real-time queue, orders queued behind id are also shifted earlier by the saved duration.

func (*Queue) Step

func (q *Queue) Step(dt time.Duration) []CraftOrder

Step advances a fixed-loop queue by dt, moving finished orders to Completed and returning them in completion order. Surplus time after one order completes carries over to the next order in FIFO order. Non-positive dt does nothing. SpeedUp and Cancel can also finish orders at the head of a fixed-loop queue; those orders go straight to Completed without being returned by Step, so read Completed rather than Step's result to find every order ready to collect.

func (*Queue) Sync

func (q *Queue) Sync(now time.Time) []CraftOrder

Sync collects every craft job finished at or before now from q's backing idle.Jobs schedule, moves those orders from Pending to Completed in completion order, refreshes remaining durations on active orders, and returns the newly completed orders.

type QueueState

type QueueState struct {
	// Version is QueueStateVersion (1).
	Version int `json:"version" yaml:"version"`
	// NextID is the next sequential order number (at least 1).
	NextID int `json:"nextId" yaml:"nextId"`
	// Pending holds in-progress and waiting orders in FIFO order.
	Pending []CraftOrder `json:"pending,omitempty" yaml:"pending,omitempty"`
	// Completed holds finished orders waiting to be collected.
	Completed []CraftOrder `json:"completed,omitempty" yaml:"completed,omitempty"`
	// Jobs holds the backing idle.JobsState when the Queue runs in real-time offline mode.
	Jobs *idle.JobsState `json:"jobs,omitempty" yaml:"jobs,omitempty"`
}

QueueState is the versioned persisted state of a Queue that encodes deterministically to JSON or YAML.

func (QueueState) MarshalJSON

func (s QueueState) MarshalJSON() ([]byte, error)

MarshalJSON encodes s deterministically. It returns an error if s fails Validate.

func (QueueState) MarshalYAML

func (s QueueState) MarshalYAML() (any, error)

MarshalYAML encodes s deterministically with fixed field order. It returns an error if s fails Validate.

func (*QueueState) UnmarshalJSON

func (s *QueueState) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes s strictly from JSON, refusing unknown fields, null values, trailing data and invalid states.

func (*QueueState) UnmarshalYAML

func (s *QueueState) UnmarshalYAML(n *yaml.Node) error

UnmarshalYAML decodes s strictly from YAML, refusing unknown fields, null values and invalid states.

func (QueueState) Validate

func (s QueueState) Validate() error

Validate reports whether s is a well-formed version 1 QueueState.

type Recipe

type Recipe struct {
	// ID is the stable recipe identifier.
	ID string `yaml:"id"`
	// Inputs are the item stacks consumed by the recipe.
	Inputs []Stack `yaml:"inputs"`
	// Outputs are the item stacks produced by the recipe.
	Outputs []Stack `yaml:"outputs"`
}

Recipe exchanges input stacks for output stacks atomically in a single container. For versioned YAML recipes with tag inputs, stations, craft times, unlock keys, multi-container exchanges and crafting queues, use RecipeDef, Book, Exchange and Queue.

type RecipeBookDoc

type RecipeBookDoc struct {
	// Version is RecipeFormatVersion (1).
	Version int `yaml:"version" schema:"required,const=1"`
	// Recipes lists the crafting recipes in file order.
	Recipes []RecipeDef `yaml:"recipes"`
}

RecipeBookDoc is the versioned YAML document layout of a crafting recipe Book.

type RecipeDef

type RecipeDef struct {
	// ID uniquely identifies the recipe within its Book.
	ID string `yaml:"id" schema:"required"`
	// Name is an optional display name or localization key.
	Name string `yaml:"name,omitempty"`
	// Description is optional longer display text or a localization key.
	Description string `yaml:"description,omitempty"`
	// Station is an optional station tag the game checks (such as "station.forge" or "campfire"); empty means craftable without a station.
	Station string `yaml:"station,omitempty"`
	// Time is how long the craft takes; 0 (omitted) means instant.
	Time time.Duration `yaml:"time,omitempty"`
	// Unlock is an optional unlock key the game checks (such as a blueprint or progression flag); empty means always unlocked.
	Unlock string `yaml:"unlock,omitempty"`
	// Inputs are the item or tag requirements consumed by the recipe; at least one is required.
	Inputs []Ingredient `yaml:"inputs" schema:"required,minItems=1"`
	// Outputs are the item stacks produced by the recipe; at least one is required.
	Outputs []RecipeOutput `yaml:"outputs" schema:"required,minItems=1"`
}

RecipeDef defines one crafting recipe in a versioned Book.

func (RecipeDef) MatchesStation

func (r RecipeDef) MatchesStation(station string) bool

MatchesStation reports whether a player at station may craft r. A recipe with an empty Station matches any station (including ""). Otherwise station must equal r.Station or be a child tag under it (via tags.MatchesName).

type RecipeOutput

type RecipeOutput struct {
	// Item is the produced item's ID in the catalog.
	Item string `yaml:"item" schema:"required"`
	// Count is how many of the item are produced; 0 means 1.
	Count int `yaml:"count,omitempty" schema:"minimum=1"`
	// Data holds optional per-stack instance fields applied on top of the item's declared defaults.
	Data StackData `yaml:"data,omitempty"`
}

RecipeOutput is one output stack produced by a RecipeDef. Count 0 means 1 and is written by omitting count in YAML; ParseRecipes refuses an explicit "count: 0".

func (RecipeOutput) Quantity

func (o RecipeOutput) Quantity() int

Quantity returns Count, or 1 when Count is 0.

func (RecipeOutput) Stack

func (o RecipeOutput) Stack() Stack

Stack converts o into a Stack with Count equal to o.Quantity() and a cloned Data map.

type RestoreChange

type RestoreChange struct {
	// Slot is the slot index the saved stack was in for a container, written in decimal, or the slot name for equipment.
	Slot string
	// From is the item ID the save held.
	From string
	// To is the item ID it was renamed to, or empty when the item was retired and dropped.
	To string
	// Count is how many of the item the saved stack held.
	Count int
}

RestoreChange describes one content migration applied while restoring a save.

type RestoreReport

type RestoreReport struct {
	Changes []RestoreChange
}

RestoreReport records item renames and retirements applied during restore.

type Retirement

type Retirement struct {
	// ID is the retired item's ID, which the catalog must not define.
	ID string `yaml:"id"`
	// Replacement is the item ID the retired item's stacks become; empty drops them.
	Replacement string `yaml:"replacement,omitempty"`
	// Refund is what the game may grant for each retired unit, such as the currency its price converted to; nil grants nothing.
	Refund *Grant `yaml:"refund,omitempty"`
}

Retirement declares an item the catalog no longer defines, so a save that holds it still restores: its stacks become the replacement item when one is declared and are dropped otherwise, and Refund says what the game may grant for each saved unit. The package reports the change and never grants the refund itself.

type SlotRef

type SlotRef struct {
	// Container is the index into Exchange.From (deduplicated in first-seen order).
	Container int
	// Slot is the slot index within that container.
	Slot int
	// Stack is a copy of the stack currently in that slot.
	Stack Stack
}

SlotRef identifies one occupied slot in an Exchange's From container list.

type SlotState

type SlotState struct {
	// Slot is the slot index.
	Slot int `json:"slot"`
	// Item is the item's ID.
	Item string `json:"item"`
	// Count is how many of the item the slot holds.
	Count int `json:"count"`
	// Data holds optional per-stack instance fields declared on the item's ItemDef.
	Data StackData `json:"data,omitempty"`
}

SlotState is one non-empty slot in a ContainerState.

type Stack

type Stack struct {
	// Item is the item's ID in the catalog; empty for an empty slot.
	Item string `json:"item" yaml:"item"`
	// Count is how many of the item the slot holds; 0 for an empty slot.
	Count int `json:"count,omitempty" yaml:"count,omitempty"`
	// Data holds optional per-stack instance fields declared on the item's ItemDef, such as durability, quality or a custom name.
	Data StackData `json:"data,omitempty" yaml:"data,omitempty"`
}

Stack is a count of one item in a slot, with optional per-stack Data. The zero Stack is an empty slot.

func (Stack) Clone

func (s Stack) Clone() Stack

Clone returns an independent copy of s, including a copy of s.Data.

func (Stack) Empty

func (s Stack) Empty() bool

Empty reports whether the stack holds nothing.

func (Stack) Equal

func (s Stack) Equal(other Stack) bool

Equal reports whether s and other represent the same item, count and per-stack data. Any two empty stacks are equal.

type StackData

type StackData map[string]DataValue

StackData holds per-stack instance fields declared on an item's ItemDef, such as durability, quality or a custom name. A nil and an empty StackData are equivalent.

func (StackData) Clone

func (d StackData) Clone() StackData

Clone returns an independent copy of d, or nil when d is empty.

func (StackData) Equal

func (d StackData) Equal(other StackData) bool

Equal reports whether d and other contain the exact same keys and equal values.

func (StackData) Number

func (d StackData) Number(key string) (float64, bool)

Number returns the numeric value stored under key and whether it exists with DataNumber kind.

func (StackData) String

func (d StackData) String(key string) (string, bool)

String returns the string value stored under key and whether it exists with DataString kind.

type TakenStack

type TakenStack struct {
	// Container is the index into Exchange.From (deduplicated in first-seen order).
	Container int
	// Slot is the slot index within that container.
	Slot int
	// Stack is the item, count and per-stack data removed from that slot.
	Stack Stack
}

TakenStack records items that a Plan consumes from a single slot.

type UnfitOutput

type UnfitOutput struct {
	// Index is the output's position in Exchange.Give.
	Index int
	// Output is the requested output Stack (with item defaults applied).
	Output Stack
	// Fit is how many fit into the destination containers.
	Fit int
	// Want is Output.Count.
	Want int
	// Overflow is Want - Fit.
	Overflow int
}

UnfitOutput reports one Exchange.Give stack that could not fit into Exchange.To.

Jump to

Keyboard shortcuts

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