{"modulePath":"github.com/weakpixel/engine","version":"v0.0.0-20261205071607-94fff0387040","isLatest":true,"isStandardLibrary":false,"goos":"all","goarch":"all","docs":"# package script\n\n\\+game:group:name=script\n\nPackage script runs goscript scripts inside a game.Engine.\n\n[Install](#Install) wires the runtime into an Engine: it builds the script environment from the registered Game Object components, registers the script asset kind (\\*.gs files, compiled on an asset worker and hot reloaded) and returns the [Runtime](#Runtime). [System](#System) then makes a script a game.Runner:\n\n\trt := script.Install(e, script.Config{})\n\te.AddRunner(game.StageSimulate, script.System(\"systems/movement.gs\"))\n\nA system script defines Init() (run once, when the system is set up and after every reload) and Update(dt) (run every tick with ctx.Time.Dt):\n\n\tfunc Update(dt) {\n\t\tfor e := range world.Query(gfx.Transform, game.Velocity) {\n\t\t\te.gfx.Transform.Pos += e.game.Velocity.V * dt\n\t\t}\n\t}\n\nScripts reach components as e.group.Name, resources as world.group.Name, and change the world through world.Spawn, world.Despawn and world.Remove, which queue like ctx.Commands. Reading and writing component fields, vector math and query loops allocate nothing.\n\nThe guide is doc/guide/engine/scripting.md; the language is doc/design/goscript.md.\n\n## Constants\n\n```go\nconst AssetKindScript = \"script\"\n```\nAssetKindScript is the asset kind of a [Script](#Script) (a \\*.gs file): the name a component field carries in its +game:asset:kind=... marker, as [Behavior.Script](#Behavior.Script) does.\n\n```go\nconst DefaultBudget = 1_000_000\n```\nDefaultBudget is the budget of one script call when Config.Budget is 0: about a million loop iterations and calls.\n\n```go\nconst ParamMarker = \"+script:param\"\n```\nParamMarker is the marker that describes a parameter, on the line of its var or in its doc comment:\n\n\tvar Speed = 40.0 // +script:param min=0 max=200 step=5 label=\"Top speed\"\n\n```go\nconst Suffix = \".gs\"\n```\nSuffix is the file suffix of script assets.\n\n## Variables\n\n```go\nvar (\n\t// Vec2Type is xmath.Vec2 in scripts: two float32, written vec2(x, y) or\n\t// Vec2{X: x, Y: y}, with + and - between vectors, * and / by a number,\n\t// unary -, the fields X and Y and the methods Len, Norm, Dot and Angle.\n\tVec2Type = \u0026goscript.Type{Name: \"Vec2\", Inline: true}\n\t// ColorType is gfx.Color in scripts: rgba(r, g, b, a) with 0..255\n\t// channels, the int fields R, G, B and A, printed as \"#rrggbbaa\".\n\tColorType = \u0026goscript.Type{Name: \"Color\", Inline: true}\n)\n```\nThe engine's value types. Vec2 and Color are inline (the whole value is in the 64 bits of a goscript.Value), so making and computing with them allocates nothing. The types are process-wide: their hooks hold no state.\n\n```go\nvar (\n\tCID_Bag      = ecs.RegisterComp[Bag]()\n\tCID_Behavior = ecs.RegisterComp[Behavior]()\n)\n```\n\n## Functions\n\n```go\nfunc AsColor(v goscript.Value) (gfx.Color, bool)\n```\nAsColor returns the color v holds and true when v is a Color.\n\n```go\nfunc AsVec2(v goscript.Value) (xmath.Vec2, bool)\n```\nAsVec2 returns the vector v holds and true when v is a Vec2.\n\n```go\nfunc Behaviors() game.Runner\n```\nBehaviors returns the game system that runs behaviors: the scripts of the entities with a [Behavior](#Behavior) that its scene owns ([game.Engine.SceneOf](/github.com/weakpixel/engine/game#Engine.SceneOf)). Add it to StageSimulate of the root, and of every scene whose entities have behaviors, where it fits against the other systems:\n\n\te.AddRunner(game.StageSimulate, input, script.Behaviors(), game.Wrap(phys))\n\nEvery Run, for each behavior entity of the scene, it calls the script's\n\n  - Spawn(self) the first time it runs the entity's script, before its Update;\n  - Update(self, dt) with ctx.Time.Dt;\n  - Despawn(self) once the entity is dead or lost its Behavior, at the end of a Run; a dead self fails component access, so the function is for the script's own bookkeeping (world.Alive(self) tells which);\n\nand before those, for the tick's collision events whose Self is such an entity, Enter(self, other), Stay(self, other) and Exit(self, other) (collision.Enter, Stay, Exit) and Impact(self, other) (physics.Impact). Every function is optional. Each call runs with the entity's parameters ([Behavior.Params](#Behavior.Params) over the script's defaults) swapped in.\n\nA script's module (its lowercase top-level vars) is shared by every entity that runs it, in every scene. When the file is reloaded, the next Run loads it again with fresh top-level vars and rebuilds each entity's parameters; Spawn does not run again, and bags keep their data.\n\nRuntime errors go to Config.OnError with the script position and the entity; the entity runs again next tick. Bad parameters and overrides go to game.Config.OnAssetError. Init panics with \"script: Install was not called for this Engine\" when the Engine has no runtime.\n\n```go\nfunc ColorValue(c gfx.Color) goscript.Value\n```\nColorValue returns c as a script value.\n\n```go\nfunc Load(sc *asset.Scope, key string) gfx.ScriptHandle\n```\nLoad returns the handle for a script key (\"enemies/bat.gs\") and adds a hold for sc. It never blocks; the script compiles on an asset worker. It panics like [asset.Load](/github.com/weakpixel/asset#Load), also when [Install](#Install) has not run for the Engine that owns sc's server.\n\n```go\nfunc LoadSync(sc *asset.Scope, key string) (gfx.ScriptHandle, error)\n```\nLoadSync is Load followed by loading until the script is compiled or failed, like [asset.LoadSync](/github.com/weakpixel/asset#LoadSync). It blocks: use it for setup, tests and tools.\n\n```go\nfunc ParamSchema(params []Param) *god.TypeSchema\n```\nParamSchema returns the GOD schema of a [Behavior.Params](#Behavior.Params) for a script with params: an object with one property per parameter, in script order (x-editor order), each with the script's default, its label (x-editor name), min, max and step, enums as x-enum. A Vec2 is an object of X and Y, a Color a string of format color, an asset parameter a string of format asset with its kind (x-asset) and no default. Entity parameters are in [RefSchema](#RefSchema), and parameters without a type are left out. Editors draw overrides with it; the runtime does not validate Params against it.\n\n```go\nfunc RefSchema(params []Param) *god.TypeSchema\n```\nRefSchema returns the GOD schema of a [Behavior.Refs](#Behavior.Refs) for a script with params: an object with one nullable entity reference per Entity parameter, with its label and script order (x-editor name and order).\n\n```go\nfunc RegisterResource[T any](group, name string)\n```\nRegisterResource makes the ECS resource of type T (a struct) reachable from scripts as world.group.Name: reading it gives a reference to the World's resource (nil when it is not set), writing its fields writes the resource, and assigning a value of the type replaces it with a copy (ecs.SetResource). Register resource types before [Install](#Install), like component types; registering the same type under the same key again is a no-op.\n\nPanics with \"script: resource group and name must be identifiers\" and \"script: resource group:name registered twice with different types\".\n\n```go\nfunc System(key string) game.Runner\n```\nSystem returns a game system that runs the script file key. Add it to a stage like any runner:\n\n\te.AddRunner(game.StageSimulate, script.System(\"systems/movement.gs\"))\n\nIts Init loads the file into the scene's asset scope and waits until it is compiled, then loads the script (top-level vars and init functions) and calls its Init(), if the script defines one. Every Run calls Update(dt) with ctx.Time.Dt, if defined. When the file is reloaded, the next Run loads the new version, with fresh top-level vars, and calls Init() again.\n\nErrors do not stop the game. A file that fails to load or compile is reported to game.Config.OnAssetError, as any asset is, and the system does nothing until a version compiles. A runtime error in Init or Update goes to Config.OnError, and the system runs Update again on the next tick. Init panics with \"script: Install was not called for this Engine\" when the Engine has no runtime.\n\n```go\nfunc Vec2Value(v xmath.Vec2) goscript.Value\n```\nVec2Value returns v as a script value.\n\n## Types\n\n```go\ntype Bag struct {\n\t// contains filtered or unexported fields\n}\n```\nBag is a data bag: string-keyed, dynamic script data. As a component it holds one entity's data (e.script.Bag in scripts); as a resource, data scripts share (world.script.Bag). In GOD files it is a JSON object of plain data: numbers, strings, bools, lists and objects, and entities as {\"$entity\": \"\\\u003cobject id\u003e\"}, mapped like entity fields.\n\n\\+game:component +game:entityrefs\n\n```go\nfunc NewBag(d *goscript.Dict) Bag\n```\nNewBag returns a bag holding d, or an empty one when d is nil.\n\n```go\nfunc (b Bag) Dict() *goscript.Dict\n```\nDict returns the bag's dict, which scripts index. The zero Bag has none and returns nil.\n\n```go\nfunc (b Bag) MarshalJSON() ([]byte, error)\n```\nMarshalJSON writes the bag as a JSON object, an entity as {\"$entity\": {\"ID\": id, \"Generation\": gen}} (god maps it to an object id). It fails on a value that is not plain data or an entity (a function, a struct, another host value) or a key that is not a string, naming the key.\n\n```go\nfunc (b *Bag) UnmarshalJSON(data []byte) error\n```\nUnmarshalJSON reads a JSON object into a fresh dict: integral numbers become ints, other numbers floats, arrays lists, objects dicts, and {\"$entity\": {\"ID\": id, \"Generation\": gen}} entities, which become script values when a script first reads the bag.\n\n```go\ntype Behavior struct {\n\t// Script is the *.gs file. The zero handle, a missing or a failed\n\t// script does nothing until a version compiles.\n\t//\n\t// +game:asset:kind=script\n\tScript gfx.ScriptHandle `json:\"-\"`\n\t// Params overrides the script's parameters (its exported top-level\n\t// vars) for this entity, by name: numbers, strings, bools, Vec2 as\n\t// {\"X\": x, \"Y\": y}, Color as \"#rrggbbaa\" and asset parameters (Sprite,\n\t// Sound, Prefab, ...) as asset keys. A parameter left out keeps\n\t// the script's default. A name the script does not declare, or a value\n\t// of the wrong type, is reported to game.Config.OnAssetError and the\n\t// default is used.\n\tParams map[string]any\n\t// Refs sets the script's entity parameters (vars of type Entity) for\n\t// this entity, by name: in a GOD file the id of another object of the\n\t// same document, or null. A parameter left out reads as nil. Like\n\t// Params, a name the script does not declare is reported to\n\t// game.Config.OnAssetError.\n\tRefs map[string]ecs.Entity\n\t// contains filtered or unexported fields\n}\n```\nBehavior gives an entity a script: the behavior runner ([Behaviors](#Behaviors)) calls the script's Spawn(self), Update(self, dt), Despawn(self) and event handlers for it. An entity has at most one behavior.\n\n\\+game:component\n\n```go\ntype Config struct {\n\t// OnError receives compile errors of scripts that fail to reload and\n\t// runtime errors of script calls, with the script position. Nil logs\n\t// them with the log package.\n\tOnError func(error)\n\t// Budget bounds the loop iterations and calls of one script call (see\n\t// goscript.Options.Budget). 0 means DefaultBudget; a negative value\n\t// means unlimited.\n\tBudget int64\n\t// Output receives print output. Nil discards it.\n\tOutput io.Writer\n\t// Env, when set, is called with the script environment after the\n\t// engine's own functions and types are in it, so a game can add its own\n\t// (env.Func(\"game.Score\", ...)). It runs once, in Install.\n\tEnv func(env *goscript.Env)\n}\n```\nConfig configures [Install](#Install).\n\n```go\ntype Param struct {\n\t// Name is the var's name.\n\tName string\n\t// Type is the annotation, or the kind of the default when the var has\n\t// none.\n\tType ParamType\n\t// Default is the value the script's initializer gave the var.\n\tDefault goscript.Value\n\t// Min, Max and Step bound a number in the editor (marker min=, max=,\n\t// step=); nil when not set.\n\tMin, Max, Step *float64\n\t// Label is the editor's label (marker label=\"...\"); empty means Name.\n\tLabel string\n\t// Enum names the values 0, 1, ... of an int parameter (marker\n\t// enum=idle,chase,flee); an override may use a name instead of the\n\t// number.\n\tEnum []string\n\t// Pos is where the var is declared.\n\tPos token.Position\n}\n```\nParam is a parameter of a behavior script: an exported top-level var, which the editor shows on each entity that uses the script and which each entity may override ([Behavior.Params](#Behavior.Params)).\n\n```go\ntype ParamType string\n```\nParamType is the type of a behavior parameter.\n\n```go\nconst (\n\tParamInt    ParamType = \"int\"\n\tParamFloat  ParamType = \"float\"\n\tParamBool   ParamType = \"bool\"\n\tParamString ParamType = \"string\"\n\tParamVec2   ParamType = \"Vec2\"\n\tParamColor  ParamType = \"Color\"\n\t// ParamEntity is another object of the level, set in [Behavior.Refs].\n\tParamEntity ParamType = \"Entity\"\n)\n```\nParameter types.\n\n```go\nfunc (t ParamType) AssetKind() string\n```\nAssetKind is the asset kind of an asset type's keys (\"sprite\", \"sound\", ...), \"\" for other types.\n\n```go\nfunc (t ParamType) IsAsset() bool\n```\nIsAsset reports whether t is an asset handle type (Sprite, Sound, Prefab, ...), whose overrides in [Behavior.Params](#Behavior.Params) are asset keys.\n\n```go\ntype Runtime struct {\n\t// contains filtered or unexported fields\n}\n```\nRuntime is the script runtime of one Engine: the script environment, the VM every script of the Engine runs on, and the per-call state. Get it from [Install](#Install) or [Of](#Of). Like the Engine it is single-goroutine.\n\n```go\nfunc Install(e *game.Engine, cfg Config) *Runtime\n```\nInstall builds the script runtime of e and returns it. It registers the script asset type on e's asset server and on e's library (when it has one), and builds the script environment from the Game Object components registered at this point ([god.Components](/github.com/weakpixel/engine/god#Components)) and the resource types registered with [RegisterResource](#RegisterResource): register game types before calling it, as with every Install.\n\nPanics with \"script: Install called twice for this Engine\".\n\n```go\nfunc Of(w *ecs.World) *Runtime\n```\nOf returns the runtime installed on the Engine that owns w, or nil.\n\n```go\nfunc (rt *Runtime) Env() *goscript.Env\n```\nEnv returns the script environment. Scripts compiled against it can run on this runtime only. Do not change it after the first script compiled.\n\n```go\nfunc (rt *Runtime) ParamsOf(prog *goscript.Program) ([]Param, error)\n```\nParamsOf loads prog into a throwaway module and describes its parameters, as a behavior runner would: for tools such as the level editor, which show a script's parameters before anything runs it. The module's top-level initializers run outside a script call, so one that touches the world (world.Spawn, a component) fails with an error instead of changing the game. Problems with markers or types are returned joined, next to the parameters that could be described.\n\n```go\nfunc (rt *Runtime) ScriptParams(h gfx.ScriptHandle) []Param\n```\nScriptParams returns the parameters of the behavior script h as loaded by a behavior runner: name, type, default and editor hints. It returns nil until a runner has run an entity with the script.\n\n```go\nfunc (rt *Runtime) VM() *goscript.VM\n```\nVM returns the VM every script of the runtime runs on.\n\n```go\ntype Script struct {\n\t// Program is the compiled script. It is immutable and shared by every\n\t// system that runs the file.\n\tProgram *goscript.Program\n}\n```\nScript is a compiled script file (\\*.gs): the asset type that [System](#System) loads. Compiling happens on an asset worker, so a big script never stalls a tick, and hot reload replaces the value when the file changes: a file that fails to compile keeps the last good version and reports the error (with file:line:col) to game.Config.OnAssetError, like any asset that fails to reload.\n\nThe placeholder (a missing or failed first load) has a nil Program.\n\n```go\ntype Store struct {\n\t// contains filtered or unexported fields\n}\n```\nStore resolves [gfx.ScriptHandle](/github.com/weakpixel/engine/gfx#ScriptHandle) values. Get one with [StoreOf](#StoreOf). It is a small value; copy it freely.\n\n```go\nfunc StoreOf(srv *asset.Server) Store\n```\nStoreOf returns the script store of srv. It panics like [asset.StoreOf](/github.com/weakpixel/asset#StoreOf) if [Install](#Install) has not run for the Engine that owns srv.\n\n```go\nfunc (s Store) Err(h gfx.ScriptHandle) error\n```\nErr returns why the script failed to load or compile, or nil.\n\n```go\nfunc (s Store) Generic() *asset.Store[Script]\n```\nGeneric returns the underlying generic store.\n\n```go\nfunc (s Store) Get(h gfx.ScriptHandle) *Script\n```\nGet returns the script, or the placeholder (a nil Program); see [asset.Store.Get](/github.com/weakpixel/asset#Store.Get) for the pointer validity rule. It does not allocate.\n\n```go\nfunc (s Store) Key(h gfx.ScriptHandle) asset.Key\n```\nKey returns the key h was loaded from, or the zero Key for a zero or stale handle.\n\n```go\nfunc (s Store) Lookup(h gfx.ScriptHandle) (*Script, asset.State)\n```\nLookup is Get plus the load state; see [asset.Store.Lookup](/github.com/weakpixel/asset#Store.Lookup).\n\n```go\nfunc (s Store) Ready(h gfx.ScriptHandle) bool\n```\nReady reports whether h refers to a compiled script.\n\n```go\nfunc (s Store) Version(h gfx.ScriptHandle) uint32\n```\nVersion returns the script's version, which a hot reload increments; see [asset.Store.Version](/github.com/weakpixel/asset#Store.Version).\n\n","path":"github.com/weakpixel/engine/script","name":"script","synopsis":"+game:group:name=script","isRedistributable":true}
