Documentation
¶
Index ¶
- Constants
- func CheckComponents(group, class string, raw map[string]json.RawMessage) error
- func ComponentKey(group, name string) string
- func Components() iter.Seq[ComponentSchema]
- func DecodeComponent(world *ecs.World, c Component, raw json.RawMessage, refs Refs) (any, error)
- func DecodeFunc[T any]() func(json.RawMessage) (any, error)
- func DocumentName(data []byte) string
- func EncodeComponent(world *ecs.World, c Component, v any, refs Refs) (json.RawMessage, error)
- func Objects(world *ecs.World) iter.Seq[Object]
- func PrefabKeys(data []byte) ([]string, error)
- func PrefabOf(world *ecs.World, e ecs.Entity) (string, bool)
- func PrefabPartOf(world *ecs.World, e ecs.Entity) (key, part string, ok bool)
- func Ptr[T any](v T) *T
- func RegisterComponent(c ComponentSchema)
- func RegisterDataOnly(r io.Reader) error
- func RegisterSchema(s Schema)
- func Schemas() iter.Seq[Schema]
- func Serialize(world *ecs.World, w io.Writer, objs ...Object) error
- func SerializeComponents(world *ecs.World, group, class string, e ecs.Entity) (json.RawMessage, error)
- func SetAssetResolver(world *ecs.World, r AssetResolver)
- func SetPrefabSource(world *ecs.World, src PrefabSource)
- type AssetResolver
- type BoundPrefab
- type Component
- type ComponentSchema
- type EditorHints
- type EnumValue
- type ExpandedObject
- type Object
- type ObjectClass
- type Prefab
- func (p *Prefab) Base() string
- func (p *Prefab) Bind(world *ecs.World, assets AssetResolver) (*BoundPrefab, error)
- func (p *Prefab) Component(key string) (json.RawMessage, bool)
- func (p *Prefab) Expand(group, class string, overrides map[string]json.RawMessage) (map[string]json.RawMessage, error)
- func (p *Prefab) ExpandInstance(e PrefabEntry) ([]ExpandedObject, error)
- func (p *Prefab) ID() string
- func (p *Prefab) Key() string
- func (p *Prefab) Meta() SchemaMeta
- func (p *Prefab) Name() string
- func (p *Prefab) Overrides(comps map[string]json.RawMessage) (map[string]json.RawMessage, error)
- func (p *Prefab) PartComponent(id, key string) (json.RawMessage, bool)
- func (p *Prefab) PartIndex(id string) int
- func (p *Prefab) PartOverrides(rootID, part string, comps map[string]json.RawMessage) (map[string]json.RawMessage, error)
- func (p *Prefab) Parts() []string
- type PrefabEntry
- type PrefabInstance
- type PrefabMap
- type PrefabSource
- type Refs
- type Schema
- type SchemaMeta
- type ShowIf
- type TypeSchema
- func (s *TypeSchema) Fill(raw json.RawMessage) (json.RawMessage, error)
- func (s *TypeSchema) InitialValue() json.RawMessage
- func (s *TypeSchema) IsDefault(raw json.RawMessage) bool
- func (s *TypeSchema) Prune(raw json.RawMessage) (json.RawMessage, error)
- func (s *TypeSchema) Validate(raw json.RawMessage) error
- func (s *TypeSchema) WithoutDescriptions() *TypeSchema
Constants ¶
const EntityRefKey = "$entity"
EntityRefKey is the key of the one-member object that stands for an entity reference inside a value marked x-entity-refs: {"$entity": ref}.
const FormatColor = "color"
FormatColor is the Format of a color: a string property that holds "#rrggbbaa", or "#rrggbb" for an opaque color, in any case. The generator emits it for every field of type gfx.Color. Its initial value is "#00000000", the zero gfx.Color, which draws white (no tint); a transparent color has other bits set, such as "#ffffff00". Editors show a color picker for it.
const FormatEntity = "entity"
FormatEntity is the Format of an entity reference: a string property that holds the document id of another object (see Refs). The generator emits it, nullable, for every field of type ecs.Entity.
const UnitDegrees = "deg"
UnitDegrees is the EditorHints.Unit of a value stored in radians and shown in degrees.
Variables ¶
This section is empty.
Functions ¶
func CheckComponents ¶
func CheckComponents(group, class string, raw map[string]json.RawMessage) error
CheckComponents verifies that raw holds every required component of the object registered under group:class, and that every other key names a registered component type (see RegisterComponent) or a data-only one (see RegisterDataOnly; its value is checked against its GOD schema): the class sets the minimum of an object, not its limit. All problems are reported, in key order.
func ComponentKey ¶
ComponentKey returns the key "group:name" of a component type.
func Components ¶
func Components() iter.Seq[ComponentSchema]
Components returns every registered component type, sorted by key, used by an object or not. Like Schemas it iterates a snapshot.
func DecodeComponent ¶
DecodeComponent turns the JSON of one component into a value ready for World.SetComp or NewEntity: it validates raw against c.Schema, fills in the properties raw leaves out with their defaults (TypeSchema.Fill), resolves entity references through refs, decodes it with c.Decode, and resolves asset keys through the world's AssetResolver. A nil refs is fine for components without references; a non-null reference is then an error ("no Refs for entity reference"). Errors carry $-paths and are all reported. Deserialize and Lua use it; so can tools that edit one component at a time.
func DecodeFunc ¶
func DecodeFunc[T any]() func(json.RawMessage) (any, error)
DecodeFunc returns a Component.Decode for component type T.
func DocumentName ¶
DocumentName returns the optional top-level "name" of a GOD document (a level or a prefab file), a human-readable label for editors, or "" when there is none. Like PrefabKeys it reads only the JSON shape: invalid JSON and a name that is not a string also give "" (Deserialize reports real errors). Deserialize and ParsePrefab accept the key; names are not unique and nothing looks documents up by them.
func EncodeComponent ¶
EncodeComponent is the inverse of DecodeComponent: the JSON of component value v (a T or *T of c's type), with asset handles written as keys and entity references as ids from refs. A nil refs fails on any non-zero reference. Runtime fields are left out like in Serialize.
func Objects ¶
Objects yields every entity of world whose class ClassOf resolves, as an Object (with Object.Prefab and Object.Part set from its PrefabInstance tag), in query order (archetype, then row; not creation order). Its result can go straight to Serialize:
types.Serialize(world, w, slices.Collect(types.Objects(world))...)
Structural changes to world while iterating follow the rules of ecs.Query.Each.
func PrefabKeys ¶
PrefabKeys returns the distinct "prefab" keys of the objects of a GOD document (a level or a prefab file), in document order. Loaders use it to load a document's prefabs before deserializing it. Only the JSON shape is read; nothing is validated.
func PrefabOf ¶
PrefabOf returns the key of the prefab e was made from, and false if e has no PrefabInstance tag. A part of a multi-object instance reports its instance's prefab.
Panics with "ecs: invalid or stale entity: <e>" if e is stale.
func PrefabPartOf ¶
PrefabPartOf is PrefabOf that also returns which object of the prefab e is: "" for the root, else the part's id (`sword`, `horse/saddle`).
Panics with "ecs: invalid or stale entity: <e>" if e is stale.
func Ptr ¶
func Ptr[T any](v T) *T
Ptr returns a pointer to v, for the optional numeric fields of TypeSchema.
func RegisterComponent ¶
func RegisterComponent(c ComponentSchema)
RegisterComponent registers a component type under its key. Generated code calls it from init for every component type a package declares or uses, so the same type is often registered by several packages: registering an identical definition again is a no-op (Doc, schema descriptions and Decode are not compared).
Panics with "god: component without a group or name" if Group or Name is empty, "god: component \"<key>\": group and name must not contain ':'", "god: component \"<key>\" has no schema" or "... has no decoder" for a nil Schema or Decode, and "god: component \"<key>\" registered twice with different definitions" when the key is taken by a different type or schema.
func RegisterDataOnly ¶
RegisterDataOnly reads one GOD file (version 0) and records every component type and object class it names that the program has not registered, as data only: CheckComponents accepts such a component key and checks its value against the schema of the file, and DataOnlyComponent returns the schema. Nothing is decoded or put into a world: ObjectComponents, Bind and Serialize skip them as they skip any unregistered key.
An editor that opens a prefab without the game's code calls it for each GOD file of the project; a game never does. A registered component type or object class always wins: an entry of the file for one is ignored, so a stale engine entry is harmless. A class that is not registered is registered with its registered components only, so ClassTag and LookupSchema work for it; its data-only components are checked from the record. Registering the same file again is a no-op; a data-only component of an earlier file is replaced by the same key of a later one.
It returns an error, and records nothing, for input that is not a GOD file, has another version, or has a component without a group, name or schema; all problems are reported together. It is safe for concurrent use.
func RegisterSchema ¶
func RegisterSchema(s Schema)
RegisterSchema registers a game object schema under its key. It panics if a component has an empty group or name, a duplicate key, a nil Schema or Decode, or is both Readonly and Optional, and if the key is already registered with a different definition (registering an identical one again is a no-op; Decode is not compared).
func Schemas ¶
Schemas returns every registered schema, sorted by key. It iterates a snapshot taken when iteration starts, so registering a schema meanwhile neither blocks nor shows up in the running iteration.
func Serialize ¶
Serialize writes one JSON document to w with one entry per Object, in argument order — the inverse of Deserialize. Each object gets the components of its class the entity has, plus every other registered component type it has; optional components it lacks are left out; a missing required component or an unregistered group:class is an error, prefixed with the object's index ("objects[i]: ..."). The whole document is built before anything is written, so on error nothing reaches w.
Entity references are written as object ids: an object's id is its Object.ID, and a referenced object without one gets "_<i>" (its index in objs). "id" is written only for objects that have one after that, so a document without references has no ids. A reference to an entity that is not among objs, and two objects with the same id, are errors.
An Object with a Prefab is written as an instance of that prefab (found through the world's PrefabSource): "prefab" instead of group and class, and as "components" only what differs from the prefab (a removed optional component is null); "components" is left out when nothing differs. The objects of an instance with Object.Part set (their ID is `<root ID>/<Part>`) are not entries of their own: they are folded into the root's "children", again as what differs from the prefab, and a part of the prefab that is not among objs is written as null. A part without its root among objs, or with another ID, is an error.
Panics with "ecs: invalid or stale entity: <e>" if any Entity is stale (see the ecs panic table).
func SerializeComponents ¶
func SerializeComponents(world *ecs.World, group, class string, e ecs.Entity) (json.RawMessage, error)
SerializeComponents returns the JSON `components` object of e (a map of component key "group:name" to its JSON value), as described by the schema registered as group:class. Optional components e lacks are left out; a missing required component is an error. Use it to embed object data in your own file format. It has no document, so a non-zero entity reference is an error ("no Refs for entity reference"); use EncodeComponent with Refs for those.
Panics with "ecs: invalid or stale entity: <e>" if e is stale.
func SetAssetResolver ¶
func SetAssetResolver(world *ecs.World, r AssetResolver)
SetAssetResolver makes r the world's AssetResolver, used by Deserialize and SerializeComponents for components with asset properties. It is a world resource of type AssetResolver (an interface), so other code can read it with ecs.GetResourceOrNil[types.AssetResolver].
func SetPrefabSource ¶
func SetPrefabSource(world *ecs.World, src PrefabSource)
SetPrefabSource makes src the world's PrefabSource, used by Deserialize for object entries with a "prefab" and by Serialize for objects with Object.Prefab. It is a world resource of type PrefabSource (an interface).
Types ¶
type AssetResolver ¶
type AssetResolver interface {
// ResolveAsset loads (or finds) the asset behind path and returns its
// handle. The result must be assignable to the Go type of the field.
ResolveAsset(kind, path string) (any, error)
// AssetKey returns the key of handle h, which is the (non-zero) value
// of a field of the given kind. It is the inverse of ResolveAsset.
AssetKey(kind string, h any) (string, error)
}
AssetResolver converts between the asset keys of serialized data and the runtime handles stored in components. The engine implements it on top of its asset server; god knows nothing about handle types.
A schema property with Format "asset" and XAsset kind is a string key (e.g. "chars/hero.aseprite.json#run") in JSON and a handle in the Go field. The kind ("sprite", "clip", "font", ...) is a free string that only the resolver interprets.
Lifetime: the interface has no scope parameter. An implementation loads into whatever scope it currently holds, so releasing that scope frees what a Deserialize call loaded. Deleting an entity releases nothing.
type BoundPrefab ¶
type BoundPrefab struct {
// contains filtered or unexported fields
}
BoundPrefab is a Prefab decoded for one World: its component values, with asset keys already resolved, ready to be copied into new entities. Get one with Prefab.Bind. Like the World it is single-goroutine.
func (*BoundPrefab) Prefab ¶
func (b *BoundPrefab) Prefab() *Prefab
Prefab returns the prefab b was bound from.
func (*BoundPrefab) Spawn ¶
func (b *BoundPrefab) Spawn(overrides ...any) ecs.Entity
Spawn creates one entity per object of the prefab, each with the object's components, its ObjectClass and its PrefabInstance tag, and returns the root. Each override is a component value (a T, not *T) that replaces the root's value of that type, or adds a component the root lacks (any registered component type, see RegisterComponent): typically the position, which moves a group whose parts follow the root.
e := goblin.Spawn(gfx.Transform{Pos: at, Scale: gfx.Vec2{X: 1, Y: 1}})
No JSON is read: the values were decoded by Bind. Entity references between the objects are patched into a copy of the decoded value, which costs one allocation per component with references; only a reference below a slice, a map or a pointer is decoded from JSON per spawn. To get the other entities use BoundPrefab.SpawnAll.
Panics with "god: Spawn: <T> is not a registered component" for an override of a type that is neither in the prefab's class nor in the component registry, and with the ecs panics of NewEntity.
func (*BoundPrefab) SpawnAll ¶
SpawnAll is BoundPrefab.Spawn that appends every spawned entity to dst in Prefab.Parts order, the root first, and returns it. A caller that reuses dst allocates nothing for the slice.
type Component ¶
type Component struct {
// Group and Name identify the component type. Key() ("group:name") is
// the key of the component in JSON instances.
Group string `json:"-"`
Name string `json:"-"`
// Field is the Go field name of the component in the object struct. It
// is documentation (and Go sugar): instances are keyed by Key().
Field string `json:"field,omitempty"`
// Optional components may be absent from an instance. They are
// suggestions for editors, not a limit: an object may also hold any
// other registered component type (see [ObjectComponents]).
Optional bool `json:"optional,omitempty"`
// Readonly marks a value component (copied out on Get). It is always required.
Readonly bool `json:"readonly,omitempty"`
// RuntimeID is the runtime ID of the component type. It is only valid for the
// current running instance of the program and is not persisted.
RuntimeID ecs.ComponentID `json:"-"`
// Schema describes the JSON form of the component.
Schema *TypeSchema `json:"schema,omitempty"`
// Doc is the doc comment of the object field that declares the component.
// Documentation only: not compared by RegisterSchema.
Doc string `json:"doc,omitempty"`
// EmbeddedVia lists the embedded objects the component is promoted
// through, outermost first (e.g. ["Common"]); empty when the object
// declares it directly. Documentation only: not compared by RegisterSchema.
EmbeddedVia []string `json:"embeddedVia,omitempty"`
// Decode unmarshals JSON into a value of the component type T (not *T),
// ready to be stored in a World.
Decode func(json.RawMessage) (any, error) `json:"-"`
}
Component is one component of an object schema: a reference to a component type (identified by Group and Name, see ComponentSchema) plus how the object uses it.
In JSON (the GOD and the editor protocol) the identity is one key, "component": "group:name"; Schema is left out when nil, as in the object entries of a GOD file, where each component schema appears once at the top level.
func ComponentOf ¶
ComponentOf returns how an object of class s holds the component with key "group:name": the class's own entry, or, for any other component type in the component registry, an optional Component built from its ComponentSchema. ok is false for a key that names neither.
func ObjectComponents ¶
ObjectComponents returns the components of an object of class s that has the component keys keys: every component of the class in declaration order, then every other key that names a registered component type, sorted, as optional components (see ComponentOf). Keys that name no registered type are left out; CheckComponents reports them.
func (Component) Key ¶
Key returns the component's key "group:name", which names it in JSON instances, prefab overrides and error messages.
func (Component) MarshalJSON ¶
MarshalJSON writes the component with its identity as "component": "group:name".
func (*Component) UnmarshalJSON ¶
UnmarshalJSON reads the form MarshalJSON writes.
type ComponentSchema ¶
type ComponentSchema struct {
// Group and Name identify the component type. Name defaults to the Go
// type name, Group to the declaring package's group (see the
// +game:component marker). Neither contains ':'.
Group string `json:"group"`
Name string `json:"name"`
// Doc is the doc comment of the Go type. Documentation only.
Doc string `json:"doc,omitempty"`
// GoType is the Go type, "importpath.Type". Documentation only.
GoType string `json:"goType,omitempty"`
// Schema describes the JSON form of the component.
Schema *TypeSchema `json:"schema"`
// RuntimeID is the runtime ID of the component type. It is only valid
// for the current running instance of the program and is not persisted.
RuntimeID ecs.ComponentID `json:"-"`
// Decode unmarshals JSON into a value of the component type T (not *T).
Decode func(json.RawMessage) (any, error) `json:"-"`
}
ComponentSchema describes a component type: its identity and its JSON form. Every object that uses the type refers to it by Key(); the GOD lists each component type once (its "components").
func DataOnlyComponent ¶
func DataOnlyComponent(key string) (ComponentSchema, bool)
DataOnlyComponent returns the schema of the data-only component type with key "group:name" (see RegisterDataOnly). It reports false for a registered component type, which LookupComponent returns, and for an unknown key. Decode and RuntimeID of the result are unset.
func DataOnlyComponents ¶
func DataOnlyComponents() []ComponentSchema
DataOnlyComponents returns the data-only component types, sorted by key.
func LookupComponent ¶
func LookupComponent(group, name string) (ComponentSchema, bool)
LookupComponent returns the component type registered as group:name.
func (ComponentSchema) Key ¶
func (c ComponentSchema) Key() string
Key returns the component's key "group:name".
type EditorHints ¶
type EditorHints struct {
// Name is the label shown instead of the Go field name.
Name string `json:"name,omitempty"`
// Min, Max and Step bound and step a number (for an array or an object of
// numbers, each element). They guide the widget (a slider when Min and Max
// are set); they do not validate. With Unit "deg" they are in degrees.
Min *float64 `json:"min,omitempty"`
Max *float64 `json:"max,omitempty"`
Step *float64 `json:"step,omitempty"`
// Unit labels the value ("s", "px", "px/s"). The unit UnitDegrees means
// the stored number is in radians and the editor shows degrees.
Unit string `json:"unit,omitempty"`
// Order sorts the property among its siblings, lowest first; properties
// without an Order come after the ones that have it, in declaration order.
Order *int `json:"order,omitempty"`
// Color asks for a color picker; the property is an object with R, G, B
// and A or an array of 3 or 4 numbers.
Color bool `json:"color,omitempty"`
// Hidden keeps the property out of the editor's property list. It stays
// in the file.
Hidden bool `json:"hidden,omitempty"`
// ShowIf shows the property only while a condition on a sibling holds.
ShowIf *ShowIf `json:"showIf,omitempty"`
}
EditorHints say how an editor shows and edits a property. Every field is optional; the zero value means "no hint".
type EnumValue ¶
type EnumValue struct {
Value int64 `json:"value"`
Name string `json:"name"` // the Go constant name, e.g. "EmitCircle"
// Doc is documentation text (the constant's doc comment). Like
// Description it has no effect on validation and is left out of
// generated Go.
Doc string `json:"doc,omitempty"`
}
EnumValue is one member of an x-enum: a Go constant of the enum type.
type ExpandedObject ¶
type ExpandedObject struct {
// ID is the object's id in the document: the entry's ID for the root,
// `<entry ID>/<Part>` for a part.
ID string
// Group and Class are the object's type.
Group, Class string
// Components are the complete components: the prefab's merged with the
// overrides. They are not validated against the schema (see
// [CheckComponents]); values the prefab holds are shared and must not
// be modified.
Components map[string]json.RawMessage
// Part is the id of the object within the prefab ("sword",
// "horse/saddle"), or "" for the root.
Part string
}
ExpandedObject is one plain object of an expanded prefab instance.
type Object ¶
type Object struct {
SchemaMeta
// ID is the object's document id ("id" in the document), unique within
// one document. It is empty for objects without one. Entity references
// (component fields of type ecs.Entity) point at objects by ID.
ID string
// Prefab is the key of the prefab the object is an instance of, or "".
// Deserialize fills it for entries with a "prefab", [Objects] from the
// entity's [PrefabInstance] tag; Serialize then writes only what
// differs from the prefab.
Prefab string
// Part is the id within the prefab of an object that is not the root of
// its instance: `sword` or `horse/saddle` for an object of a
// multi-object prefab. It is "" for plain objects and instance roots.
// Its ID is `<root ID>/<Part>`. Deserialize returns the parts of an
// instance right after its root, in prefab order; Serialize folds them
// back into the root's entry as "children".
Part string
Entity ecs.Entity
}
Object pairs an object's identity (group:class) with the entity that holds its components. Deserialize returns these in document order; passing the result straight to Serialize writes back the same document shape.
func Deserialize ¶
Deserialize reads a JSON document of the form
{"objects": [{"id": "hero", "group": "g", "class": "c", "components": {"g:Comp": {...}}}, ...]}
and creates one entity per object in world, with the object's components and its ObjectClass tag. "id" is optional and must be unique; component fields of type ecs.Entity hold the id of another object of the document (or null), forward references included. Each object is checked against its registered schema: missing required components and components that are not registered are errors; an object may hold any registered component type, not only those of its class. It returns the objects in input order. On error no entity of this call remains in the world.
An entry with "prefab": "<key>" is an instance of that prefab, found through the world's PrefabSource: group and class may be left out, and its components are overrides merged over the prefab's (see Prefab). Such entities also get a PrefabInstance tag. An instance of a prefab with several objects (it needs an "id") also creates the other objects, returned right after the root with ids `<id>/<part>` and Object.Part set; "children" overrides them (see PrefabEntry). Authored ids must not contain "/".
type ObjectClass ¶
type ObjectClass struct {
// contains filtered or unexported fields
}
ObjectClass is a component that records which registered object type (group:class) an entity is. Deserialize adds it to every entity it creates; code that spawns objects itself can add the value returned by ClassTag. It is in no object schema, so Serialize never writes it.
The value is an index into the process's registered schemas: 4 bytes, no pointers. It is only meaningful in the running process; never persist it. The zero value is no class.
func ClassTag ¶
func ClassTag(group, class string) (ObjectClass, bool)
ClassTag returns the ObjectClass of the schema registered as group:class, and false if there is none.
func (ObjectClass) Meta ¶
func (c ObjectClass) Meta() SchemaMeta
Meta returns the group and class c stands for, and the zero SchemaMeta for the zero ObjectClass.
type Prefab ¶
type Prefab struct {
// contains filtered or unexported fields
}
Prefab is a parsed, validated prefab: pre-defined Game Objects whose component values are filled in, stored as a GOD document (`*.prefab.json`) of one or more objects. The first object is the root. Documents place it with an object entry `{"id": ..., "prefab": "<key>", "components": {<overrides>}, "children": {<part>: <overrides>}}` and game code spawns copies with Prefab.Bind and BoundPrefab.Spawn.
A prefab with several objects is spawned as a group: the other objects are its parts, and entity references between the objects are remapped to each copy. This package does not know what ties the parts together; the engine requires every part to be attached to the root through `hierarchy:Parent`.
A variant is a prefab whose first object is itself an instance of another prefab (its "base"); its objects are the base's, merged with its own, followed by its other objects. An object after the first may be an instance of another prefab too (a nested prefab); its objects join the list as parts with qualified ids (`horse`, `horse/saddle`).
A Prefab is immutable and safe for concurrent use.
func ParsePrefab ¶
func ParsePrefab(key string, data []byte, src PrefabSource) (*Prefab, error)
ParsePrefab parses data, the content of the prefab file key: a GOD document with one or more objects. A prefab with several objects needs an "id" on each of them, and ids must not contain "/". The first object may name a base prefab ("prefab"), and any other may be an instance of a prefab to nest, which src must return; a missing src is then an error. Every component is validated against its object's schema after merging, and every entity reference must name an object of the prefab, so a Prefab always holds complete, valid objects. Errors start with `prefab "<key>": ` and are all reported.
func (*Prefab) Bind ¶
func (p *Prefab) Bind(world *ecs.World, assets AssetResolver) (*BoundPrefab, error)
Bind decodes p's components for world, resolving asset keys with assets (nil means the world's AssetResolver, see SetAssetResolver). Handles it resolves are held by whatever scope the resolver loads into. Bind once and spawn many times.
func (*Prefab) Component ¶
func (p *Prefab) Component(key string) (json.RawMessage, bool)
Component returns the expanded JSON of the root's component with key "group:name" and whether the root has it. The result must not be modified.
func (*Prefab) Expand ¶
func (p *Prefab) Expand(group, class string, overrides map[string]json.RawMessage) (map[string]json.RawMessage, error)
Expand returns the components of an instance of p's root: overrides, the "components" of a document entry that names p as its "prefab", merged over the root's components (objects merge key by key, other values replace, an override of null removes an optional component). group and class are the entry's: empty, or p's object type. The result is not validated against the schema (see CheckComponents); the prefab's own values are shared and must not be modified. Errors name the component and the JSON path.
Expand knows only the root and does not rewrite entity references; for a prefab with several objects use Prefab.ExpandInstance.
func (*Prefab) ExpandInstance ¶
func (p *Prefab) ExpandInstance(e PrefabEntry) ([]ExpandedObject, error)
ExpandInstance turns an entry that names p as its prefab into plain objects, the root first and the other objects in prefab order. The prefab's entity references are rewritten into the document's id space first (the root's id becomes e.ID, a part's `<id>` becomes `<e.ID>/<id>`), then e.Components and e.Children are merged over the objects, so override values are written in the document's ids and may point at any object of the document.
Errors name the component and the JSON path. They include a Children key that is no part of p, a removed part that another object still references, and an entry without an ID for a prefab with several objects.
func (*Prefab) ID ¶
ID returns the "id" of the prefab's root object, or "". Entity references inside the prefab point at the root by it. A variant that names no id of its own has its base's.
func (*Prefab) Meta ¶
func (p *Prefab) Meta() SchemaMeta
Meta returns the object type of the prefab's root.
func (*Prefab) Name ¶
Name returns the document's optional top-level "name", a human-readable label for editors, or "". It labels the file: a variant does not inherit its base's name, and nothing looks prefabs up by it.
func (*Prefab) Overrides ¶
func (p *Prefab) Overrides(comps map[string]json.RawMessage) (map[string]json.RawMessage, error)
Overrides is the inverse of Prefab.Expand: the "components" of an instance of p whose complete root components are comps, as compact JSON. Components and fields equal to the root's are left out, a component of the root that comps lacks is null. Only fields can be overridden: an error is returned for a value that would need to delete a map entry of p.
func (*Prefab) PartComponent ¶
func (p *Prefab) PartComponent(id, key string) (json.RawMessage, bool)
PartComponent is Prefab.Component for the object with id (see Prefab.Parts). It returns false for an unknown id or a component the object lacks.
func (*Prefab) PartIndex ¶
PartIndex returns the position of the object with id in Prefab.Parts, or -1 if there is none.
func (*Prefab) PartOverrides ¶
func (p *Prefab) PartOverrides(rootID, part string, comps map[string]json.RawMessage) (map[string]json.RawMessage, error)
PartOverrides is Prefab.Overrides for one object of an instance whose root has the document id rootID: the "components" (part is "", the root) or the "children" entry (part is the part's id) that turn the prefab's object, expanded for that instance, into comps. Only the keys of comps are looked at, and references in comps are in the document's ids. An unknown part is an error.
func (*Prefab) Parts ¶
Parts returns the ids of the prefab's objects in spawn order, the root first: the order of the entities BoundPrefab.SpawnAll returns. A part of a nested prefab is `<instance id>/<part id>`. The ids of a prefab with one object may be [""].
type PrefabEntry ¶
type PrefabEntry struct {
// ID is the entry's "id": the id of the instance's root. The other
// objects of the instance get `<ID>/<part>`. A prefab with several
// objects needs one.
ID string
// Group and Class may be left out, or must be the prefab's object type.
Group, Class string
// Components are overrides of the root's components, merged over the
// prefab's (see [Prefab.Expand]).
Components map[string]json.RawMessage
// Children maps the id of a part of the prefab (not the root) to
// either an object of component overrides, as in Components, or null,
// which removes the part from this instance.
Children map[string]json.RawMessage
}
PrefabEntry is the object entry of a document that names a prefab: the parts of an `{"id", "prefab", "components", "children"}` entry that Prefab.ExpandInstance reads.
type PrefabInstance ¶
type PrefabInstance struct {
// contains filtered or unexported fields
}
PrefabInstance is a component that records which prefab an entity was made from, and which of its objects it is. Deserialize adds it to the entities of object entries with a "prefab", and BoundPrefab.Spawn to every entity it spawns. Like ObjectClass it is in no object schema, so Serialize never writes it as a component; it writes the entity as an instance of the prefab instead.
The value is two indexes into process-wide tables of prefab keys and part ids: 8 bytes, no pointers, meaningless outside the running process. The zero value is no prefab.
func PrefabPartTag ¶
func PrefabPartTag(key, part string) PrefabInstance
PrefabPartTag is PrefabTag for an object other than the root: part is its id within the prefab ("sword", "horse/saddle"). An empty part is the root.
func PrefabTag ¶
func PrefabTag(key string) PrefabInstance
PrefabTag returns the PrefabInstance component that marks an entity as the root of an instance of the prefab key, for code that creates instances without Deserialize or BoundPrefab.Spawn (the level editor). Keys are interned for the life of the process.
func (PrefabInstance) Key ¶
func (p PrefabInstance) Key() string
Key returns the prefab key p stands for, or "" for the zero value.
func (PrefabInstance) Part ¶
func (p PrefabInstance) Part() string
Part returns the id of the object within the prefab that p stands for, or "" for the root.
type PrefabMap ¶
PrefabMap is a PrefabSource over a fixed set of prefabs, keyed by Prefab.Key.
type PrefabSource ¶
type PrefabSource interface {
// Prefab returns the prefab stored under key, or an error if there is
// none or it is not available (not loaded yet, failed).
Prefab(key string) (*Prefab, error)
}
PrefabSource finds prefabs by key for Deserialize, Serialize and ParsePrefab (the base of a variant). The engine implements it on top of its asset server; PrefabMap is a fixed set.
type Refs ¶
type Refs interface {
// RefID returns the document id of e, for encoding.
RefID(e ecs.Entity) (string, error)
// RefEntity returns the entity of document id, for decoding.
RefEntity(id string) (ecs.Entity, error)
}
Refs maps between the entities of a World and the object ids of a document, for component fields of type ecs.Entity (schema format "entity"). DecodeComponent calls RefEntity for every non-null id it reads, EncodeComponent calls RefID for every non-zero Entity it writes.
func ObjectRefs ¶
ObjectRefs returns the Refs of a set of objects: an object's id is its Object.ID. RefEntity fails for an id no object has, RefID for an entity that is not among objs or whose object has no id. The objects are read when ObjectRefs is called.
type Schema ¶
type Schema struct {
SchemaMeta
// Doc is the doc comment of the object type. Documentation only.
Doc string `json:"doc,omitempty"`
// GoType is the Go struct of the object, "importpath.Type". Documentation
// only: RegisterSchema does not compare it.
GoType string `json:"goType,omitempty"`
// Components are the object's components in declaration order. A component
// is required unless Optional is set.
Components []Component `json:"components"`
}
Schema describes a game object: the components it is made of.
func LookupSchema ¶
LookupSchema returns the schema registered under group and class.
type SchemaMeta ¶
type SchemaMeta struct {
// Group is the group to which the object belongs.
Group string `json:"group"`
// Class is the class within the group.
Class string `json:"class"`
}
SchemaMeta identifies a game object for external systems.
func ClassOf ¶
ClassOf returns the object type of e. An entity with an ObjectClass component is that class. Otherwise the class is inferred from e's components: candidates are the schemas whose required components e all has, and the one with the most of its components (required and optional) present wins. A tie, or no candidate, returns false, as does an entity with no registered schema at all.
Inference costs O(schemas × components) component lookups: fine for tools, not for per-tick game code.
Panics with "ecs: invalid or stale entity: <e>" if e is stale.
func (SchemaMeta) Key ¶
func (m SchemaMeta) Key() string
Key returns the registry key "group:class". Groups may contain ':' (import paths do not, but explicit values are free-form), so splitting uses the last ':'.
type ShowIf ¶
type ShowIf struct {
Field string `json:"field"`
Equals json.RawMessage `json:"equals,omitempty"`
Not bool `json:"not,omitempty"`
}
ShowIf is a condition on a sibling property of the same struct. Without Equals the sibling must be truthy (true, a non-zero number, a non-empty string); with it, the sibling must equal the JSON value (an enum is compared by its integer). Not negates the result.
type TypeSchema ¶
type TypeSchema struct {
Type string `json:"type,omitempty"`
Format string `json:"format,omitempty"` // int32, int64, float, double, byte, asset, entity, color
Nullable bool `json:"nullable,omitempty"`
// Description is documentation text (the Go doc comment of a type or
// field). It has no effect on validation and is left out of generated Go.
Description string `json:"description,omitempty"`
Properties map[string]*TypeSchema `json:"properties,omitempty"`
Required []string `json:"required,omitempty"`
AdditionalProperties *TypeSchema `json:"additionalProperties,omitempty"`
Items *TypeSchema `json:"items,omitempty"`
MinItems *int `json:"minItems,omitempty"`
MaxItems *int `json:"maxItems,omitempty"`
Minimum *float64 `json:"minimum,omitempty"`
Maximum *float64 `json:"maximum,omitempty"`
// Default is the value of a property that a file leaves out, declared
// with +game:default: decoding fills it in (see Fill), editors show it
// and start new components with it (see InitialValue), and writing leaves
// a property out when it equals it (see Prune). Without a Default the Go
// zero value is the default. The generator has already checked it
// against the schema; Validate does not.
Default json.RawMessage `json:"default,omitempty"`
// XEnum lists the named values of an integer type marked +game:enum,
// sorted by value. When set, Validate accepts only these values. The wire
// value stays the integer; the names are for tools such as the editor.
XEnum []EnumValue `json:"x-enum,omitempty"`
// GoType names a Go type with a custom JSON encoding (e.g. "time.Time"). Its
// wire shape is not described and not validated.
GoType string `json:"x-go-type,omitempty"`
// XEntityRefs marks a value of free shape (a custom-JSON type declared
// with +game:entityrefs) that holds entity references as
// {"$entity": ref} objects anywhere inside it: in a document ref is an
// object id, in the type's own JSON the encoded ecs.Entity. The codec
// maps them like fields of format entity.
XEntityRefs bool `json:"x-entity-refs,omitempty"`
// XAsset is the asset kind ("sprite", "clip", "font", ...) of a string
// property with Format "asset". The string is an asset key
// ("chars/hero.aseprite.json#run"); Deserialize and SerializeComponents
// convert it to and from the runtime handle through the world's
// AssetResolver. The kind is a free string interpreted by the resolver.
XAsset string `json:"x-asset,omitempty"`
// XRuntime marks a property of runtime state (e.g. animation playback
// time). It is part of the schema for tools and scripts, but it is not
// authored data: Serialize omits it and Validate rejects it in input.
XRuntime bool `json:"x-runtime,omitempty"`
// XEditor holds hints for tools that edit the value, declared with
// +game:editor. They are like Default: editor data with no effect on
// validation or decoding, kept in the compiled schema so that an editor
// built into the game sees them.
XEditor *EditorHints `json:"x-editor,omitempty"`
// PreserveUnknownFields marks a value of unknown shape (interfaces,
// recursive types, ...). It is not validated.
PreserveUnknownFields bool `json:"x-preserve-unknown-fields,omitempty"`
}
TypeSchema describes the JSON form of a component or one of its parts. It is a subset of OpenAPI v3 / JSON Schema: the same keywords with the same meaning, plus the x- extensions below.
Type is one of "object", "array", "string", "integer", "number" and "boolean". Structs are objects with Properties (keyed by JSON name) and Required; maps are objects with AdditionalProperties. Unknown properties of an object with Properties are invalid.
func MustParseSchema ¶
func MustParseSchema(data string) *TypeSchema
MustParseSchema decodes a TypeSchema from its JSON form and panics on error.
func (*TypeSchema) Fill ¶
func (s *TypeSchema) Fill(raw json.RawMessage) (json.RawMessage, error)
Fill returns raw with every property it leaves out filled in: a missing property of an object with Properties takes the TypeSchema.InitialValue of its schema (its Default, else its zero value), and a present object value is filled the same way, recursively. Arrays and maps are values: a present one is kept whole. Runtime properties and pointer properties without a Default stay absent (nil is their zero value). This is how DecodeComponent reads a component, so a file may leave out any field; see doc/guide/god/game-object-definition.md#defaults.
Fill does not validate: unknown properties and wrong types pass through for TypeSchema.Validate to report. It returns raw itself, without allocating beyond the parse, when nothing is missing, and an error only when raw is not JSON. Not for per-tick paths: it parses raw.
func (*TypeSchema) InitialValue ¶
func (s *TypeSchema) InitialValue() json.RawMessage
InitialValue is the JSON an editor writes for a new value of this schema: the Default when set, else for an object the initial value of each property, else the zero value (arrays get MinItems zero elements, numbers 0, booleans false, strings "", colors "#00000000", and entity references and values of unknown shape null). Runtime properties are left out, as they are not authored data, and so are pointer properties without a Default: nil is their zero value and means "not set" (the editor offers an override), so a new component does not override what another source, such as a particle effect's file, provides. A nil schema yields null.
func (*TypeSchema) IsDefault ¶
func (s *TypeSchema) IsDefault(raw json.RawMessage) bool
IsDefault reports whether raw is what a property of this schema stands for when a file leaves it out (see TypeSchema.Fill): null for a pointer without a Default, else the initial value, numbers compared by value. An editor uses it to remove a property that is set back to its default. It is false for runtime properties and for raw that is not JSON.
func (*TypeSchema) Prune ¶
func (s *TypeSchema) Prune(raw json.RawMessage) (json.RawMessage, error)
Prune is the inverse of TypeSchema.Fill, for writing: it leaves out every property of an object with Properties whose value equals the property's initial value (numbers compared by value, so 1 equals 1.0), and prunes the object values that differ the same way, recursively. Properties listed in Required are always kept (generated schemas list none). A pointer property without a Default is left out when it is null. Arrays, maps and scalars are written whole. So a component equal to its initial value becomes {}, and a Transform at (40, 96) becomes {"Pos":{"X":40,"Y":96}}.
Prune(Fill(raw)) equals Prune(raw). Prune returns compact JSON with sorted keys for objects (raw itself for any other schema), and an error only when raw is not JSON. Not for per-tick paths.
func (*TypeSchema) Validate ¶
func (s *TypeSchema) Validate(raw json.RawMessage) error
Validate checks that raw conforms to the schema. All violations are reported, each with the path of the offending value (e.g. "$.Pos.X").
func (*TypeSchema) WithoutDescriptions ¶
func (s *TypeSchema) WithoutDescriptions() *TypeSchema
WithoutDescriptions returns a deep copy of s with every Description (and every EnumValue.Doc) removed. Documentation is not part of a schema's identity, so the generator strips it from the schemas it compiles into Go and RegisterSchema compares schemas without it.