Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

feat(prefab): a prefab you can spawn in one frame, because its loading is done

esengine950a98728f76
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 691fd345c..b319cbb7d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -53,15 +53,26 @@ published separately; it ships inside the editor.
documented as a `BehaviorContext` superset and was missing the one thing
gameplay is written against.
+ A graph can SPAWN. `entity.spawn` hands the new entity to the next node on the
+ wire, so it cannot wait for a load — and loading is all `instantiatePrefab` is
+ asynchronous for. The wait moved to where the graph itself is loaded: the
+ loader prepares every prefab its spawn nodes name (loaded, flattened, asset
+ handles written in) through the context door that records the acquisition, so
+ the prefab is owned by that graph's era and given back when it retires.
+ `preparePrefab` / `spawnPrepared` are the same pair for code — the scene path
+ reused rather than reimplemented, so a prefab spawned at runtime and one
+ placed in a scene resolve identically.
+
Two projects carry it. `examples/script-graph-demo` is two squares that move
because of what they were drawn to do, one of them through a value node the
project registered itself. `examples/dodge-graph` is a GAME — move with the
arrows, dodge the falling blocks, score, lose, press Space to start over —
with no gameplay code at all: one component declares what the run remembers
- (graph variables belong to one entity; a score three blocks and a HUD agree on
- does not), and three graphs do the rest. A gate plays it: holds a key and the
- player moves, releases it and they stop, lets a block through and the HUD says
- so, presses Space and the run begins again.
+ (graph variables belong to one entity; a score the blocks and the HUD agree on
+ does not), and four graphs do the rest — including the one that spawns the
+ blocks, of which the scene contains none. A gate plays it: holds a key and the
+ player moves, releases it and they stop, dodges and the score rises, chases a
+ block and the run ends, presses Space and it begins again on a clear board.
### Fixed
diff --git a/desktop b/desktop
index ee2dd9cab..caed5b386 160000
--- a/desktop
+++ b/desktop
@@ -1 +1 @@
-Subproject commit ee2dd9cabac51c270209c0fec27e172980e50ce1
+Subproject commit caed5b3860b84d43b69dec0671603734a5eec868
diff --git a/docs/astro/src/data/apiStability.generated.json b/docs/astro/src/data/apiStability.generated.json
index 54dd574cc..19ef95184 100644
--- a/docs/astro/src/data/apiStability.generated.json
+++ b/docs/astro/src/data/apiStability.generated.json
@@ -3,10 +3,10 @@
"counts": {
"public": 114,
"beta": 101,
- "experimental": 1962,
+ "experimental": 1963,
"deprecated": 3
},
- "total": 2177,
+ "total": 2178,
"subsystems": [
{
"id": "ecs",
diff --git a/examples/dodge-graph/assets/block.esprefab b/examples/dodge-graph/assets/block.esprefab
new file mode 100644
index 000000000..b4ed6ea02
--- /dev/null
+++ b/examples/dodge-graph/assets/block.esprefab
@@ -0,0 +1,47 @@
+{
+ "version": "2",
+ "name": "Block",
+ "rootEntityId": "root",
+ "entities": [
+ {
+ "prefabEntityId": "root",
+ "name": "Block",
+ "parent": null,
+ "children": [],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {
+ "position": {
+ "x": 0,
+ "y": 360,
+ "z": 0
+ }
+ }
+ },
+ {
+ "type": "Sprite",
+ "data": {
+ "size": {
+ "x": 56,
+ "y": 56
+ },
+ "color": {
+ "r": 0.8,
+ "g": 0.42,
+ "b": 0.36,
+ "a": 1
+ }
+ }
+ },
+ {
+ "type": "ScriptGraphAgent",
+ "data": {
+ "graph": "assets/logic/block.esgraph"
+ }
+ }
+ ]
+ }
+ ]
+}
\ No newline at end of file
diff --git a/examples/dodge-graph/assets/block.esprefab.meta b/examples/dodge-graph/assets/block.esprefab.meta
new file mode 100644
index 000000000..74abad554
--- /dev/null
+++ b/examples/dodge-graph/assets/block.esprefab.meta
@@ -0,0 +1,6 @@
+{
+ "uuid": "7c0d0b10-2c44-4a8e-9f21-7c6b1d3e4b10",
+ "version": "2.0",
+ "type": "prefab",
+ "importer": {}
+}
\ No newline at end of file
diff --git a/examples/dodge-graph/assets/logic/block.esgraph b/examples/dodge-graph/assets/logic/block.esgraph
index 1e813db36..39bae0f83 100644
--- a/examples/dodge-graph/assets/logic/block.esgraph
+++ b/examples/dodge-graph/assets/logic/block.esgraph
@@ -1,431 +1,374 @@
{
"version": "1.0",
"name": "Block",
+ "variables": [
+ {
+ "name": "y",
+ "type": "number",
+ "default": 360
+ }
+ ],
"nodes": [
+ {
+ "id": "start",
+ "kind": "event.start",
+ "x": 0,
+ "y": 60
+ },
+ {
+ "id": "seed",
+ "kind": "call",
+ "ref": "property.get",
+ "literals": {
+ "path": "Transform.position.y"
+ },
+ "x": 34,
+ "y": 250
+ },
+ {
+ "id": "seedSet",
+ "kind": "var.set",
+ "literals": {
+ "name": "y"
+ },
+ "x": 250,
+ "y": 60
+ },
{
"id": "upd",
"kind": "event.update",
"x": 0,
- "y": 60
+ "y": 960
},
{
"id": "step",
"kind": "call",
- "x": 68,
- "y": 440,
"ref": "math.multiply",
"literals": {
"a": -320
- }
+ },
+ "x": 68,
+ "y": 1340
},
{
"id": "getY",
"kind": "var.get",
- "x": 68,
- "y": 630,
"literals": {
"name": "y"
- }
+ },
+ "x": 68,
+ "y": 1530
},
{
"id": "nextY",
"kind": "call",
+ "ref": "math.add",
"x": 284,
- "y": 250,
- "ref": "math.add"
+ "y": 1150
},
{
"id": "setY",
"kind": "var.set",
- "x": 500,
- "y": 60,
"literals": {
"name": "y"
- }
+ },
+ "x": 500,
+ "y": 960
},
{
"id": "writeY",
"kind": "call",
- "x": 750,
- "y": 60,
"ref": "property.set",
"literals": {
"path": "Transform.position.y"
- }
+ },
+ "x": 750,
+ "y": 960
},
{
- "id": "below",
+ "id": "gone",
"kind": "call",
- "x": 784,
- "y": 250,
"ref": "compare.less",
"literals": {
"b": -340
- }
+ },
+ "x": 784,
+ "y": 1150
},
{
- "id": "wrap",
+ "id": "off",
"kind": "flow.branch",
"x": 1000,
- "y": 60
- },
- {
- "id": "top",
- "kind": "var.set",
- "x": 1250,
- "y": 60,
- "literals": {
- "name": "y"
- }
- },
- {
- "id": "topVal",
- "kind": "lit.number",
- "x": 1034,
- "y": 250,
- "literals": {
- "value": 360
- }
- },
- {
- "id": "newX",
- "kind": "call",
- "x": 1284,
- "y": 250,
- "ref": "math.random",
- "literals": {
- "min": -340,
- "max": 340
- }
- },
- {
- "id": "setX",
- "kind": "var.set",
- "x": 1500,
- "y": 60,
- "literals": {
- "name": "x"
- }
- },
- {
- "id": "writeX",
- "kind": "call",
- "x": 1750,
- "y": 60,
- "ref": "property.set",
- "literals": {
- "path": "Transform.position.x"
- }
- },
- {
- "id": "getX",
- "kind": "var.get",
- "x": 1534,
- "y": 250,
- "literals": {
- "name": "x"
- }
+ "y": 960
},
{
"id": "game",
"kind": "call",
- "x": -216,
- "y": 250,
"ref": "entity.byName",
"literals": {
"name": "Game"
- }
+ },
+ "x": -216,
+ "y": 250
},
{
"id": "score",
"kind": "call",
- "x": 1568,
- "y": 440,
"ref": "property.get",
"literals": {
"path": "GameState.score"
- }
+ },
+ "x": 818,
+ "y": 1340
},
{
"id": "plus",
"kind": "call",
- "x": 1784,
- "y": 250,
"ref": "math.add",
"literals": {
"b": 1
- }
+ },
+ "x": 1034,
+ "y": 1150
},
{
"id": "bump",
"kind": "call",
- "x": 2000,
- "y": 60,
"ref": "property.set",
"literals": {
"path": "GameState.score"
- }
+ },
+ "x": 1250,
+ "y": 960
+ },
+ {
+ "id": "die",
+ "kind": "call",
+ "ref": "entity.despawn",
+ "x": 1500,
+ "y": 960
},
{
"id": "hit",
"kind": "flow.branch",
"x": 1250,
- "y": 60
+ "y": 960
},
{
"id": "player",
"kind": "call",
- "x": -216,
- "y": 440,
"ref": "entity.byName",
"literals": {
"name": "Player"
- }
+ },
+ "x": -216,
+ "y": 440
},
{
"id": "px",
"kind": "call",
- "x": -216,
- "y": 630,
"ref": "property.get",
"literals": {
"path": "Transform.position.x"
- }
+ },
+ "x": -216,
+ "y": 630
},
{
"id": "py",
"kind": "call",
- "x": -216,
- "y": 820,
"ref": "property.get",
"literals": {
"path": "Transform.position.y"
- }
+ },
+ "x": -216,
+ "y": 820
+ },
+ {
+ "id": "myx",
+ "kind": "call",
+ "ref": "property.get",
+ "literals": {
+ "path": "Transform.position.x"
+ },
+ "x": -216,
+ "y": 1010
},
{
"id": "dx",
"kind": "call",
+ "ref": "math.subtract",
"x": -216,
- "y": 1010,
- "ref": "math.subtract"
+ "y": 1200
},
{
"id": "dy",
"kind": "call",
+ "ref": "math.subtract",
"x": -216,
- "y": 1200,
- "ref": "math.subtract"
+ "y": 1390
},
{
"id": "adx",
"kind": "call",
+ "ref": "math.abs",
"x": -216,
- "y": 1390,
- "ref": "math.abs"
+ "y": 1580
},
{
"id": "ady",
"kind": "call",
+ "ref": "math.abs",
"x": -216,
- "y": 1580,
- "ref": "math.abs"
+ "y": 1770
},
{
"id": "nearX",
"kind": "call",
- "x": 818,
- "y": 630,
"ref": "compare.less",
"literals": {
"b": 62
- }
+ },
+ "x": 818,
+ "y": 1530
},
{
"id": "nearY",
"kind": "call",
- "x": 818,
- "y": 820,
"ref": "compare.less",
"literals": {
"b": 62
- }
+ },
+ "x": 818,
+ "y": 1720
},
{
"id": "both",
"kind": "call",
+ "ref": "logic.and",
"x": 1034,
- "y": 440,
- "ref": "logic.and"
+ "y": 1340
},
{
"id": "out",
"kind": "call",
- "x": 1500,
- "y": 60,
"ref": "property.set",
"literals": {
"path": "GameState.alive",
"value": "false"
- }
- },
- {
- "id": "start",
- "kind": "event.start",
- "x": 0,
+ },
+ "x": 1500,
"y": 960
},
- {
- "id": "seed",
- "kind": "call",
- "ref": "property.get",
- "x": 34,
- "y": 1150,
- "literals": {
- "path": "Transform.position.y"
- }
- },
- {
- "id": "seedSet",
- "kind": "var.set",
- "x": 250,
- "y": 960,
- "literals": {
- "name": "y"
- }
- },
- {
- "id": "alive",
- "kind": "call",
- "ref": "property.get",
- "x": 34,
- "y": 250,
- "literals": {
- "path": "GameState.alive"
- }
- },
- {
- "id": "live",
- "kind": "flow.branch",
- "x": 250,
- "y": 60
- },
- {
- "id": "waitY",
- "kind": "call",
- "ref": "math.random",
- "x": 284,
- "y": 440,
- "literals": {
- "min": 380,
- "max": 820
- }
- },
- {
- "id": "park",
- "kind": "var.set",
- "x": 500,
- "y": 60,
- "literals": {
- "name": "y"
- }
- },
- {
- "id": "parkW",
- "kind": "call",
- "ref": "property.set",
- "x": 750,
- "y": 60,
- "literals": {
- "path": "Transform.position.y"
- }
- },
{
"id": "getY_1",
"kind": "var.get",
- "x": 534,
- "y": 250,
"literals": {
"name": "y"
- }
+ },
+ "x": 534,
+ "y": 1150
},
{
"id": "getY_2",
"kind": "var.get",
- "x": 568,
- "y": 440,
"literals": {
"name": "y"
- }
+ },
+ "x": 568,
+ "y": 1340
},
{
"id": "getY_3",
"kind": "var.get",
- "x": -432,
- "y": 1390,
- "literals": {
- "name": "y"
- }
- },
- {
- "id": "getY_4",
- "kind": "var.get",
- "x": 534,
- "y": 440,
"literals": {
"name": "y"
- }
- },
- {
- "id": "getX_1",
- "kind": "var.get",
+ },
"x": -432,
- "y": 1200,
- "literals": {
- "name": "x"
- }
+ "y": 1580
},
{
"id": "game_1",
"kind": "call",
- "x": 1784,
- "y": 440,
"ref": "entity.byName",
"literals": {
"name": "Game"
- }
+ },
+ "x": 1034,
+ "y": 1720
},
{
"id": "game_2",
"kind": "call",
- "x": 1284,
- "y": 440,
"ref": "entity.byName",
"literals": {
"name": "Game"
- }
+ },
+ "x": 1284,
+ "y": 1150
},
{
- "id": "game_3",
+ "id": "player_1",
+ "kind": "call",
+ "ref": "entity.byName",
+ "literals": {
+ "name": "Player"
+ },
+ "x": -432,
+ "y": 1010
+ },
+ {
+ "id": "alive",
+ "kind": "call",
+ "ref": "property.get",
+ "literals": {
+ "path": "GameState.alive"
+ },
+ "x": 34,
+ "y": 1150
+ },
+ {
+ "id": "live",
+ "kind": "flow.branch",
+ "x": 250,
+ "y": 960
+ },
+ {
+ "id": "game_1",
"kind": "call",
- "x": -182,
- "y": 440,
"ref": "entity.byName",
"literals": {
"name": "Game"
- }
+ },
+ "x": 1034,
+ "y": 1720
},
{
- "id": "player_1",
+ "id": "game_1_1",
"kind": "call",
- "x": -432,
- "y": 1010,
"ref": "entity.byName",
"literals": {
- "name": "Player"
- }
+ "name": "Game"
+ },
+ "x": -182,
+ "y": 1340
}
],
"edges": [
+ {
+ "id": "start.then->seedSet.",
+ "from": "start",
+ "fromPort": "then",
+ "to": "seedSet",
+ "toPort": ""
+ },
+ {
+ "id": "seed.value->seedSet.value",
+ "from": "seed",
+ "fromPort": "value",
+ "to": "seedSet",
+ "toPort": "value"
+ },
{
"id": "upd.dt->step.b",
"from": "upd",
@@ -469,72 +412,30 @@
"toPort": "value"
},
{
- "id": "writeY.then->wrap.",
+ "id": "writeY.then->off.",
"from": "writeY",
"fromPort": "then",
- "to": "wrap",
+ "to": "off",
"toPort": ""
},
{
- "id": "getY_2.value->below.a",
+ "id": "getY_2.value->gone.a",
"from": "getY_2",
"fromPort": "value",
- "to": "below",
+ "to": "gone",
"toPort": "a"
},
{
- "id": "below.result->wrap.cond",
- "from": "below",
+ "id": "gone.result->off.cond",
+ "from": "gone",
"fromPort": "result",
- "to": "wrap",
+ "to": "off",
"toPort": "cond"
},
{
- "id": "wrap.true->top.",
- "from": "wrap",
+ "id": "off.true->bump.",
+ "from": "off",
"fromPort": "true",
- "to": "top",
- "toPort": ""
- },
- {
- "id": "topVal.value->top.value",
- "from": "topVal",
- "fromPort": "value",
- "to": "top",
- "toPort": "value"
- },
- {
- "id": "top.then->setX.",
- "from": "top",
- "fromPort": "then",
- "to": "setX",
- "toPort": ""
- },
- {
- "id": "newX.result->setX.value",
- "from": "newX",
- "fromPort": "result",
- "to": "setX",
- "toPort": "value"
- },
- {
- "id": "setX.then->writeX.",
- "from": "setX",
- "fromPort": "then",
- "to": "writeX",
- "toPort": ""
- },
- {
- "id": "getX.value->writeX.value",
- "from": "getX",
- "fromPort": "value",
- "to": "writeX",
- "toPort": "value"
- },
- {
- "id": "writeX.then->bump.",
- "from": "writeX",
- "fromPort": "then",
"to": "bump",
"toPort": ""
},
@@ -567,8 +468,15 @@
"toPort": "entity"
},
{
- "id": "wrap.false->hit.",
- "from": "wrap",
+ "id": "bump.then->die.",
+ "from": "bump",
+ "fromPort": "then",
+ "to": "die",
+ "toPort": ""
+ },
+ {
+ "id": "off.false->hit.",
+ "from": "off",
"fromPort": "false",
"to": "hit",
"toPort": ""
@@ -587,6 +495,13 @@
"to": "py",
"toPort": "entity"
},
+ {
+ "id": "myx.value->dx.a",
+ "from": "myx",
+ "fromPort": "value",
+ "to": "dx",
+ "toPort": "a"
+ },
{
"id": "px.value->dx.b",
"from": "px",
@@ -595,10 +510,10 @@
"toPort": "b"
},
{
- "id": "getX_1.value->dx.a",
- "from": "getX_1",
+ "id": "getY_3.value->dy.a",
+ "from": "getY_3",
"fromPort": "value",
- "to": "dx",
+ "to": "dy",
"toPort": "a"
},
{
@@ -608,13 +523,6 @@
"to": "dy",
"toPort": "b"
},
- {
- "id": "getY_3.value->dy.a",
- "from": "getY_3",
- "fromPort": "value",
- "to": "dy",
- "toPort": "a"
- },
{
"id": "dx.result->adx.a",
"from": "dx",
@@ -678,20 +586,6 @@
"to": "out",
"toPort": "entity"
},
- {
- "id": "start.then->seedSet.",
- "from": "start",
- "fromPort": "then",
- "to": "seedSet",
- "toPort": ""
- },
- {
- "id": "seed.value->seedSet.value",
- "from": "seed",
- "fromPort": "value",
- "to": "seedSet",
- "toPort": "value"
- },
{
"id": "upd.then->live.",
"from": "upd",
@@ -699,6 +593,13 @@
"to": "live",
"toPort": ""
},
+ {
+ "id": "game_1_1.entity->alive.entity",
+ "from": "game_1_1",
+ "fromPort": "entity",
+ "to": "alive",
+ "toPort": "entity"
+ },
{
"id": "alive.value->live.cond",
"from": "alive",
@@ -714,51 +615,11 @@
"toPort": ""
},
{
- "id": "game_3.entity->alive.entity",
- "from": "game_3",
- "fromPort": "entity",
- "to": "alive",
- "toPort": "entity"
- },
- {
- "id": "live.false->park.",
+ "id": "live.false->die.",
"from": "live",
"fromPort": "false",
- "to": "park",
- "toPort": ""
- },
- {
- "id": "waitY.result->park.value",
- "from": "waitY",
- "fromPort": "result",
- "to": "park",
- "toPort": "value"
- },
- {
- "id": "park.then->parkW.",
- "from": "park",
- "fromPort": "then",
- "to": "parkW",
+ "to": "die",
"toPort": ""
- },
- {
- "id": "getY_4.value->parkW.value",
- "from": "getY_4",
- "fromPort": "value",
- "to": "parkW",
- "toPort": "value"
- }
- ],
- "variables": [
- {
- "name": "y",
- "type": "number",
- "default": 340
- },
- {
- "name": "x",
- "type": "number",
- "default": 0
}
]
}
\ No newline at end of file
diff --git a/examples/dodge-graph/assets/logic/spawner.esgraph b/examples/dodge-graph/assets/logic/spawner.esgraph
new file mode 100644
index 000000000..ba0fcb51b
--- /dev/null
+++ b/examples/dodge-graph/assets/logic/spawner.esgraph
@@ -0,0 +1,236 @@
+{
+ "version": "1.0",
+ "name": "Spawner",
+ "variables": [
+ {
+ "name": "wait",
+ "type": "number",
+ "default": 0.4
+ }
+ ],
+ "nodes": [
+ {
+ "id": "upd",
+ "kind": "event.update",
+ "x": 0,
+ "y": 60
+ },
+ {
+ "id": "game",
+ "kind": "call",
+ "ref": "entity.byName",
+ "literals": {
+ "name": "Game"
+ },
+ "x": -182,
+ "y": 440
+ },
+ {
+ "id": "alive",
+ "kind": "call",
+ "ref": "property.get",
+ "literals": {
+ "path": "GameState.alive"
+ },
+ "x": 34,
+ "y": 250
+ },
+ {
+ "id": "live",
+ "kind": "flow.branch",
+ "x": 250,
+ "y": 60
+ },
+ {
+ "id": "getW",
+ "kind": "var.get",
+ "literals": {
+ "name": "wait"
+ },
+ "x": 68,
+ "y": 440
+ },
+ {
+ "id": "tick",
+ "kind": "call",
+ "ref": "math.subtract",
+ "x": 284,
+ "y": 250
+ },
+ {
+ "id": "setW",
+ "kind": "var.set",
+ "literals": {
+ "name": "wait"
+ },
+ "x": 500,
+ "y": 60
+ },
+ {
+ "id": "due",
+ "kind": "call",
+ "ref": "compare.less",
+ "literals": {
+ "b": 0
+ },
+ "x": 534,
+ "y": 250
+ },
+ {
+ "id": "drop",
+ "kind": "flow.branch",
+ "x": 750,
+ "y": 60
+ },
+ {
+ "id": "spawn",
+ "kind": "entity.spawn",
+ "literals": {
+ "prefab": "assets/block.esprefab",
+ "y": 360
+ },
+ "x": 1000,
+ "y": 60
+ },
+ {
+ "id": "col",
+ "kind": "call",
+ "ref": "math.random",
+ "literals": {
+ "min": -340,
+ "max": 340
+ },
+ "x": 784,
+ "y": 250
+ },
+ {
+ "id": "rearm",
+ "kind": "var.set",
+ "literals": {
+ "name": "wait"
+ },
+ "x": 1250,
+ "y": 60
+ },
+ {
+ "id": "gap",
+ "kind": "call",
+ "ref": "math.random",
+ "literals": {
+ "min": 0.55,
+ "max": 1.1
+ },
+ "x": 1034,
+ "y": 250
+ },
+ {
+ "id": "getW_1",
+ "kind": "var.get",
+ "literals": {
+ "name": "wait"
+ },
+ "x": 318,
+ "y": 440
+ }
+ ],
+ "edges": [
+ {
+ "id": "upd.then->live.",
+ "from": "upd",
+ "fromPort": "then",
+ "to": "live",
+ "toPort": ""
+ },
+ {
+ "id": "game.entity->alive.entity",
+ "from": "game",
+ "fromPort": "entity",
+ "to": "alive",
+ "toPort": "entity"
+ },
+ {
+ "id": "alive.value->live.cond",
+ "from": "alive",
+ "fromPort": "value",
+ "to": "live",
+ "toPort": "cond"
+ },
+ {
+ "id": "live.true->setW.",
+ "from": "live",
+ "fromPort": "true",
+ "to": "setW",
+ "toPort": ""
+ },
+ {
+ "id": "getW.value->tick.a",
+ "from": "getW",
+ "fromPort": "value",
+ "to": "tick",
+ "toPort": "a"
+ },
+ {
+ "id": "upd.dt->tick.b",
+ "from": "upd",
+ "fromPort": "dt",
+ "to": "tick",
+ "toPort": "b"
+ },
+ {
+ "id": "tick.result->setW.value",
+ "from": "tick",
+ "fromPort": "result",
+ "to": "setW",
+ "toPort": "value"
+ },
+ {
+ "id": "setW.then->drop.",
+ "from": "setW",
+ "fromPort": "then",
+ "to": "drop",
+ "toPort": ""
+ },
+ {
+ "id": "getW_1.value->due.a",
+ "from": "getW_1",
+ "fromPort": "value",
+ "to": "due",
+ "toPort": "a"
+ },
+ {
+ "id": "due.result->drop.cond",
+ "from": "due",
+ "fromPort": "result",
+ "to": "drop",
+ "toPort": "cond"
+ },
+ {
+ "id": "drop.true->spawn.",
+ "from": "drop",
+ "fromPort": "true",
+ "to": "spawn",
+ "toPort": ""
+ },
+ {
+ "id": "col.result->spawn.x",
+ "from": "col",
+ "fromPort": "result",
+ "to": "spawn",
+ "toPort": "x"
+ },
+ {
+ "id": "spawn.then->rearm.",
+ "from": "spawn",
+ "fromPort": "then",
+ "to": "rearm",
+ "toPort": ""
+ },
+ {
+ "id": "gap.result->rearm.value",
+ "from": "gap",
+ "fromPort": "result",
+ "to": "rearm",
+ "toPort": "value"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/examples/dodge-graph/assets/logic/spawner.esgraph.meta b/examples/dodge-graph/assets/logic/spawner.esgraph.meta
new file mode 100644
index 000000000..8f477bcf6
--- /dev/null
+++ b/examples/dodge-graph/assets/logic/spawner.esgraph.meta
@@ -0,0 +1,6 @@
+{
+ "uuid": "7c0d0b10-2c44-4a8e-9f21-7c6b1d3e4b04",
+ "version": "2.0",
+ "type": "scriptgraph",
+ "importer": {}
+}
\ No newline at end of file
diff --git a/examples/dodge-graph/assets/scenes/main.esscene b/examples/dodge-graph/assets/scenes/main.esscene
index 87768ef4e..14b72d769 100644
--- a/examples/dodge-graph/assets/scenes/main.esscene
+++ b/examples/dodge-graph/assets/scenes/main.esscene
@@ -97,88 +97,8 @@
]
},
{
- "id": 3,
- "name": "Block1",
- "parent": null,
- "children": [],
- "visible": true,
- "components": [
- {
- "type": "Transform",
- "data": {
- "position": {
- "x": -220,
- "y": 340,
- "z": 0
- }
- }
- },
- {
- "type": "Sprite",
- "data": {
- "size": {
- "x": 56,
- "y": 56
- },
- "color": {
- "r": 0.8,
- "g": 0.42,
- "b": 0.36,
- "a": 1
- }
- }
- },
- {
- "type": "ScriptGraphAgent",
- "data": {
- "graph": "assets/logic/block.esgraph"
- }
- }
- ]
- },
- {
- "id": 4,
- "name": "Block2",
- "parent": null,
- "children": [],
- "visible": true,
- "components": [
- {
- "type": "Transform",
- "data": {
- "position": {
- "x": 150,
- "y": 560,
- "z": 0
- }
- }
- },
- {
- "type": "Sprite",
- "data": {
- "size": {
- "x": 56,
- "y": 56
- },
- "color": {
- "r": 0.8,
- "g": 0.42,
- "b": 0.36,
- "a": 1
- }
- }
- },
- {
- "type": "ScriptGraphAgent",
- "data": {
- "graph": "assets/logic/block.esgraph"
- }
- }
- ]
- },
- {
- "id": 5,
- "name": "Block3",
+ "id": 6,
+ "name": "ScoreText",
"parent": null,
"children": [],
"visible": true,
@@ -187,23 +107,21 @@
"type": "Transform",
"data": {
"position": {
- "x": 260,
- "y": 800,
+ "x": -360,
+ "y": 280,
"z": 0
}
}
},
{
- "type": "Sprite",
+ "type": "Text",
"data": {
- "size": {
- "x": 56,
- "y": 56
- },
+ "content": "SCORE 0",
+ "fontSize": 30,
"color": {
- "r": 0.8,
- "g": 0.42,
- "b": 0.36,
+ "r": 0.92,
+ "g": 0.92,
+ "b": 0.88,
"a": 1
}
}
@@ -211,14 +129,14 @@
{
"type": "ScriptGraphAgent",
"data": {
- "graph": "assets/logic/block.esgraph"
+ "graph": "assets/logic/hud.esgraph"
}
}
]
},
{
- "id": 6,
- "name": "ScoreText",
+ "id": 7,
+ "name": "Spawner",
"parent": null,
"children": [],
"visible": true,
@@ -227,29 +145,16 @@
"type": "Transform",
"data": {
"position": {
- "x": -360,
- "y": 280,
+ "x": 0,
+ "y": 0,
"z": 0
}
}
},
- {
- "type": "Text",
- "data": {
- "content": "SCORE 0",
- "fontSize": 30,
- "color": {
- "r": 0.92,
- "g": 0.92,
- "b": 0.88,
- "a": 1
- }
- }
- },
{
"type": "ScriptGraphAgent",
"data": {
- "graph": "assets/logic/hud.esgraph"
+ "graph": "assets/logic/spawner.esgraph"
}
}
]
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index ca6b9e8c4..a3711e333 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 114 public · 94 beta · 1801 experimental · 3 deprecated
+Symbols: 114 public · 94 beta · 1802 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -2517,6 +2517,7 @@ events: Map<string, string[]>
execTargets: Map<string, string>
graph: ScriptGraph
nodes: Map<string, ScriptGraphNode>
+prefabs: Map<string, PreparedPrefab>
problems: string[]
shapes: Map<string, ScriptNodeShape>
starts: string[]
@@ -8123,6 +8124,7 @@ ctx: Ctx
dt: number
onProblem: ((message: string) => void) | undefined
registry: AiRegistry<Ctx>
+world: World | undefined
```
## ScriptValue — type @experimental
@@ -13928,6 +13930,11 @@ Plugin
ScriptGraphPlugin
```
+## scriptGraphPrefabRefs — function @experimental
+```
+(graph: ScriptGraph): string[]
+```
+
## scriptGraphTouches — function @experimental
```
(app: App): SystemTouches
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index 51e99b610..43fbaf30a 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index.native
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 114 public · 99 beta · 1820 experimental · 3 deprecated
+Symbols: 114 public · 99 beta · 1821 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -2517,6 +2517,7 @@ events: Map<string, string[]>
execTargets: Map<string, string>
graph: ScriptGraph
nodes: Map<string, ScriptGraphNode>
+prefabs: Map<string, PreparedPrefab>
problems: string[]
shapes: Map<string, ScriptNodeShape>
starts: string[]
@@ -8316,6 +8317,7 @@ ctx: Ctx
dt: number
onProblem: ((message: string) => void) | undefined
registry: AiRegistry<Ctx>
+world: World | undefined
```
## ScriptValue — type @experimental
@@ -14171,6 +14173,11 @@ Plugin
ScriptGraphPlugin
```
+## scriptGraphPrefabRefs — function @experimental
+```
+(graph: ScriptGraph): string[]
+```
+
## scriptGraphTouches — function @experimental
```
(app: App): SystemTouches
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index 9dbc8d99f..f5799da99 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index.node
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 114 public · 96 beta · 1800 experimental · 3 deprecated
+Symbols: 114 public · 96 beta · 1801 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -2512,6 +2512,7 @@ events: Map<string, string[]>
execTargets: Map<string, string>
graph: ScriptGraph
nodes: Map<string, ScriptGraphNode>
+prefabs: Map<string, PreparedPrefab>
problems: string[]
shapes: Map<string, ScriptNodeShape>
starts: string[]
@@ -8118,6 +8119,7 @@ ctx: Ctx
dt: number
onProblem: ((message: string) => void) | undefined
registry: AiRegistry<Ctx>
+world: World | undefined
```
## ScriptValue — type @experimental
@@ -13933,6 +13935,11 @@ Plugin
ScriptGraphPlugin
```
+## scriptGraphPrefabRefs — function @experimental
+```
+(graph: ScriptGraph): string[]
+```
+
## scriptGraphTouches — function @experimental
```
(app: App): SystemTouches
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index 189df7f84..9a686af98 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/minigame
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 114 public · 94 beta · 1822 experimental · 3 deprecated
+Symbols: 114 public · 94 beta · 1823 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -2512,6 +2512,7 @@ events: Map<string, string[]>
execTargets: Map<string, string>
graph: ScriptGraph
nodes: Map<string, ScriptGraphNode>
+prefabs: Map<string, PreparedPrefab>
problems: string[]
shapes: Map<string, ScriptNodeShape>
starts: string[]
@@ -8366,6 +8367,7 @@ ctx: Ctx
dt: number
onProblem: ((message: string) => void) | undefined
registry: AiRegistry<Ctx>
+world: World | undefined
```
## ScriptValue — type @experimental
@@ -14192,6 +14194,11 @@ Plugin
ScriptGraphPlugin
```
+## scriptGraphPrefabRefs — function @experimental
+```
+(graph: ScriptGraph): string[]
+```
+
## scriptGraphTouches — function @experimental
```
(app: App): SystemTouches
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index 4dceb70ab..42d793ed3 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/wechat
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 114 public · 94 beta · 1812 experimental · 3 deprecated
+Symbols: 114 public · 94 beta · 1813 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -2512,6 +2512,7 @@ events: Map<string, string[]>
execTargets: Map<string, string>
graph: ScriptGraph
nodes: Map<string, ScriptGraphNode>
+prefabs: Map<string, PreparedPrefab>
problems: string[]
shapes: Map<string, ScriptNodeShape>
starts: string[]
@@ -8125,6 +8126,7 @@ ctx: Ctx
dt: number
onProblem: ((message: string) => void) | undefined
registry: AiRegistry<Ctx>
+world: World | undefined
```
## ScriptValue — type @experimental
@@ -13956,6 +13958,11 @@ Plugin
ScriptGraphPlugin
```
+## scriptGraphPrefabRefs — function @experimental
+```
+(graph: ScriptGraph): string[]
+```
+
## scriptGraphTouches — function @experimental
```
(app: App): SystemTouches
diff --git a/sdk/src/asset/AssetLoader.ts b/sdk/src/asset/AssetLoader.ts
index 4c85ce06e..65e401c85 100644
--- a/sdk/src/asset/AssetLoader.ts
+++ b/sdk/src/asset/AssetLoader.ts
@@ -2,6 +2,7 @@
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
import type { Backend } from './Backend';
import type { AssetLease } from './AssetLease';
+import type { PreparedPrefab } from '../prefab/preparedPrefab';
import type { RegistryEra } from './registryAssets';
import type { Catalog } from './Catalog';
import type { TextureHandle, FontHandle } from '../types';
@@ -120,6 +121,12 @@ export interface LoadContext {
* one specialization, for the flip variants a texture has.
*/
acquireAsset<T>(type: string, ref: string): Promise<AssetLease<T>>;
+ /**
+ * A prefab loaded, flattened and resolved, so it can be spawned in one
+ * frame. Optional: a context built for a loader that never spawns has no
+ * reason to carry it.
+ */
+ preparePrefab?(ref: string): Promise<AssetLease<PreparedPrefab>>;
loadText(path: string): Promise<string>;
loadBinary(path: string): Promise<ArrayBuffer>;
/**
diff --git a/sdk/src/asset/Assets.ts b/sdk/src/asset/Assets.ts
index 7c23fd383..d24a11abc 100644
--- a/sdk/src/asset/Assets.ts
+++ b/sdk/src/asset/Assets.ts
@@ -45,6 +45,7 @@ import { AnimatorControllerAssetLoader } from './loaders/AnimatorControllerAsset
import { AvatarAssetLoader } from './loaders/AvatarAssetLoader';
import { BtAssetLoader } from './loaders/BtAssetLoader';
import { ScriptGraphAssetLoader } from './loaders/ScriptGraphAssetLoader';
+import { preparePrefab, type PreparedPrefab } from '../prefab/preparedPrefab';
import { LocaleAssetLoader } from './loaders/LocaleAssetLoader';
import { JsonAssetLoader } from './loaders/JsonAssetLoader';
import { getComponentDefaults } from '../ecs/component';
@@ -356,6 +357,9 @@ export class Assets {
private textureImportResolver_: TextureImportSettingsResolver | null = null;
private spineLoader_: SpineAssetLoader;
+ /** Prefabs flattened and resolved for one-frame spawning, by resolved path. */
+ private preparedPrefabs_ = new Map<string, { holders: number; prepared: PreparedPrefab }>();
+
private textureCache_ = new AsyncCache<TextureResult>((result) => {
// A texture whose load finished after its getOrLoad timed out has no
// owner; release its GL handle so it doesn't leak VRAM.
@@ -2442,6 +2446,42 @@ export class Assets {
};
}
+ /**
+ * A prepared prefab as a lease: one preparation per ref per realm, released
+ * when the last holder lets go. Shared, because two graphs spawning the same
+ * prefab want the same flattened copy — preparing it twice would load its
+ * textures twice and leave two scopes to release.
+ */
+ private async preparePrefabLease_(ref: string): Promise<AssetLease<PreparedPrefab>> {
+ const key = `prepared-prefab:${this.resolveLoadPath_(ref)}`;
+ let entry = this.preparedPrefabs_.get(key);
+ if (!entry) {
+ entry = { holders: 0, prepared: await preparePrefab(this, ref) };
+ this.preparedPrefabs_.set(key, entry);
+ }
+ const held = entry;
+ const receipt = (): AssetLease<PreparedPrefab> => {
+ held.holders++;
+ let released = false;
+ return {
+ key,
+ generation: 0,
+ value: held.prepared,
+ release: () => {
+ if (released) return;
+ released = true;
+ if (--held.holders > 0) return;
+ this.preparedPrefabs_.delete(key);
+ held.prepared.release();
+ },
+ // A second receipt for the same preparation — the splitting owner
+ // stays bound to this one, which is the point of splitting.
+ retain: () => receipt(),
+ };
+ };
+ return receipt();
+ }
+
/**
* Run one preparation: what the loader takes IS the result's ownership and
* IS the graph's edges. A transaction, because an acquisition on the way to
@@ -2469,6 +2509,7 @@ export class Assets {
acquireTexture: async (path, flipY) =>
recorder.own(path, await base.acquireTexture(path, flipY), 'texture'),
acquireAsset: async (type, ref) => recorder.own(ref, await base.acquireAsset(type, ref), type),
+ preparePrefab: async (ref) => recorder.own(ref, await this.preparePrefabLease_(ref), 'prefab'),
createOwnedTexture: async (width, height, pixels, flipY) => {
const lease = await base.createOwnedTexture!(width, height, pixels, flipY);
return recorder.own(`composed:${lease.value.handle}`, lease);
diff --git a/sdk/src/asset/loaders/ScriptGraphAssetLoader.ts b/sdk/src/asset/loaders/ScriptGraphAssetLoader.ts
index 553dd0a29..da6446940 100644
--- a/sdk/src/asset/loaders/ScriptGraphAssetLoader.ts
+++ b/sdk/src/asset/loaders/ScriptGraphAssetLoader.ts
@@ -8,11 +8,18 @@
* The payload IS the runtime definition — the compile here only indexes it (pins
* resolved, wires turned into lookups), which is why it happens once per era and
* not once per name.
+ *
+ * It also PREPARES what the graph may spawn. A spawn node hands the new entity
+ * to the next node on the wire, so it cannot wait for a load; the wait belongs
+ * here, where the graph itself is being loaded. Acquired through the context, so
+ * the prefab is owned by this era and given back when it retires.
*/
import type { AssetLoader, LoadContext, RegistryAssetLoader, ScriptGraphResult } from '../AssetLoader';
import type { RegistryEra } from '../registryAssets';
import { compileAgainstRegistry } from '../../logic/ScriptGraphAgent';
+import { scriptGraphPrefabRefs } from '../../logic/nodes';
import type { ScriptGraph } from '../../logic/types';
+import { log } from '../../util/logger';
export class ScriptGraphAssetLoader implements AssetLoader<ScriptGraphResult> {
readonly type = 'scriptgraph';
@@ -22,7 +29,17 @@ export class ScriptGraphAssetLoader implements AssetLoader<ScriptGraphResult> {
prepare: async (path: string, ctx: LoadContext): Promise<RegistryEra<ScriptGraphResult>> => {
const text = await ctx.loadText(ctx.catalog.getBuildPath(path));
const graph = JSON.parse(text) as ScriptGraph;
- return { published: compileAgainstRegistry(graph), value: { graphId: path } };
+ const compiled = compileAgainstRegistry(graph);
+ for (const ref of scriptGraphPrefabRefs(graph)) {
+ try {
+ compiled.prefabs.set(ref, (await ctx.preparePrefab!(ref)).value);
+ } catch (e) {
+ // Reported, not thrown: one unspawnable prefab must not take
+ // the whole graph — every other node in it still runs.
+ log.warn('logic', `${path}: prefab "${ref}" did not prepare: ${String(e)}`);
+ }
+ }
+ return { published: compiled, value: { graphId: path } };
},
};
}
diff --git a/sdk/src/core-content.ts b/sdk/src/core-content.ts
index 9f5bd5e31..90cf00fdd 100644
--- a/sdk/src/core-content.ts
+++ b/sdk/src/core-content.ts
@@ -1006,6 +1006,7 @@ export {
describeNode,
sequenceCount,
BUILTIN_NODE_KINDS,
+ scriptGraphPrefabRefs,
compileScriptGraph,
createScriptRunState,
stepScriptGraph,
diff --git a/sdk/src/logic/ScriptGraphPlugin.ts b/sdk/src/logic/ScriptGraphPlugin.ts
index ef3a2fc5b..289ce0e30 100644
--- a/sdk/src/logic/ScriptGraphPlugin.ts
+++ b/sdk/src/logic/ScriptGraphPlugin.ts
@@ -102,6 +102,7 @@ export function stepScriptGraphs(
ctx.blackboard = st.bb;
return {
ctx: ctx as AiContext, bb: st.bb, registry: aiRegistry, dt: delta,
+ world: world as unknown as World,
onProblem: message => onProblem?.(entity, message),
};
};
@@ -270,6 +271,7 @@ export class ScriptGraphPlugin implements Plugin {
ctx.input = input_;
return {
ctx: ctx as AiContext, bb: st.bb, registry: aiRegistry, dt: dt_,
+ world: world as unknown as World,
onProblem: message => onProblem(entity, message),
};
});
diff --git a/sdk/src/logic/ScriptGraphRunner.ts b/sdk/src/logic/ScriptGraphRunner.ts
index 066b0eb68..3a1277323 100644
Binary files a/sdk/src/logic/ScriptGraphRunner.ts and b/sdk/src/logic/ScriptGraphRunner.ts differ
diff --git a/sdk/src/logic/index.ts b/sdk/src/logic/index.ts
index 8493b58e5..9f416af27 100644
--- a/sdk/src/logic/index.ts
+++ b/sdk/src/logic/index.ts
@@ -29,6 +29,8 @@ export {
describeNode,
sequenceCount,
BUILTIN_NODE_KINDS,
+ spawnPrefabRef,
+ scriptGraphPrefabRefs,
THEN,
type ScriptNodeShape,
type ScriptVerbCatalog,
diff --git a/sdk/src/logic/nodes.ts b/sdk/src/logic/nodes.ts
index 58791b427..046c50fb4 100644
--- a/sdk/src/logic/nodes.ts
+++ b/sdk/src/logic/nodes.ts
@@ -133,6 +133,21 @@ export function describeNode(
inputs: [{ name: 'seconds', type: 'number' }], outputs: NO_PORTS, pure: false,
};
+ case 'entity.spawn':
+ // A built-in rather than a registered verb: what it spawns is the
+ // prefab THIS graph prepared, and a name in the shared registry has
+ // no way to reach a particular graph's preparations.
+ return {
+ execIn: true, execOut: [THEN],
+ inputs: [
+ { name: 'x', type: 'number' },
+ { name: 'y', type: 'number' },
+ { name: 'parent', type: 'entity' },
+ ],
+ outputs: [{ name: 'entity', type: 'entity' }],
+ pure: false,
+ };
+
case 'var.get':
return {
execIn: false, execOut: [], inputs: NO_PORTS,
@@ -174,6 +189,24 @@ export function describeNode(
export const BUILTIN_NODE_KINDS: readonly string[] = [
'event.start', 'event.update', 'event.destroy', 'event.on',
'flow.branch', 'flow.sequence', 'flow.while', 'flow.delay',
+ 'entity.spawn',
'var.get', 'var.set',
'lit.number', 'lit.bool', 'lit.string',
];
+
+/** The prefab an `entity.spawn` node names, or '' — read by the compile step
+ * (to say what to prepare) and by the loader (to prepare it). One reader of
+ * the literal, so the two cannot disagree about which refs a graph needs. */
+export function spawnPrefabRef(node: ScriptGraphNode): string {
+ return node.kind === 'entity.spawn' ? String(node.literals?.prefab ?? '') : '';
+}
+
+/** Every prefab a graph may spawn, deduplicated, in document order. */
+export function scriptGraphPrefabRefs(graph: ScriptGraph): string[] {
+ const out: string[] = [];
+ for (const node of graph.nodes) {
+ const ref = spawnPrefabRef(node);
+ if (ref && !out.includes(ref)) out.push(ref);
+ }
+ return out;
+}
diff --git a/sdk/src/prefab/preparedPrefab.ts b/sdk/src/prefab/preparedPrefab.ts
new file mode 100644
index 000000000..fe72bdd49
--- /dev/null
+++ b/sdk/src/prefab/preparedPrefab.ts
@@ -0,0 +1,150 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file preparedPrefab.ts
+ * @brief A prefab that can be spawned in one frame, because everything it
+ * names is already in hand.
+ *
+ * `instantiatePrefab` is async, and every bit of that is asset loading: nested
+ * prefabs, then the textures and materials the flattened entities reference. A
+ * caller that wants an entity NOW — a script graph's spawn node, a bullet in a
+ * system's body — cannot wait for a microtask and still hand the id to the next
+ * thing it does.
+ *
+ * So the wait is moved: `preparePrefab` does the loading once, at the moment the
+ * thing that will spawn it is itself being loaded, and keeps the flattened scene
+ * with its asset handles already written in. {@link spawnPrepared} is then a
+ * clone and a spawn, synchronous by construction.
+ *
+ * It reuses the scene path rather than reimplementing it — `flattenPrefab`,
+ * `preloadSceneAssets`, `resolveSceneAssetPaths`, `loadSceneData` — so a prefab
+ * spawned this way and the same prefab placed in a scene resolve identically.
+ */
+
+import type { World } from '../ecs/world';
+import type { Entity } from '../types';
+import type { Assets } from '../asset/Assets';
+import { loadSceneData, SCENE_FORMAT_VERSION, type SceneData } from '../scene/scene';
+import { Transform } from '../ecs/component';
+import { flattenPrefab, migratePrefabData, type FlattenContext, type PrefabData, type PrefabOverride } from './index';
+
+/**
+ * A prefab with its loading done: the flattened entities, their asset handles
+ * already written in, and the acquisitions that keeps true.
+ */
+export interface PreparedPrefab {
+ /** The ref it was prepared from — what a report names. */
+ readonly ref: string;
+ /** Flattened, resolved, and never handed out: each spawn clones it. */
+ readonly scene: SceneData;
+ /** Id of the root within {@link scene}. */
+ readonly rootId: number;
+ /** Assets referenced but not loaded — spawning still works, they draw as nothing. */
+ readonly missing: readonly string[];
+ /** Give back everything the preparation took. */
+ release(): void;
+}
+
+/**
+ * Load a prefab and everything it names, and flatten it once.
+ *
+ * The overrides are baked in here, not at spawn: a prepared prefab is one shape
+ * repeated, and a caller that wants two shapes prepares two.
+ */
+export async function preparePrefab(
+ assets: Assets,
+ ref: string,
+ overrides: readonly PrefabOverride[] = [],
+): Promise<PreparedPrefab> {
+ const loaded = await assets.loadPrefab(ref);
+ const normalized = migratePrefabData(loaded.data as PrefabData).data;
+
+ // Nested prefabs first: flattening reads them synchronously, so they have to
+ // be in the cache before it runs.
+ const cache = new Map<string, PrefabData>();
+ await collectNested(assets, normalized, cache);
+
+ let nextId = 0;
+ const ctx: FlattenContext = {
+ allocateId: () => nextId++,
+ loadPrefab: (path: string) => cache.get(path) ?? null,
+ visited: new Set<string>(),
+ };
+ const { entities, rootId } = flattenPrefab(normalized, [...overrides], ctx);
+
+ const scene: SceneData = {
+ version: SCENE_FORMAT_VERSION,
+ name: normalized.name,
+ entities: entities.map((e) => ({
+ id: e.id, name: e.name, parent: e.parent,
+ children: e.children, components: e.components, visible: e.visible,
+ })),
+ };
+
+ // The same preload the scene runs, on the same shape — so a prefab spawned
+ // from here and one placed in a scene get the same handles for the same refs.
+ const result = await assets.preloadSceneAssets(scene);
+ assets.resolveSceneAssetPaths(scene, result);
+
+ return {
+ ref,
+ scene,
+ rootId,
+ missing: result.missing.map((m) => m.ref),
+ release: () => result.scope.releaseAll(),
+ };
+}
+
+/** Load every prefab nested inside `prefab`, into `cache`, depth first. */
+async function collectNested(
+ assets: Assets, prefab: PrefabData, cache: Map<string, PrefabData>,
+): Promise<void> {
+ for (const path of nestedRefs(prefab)) {
+ if (cache.has(path)) continue;
+ // Reserve before awaiting: a prefab that nests itself would otherwise
+ // recurse until the stack gave out.
+ cache.set(path, { entities: [], root: '' } as unknown as PrefabData);
+ const nested = migratePrefabData((await assets.loadPrefab(path)).data as PrefabData).data;
+ cache.set(path, nested);
+ await collectNested(assets, nested, cache);
+ }
+}
+
+/** The prefab paths one prefab's entities nest, in document order. */
+function nestedRefs(prefab: PrefabData): string[] {
+ const out: string[] = [];
+ for (const entity of prefab.entities ?? []) {
+ const ref = (entity as { prefab?: { path?: string } }).prefab?.path;
+ if (typeof ref === 'string' && ref) out.push(ref);
+ }
+ return out;
+}
+
+export interface SpawnPreparedOptions {
+ parent?: Entity;
+ /** Where the root lands. Absent leaves the prefab's own transform. */
+ position?: { x: number; y: number; z?: number };
+}
+
+/**
+ * Spawn a prepared prefab. Synchronous: everything it names is already loaded
+ * and its handles are already in the data, so this is a clone and a spawn.
+ */
+export function spawnPrepared(
+ world: World,
+ prepared: PreparedPrefab,
+ options?: SpawnPreparedOptions,
+): { root: Entity; entities: Map<number, Entity> } {
+ // `loadSceneData` migrates, and migration deep-clones — so the prepared
+ // scene is never mutated and one preparation spawns any number of copies.
+ const entities = loadSceneData(world, prepared.scene);
+ const root = entities.get(prepared.rootId)!;
+ if (options?.parent !== undefined) world.setParent(root, options.parent);
+ if (options?.position) {
+ // Transform is C++-backed, so the read is a copy: change it and hand it back.
+ const transform = world.get(root, Transform);
+ transform.position = { ...transform.position, ...options.position };
+ world.set(root, Transform, transform);
+ }
+ return { root, entities };
+}
diff --git a/sdk/tests/script-graph-runner.test.ts b/sdk/tests/script-graph-runner.test.ts
index cb1ca93c1..e743cf198 100644
--- a/sdk/tests/script-graph-runner.test.ts
+++ b/sdk/tests/script-graph-runner.test.ts
@@ -16,6 +16,7 @@ import {
fireScriptGraphEvent, type ScriptTickContext,
} from '../src/logic/ScriptGraphRunner';
import { SCRIPT_GRAPH_VERSION, type ScriptGraph, type ScriptGraphEdge, type ScriptGraphNode } from '../src/logic/types';
+import { scriptGraphPrefabRefs } from '../src/logic/nodes';
interface TestCtx { log: string[]; }
@@ -351,6 +352,33 @@ describe('flow.delay waits without blocking the frame', () => {
});
});
+describe('entity.spawn', () => {
+ it('names the prefab it needs, so whoever loads the graph can prepare it', () => {
+ const g = graphOf([
+ node('a', 'entity.spawn', { literals: { prefab: 'assets/bullet.esprefab' } }),
+ node('b', 'entity.spawn', { literals: { prefab: 'assets/bullet.esprefab' } }),
+ node('c', 'entity.spawn', { literals: { prefab: 'assets/enemy.esprefab' } }),
+ node('d', 'flow.branch'),
+ ], []);
+ // Deduplicated: two nodes spawning one prefab is one preparation.
+ expect(scriptGraphPrefabRefs(g)).toEqual(['assets/bullet.esprefab', 'assets/enemy.esprefab']);
+ });
+
+ it('reports a prefab nothing prepared instead of spawning nothing quietly', () => {
+ const { reg } = registry();
+ const g = graphOf([
+ node('start', 'event.start'),
+ node('sp', 'entity.spawn', { literals: { prefab: 'assets/gone.esprefab' } }),
+ node('say', 'call', { ref: 'test.say', literals: { text: 'after' } }),
+ ], [edge('start', 'then', 'sp', ''), edge('sp', 'then', 'say', '')]);
+ const r = run(g, reg);
+ r.tick();
+ expect(r.problems.some((p) => p.includes('was not prepared'))).toBe(true);
+ // …and the chain continues: one unspawnable prefab is not the graph.
+ expect(r.log).toEqual(['after']);
+ });
+});
+
describe('a graph that asks for what is not there says so', () => {
it('reports an unregistered name at compile rather than running past it', () => {
const { reg } = registry();
diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjs
index 4bda90e39..653812667 100644
--- a/tools/releaseNotes.mjs
+++ b/tools/releaseNotes.mjs
@@ -28,6 +28,12 @@ export const NOTES_FLOOR = 'v0.65.0';
* the reader recognises anyway.
*/
export const NOTED = {
+ 'feat(logic): a graph can spawn a prefab, and the node says which one':
+ { note: 'Gameplay you can draw.' },
+
+ 'feat(prefab): a prefab you can spawn in one frame, because its loading is done':
+ { note: 'Gameplay you can draw.' },
+
'feat(logic): a graph can reach a keyboard, another entity, and who an event named':
{ note: 'Gameplay you can draw.' },