threedog 1.1.0 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +879 -798
- package/README.md +1 -1
- package/core/assets/Animator.js +41 -3
- package/core/assets/Assets.js +100 -24
- package/core/assets/assetEntry.js +73 -20
- package/core/assets/assetHot.js +68 -16
- package/core/assets/assetLoad.js +6 -6
- package/core/assets/assetLod.js +9 -2
- package/core/assets/assetManifest.js +12 -2
- package/core/assets/assetPart.js +54 -0
- package/core/assets/ik.js +271 -0
- package/core/assets/modelNeeds.js +37 -0
- package/core/assets/namedModel.js +102 -29
- package/core/assets/nodeVisibility.js +15 -0
- package/core/audio/Audio.js +36 -4
- package/core/audio/audioReverb.js +99 -0
- package/core/audio/audioRules.js +1 -1
- package/core/audio/audioVoice.js +1 -1
- package/core/base/Events.js +14 -4
- package/core/base/Random.js +1 -1
- package/core/base/Vars.js +1 -1
- package/core/base/docRef.js +51 -0
- package/core/base/errorCodes.js +178 -126
- package/core/base/errorHints.js +9 -7
- package/core/base/errors.js +25 -10
- package/core/base/events.generated.js +2 -0
- package/core/base/freeParts.js +76 -0
- package/core/base/math.js +28 -0
- package/core/base/sections.js +5 -5
- package/core/base/validate.js +31 -3
- package/core/engine/Engine.js +16 -6
- package/core/engine/Loading.js +5 -3
- package/core/engine/copies.js +1 -1
- package/core/engine/headlessLoad.js +4 -1
- package/core/engine/lifecycle.js +32 -16
- package/core/engine/loop.js +71 -27
- package/core/engine/moduleSlots.js +2 -2
- package/core/engine/moduleTypes.js +3 -3
- package/core/engine/modules.js +65 -39
- package/core/engine/page.js +6 -3
- package/core/engine/services.js +6 -5
- package/core/engine/startup.js +5 -5
- package/core/input/Input.js +28 -14
- package/core/input/inputContext.js +28 -16
- package/core/input/inputKeyboard.js +31 -3
- package/core/input/inputPad.js +4 -0
- package/core/input/inputPointer.js +2 -1
- package/core/input/inputSeat.js +1 -1
- package/core/inspect/Budget.js +109 -19
- package/core/inspect/DebugOverrides.js +28 -4
- package/core/inspect/Describe.js +17 -9
- package/core/inspect/Inspect.js +4 -2
- package/core/inspect/InspectMaterials.js +3 -1
- package/core/inspect/InspectPerf.js +19 -9
- package/core/inspect/InspectScene.js +32 -7
- package/core/inspect/MaterialInfo.js +19 -2
- package/core/inspect/UrlState.js +46 -27
- package/core/inspect/catalog.js +28 -9
- package/core/inspect/debugView.js +2 -1
- package/core/inspect/describeRender.js +25 -13
- package/core/inspect/describeText.js +14 -6
- package/core/inspect/lightWatch.js +1 -1
- package/core/inspect/metadata.generated.js +35 -17
- package/core/inspect/pictureChecks.js +148 -0
- package/core/inspect/pictureMenu.js +84 -0
- package/core/inspect/pictureWriters.js +26 -6
- package/core/inspect/textureBytes.js +12 -2
- package/core/inspect/toolDoor.js +2 -4
- package/core/ops/Ops.js +11 -4
- package/core/ops/holds.js +27 -10
- package/core/ops/opsAtomic.js +15 -7
- package/core/ops/opsGuard.js +2 -2
- package/core/ops/opsRun.js +8 -7
- package/core/ops/sharedPoint.js +72 -21
- package/core/ops/stacks.js +56 -16
- package/core/saves/SaveStore.js +9 -3
- package/core/saves/Saves.js +32 -23
- package/core/saves/saveApply.js +96 -44
- package/core/saves/saveIds.js +1 -1
- package/core/saves/saveVersions.js +7 -5
- package/core/saves/session.js +17 -8
- package/core/saves/stateReplace.js +34 -15
- package/core/scene/Rays.js +52 -10
- package/core/scene/Views.js +13 -7
- package/core/scene/adaptive.js +144 -21
- package/core/scene/drawOnly.js +17 -0
- package/core/scene/gameLights.js +44 -3
- package/core/scene/sceneMethods.js +13 -11
- package/core/scene/stepPoses.js +11 -3
- package/core/scene/targeting.js +5 -3
- package/core/scene/thingOps.js +1 -1
- package/core/scene/tier.js +15 -0
- package/core/stream/Batching.js +30 -7
- package/core/stream/Stream.js +26 -7
- package/core/stream/batchGroups.js +2 -2
- package/core/stream/chunkStream.js +7 -5
- package/core/stream/prepare.js +77 -0
- package/core/time/skip.js +3 -1
- package/core/time/time.js +4 -2
- package/docs/AI.md +82 -83
- package/docs/API.md +16 -16
- package/docs/CODEMAP.md +16 -11
- package/docs/COMMANDS.md +139 -142
- package/docs/CONVENTIONS.md +37 -49
- package/docs/MIGRATING-0.8.md +2 -2
- package/docs/MIGRATING-1.0.md +2 -2
- package/docs/THREE.md +28 -35
- package/docs/api/assets.md +3 -1
- package/docs/api/audio.md +4 -2
- package/docs/api/budget.md +5 -0
- package/docs/api/characters.md +10 -8
- package/docs/api/collision.md +6 -4
- package/docs/api/engine.md +16 -16
- package/docs/api/events.md +3 -2
- package/docs/api/ground.md +6 -5
- package/docs/api/hud.md +4 -2
- package/docs/api/input.md +5 -5
- package/docs/api/particles.md +2 -1
- package/docs/api/photo.md +3 -0
- package/docs/api/post.md +7 -4
- package/docs/api/quests.md +2 -2
- package/docs/api/rays.md +1 -2
- package/docs/api/saves.md +7 -7
- package/docs/api/settings.md +2 -2
- package/docs/api/tools.md +3 -1
- package/docs/api/vars.md +1 -1
- package/docs/api/vegetation.md +4 -2
- package/docs/api/world.md +1 -1
- package/docs/recipes/01-new-game.md +16 -17
- package/docs/recipes/02-npc.md +22 -18
- package/docs/recipes/03-items-pickups.md +37 -35
- package/docs/recipes/04-quests.md +15 -10
- package/docs/recipes/05-props-bake.md +101 -95
- package/docs/recipes/06-clock-events.md +28 -28
- package/docs/recipes/07-flow-scenes-pause.md +29 -26
- package/docs/recipes/08-weather-sky.md +52 -64
- package/docs/recipes/09-materials-lights-models.md +26 -17
- package/docs/recipes/10-blender-level.md +15 -10
- package/docs/recipes/11-vehicles.md +12 -7
- package/docs/recipes/12-navmesh.md +44 -26
- package/docs/recipes/13-animation.md +56 -45
- package/docs/recipes/14-custom-module.md +21 -18
- package/docs/recipes/15-perf.md +61 -55
- package/docs/recipes/16-dev-bridge.md +23 -33
- package/docs/recipes/18-world.md +36 -42
- package/docs/recipes/19-shooting-picking.md +20 -15
- package/docs/recipes/20-content-actions-save.md +48 -56
- package/docs/recipes/21-camera.md +45 -54
- package/docs/recipes/22-shop-gold.md +12 -7
- package/docs/recipes/23-ops.md +25 -23
- package/docs/recipes/26-ui-parts.md +67 -47
- package/docs/recipes/27-net.md +12 -7
- package/docs/recipes/28-terrain.md +24 -21
- package/docs/recipes/29-grid.md +32 -27
- package/docs/recipes/30-templates.md +21 -20
- package/docs/recipes/31-audio.md +39 -22
- package/docs/recipes/32-action-game.md +19 -14
- package/docs/recipes/33-stream-sources.md +15 -11
- package/docs/recipes/34-environment-lighting.md +126 -70
- package/docs/recipes/35-picture-from-reference.md +8 -8
- package/docs/recipes/36-ground-plants.md +27 -21
- package/docs/recipes/40-scene.md +19 -28
- package/docs/recipes/43-shader-patches-surfaces.md +15 -12
- package/docs/recipes/44-water-weather-hooks.md +34 -31
- package/docs/recipes/45-cascaded-shadows.md +35 -26
- package/docs/recipes/46-blender-art-route.md +6 -1
- package/docs/recipes/49-game-module-contract.md +13 -8
- package/docs/recipes/50-own-renderer.md +6 -2
- package/docs/recipes/51-capability-catalog.md +15 -8
- package/docs/recipes/52-around-the-picture.md +34 -32
- package/docs/recipes/53-ground-up-close.md +6 -1
- package/docs/recipes/55-mods-time-wrap.md +27 -19
- package/docs/recipes/56-webgpu-tsl.md +74 -43
- package/docs/recipes/57-control.md +18 -13
- package/docs/recipes/58-input.md +26 -16
- package/docs/recipes/59-depth-post-effects.md +8 -3
- package/docs/recipes/60-judge-the-picture.md +9 -8
- package/docs/recipes/61-deploy.md +5 -0
- package/docs/recipes/62-picture-code.md +70 -79
- package/docs/recipes/63-third-person-start.md +47 -45
- package/docs/recipes/64-particles.md +22 -10
- package/docs/recipes/65-swarm.md +18 -13
- package/docs/recipes/66-common-tasks.md +38 -35
- package/examples/action/GAMEMAP.md +2 -3
- package/examples/action/main.js +3 -3
- package/examples/action/picture/lights.js +3 -1
- package/examples/perf-island/GAMEMAP.md +3 -3
- package/examples/perf-island/picture/lights.js +2 -1
- package/examples/plain-picture/GAMEMAP.md +1 -1
- package/examples/rc2d/GAMEMAP.md +1 -1
- package/examples/styletest/GAMEMAP.md +2 -2
- package/examples/styletest/main.js +1 -1
- package/examples/techniques/interior-light/README.md +3 -3
- package/examples/techniques/interior-light/interiorLight.js +2 -4
- package/examples/techniques/interior-light/picture/lights.js +2 -1
- package/examples/techniques/modular-building/picture/lights.js +3 -1
- package/examples/techniques/outlines-and-rim/picture/lights.js +3 -1
- package/examples/techniques/procedural-animation/README.md +1 -1
- package/examples/techniques/procedural-animation/main.js +1 -1
- package/examples/webgpu-tsl/GAMEMAP.md +1 -1
- package/examples/world/GAMEMAP.md +2 -3
- package/examples/world/art/humanoid.js +1 -1
- package/examples/world/main.js +6 -3
- package/index.d.ts +2 -2
- package/llms.txt +101 -0
- package/modules/ambience/Ambience.js +21 -5
- package/modules/calendar/index.js +9 -5
- package/modules/calendar/schedule.js +23 -8
- package/modules/camera/FirstPersonCamera.js +3 -1
- package/modules/camera/FollowCamera.js +10 -5
- package/modules/camera/RtsCamera.js +4 -3
- package/modules/camera/common.js +70 -8
- package/modules/camera/contract.js +1 -1
- package/modules/characters/Character.js +16 -10
- package/modules/characters/NPC.js +31 -19
- package/modules/characters/assetModel.js +14 -9
- package/modules/characters/astar.js +6 -1
- package/modules/characters/contract.js +2 -2
- package/modules/characters/index.js +34 -22
- package/modules/characters/movers/manual.js +1 -1
- package/modules/characters/movers/rapier.js +17 -2
- package/modules/characters/movers/simple.js +1 -1
- package/modules/characters/movers/support.js +16 -7
- package/modules/characters/npcAvoid.js +2 -2
- package/modules/characters/npcSim.js +3 -2
- package/modules/characters/pathAsync.js +24 -8
- package/modules/characters/pathJob.js +1 -1
- package/modules/characters/player.js +10 -9
- package/modules/characters/playerStrings.js +5 -5
- package/modules/characters/proceduralRig.js +5 -5
- package/modules/characters/useModel.js +6 -0
- package/modules/characters/walkTo.js +1 -1
- package/modules/collision/Collision.js +29 -18
- package/modules/collision/grid.js +22 -4
- package/modules/content/index.js +3 -1
- package/modules/content/loader.js +1 -1
- package/modules/content/models.js +82 -33
- package/modules/content/props.js +2 -1
- package/modules/content/rules.js +11 -5
- package/modules/content/templates.js +3 -3
- package/modules/content/words.js +2 -2
- package/modules/debug/DebugPanel.js +9 -9
- package/modules/flow/index.js +9 -6
- package/modules/gameplay/Dialogue.js +34 -20
- package/modules/gameplay/Interactions.js +19 -15
- package/modules/gameplay/Inventory.js +9 -4
- package/modules/gameplay/Quests.js +12 -10
- package/modules/gameplay/pickups.js +23 -11
- package/modules/grid/index.js +1 -1
- package/modules/grid/preview.js +2 -2
- package/modules/grid/tiles.js +1 -1
- package/modules/hlod/index.js +4 -1
- package/modules/hud/index.js +47 -10
- package/modules/hud/parts.js +28 -9
- package/modules/level/geometry.js +8 -3
- package/modules/level/index.js +10 -5
- package/modules/level/load.js +4 -2
- package/modules/lights/sources.js +1 -1
- package/modules/music/Music.js +22 -4
- package/modules/nav/index.js +20 -10
- package/modules/particles/Particles.js +31 -14
- package/modules/particles/effect.js +20 -5
- package/modules/particles/lit.js +72 -0
- package/modules/photo/Photo.js +72 -28
- package/modules/photo/pathTrace.js +106 -0
- package/modules/rigid/RigidBodies.js +23 -14
- package/modules/rigid/Vehicles.js +3 -13
- package/modules/rigid/sync.js +2 -1
- package/modules/settings/Settings.js +52 -20
- package/modules/settings/apply.js +23 -9
- package/modules/settings/sections.js +39 -6
- package/modules/settings/strings.js +2 -0
- package/modules/settings/view.js +19 -3
- package/modules/sky/dome.js +15 -3
- package/modules/sky/environment.js +28 -12
- package/modules/sky/fog.js +1 -1
- package/modules/sky/frame.js +6 -1
- package/modules/sky/shader.js +4 -3
- package/modules/sky/skyModule.js +8 -4
- package/modules/swarm/Swarm.js +1 -1
- package/modules/terrain/ChunkManager.js +61 -15
- package/modules/terrain/chunkJob.js +2 -2
- package/modules/terrain/index.js +20 -5
- package/modules/terrain/terrainEdit.js +8 -4
- package/modules/terrain/terrainTexture.js +4 -2
- package/modules/timeline/Timeline.js +4 -3
- package/modules/timeline/Tween.js +3 -0
- package/modules/timeline/letterbox.js +1 -0
- package/modules/triggers/index.js +36 -17
- package/modules/vegetation/Vegetation.js +81 -19
- package/modules/vegetation/densityMap.js +13 -8
- package/modules/vegetation/draw.js +147 -24
- package/modules/vegetation/groundChunks.js +20 -5
- package/modules/vegetation/index.js +3 -3
- package/modules/vegetation/modelGeometry.js +9 -4
- package/modules/water/Water.js +11 -8
- package/modules/weather/Weather.js +7 -2
- package/modules/weather/shaders.js +25 -5
- package/modules/weather/weatherDraw.js +20 -6
- package/modules/world/World.js +2 -1
- package/modules/world/index.js +2 -2
- package/modules/world/persist.js +6 -2
- package/modules/world/views.js +15 -2
- package/package.json +4 -1
- package/presets.js +5 -5
- package/render/PostFX.js +84 -41
- package/render/backend.js +137 -16
- package/render/cascades.js +3 -1
- package/render/cascades.tsl.js +2 -0
- package/render/daylight.js +7 -1
- package/render/detail.js +7 -4
- package/render/effects.js +27 -8
- package/render/fogLook.js +24 -0
- package/render/fuse.js +5 -2
- package/render/fx/detail.tsl.js +9 -7
- package/render/fx/index.js +7 -2
- package/render/fx/library.tsl.js +1 -0
- package/render/fx/lightShaft.tsl.js +114 -0
- package/render/fx/noise.tsl.js +25 -8
- package/render/fx/objectOrigin.tsl.js +39 -10
- package/render/fx/particles.tsl.js +23 -6
- package/render/fx/patchNodes.tsl.js +17 -12
- package/render/fx/pcss.tsl.js +51 -0
- package/render/fx/postWebGPU.tsl.js +89 -29
- package/render/fx/sky.tsl.js +3 -9
- package/render/fxNumbers.js +10 -4
- package/render/impostor.tsl.js +107 -0
- package/render/lighting.js +33 -1
- package/render/lightmap.js +42 -28
- package/render/lights.js +19 -3
- package/render/materials.js +6 -4
- package/render/mergeCommon.js +4 -1
- package/render/occlusion.js +14 -4
- package/render/patches.js +79 -41
- package/render/postRuns.js +32 -0
- package/render/postWebGL.js +97 -10
- package/render/probes.js +10 -14
- package/render/shaderErrors.js +2 -1
- package/render/shadowCache.tsl.js +33 -5
- package/render/shadows.js +42 -16
- package/render/slots.js +8 -5
- package/render/vertexInputs.js +52 -0
- package/types/core.d.ts +114 -46
- package/types/gameplay.d.ts +56 -23
- package/types/generated/core/audio/Audio.d.ts +27 -1
- package/types/generated/core/base/Random.d.ts +1 -1
- package/types/generated/core/input/Input.d.ts +6 -8
- package/types/generated/core/input/inputSeat.d.ts +1 -1
- package/types/generated/core/inspect/Budget.d.ts +26 -0
- package/types/generated/core/inspect/DebugOverrides.d.ts +0 -2
- package/types/generated/core/saves/Saves.d.ts +10 -7
- package/types/generated/core/saves/session.d.ts +8 -2
- package/types/generated/core/scene/Rays.d.ts +1 -3
- package/types/generated/modules/particles/Particles.d.ts +1 -1
- package/types/generated/modules/world/World.d.ts +2 -1
- package/types/generated/render/PostFX.d.ts +35 -9
- package/types/physics.d.ts +796 -764
- package/types/pixel.d.ts +1 -1
- package/types/tsl.d.ts +62 -1
- package/types/world.d.ts +12 -3
- package/ui/Focus.js +7 -5
- package/ui/Parts.js +1 -1
- package/ui/touchPart.js +6 -3
|
@@ -1,5 +1,10 @@
|
|
|
1
1
|
# Physics: rigid bodies, pushing, joints, vehicles
|
|
2
2
|
|
|
3
|
+
> **Covers:** rigid bodies, pushing, joints, vehicles, boarding and driving, ragdolls.
|
|
4
|
+
> **Use when:** crates that tumble, doors on hinges, a car or a boat.
|
|
5
|
+
> **Shortest:** `engine.rigid.addBox(mesh, { id })` with `rigid()` installed (§3).
|
|
6
|
+
> **Sections:** 1 Build a car · 2 Boarding and driving · 3 Rigid bodies saves · 3b Ragdoll experimental) · 4 Verify
|
|
7
|
+
|
|
3
8
|
Any physics body (crates the player pushes, balls, doors on hinges, ropes): §3, read it first when the game has no car. Cars and
|
|
4
9
|
boarding: §1–2.
|
|
5
10
|
|
|
@@ -18,7 +23,7 @@ function makeCar() {
|
|
|
18
23
|
body.position.y = 0.3; body.castShadow = true; car.add(body);
|
|
19
24
|
const wheels = [[-0.85, 1.2, true, false], [0.85, 1.2, true, false], [-0.85, -1.2, false, true], [0.85, -1.2, false, true]].map(([x, z, steer, drive]) => {
|
|
20
25
|
const w = new THREE.Mesh(new THREE.CylinderGeometry(0.35, 0.35, 0.25, 10).rotateZ(Math.PI / 2), new THREE.MeshLambertMaterial({ color: 0x333333 }));
|
|
21
|
-
w.position.set(x, 0, z); car.add(w);
|
|
26
|
+
w.position.set(x, 0, z); car.add(w); // wheels are children of the body: they follow suspension, steering and rolling
|
|
22
27
|
return { position: [x, 0, z], radius: 0.35, steer, drive, object: w };
|
|
23
28
|
});
|
|
24
29
|
return { car, wheels };
|
|
@@ -26,9 +31,9 @@ function makeCar() {
|
|
|
26
31
|
|
|
27
32
|
engine.events.on('engine:ready', () => {
|
|
28
33
|
const { car, wheels } = makeCar();
|
|
29
|
-
car.position.set(10, engine.surface(10, 0) + 1.5, 0);
|
|
34
|
+
car.position.set(10, engine.surface(10, 0) + 1.5, 0); // place it slightly above the ground and let it drop
|
|
30
35
|
const v = engine.rigid.addWheeled(car, { wheels, mass: 600, engineForce: 3000, camera: { distance: 14, height: 2 } });
|
|
31
|
-
window.car = v;
|
|
36
|
+
window.car = v; // handy for tests and the console
|
|
32
37
|
});
|
|
33
38
|
```
|
|
34
39
|
Options: `../api/rigid.md` (VehicleOptions). `id` is the stable id saves use (default `vehicle1`, `vehicle2`... in creation order; give one when that order varies).
|
|
@@ -71,14 +76,14 @@ where a game re-creates its joints, with the same code that made them:
|
|
|
71
76
|
```js fragment
|
|
72
77
|
const R = engine.rigid, J = R.rapier.JointData;
|
|
73
78
|
const post = R.addBox(postMesh, { fixed: true }), door = R.addBox(doorMesh, { mass: 8 });
|
|
74
|
-
function hang() {
|
|
79
|
+
function hang() { // makes the joints; called after the bodies are added, and again after every rebuild
|
|
75
80
|
// hinge on the post's right edge, turning around Y; anchors are in each body's local space
|
|
76
81
|
const h = R.world.createImpulseJoint(J.revolute({ x: 0.5, y: 0, z: 0 }, { x: -0.5, y: 0, z: 0 }, { x: 0, y: 1, z: 0 }), post.body, door.body, true);
|
|
77
82
|
h.setLimits(-1.5, 1.5);
|
|
78
83
|
R.world.createImpulseJoint(J.rope(2, { x: 0, y: -0.5, z: 0 }, { x: 0, y: 0.5, z: 0 }), hook.body, weight.body, true);
|
|
79
84
|
}
|
|
80
85
|
hang();
|
|
81
|
-
engine.events.on('rigid:rebuilt', hang);
|
|
86
|
+
engine.events.on('rigid:rebuilt', hang); // { world, player, bodies }: bodies maps the ids you gave addBox / addBall / addHull
|
|
82
87
|
```
|
|
83
88
|
`entry.body` already points at the rebuilt body there; a joint object kept from before belongs to the freed world (hold the new one). A body
|
|
84
89
|
the game made with `world.createRigidBody` is not rebuilt: make anchors with `addBox(mesh, { fixed: true })`. In development a `rigid-misuse`
|
|
@@ -99,8 +104,8 @@ stay). Removing a body removes its joints (Rapier does that).
|
|
|
99
104
|
## 3b. Ragdoll (experimental)
|
|
100
105
|
|
|
101
106
|
```js fragment
|
|
102
|
-
const rd = engine.rigid.ragdoll(enemy, { impulse: [0, 150, -400], position: hit.point });
|
|
103
|
-
engine.clock.after(4, () => rd.remove(), { channel: 'real' });
|
|
107
|
+
const rd = engine.rigid.ragdoll(enemy, { impulse: [0, 150, -400], position: hit.point }); // a Character, NPC handle, id or skinned Object3D
|
|
108
|
+
engine.clock.after(4, () => rd.remove(), { channel: 'real' }); // back to animation where the body lies; a get-up clip is yours to play
|
|
104
109
|
```
|
|
105
110
|
- **Skeletons.** Mixamo, Blender, Unreal, Bip01, VRM and Quaternius names are read by themselves. Otherwise name the parts: `{ bones: { lowerLegL: 'Shin_01' } }`; an unreadable skeleton throws, naming the missing parts.
|
|
106
111
|
Parts: `hips chest head upperArmL lowerArmL upperArmR lowerArmR upperLegL lowerLegL upperLegR lowerLegR`.
|
|
@@ -1,9 +1,14 @@
|
|
|
1
1
|
# Navigation mesh (nav)
|
|
2
2
|
|
|
3
|
+
> **Covers:** the navigation mesh, paths, many paths at once, links across gaps, sight lines.
|
|
4
|
+
> **Use when:** characters walk around obstacles to a goal.
|
|
5
|
+
> **Shortest:** `engine.characters.findPath(from, to)` (with `nav()` for a mesh).
|
|
6
|
+
> **Sections:** 1 Install main.js) · 2 Use · 3 Verify · 4 Many paths at · 5 One source for · 6 NPC links across · Fences and rivers collision) · Gates some characters pass · Line of sight, stealth
|
|
7
|
+
|
|
3
8
|
There is a single pathfinding entry point: `engine.characters.findPath(from, to)`; NPC schedules use it too.
|
|
4
9
|
- Without `nav()` (or before it is built): the collision module's grid A* (good enough for open terrain with a few obstacles).
|
|
5
10
|
- With `nav()`: after a level loads, a Recast navmesh is built; paths are more accurate and go around walls more cleverly. **Only level ground (the
|
|
6
|
-
level module) is supported**; procedural terrain keeps using A*. The mesh is built once per level: `engine.terrain.edit` and other ground changes do not
|
|
11
|
+
level module) is supported**; procedural terrain keeps using A*. Without a level mesh dev warns once (`nav-fallback`): A* has no nav links, crowd or floor changes. The mesh is built once per level: `engine.terrain.edit` and other ground changes do not
|
|
7
12
|
update it, so a game that reshapes walkable ground at runtime leaves `nav()` out.
|
|
8
13
|
|
|
9
14
|
## 1. Install (main.js)
|
|
@@ -11,7 +16,7 @@ A level is a file or a `THREE.Object3D` built in code: `level({ scene: group })`
|
|
|
11
16
|
```js fragment
|
|
12
17
|
import { level, collision, followCamera, characters, nav } from 'threedog';
|
|
13
18
|
engine.use(level({ url: '/models/town.glb' }), collision(), followCamera(), characters(),
|
|
14
|
-
nav({ agentRadius: 0.4, agentHeight: 1.8, maxClimb: 0.45, maxSlope: 45, debug: false }));
|
|
19
|
+
nav({ agentRadius: 0.4, agentHeight: 1.8, maxClimb: 0.45, maxSlope: 45, debug: false })); // debug: true draws the navmesh
|
|
15
20
|
```
|
|
16
21
|
- Mesh source: the walkable meshes in the level (naming convention in `10-blender-level.md`). Walls = the level's `col_` boxes + every
|
|
17
22
|
`addBox / addCircle` in the collision module;
|
|
@@ -20,11 +25,11 @@ engine.use(level({ url: '/models/town.glb' }), collision(), followCamera(), char
|
|
|
20
25
|
|
|
21
26
|
## 2. Use
|
|
22
27
|
```js fragment
|
|
23
|
-
const path = engine.characters.findPath(engine.player.position, { x: 4, z: 5 });
|
|
24
|
-
const wall = engine.collision.addBox([16, 0, 0], { halfWidth: 4.5, halfDepth: 1 });
|
|
25
|
-
wall.remove();
|
|
28
|
+
const path = engine.characters.findPath(engine.player.position, { x: 4, z: 5 }); // [{ x, y, z }...] or null (unreachable); a y on either end picks the floor
|
|
29
|
+
const wall = engine.collision.addBox([16, 0, 0], { halfWidth: 4.5, halfDepth: 1 }); // temporarily block a gap (center, half width, half depth); the navmesh updates with it
|
|
30
|
+
wall.remove(); // remove the obstacle
|
|
26
31
|
engine.npcs.add({ name: 'Courier', position: [4, 0, -5], schedule: [{ at: 0, position: [4, 0, 5] }] }); // the NPC finds its own way there
|
|
27
|
-
engine.nav.dispose();
|
|
32
|
+
engine.nav.dispose(); // unload the navmesh; afterwards A* is used again
|
|
28
33
|
```
|
|
29
34
|
Native Recast objects: `engine.nav.navMesh / query / tileCache / crowd` (crowd needs `nav({ crowd: true })`).
|
|
30
35
|
|
|
@@ -38,13 +43,13 @@ Native Recast objects: `engine.nav.navMesh / query / tileCache / crowd` (crowd n
|
|
|
38
43
|
|
|
39
44
|
## 4. Many paths at once: findPathAsync
|
|
40
45
|
`findPath` answers now, on the main thread. For crowds (dozens of NPCs repathing, AI squads) use `findPathAsync`: the same search (navmesh if ready, else A*)
|
|
41
|
-
runs in `engine.threads` workers and `done(path, status)` runs at the start of a fixed step about 4 steps (67 ms) later, through `
|
|
46
|
+
runs in `engine.threads` workers and `done(path, status)` runs at the start of a fixed step about 4 steps (67 ms) later, through `ctx.commits`.
|
|
42
47
|
```js fragment
|
|
43
|
-
const req = engine.characters.findPathAsync(guard.position, target, (path, status) => {
|
|
48
|
+
const req = engine.characters.findPathAsync(guard.position, target, (path, status) => { // status 'ok' | 'noPath' | 'notReady', as findPath({ detailed: true })
|
|
44
49
|
guard.path = path;
|
|
45
50
|
}, { radius: 0.5 });
|
|
46
|
-
req.remove();
|
|
47
|
-
engine.characters.pathsPerStep = 64;
|
|
51
|
+
req.remove(); // the target changed before the answer came: done is never called
|
|
52
|
+
engine.characters.pathsPerStep = 64; // requests sent per fixed step (default 32); the rest wait in order
|
|
48
53
|
```
|
|
49
54
|
- Built-in NPCs already use it; keep `findPath` for the few calls that need a path this step (player click-to-move).
|
|
50
55
|
- threads on / off / slow / crashed give identical paths on the identical step: the worker mirrors the navmesh (exported bytes) and the collision colliders;
|
|
@@ -58,45 +63,45 @@ engine.characters.pathsPerStep = 64; // requests sent per fixed step (
|
|
|
58
63
|
navmesh, A* and level steps all read it, so a module never writes its own 0.4 or 0.45. A character's position belongs to its mover: other systems
|
|
59
64
|
request movement (`placeAt`, `move`, vehicle `enter`) and never set `player.position`.
|
|
60
65
|
|
|
61
|
-
A navmesh is cut for one body
|
|
66
|
+
A navmesh is cut for one body; other sizes get their own. `nav({ agentRadius })` is the size built at load; a path with another `radius` (`findPath`, `findPathAsync`, `walkTo` and NPCs, which pass the character's own) uses a mesh of that size, built on first ask and kept until the next rebuild. A small body takes the gap a large one cannot; a body too wide for every way gets `noPath` and stays put.
|
|
62
67
|
- Sizes are whole cells (`cellSize`, 0.3 m by default), rounded up: 0.5 and 0.6 share a mesh, and only a body no wider than `agentRadius` shares that one. To tell closer sizes apart, or fit a gap within a cell of the body, make `cellSize` smaller.
|
|
63
|
-
- Each extra size is another mesh in memory,
|
|
68
|
+
- Each extra size is another mesh in memory, built on the main thread at its first ask: about 10 ms on a 40 m level, 0.3 s on a 200 m one with 300 walls. Ask once during loading: `engine.nav.findPath(a, b, { radius })`. Obstacles and rebuilds reach all sizes.
|
|
64
69
|
- Links exist on each size where both ends still reach its mesh, and their ends sit a little differently on each. `engine.nav.links` is the links of `agentRadius`; `crossing.to` on a path is the walker's own.
|
|
65
70
|
- Height, step and slope are the same for all sizes: only the radius differs.
|
|
66
71
|
- `nav({ crowd: true })` keeps one crowd on the `agentRadius` mesh: Recast's crowd runs on a single mesh, so give it the size of the widest crowd NPC. Use plain NPCs where sizes must differ.
|
|
67
72
|
|
|
68
|
-
Floors: a `y` on a path, a stop or `collision.walkable([x, y, z])` picks the floor nearest that height, and `{ x, z }` means the ground. A height more than `engine.movement.height` from every surface there goes to the nearest one and warns once `[nav-height]`. A box added with `y` blocks only that floor, for
|
|
73
|
+
Floors: a `y` on a path, a stop or `collision.walkable([x, y, z])` picks the floor nearest that height, and `{ x, z }` means the ground. A height more than `engine.movement.height` from every surface there goes to the nearest one and warns once `[nav-height]`. A box added with `y` blocks only that floor, for every mover. Between floors takes the navmesh; A* answers `noPath` for a goal on another floor. Without `nav()` a game names its stairs: `engine.mod('characters.path', { owner, set: ({ from, to }) => points })` returns waypoints with `y` that `walkTo`, NPCs and `findPath` follow; a walker that falls off asks again, so it must work from anywhere.
|
|
69
74
|
|
|
70
75
|
## 6. NPC links across gaps
|
|
71
76
|
A link joins two places no one can walk between (Recast calls it an off-mesh connection): a gap, a ledge, a teleporter. Paths use it like any other way, and a walker with no help from the game crosses in a straight line at walking speed.
|
|
72
77
|
```js fragment
|
|
73
78
|
nav({ links: [
|
|
74
|
-
{ id: 'gap', from: [-2.2, 0, 0], to: [2.2, 1.5, 0] },
|
|
75
|
-
{ id: 'drop', from: [10, 4, 2], to: [12, 0, 2], oneWay: true },
|
|
79
|
+
{ id: 'gap', from: [-2.2, 0, 0], to: [2.2, 1.5, 0] }, // both ways
|
|
80
|
+
{ id: 'drop', from: [10, 4, 2], to: [12, 0, 2], oneWay: true }, // down only
|
|
76
81
|
] });
|
|
77
|
-
const path = engine.characters.findPath(a, b);
|
|
82
|
+
const path = engine.characters.findPath(a, b); // [{ x, y, z }, { x, y, z, link: { id: 'gap', from, to } }, { x, y, z }...]: the leg after a point with link is the crossing
|
|
78
83
|
```
|
|
79
84
|
- Put each end on or near walkable ground: within `radius` sideways (default the agent radius + 3 cells, enough for a point at a ledge or a ladder just off it) and within `maxClimb` in height. A `y` left out is the ground there.
|
|
80
|
-
- Each end then moves onto the mesh, and that is where walkers step on and land: the mesh stops about the agent radius short of every edge, so a ladder at a deck's side or through a hatch ends 0.6 to 0.8 m in from the edge (cells round it),
|
|
85
|
+
- Each end then moves onto the mesh, and that is where walkers step on and land: the mesh stops about the agent radius short of every edge, so a ladder at a deck's side or through a hatch ends 0.6 to 0.8 m in from the edge (cells round it), wherever its top was written. `engine.nav.links` and `crossing.to` give those places. The straight line between them cuts the deck's edge: a ladder that must look straight uses `linkPose` (below) to climb first and step in last.
|
|
81
86
|
- A link reaches at most the neighbouring tile, counted where its ends meet the mesh: two platforms up to `tileSize` x `cellSize` meters (9.6 m by default) minus a little on each side. An end that attaches nowhere gets the `nav-link` warning at the build; no path uses that link.
|
|
82
87
|
- An obstacle on an end cuts the link until the obstacle goes. Elsewhere, rebuilt tiles keep their links, and `findPathAsync` sees the same ones. Links are fixed at `nav()`: none can be added at run time.
|
|
83
88
|
|
|
84
89
|
The engine moves the walker and says when; how it looks and how long it takes are yours. NPCs, `character.walkTo` and `nav({ crowd: true })` NPCs all cross this way. There is no default animation: the body keeps its last state.
|
|
85
90
|
```js
|
|
86
|
-
engine.events.on('link:enter', ({ character, crossing }) => {
|
|
91
|
+
engine.events.on('link:enter', ({ character, crossing }) => { // crossing: { link, from, to, seconds, time }
|
|
87
92
|
if (crossing.link === 'gap') { crossing.seconds = 0.7; character.playAction('jump'); }
|
|
88
93
|
});
|
|
89
94
|
engine.events.on('link:exit', ({ id, crossing }) => console.log(id, 'crossed', crossing.link));
|
|
90
|
-
engine.characters.linkPose = (t, position) => { position.y += Math.sin(t * Math.PI) * 1.2; };
|
|
91
|
-
engine.characters.linkPose = (t, position, { from: a, to: b }) => {
|
|
95
|
+
engine.characters.linkPose = (t, position) => { position.y += Math.sin(t * Math.PI) * 1.2; }; // t 0-1: bend the straight line into a hop
|
|
96
|
+
engine.characters.linkPose = (t, position, { from: a, to: b }) => { // or through a hatch: up the opening, then the step onto the deck; coming down, the step first
|
|
92
97
|
const up = b.y > a.y, side = up ? Math.max(0, t - 0.85) / 0.15 : Math.min(1, t / 0.15), rise = up ? Math.min(1, t / 0.85) : Math.max(0, t - 0.15) / 0.85;
|
|
93
98
|
position.set(a.x + (b.x - a.x) * side, a.y + (b.y - a.y) * rise, a.z + (b.z - a.z) * side);
|
|
94
99
|
};
|
|
95
100
|
```
|
|
96
|
-
- During a crossing the walker has no gravity or collision
|
|
97
|
-
- An NPC's crossing is saved (`rec.nav.link`). After a load it goes on from the same spot: `link:enter` is not sent again
|
|
101
|
+
- During a crossing the walker has no gravity or collision; its talk, goal and behavior wait. `npc.placeAt` ends it (`link:exit` still comes). A control holder above the walker (a cutscene, a ragdoll, a `walkTo` on an NPC) does not wait: the walker lands at the far end at once, with `link:exit`. A walker with no speed (a `move.speed` mod of 0) also lands at once, unless `link:enter` sets `seconds`.
|
|
102
|
+
- An NPC's crossing is saved (`rec.nav.link`). After a load it goes on from the same spot: `link:enter` is not sent again (a clip started there does not restart); `linkPose` and `link:exit` work as before. An NPC out of range mid-crossing lands at the far end at once, with `character: null` in `link:exit`. A `walkTo` is not saved: its crossing ends with the walk, and `walk.remove()` lands the character at the far end.
|
|
98
103
|
- `linkPose` must depend only on its arguments, or a loaded crossing jumps. The game cannot hold a walker on a link until a clip ends: give `seconds` the clip's length.
|
|
99
|
-
- With `crowd: true` the crowd takes a link about 1 m short of its end, so the NPC walks the rest and crosses from the end like any walker; the agent is pulled back to the NPC after the crossing, and only the character's own crossing counts. Recast does not say which link an agent took, so the nearest link end is used: keep the ends of two links apart. Recast times
|
|
104
|
+
- With `crowd: true` the crowd takes a link about 1 m short of its end, so the NPC walks the rest and crosses from the end like any walker; the agent is pulled back to the NPC after the crossing, and only the character's own crossing counts. Recast does not say which link an agent took, so the nearest link end is used: keep the ends of two links apart. Recast times a traversal by x, z distance, so ends closer than speed / 30 m (a ladder straight up through a solid deck) are over before the NPC sees them: not for crowd NPCs. Through an opening the ends are far enough apart.
|
|
100
105
|
- A link has no queue. Walkers on it share the line and pass through each other, up and down at once, and other agents do not avoid them: six crowd NPCs pacing through one hatch never jammed (44 crossings in 46 s), often two on it 0.2 m apart. Taking turns is the game's.
|
|
101
106
|
- A walker is not done while a link is left on its path, however close the goal is in x, z, so a goal at the top of a ladder is reached at the top. An NPC standing within `arriveDistance` of such a goal with no path yet, or one steered by the crowd, still stops at the foot: give the goal a place away from the ladder.
|
|
102
107
|
- Paths choose a link by its length, like walking: there is no extra cost for a jump. Start and goal heights still come from `engine.surface`, so a path from under a deck starts on top of it.
|
|
@@ -113,12 +118,25 @@ engine.collision.addSegment([-18, 0, -12], [-18, 0, -4]);
|
|
|
113
118
|
engine.collision.addSegment([-18, 0, 0], [-18, 0, 12], { thickness: 0.4 });
|
|
114
119
|
```
|
|
115
120
|
|
|
116
|
-
Walkers stop at the edge and slide along it; `collision.walkable()` and A* pathing, sync and async, see both. `fn` must be pure and deterministic (no clock, no random). Async paths cannot send a function to the worker, so `fn` is sampled into the 1 m ground raster
|
|
121
|
+
Walkers stop at the edge and slide along it; `collision.walkable()` and A* pathing, sync and async, see both. `fn` must be pure and deterministic (no clock, no random). Async paths cannot send a function to the worker, so `fn` is sampled into the 1 m ground raster (re-sampled when a field is added or removed): give `bounds`, or every requested tile is sampled in full. Navmesh mode (`nav()` installed) does not see `addBlocked`; use `addSegment` or bake the river into the mesh there.
|
|
122
|
+
|
|
123
|
+
## Gates some characters pass: collider layers
|
|
124
|
+
|
|
125
|
+
A collider with a `layer` stops every mover but those whose `passes` names it (a pen, a members' door). Walking, paths and the navmesh obey it.
|
|
126
|
+
|
|
127
|
+
```js fragment
|
|
128
|
+
engine.collision.addBox(gate, { halfWidth: 2, halfDepth: 0.3, layer: 'gate' }); // any add*
|
|
129
|
+
engine.npcs.add({ id: 'pig', name: 'Pig', passes: ['gate'] }); // or addPlayer, findPath
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
Content: `collide: { layer: 'gate' }` on a prop or template; a Blender level: custom property `layer` on a `col_` / `collider` object or its parent.
|
|
133
|
+
|
|
134
|
+
`character.passes` may be rewritten. Each layer list gets a navmesh, like a size (section 5). Rigid bodies, `lineClear`, the camera and `nav({ crowd: true })` NPCs ignore layers.
|
|
117
135
|
|
|
118
136
|
## Line of sight, stealth vision cones and straight-line checks: collision.lineClear
|
|
119
|
-
`engine.collision.lineClear(a, b, { radius })` answers "is anything solid between a and b?"
|
|
137
|
+
`engine.collision.lineClear(a, b, { radius })` answers "is anything solid between a and b?" for a 3D segment (the wall test of a guard's vision cone; the cone is your own angle check on `guard.facing`): boxes, circles and terrain trees, with heights (a 1 m wall does not block a sight line 3 m up). A boolean; `addBlocked` water is ignored. Give eye heights in `a` / `b`; `radius` fattens the line (the character radius answers "can I walk straight there").
|
|
120
138
|
```js fragment
|
|
121
|
-
const sees = engine.collision.lineClear([guard.x, 1.6, guard.z], [player.x, 1.6, player.z]);
|
|
139
|
+
const sees = engine.collision.lineClear([guard.x, 1.6, guard.z], [player.x, 1.6, player.z]); // true = clear view
|
|
122
140
|
const straight = engine.collision.lineClear(me.position, goal, { radius: engine.movement.radius });
|
|
123
141
|
```
|
|
124
142
|
The A* fallback smooths paths with the same idea: it samples each shortcut at most one character radius apart (so a thin fence cannot be skipped), starts from the character's real position, and its cell size follows `radius` (1-2 m) unless you pass `step`.
|
|
@@ -1,6 +1,9 @@
|
|
|
1
1
|
# Animation state machine (skeletal animation)
|
|
2
2
|
|
|
3
|
-
**
|
|
3
|
+
> **Covers:** skeletal animation: clips mapped to game actions, skinned and sprite characters, objects that animate, look-at and foot IK.
|
|
4
|
+
> **Use when:** a model should move its body.
|
|
5
|
+
> **Shortest:** `engine.assets.animate(model, config)`.
|
|
6
|
+
> **Sections:** 1 The model · 2 Mapping game action · 3 A character with · 3b Procedural bodies are · 3c Sprite characters a · 3d Which modules need · 3e IK heads that · 4 Non-character objects a · 5 Gameplay controls progress · 6 Verify
|
|
4
7
|
|
|
5
8
|
There is a single entry point: `engine.assets.animate(model, config)` -> Animator (advanced every frame by the engine; never call mixer.update yourself).
|
|
6
9
|
For characters (player, NPCs), passing `model` builds the Animator automatically and switches clips by character state (idle walk run swim jump fall drive).
|
|
@@ -26,9 +29,9 @@ engine.assets.manifest({ name: 'heroes', models: { hero: { url: '/models/hero.gl
|
|
|
26
29
|
fade: 0.2,
|
|
27
30
|
states: { idle: { clip: 'Idle_Sword' }, walk: { clip: 'Walk' }, attack: { clip: 'Sword_Slash', loop: false, timing: 0.62 }, hurt: { clip: 'HitRecieve', loop: false } },
|
|
28
31
|
} } } });
|
|
29
|
-
engine.characters.
|
|
32
|
+
engine.characters.addPlayer({ ...presets.player.thirdPerson, model: 'hero' }); // no clips / animation in code
|
|
30
33
|
await engine.player.whenReady;
|
|
31
|
-
engine.assets.mapping(engine.player.anim.root);
|
|
34
|
+
engine.assets.mapping(engine.player.anim.root); // the entry's mapping, or null
|
|
32
35
|
```
|
|
33
36
|
A character's default names (`Idle`, `Walk`...) never shadow a mapped state, and the entry's `fade` beats `characters({ animation })`.
|
|
34
37
|
|
|
@@ -45,18 +48,18 @@ A character's default names (`Idle`, `Walk`...) never shadow a mapped state, and
|
|
|
45
48
|
|
|
46
49
|
## 3. A character with a skinned model (most common)
|
|
47
50
|
```js
|
|
48
|
-
engine.characters.
|
|
49
|
-
clips: { idle: 'Idle', walk: 'Walk', run: 'Run', jump: 'Jump' },
|
|
51
|
+
engine.characters.addPlayer({ ...presets.player.thirdPerson, model: hero,
|
|
52
|
+
clips: { idle: 'Idle', walk: 'Walk', run: 'Run', jump: 'Jump' }, // character state -> clip name in the glTF; states you leave out use the capitalised name if the model has that clip
|
|
50
53
|
});
|
|
51
|
-
engine.player.playAction('Wave');
|
|
52
|
-
engine.player.anim.state;
|
|
54
|
+
engine.player.playAction('Wave'); // one-shot clip (skipped if the clip doesn't exist); returns to the previous state when done
|
|
55
|
+
engine.player.anim.state; // current state name
|
|
53
56
|
```
|
|
54
57
|
**The game's own states** (crouch, climb, glide, dash, roll) go on top of the built-in ones through the `states` option, without taking the mover
|
|
55
58
|
over: it runs after the mover's state each step and returns a state name or null (keep the built-in `facts.base`); the clip comes from `clips`
|
|
56
59
|
like any other state, a speed change stays `engine.mod('move.speed')`. A state only names the pose: climbing also needs someone to move the body
|
|
57
60
|
(recipe 57, Moved by script, has a ladder).
|
|
58
61
|
```js
|
|
59
|
-
engine.characters.
|
|
62
|
+
engine.characters.addPlayer({ ...presets.player.thirdPerson, model: hero, clips: { crouch: 'Crouch', glide: 'Glide' },
|
|
60
63
|
states: (c, f) => f.grounded && engine.input.down('crouch') ? 'crouch' : !f.grounded && f.vy < 0 && gliding ? 'glide' : null });
|
|
61
64
|
```
|
|
62
65
|
Deep water follows `water`: `'swim'` (default), `'block'` (never enters), `'wade'` (walks the bottom), or `(c, { depth }) => mode` per spot;
|
|
@@ -64,9 +67,9 @@ Deep water follows `water`: `'swim'` (default), `'block'` (never enters), `'wade
|
|
|
64
67
|
For smooth walk/run blending, use `animation` instead of `clips` and write a `move` blend tree (when the model has no walk/run states, move is used
|
|
65
68
|
automatically; the `speed` parameter is in m/s):
|
|
66
69
|
```js
|
|
67
|
-
engine.characters.
|
|
70
|
+
engine.characters.addPlayer({ ...presets.player.thirdPerson, model: hero, animation: { states: {
|
|
68
71
|
idle: { clip: 'Idle' },
|
|
69
|
-
move: { blend: [{ clip: 'Walk', at: 1.5 }, { clip: 'Run', at: 6 }], param: 'speed', sync: true },
|
|
72
|
+
move: { blend: [{ clip: 'Walk', at: 1.5 }, { clip: 'Run', at: 6 }], param: 'speed', sync: true }, // sync: align footsteps
|
|
70
73
|
jump: { clip: 'Jump', loop: false },
|
|
71
74
|
} } });
|
|
72
75
|
```
|
|
@@ -77,19 +80,17 @@ The default transition time for every character is `characters({ animation: { fa
|
|
|
77
80
|
`engine.characters.material = new THREE.MeshToonMaterial({ color: 0xd9a066 })` swaps them all, as given. `colors: { body }` gives one character a copy in
|
|
78
81
|
that color. A model keeps its own materials.
|
|
79
82
|
|
|
80
|
-
**By asset name.** `model` also takes
|
|
81
|
-
|
|
82
|
-
world view stay. Then `ready` turns true, `whenReady` settles and `character:model` is emitted. A name no model asset has throws with the registered
|
|
83
|
+
**By asset name.** `model` also takes a registered model asset's name (file or builder). A file shows a gray capsule until the copy replaces it under the
|
|
84
|
+
same root (position, facing, state and collision stay); then `ready` turns true, `whenReady` settles and `character:model` is emitted. A name no model asset has throws with the registered
|
|
83
85
|
names; a failed load keeps the capsule and warns once; a character disposed before loading ends never gets the model. `p.anim` is set after `await p.whenReady` (unless the load failed).
|
|
84
86
|
|
|
85
87
|
## 3b. Procedural bodies are assets too (`model: 'humanoid'`)
|
|
86
|
-
|
|
87
|
-
while walking, running, swimming, jumping); a builder is built at once, so its joints (`player.armL`, `legR`...) exist right after `createPlayer`. Without `model` (and without `rig`) a character is a gray capsule, warned once.
|
|
88
|
+
An asset pack can supply a code-built humanoid (box limbs the engine swings while walking, running, swimming, jumping); a builder is built at once, so its joints (`player.armL`, `legR`...) exist right after `addPlayer`. Without `model` (and without `rig`) a character is a gray capsule, warned once.
|
|
88
89
|
```js fragment
|
|
89
|
-
import { assets } from './assets.js';
|
|
90
|
+
import { assets } from './assets.js'; // an asset pack of yours (or a published one) with a 'humanoid' builder
|
|
90
91
|
engine.assets.manifest(assets);
|
|
91
|
-
engine.characters.
|
|
92
|
-
engine.npcs.add({ id: 'fisher', model: 'humanoid', colors: { body: 0x4f6d8f } });
|
|
92
|
+
engine.characters.addPlayer({ ...presets.player.thirdPerson, model: 'humanoid' });
|
|
93
|
+
engine.npcs.add({ id: 'fisher', model: 'humanoid', colors: { body: 0x4f6d8f } }); // per-character part colors
|
|
93
94
|
```
|
|
94
95
|
- **Colors**: a builder's materials are its own three.js materials, and colors shared by many bodies come from `this.palette` (recipe 05);
|
|
95
96
|
`colors: { body, skin, legs, hair }` recolors one character's marked parts.
|
|
@@ -98,18 +99,17 @@ engine.npcs.add({ id: 'fisher', model: 'humanoid', colors: { body: 0x4f6d8f } })
|
|
|
98
99
|
meshes `userData.part = 'body'` for `colors`. A hand-built one-off passes `{ rig }` instead ([02-npc](02-npc.md)).
|
|
99
100
|
|
|
100
101
|
## 3c. Sprite characters: a 2D billboard or flat body in plain three.js
|
|
101
|
-
A 2D sprite character is a plain three.js object handed to `model
|
|
102
|
-
|
|
103
|
-
Frames are drawing, so they live in `picture/` (recipe 62) and gameplay never touches them. `onPose` gives them the character's state each frame:
|
|
102
|
+
A 2D sprite character is a plain three.js object handed to `model`. `THREE.Sprite` always faces the camera; a `Mesh` with a `PlaneGeometry` turns with
|
|
103
|
+
`character.root`, takes light and can cast a shadow. Frames live in `picture/` (recipe 62); `onPose` gives them the character's state each frame:
|
|
104
104
|
```js fragment
|
|
105
105
|
// picture/sprites.js: a sheet of cols x rows frames; which row is which is your sheet's layout
|
|
106
106
|
const ROW = { idle: 0, walk: 1, run: 1, jump: 2, fall: 2 };
|
|
107
107
|
export function spriteBody(texture, cols, rows, framesPerSecond) {
|
|
108
|
-
const map = texture.clone();
|
|
108
|
+
const map = texture.clone(); // offset lives on the texture, so one clone per character; the image stays shared
|
|
109
109
|
map.needsUpdate = true;
|
|
110
110
|
map.repeat.set(1 / cols, 1 / rows);
|
|
111
111
|
const sprite = new THREE.Sprite(new THREE.SpriteMaterial({ map }));
|
|
112
|
-
sprite.center.set(0.5, 0);
|
|
112
|
+
sprite.center.set(0.5, 0); // feet on the character's origin
|
|
113
113
|
let t = 0;
|
|
114
114
|
const animate = (c, dt) => {
|
|
115
115
|
t += dt;
|
|
@@ -119,14 +119,14 @@ export function spriteBody(texture, cols, rows, framesPerSecond) {
|
|
|
119
119
|
}
|
|
120
120
|
// main.js: the sheet is a name in assets.js like any texture
|
|
121
121
|
const hero = spriteBody(await engine.assets.texture('hero-sheet', { pixelated: true }), 4, 3, 8);
|
|
122
|
-
engine.characters.
|
|
122
|
+
engine.characters.addPlayer({ ...presets.player.thirdPerson, model: hero.sprite }).onPose(hero.animate);
|
|
123
123
|
```
|
|
124
124
|
**In an orthographic view of a 3D scene** use `pixelSprite` from `threedog/pixel` instead of a `Sprite` or a free plane (recipe 62 section 4b): a plain `Mesh` that stands upright, so walls behind it do not cut its head, and shows one texel per art pixel. `model` takes it as it is. It ignores the turn of `character.root`, and `onPose` picks the frame:
|
|
125
125
|
```js fragment
|
|
126
126
|
const hero = pixelSprite({ grid: engine.cameraRig.pixelSnap.grid, material, width: 16, height: 24, columns: 4, rows: 3, snap: 'followed' });
|
|
127
|
-
const ch = engine.characters.
|
|
128
|
-
const right = engine.cameraRig.pixelSnap.grid.axes().right;
|
|
129
|
-
ch.onPose(c => spriteFrame(hero, ROW[c.state] * 4, Math.sin(c.facing) * right.x + Math.cos(c.facing) * right.z < 0));
|
|
127
|
+
const ch = engine.characters.addPlayer({ ...presets.player.thirdPerson, model: hero });
|
|
128
|
+
const right = engine.cameraRig.pixelSnap.grid.axes().right; // the same vector every frame
|
|
129
|
+
ch.onPose(c => spriteFrame(hero, ROW[c.state] * 4, Math.sin(c.facing) * right.x + Math.cos(c.facing) * right.z < 0)); // no state machine here: which frame shows is the game's
|
|
130
130
|
```
|
|
131
131
|
`c.facing` is an angle in radians around Y (0 looks along +Z), so `c.facing < 0` is not "looks left": which way is left depends on how the camera is turned. Mirror when the heading `(sin, cos)` points against the screen's right axis, as above. Run once in a view turned 45 degrees: walking toward the screen's right gave "not mirrored"; the other direction was not run.
|
|
132
132
|
`character.root` and `hero.position` stay exact, so physics and saves see the true position. A one-off `new Character(engine, { model: hero })` still needs `engine.add(character.root)`, as in recipe 02.
|
|
@@ -139,7 +139,7 @@ ch.onPose(c => spriteFrame(hero, ROW[c.state] * 4, Math.sin(c.facing) * right.x
|
|
|
139
139
|
Tried with a `pixelSprite` mesh and a `Character` whose `model` is one (`threedog new-game name --pixel` is the starting game). Each row below was run once in a real browser, in a few lines; "not run" means only the docs were read.
|
|
140
140
|
| Module | On a sprite / plain object / position | Result |
|
|
141
141
|
|---|---|---|
|
|
142
|
-
| `characters` (`
|
|
142
|
+
| `characters` (`addPlayer`, `new Character`, `walkTo`, `onPose`) | the sprite is the character's `model` | works: moves, collides, `state` and `facing` drive `onPose`; `walkTo` on an NPC character walked there |
|
|
143
143
|
| `interactions.add(object, ...)` | any mesh or sprite, no character | works: E near it, `once`, `counter`, saved as used |
|
|
144
144
|
| `dialogue` | no object at all (a name and flags) | works: flags are in the save |
|
|
145
145
|
| `triggers.add({ position })` | a position; `who` is the actor or an id | works: fired for the player character |
|
|
@@ -150,7 +150,18 @@ Tried with a `pixelSprite` mesh and a `Character` whose `model` is one (`threedo
|
|
|
150
150
|
| `audio.sfx`, `audio.tone`, `ambience.add` | no object | ran without error (no sound file named, so nothing audible was checked) |
|
|
151
151
|
| `weather.set`, `calendar.at`, `sky` | no object | installed and started; `weather.set('rain')` kept the name `clear` without a weather table (give the module one), `calendar.at` firing: not run |
|
|
152
152
|
| `makeWindow(engine, opts)` | no object | created a window object (`open`, `toggle`, `remove`) |
|
|
153
|
-
Needs an engine character: `
|
|
153
|
+
Needs an engine character: `addPlayer`, `walkTo`, `onPose`, schedules, characters' collision and ground. Everything else above takes a position or any `THREE.Object3D`. A sprite that only stands there (a signpost, an NPC that never walks) needs no `Character`; one that walks, follows ground or is scheduled does.
|
|
154
|
+
|
|
155
|
+
## 3e. IK: heads that look, feet on the ground
|
|
156
|
+
Two layers after the clips on any Animator, off until added:
|
|
157
|
+
```js fragment
|
|
158
|
+
const look = npc.anim.addAim({ bones: ['Neck', 'Head'], target: engine.player.root, limit: 70 });
|
|
159
|
+
const feet = engine.player.anim.addFeet(); // feet on stairs and slopes
|
|
160
|
+
```
|
|
161
|
+
- `set({ weight })` fades over `fade` s; weight 0 leaves the animation pose exactly, `remove()` restores it at once; `target: null` looks ahead.
|
|
162
|
+
- `forward: [x, y, z]` (the last bone's axes): a head facing another axis than the bind pose says.
|
|
163
|
+
- `legs: [[upper, lower, foot], ...]` when it cannot tell the legs by bone name (it throws, listing them).
|
|
164
|
+
- Feet use the character's ground, platforms included (`ground: (x, z, y) => h` overrides); off while it jumps or swims, beyond `far`, or hidden.
|
|
154
165
|
|
|
155
166
|
## 4. Non-character objects (a dog, a windmill, a door)
|
|
156
167
|
```js
|
|
@@ -160,28 +171,28 @@ const anim = engine.assets.animate(dog, {
|
|
|
160
171
|
states: {
|
|
161
172
|
idle: { clip: 'Idle' },
|
|
162
173
|
move: { blend: [{ clip: 'Walk', at: 1 }, { clip: 'Run', at: 5 }], param: 'speed' },
|
|
163
|
-
bark: { clip: 'Bark', loop: false, then: 'idle', lock: true },
|
|
174
|
+
bark: { clip: 'Bark', loop: false, then: 'idle', lock: true }, // one-shot; lock: go() doesn't interrupt it while it plays
|
|
164
175
|
},
|
|
165
|
-
transitions: { '*>idle': 0.4 },
|
|
176
|
+
transitions: { '*>idle': 0.4 }, // transition seconds for specific switches
|
|
166
177
|
});
|
|
167
178
|
anim.go('idle');
|
|
168
|
-
anim.set('speed', 3); anim.go('move');
|
|
179
|
+
anim.set('speed', 3); anim.go('move'); // just set the speed every frame
|
|
169
180
|
anim.action('bark');
|
|
170
181
|
engine.events.on('anim:end', ({ root, state }) => { if (root === dog) console.log(state, 'finished'); });
|
|
171
|
-
anim.dispose();
|
|
182
|
+
anim.dispose(); // no longer needed: stop per-frame updates (call this when deleting the model)
|
|
172
183
|
```
|
|
173
184
|
**Gameplay timing never reads the animation**: the mixer advances per frame and `anim:end` is emitted per frame, so dropped frames, fast-forward
|
|
174
185
|
(step's frameEvery) and a model being torn down when it is far away all make it drift from game time. When an attack lands, cooldowns, recovery and
|
|
175
186
|
"finish the swing before moving" are timed in fixed steps:
|
|
176
187
|
```js
|
|
177
|
-
engine.input.
|
|
178
|
-
let t = -1;
|
|
188
|
+
engine.input.define('attack', { label: 'Attack', keys: ['KeyF', 'Mouse0'] }); // no module binds it for you
|
|
189
|
+
let t = -1; // seconds since the swing started (-1 = not swinging); put it in a world record if it must be saved
|
|
179
190
|
engine.onFixed(dt => {
|
|
180
191
|
if (t < 0) { if (!engine.input.pressed('attack')) return; t = 0; }
|
|
181
192
|
const before = t; t += dt;
|
|
182
|
-
if (before < 0.3 && t >= 0.3) hitEnemiesInFront();
|
|
183
|
-
if (t >= 0.6) t = -1;
|
|
184
|
-
engine.player.anim.sync(t < 0 ? null : 'attack', t);
|
|
193
|
+
if (before < 0.3 && t >= 0.3) hitEnemiesInFront(); // hit check at 0.3 s
|
|
194
|
+
if (t >= 0.6) t = -1; // can swing again after 0.6 s
|
|
195
|
+
engine.player.anim.sync(t < 0 ? null : 'attack', t); // the animation follows t (the attack state of section 5)
|
|
185
196
|
});
|
|
186
197
|
```
|
|
187
198
|
## 5. Gameplay controls progress: `sync(state, t)`
|
|
@@ -192,19 +203,19 @@ alone, so a character's per-frame locomotion cannot override it. `sync(null)` ha
|
|
|
192
203
|
state cross-fades like `go()` (the `transitions` table applies).
|
|
193
204
|
`timing` on the state maps gameplay seconds to clip seconds:
|
|
194
205
|
```js fragment
|
|
195
|
-
const anim = engine.player.anim;
|
|
206
|
+
const anim = engine.player.anim; // or engine.assets.animate(model, {...})
|
|
196
207
|
Object.assign(anim.states, {
|
|
197
208
|
// gameplay: windup 0-0.16, hit 0.16-0.28, recovery 0.28-0.62. The clip raises the sword until 0.24 s and brings it down by 0.5 s:
|
|
198
|
-
attack: { clip: 'Sword_Slash', loop: false, timing: [[0, 0], [0.16, 0.24], [0.28, 0.5], [0.62, 1]] },
|
|
199
|
-
roll: { clip: 'Roll', loop: false, timing: 0.62 },
|
|
209
|
+
attack: { clip: 'Sword_Slash', loop: false, timing: [[0, 0], [0.16, 0.24], [0.28, 0.5], [0.62, 1]] }, // piecewise linear
|
|
210
|
+
roll: { clip: 'Roll', loop: false, timing: 0.62 }, // a number: stretch the whole clip over 0.62 gameplay seconds
|
|
200
211
|
hurt: { clip: 'HitRecieve', loop: false, timing: 0.45 },
|
|
201
|
-
death: { clip: 'Death', loop: false },
|
|
212
|
+
death: { clip: 'Death', loop: false }, // no timing: clip seconds = t (clamped at the last frame)
|
|
202
213
|
});
|
|
203
|
-
engine.onFixed(() => {
|
|
214
|
+
engine.onFixed(() => { // one call site: whatever gameplay is doing decides the pose
|
|
204
215
|
if (f.dead) anim.sync('death', f.deadT);
|
|
205
216
|
else if (f.stun > 0) anim.sync('hurt', f.stunMax - f.stun);
|
|
206
217
|
else if (f.act) anim.sync(f.act.id, f.act.t);
|
|
207
|
-
else anim.sync(null);
|
|
218
|
+
else anim.sync(null); // free: locomotion (idle / walk / run) takes over
|
|
208
219
|
});
|
|
209
220
|
```
|
|
210
221
|
- Calibrate `timing` once by looking: sync the raw clip (no timing) at a few `t` and watch the weapon hand (`describe()` or a bone's world position);
|
|
@@ -215,7 +226,7 @@ engine.onFixed(() => { // one call
|
|
|
215
226
|
Use `anim:end` only for presentation (change an expression, play the next clip). Native objects: `anim.mixer` (AnimationMixer), `anim.actions` (clip
|
|
216
227
|
name -> AnimationAction). Things without a skeleton that only move/rotate as a whole use `engine.timeline.tween`, not an Animator.
|
|
217
228
|
|
|
218
|
-
Footsteps: `engine.events.on('character:step', ({ character }) => ...)` hears each foot come down (`character.groundType()` is what it stepped on), and `character:land` each landing; the engine's own footstep sound listens the same way, so yours adds to it. Bones after the pose: `const h = player.onPose((c, dt) => { sword.position.copy(hand.getWorldPosition(v)); })` runs every frame right after the character's pose is
|
|
229
|
+
Footsteps: `engine.events.on('character:step', ({ character }) => ...)` hears each foot come down (`character.groundType()` is what it stepped on), and `character:land` each landing; the engine's own footstep sound listens the same way, so yours adds to it. Bones after the pose: `const h = player.onPose((c, dt) => { sword.position.copy(hand.getWorldPosition(v)); })` runs every frame right after the character's pose (IK included: a bone written here keeps the game's value) is
|
|
219
230
|
applied (clips or procedural rig); `h.remove()` stops it. Presentation only.
|
|
220
231
|
|
|
221
232
|
## 6. Verify
|
|
@@ -1,13 +1,16 @@
|
|
|
1
1
|
# Custom module
|
|
2
2
|
|
|
3
|
-
**
|
|
3
|
+
> **Covers:** a module of your own: template, what it may own, hooks and order, what it must clean up.
|
|
4
|
+
> **Use when:** a mechanic with its own state, per-frame logic and saving.
|
|
5
|
+
> **Shortest:** `export const stamina = () => ({ name: 'stamina', install(e, ctx) { … } })`.
|
|
6
|
+
> **Sections:** 1 Template example stamina · Type what the module · 2 Hooks and order · 3 Extra steps when · 4 Verify
|
|
4
7
|
|
|
5
8
|
When to write a module: a "mechanic" that has its own state, per-frame logic and saving (stamina, a heat meter, wave spawning, oxygen, a combo
|
|
6
9
|
counter). The contracts every module should follow (state, game time, skip, describe, ops) and a second copyable module are in
|
|
7
10
|
`49-game-module-contract.md`; this page is the template and the hook cheat sheet. A module is a file of your game (next to `main.js`, or in `plugins/`);
|
|
8
11
|
keep art and text out of its code (style values, `i18n`) so it can go to another game through your asset library (`threedog lib add`).
|
|
9
12
|
|
|
10
|
-
**A whole system to reuse.** A folder `systems/<name>/` with a `system.json` (`{ "summary", "module", "plug", "requires", "entries", "content", "text" }`) carries the module, its content piece, its words and its tests (`tests/*.mjs`, game specs) as one unit: fishing, a day-night shop, wave spawning, tides. `threedog lib add systems/fishing --kind system` refuses colors, art files and text in the code and a `requires` left out of `system.json`, then proves an entry with tests by pulling it into an empty game and running them (`--no-proof` skips that). `threedog lib pull fishing` puts it in `systems/fishing/`, writes its wiring file in `plugins/`,
|
|
13
|
+
**A whole system to reuse.** A folder `systems/<name>/` with a `system.json` (`{ "summary", "module", "plug", "requires", "entries", "content", "text" }`) carries the module, its content piece, its words and its tests (`tests/*.mjs`, game specs) as one unit: fishing, a day-night shop, wave spawning, tides. `threedog lib add systems/fishing --kind system` refuses colors, art files and text in the code and a `requires` left out of `system.json`, then proves an entry with tests by pulling it into an empty game and running them (`--no-proof` skips that). `threedog lib pull fishing` puts it in `systems/fishing/`, writes its wiring file in `plugins/`, its tests in `tests/specs/` and merges its content into `content/index.js`.
|
|
11
14
|
|
|
12
15
|
## 1. Template (example: stamina, in the game as `stamina.js`)
|
|
13
16
|
```js
|
|
@@ -16,7 +19,7 @@ import { readParams } from 'threedog';
|
|
|
16
19
|
|
|
17
20
|
export function stamina(opts = {}) {
|
|
18
21
|
const PARAMS = { max: { type: 'number', default: 100 }, drain: { type: 'number', default: 20 }, regen: { type: 'number', default: 10 } };
|
|
19
|
-
const { max, drain, regen } = readParams('stamina', PARAMS, opts);
|
|
22
|
+
const { max, drain, regen } = readParams('stamina', PARAMS, opts); // a misspelled option throws in dev with the fix (a release build warns once), a wrong type or a missing required option throws in every build; put PARAMS on the module as params to show it in engine.catalog()
|
|
20
23
|
let e = null, ctx = null, tired = null, shown = -1;
|
|
21
24
|
const api = {
|
|
22
25
|
value: max, max,
|
|
@@ -24,25 +27,25 @@ export function stamina(opts = {}) {
|
|
|
24
27
|
restore(n) { api.value = Math.min(max, api.value + n); },
|
|
25
28
|
};
|
|
26
29
|
return {
|
|
27
|
-
name: 'stamina', type: 'rules', label: 'Stamina', requires: ['characters'], optional: ['hud'], stage: 'gameplay',
|
|
30
|
+
name: 'stamina', type: 'rules', label: 'Stamina', requires: ['characters'], optional: ['hud'], stage: 'gameplay', // once installed, engine.stamina === api
|
|
28
31
|
install(engine, c) {
|
|
29
|
-
e = engine; ctx = c;
|
|
30
|
-
e.i18n.add({ 'zh-CN': { 'stamina.label': '体力' }, en: { 'stamina.label': 'Stamina' } });
|
|
31
|
-
e.saves.
|
|
32
|
+
e = engine; ctx = c; // what the module adds through ctx leaves with it (uninstall, replaces, a rolled-back use)
|
|
33
|
+
e.i18n.add({ 'zh-CN': { 'stamina.label': '体力' }, en: { 'stamina.label': 'Stamina' } }); // don't hard-code UI text
|
|
34
|
+
e.saves.define('stamina', { save: () => api.value, load: v => { if (typeof v === 'number') api.value = v; } });
|
|
32
35
|
return api;
|
|
33
36
|
},
|
|
34
|
-
fixed(dt) {
|
|
37
|
+
fixed(dt) { // timing and value changes go in fixed (60 Hz, doesn't run while paused)
|
|
35
38
|
const p = e.player; if (!p) return;
|
|
36
39
|
api.value = p.state === 'run' ? Math.max(0, api.value - drain * dt) : Math.min(max, api.value + regen * dt);
|
|
37
40
|
// no stamina: run speed = walk speed. A modifier, not a write to p.runSpeed: the base stays the game's, and haste / mud entries still combine
|
|
38
|
-
if (api.value <= 0 && !tired) tired = ctx.mod('move.runSpeed', { id: 'player', set: p.speed });
|
|
41
|
+
if (api.value <= 0 && !tired) tired = ctx.mod('move.runSpeed', { id: 'player', set: p.speed }); // owner: the module
|
|
39
42
|
else if (api.value > 0 && tired) { tired.remove(); tired = null; }
|
|
40
43
|
},
|
|
41
|
-
frame() {
|
|
44
|
+
frame() { // UI goes in frame; update only when the value changed (hud.bar redraws on every call)
|
|
42
45
|
const v = Math.round(api.value);
|
|
43
46
|
if (v !== shown) { shown = v; e.hud?.bar('stamina', { value: v, max, label: e.t('stamina.label') }); }
|
|
44
47
|
},
|
|
45
|
-
describe() { return { value: Math.round(api.value), max }; },
|
|
48
|
+
describe() { return { value: Math.round(api.value), max }; }, // this becomes describe().stamina
|
|
46
49
|
};
|
|
47
50
|
}
|
|
48
51
|
```
|
|
@@ -93,16 +96,16 @@ A module that does two kinds of thing is two definitions returned together (`wea
|
|
|
93
96
|
- The `type` decides what an error does: in a `picture` or `ui` module (gameplay works without it) an error in a hook only switches that module off
|
|
94
97
|
(`module:disabled`, listed in `describe().disabledModules`); in any other type it freezes the game in development/tests and is recorded in `engine.error`.
|
|
95
98
|
- `requires` means the provider works, not only that it is installed: until a required provider runs, the module is `'blocked'` in `engine.explain({ module })` (no init, no hooks) and `engine.catalog(name).blockedBy` says on what. If it can live without the provider, list it in `optional` instead. A `critical` module blocked by a failure stops `start()`.
|
|
96
|
-
- Whatever the module registers goes through `ctx`: `ctx.ops.define`, `ctx.saves.
|
|
99
|
+
- Whatever the module registers goes through `ctx`: `ctx.ops.define`, `ctx.saves.define`, `ctx.ui.define`, `ctx.stream.addReadyCheck`, `ctx.budget.metric`, `ctx.things.addSource` / `explainWith`,
|
|
97
100
|
`ctx.ground.provide` / `addColliders`. They take the same arguments as the engine call, and `engine.catalog(name).resources` lists them. They leave with the module, so `engine.unuse` then
|
|
98
101
|
`engine.use` of the same module works; a save part's data stays in the save and goes back to the part when it registers again.
|
|
99
102
|
- Listeners and timers the module adds go through `ctx.track(...)`: `ctx.track(e.events.on('item:add', fn))`, also `onFixed` / `onFrame` /
|
|
100
103
|
`clock.after` / `audio.measure` / a `makeWindow` window, anything with `remove()`. They leave with the module: when its `engine.use(...)` batch
|
|
101
104
|
rolls back, when its `init` fails, and on `engine.dispose()` before its `dispose` hook (the spec `threedog test "Lifecycle: every built-in"`
|
|
102
105
|
checks every engine module). A class the module builds takes `ctx` as a constructor argument. DOM listeners use
|
|
103
|
-
`addEventListener(type, fn, { signal: engine.signal })`, and UI elements attach to `engine.uiRoot` (not `document.body`);
|
|
104
|
-
|
|
105
|
-
physics world, WASM objects
|
|
106
|
+
`addEventListener(type, fn, { signal: engine.signal })`, and UI elements attach to `engine.uiRoot` (not `document.body`); jobs and stream
|
|
107
|
+
entries are collected by `engine.dispose()`; scene GPU memory is its creator's: `engine.dispose()` does not free the meshes, materials and textures you made, so track their removal: `ctx.track({ remove: () => engine.remove(mesh) })` (`engine.remove` disposes geometry and materials, not their textures: three's `material.dispose()` leaves its maps, so dispose a texture you made when nothing uses it). The `dispose(e)`
|
|
108
|
+
hook frees the rest (Workers, the physics world, WASM objects, real-time timers), in reverse install order.
|
|
106
109
|
- Your data in a replaceable provider: `ctx.feeds('collision', () => addMyWalls())` runs before the `use()` of a new holder returns.
|
|
107
110
|
- Foundation slots are the ones a running game cannot swap: `world` alone, because it owns every record. Choose your own holder before `start()`; every other slot takes `replaces` at any time.
|
|
108
111
|
- A module's changes to shared values go through `ctx.mod(point, { mul: 0.8, layer: 'effect' })` (= `ctx.track(e.mod(point, { owner: ctx.name, ... }))`),
|
|
@@ -118,10 +121,10 @@ A module that does two kinds of thing is two definitions returned together (`wea
|
|
|
118
121
|
- Saved state the module writes joins the ops guard (experimental): `e.ops.guard('stamina.set')` in each writing method (a no-op in production builds,
|
|
119
122
|
no DEV check needed), `e.ops.allow(fn)` around writes that are allowed anyway (recipe 23 section 5).
|
|
120
123
|
- **Per-playthrough state** is a save part: whatever changes during play and matters for what happens next (a zone's `once` / cooldown, a
|
|
121
|
-
transition's progress, a hand-picked music track, a check timer, markers an effect placed) goes in `e.saves.
|
|
124
|
+
transition's progress, a hand-picked music track, a check timer, markers an effect placed) goes in `e.saves.define(...)`. The engine calls it
|
|
122
125
|
on all three paths: save, load, and new game (a new game loads the state captured when `start()` finished), so there is nothing to reset by
|
|
123
|
-
hand. What cannot be saved ends with its playthrough: a background result goes through `
|
|
124
|
-
keep `
|
|
126
|
+
hand. What cannot be saved ends with its playthrough: a background result goes through `ctx.commits` (a load or new game drops old ones;
|
|
127
|
+
keep `ctx.commits.epoch` on a queued request and drop it when that changed), and an effect of a running playthrough (an open dialogue, a
|
|
125
128
|
running cutscene, the music playing) stops on `ctx.track(e.events.on('session:end', ...))`. What is derived from save parts is rebuilt on
|
|
126
129
|
`'session:start'` and `'save:loaded'`, and what a rollback took down on `'session:failed'`. A `'session:end'` listener only stops things: it starts nothing for the next state. A module's `describe()` should show such state: the session spec (`threedog test "session fresh page"`) compares `describe()` after a new game with a fresh page, and the Lifecycle spec round-trips the engine's own.
|
|
127
130
|
- When you only need a per-frame callback and no module structure: `const h = engine.onFrame(dt => ...)` / `engine.onFixed`, and `h.remove()` cancels it.
|