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
|
# Shooting and picking (cast a ray from the screen center or the mouse position, with any camera)
|
|
2
2
|
|
|
3
|
+
> **Covers:** a ray from the screen center or the pointer: shooting, selecting, tapping.
|
|
4
|
+
> **Use when:** the player aims, clicks or taps at something in the scene.
|
|
5
|
+
> **Shortest:** `engine.pick(x, y)` or `engine.rays`.
|
|
6
|
+
> **Sections:** 1 A first-person shooting · 2 What happens after · 3 Testing
|
|
7
|
+
|
|
3
8
|
Works with any camera (`follow`, `firstPerson`, `rts`, `fixed`): a click-to-select strategy game, a puzzle that taps tiles or a first-person shooter all
|
|
4
9
|
use the same ray. The example below is the first-person case; a score display needs `hud()`.
|
|
5
10
|
The ray API is `engine.pick(ndcX, ndcY, opts)`: screen coordinates -1..1 (0, 0 is the screen center, which is also the first-person crosshair); it
|
|
@@ -9,17 +14,17 @@ ray registration is needed.**
|
|
|
9
14
|
## 1. A first-person shooting range (copy it and it runs)
|
|
10
15
|
```js
|
|
11
16
|
import { createEngine, presets, openWorld, hud, THREE } from 'threedog';
|
|
12
|
-
import { createPicture } from './picture/index.js';
|
|
17
|
+
import { createPicture } from './picture/index.js'; // the game's own picture, plain three.js (recipe 62)
|
|
13
18
|
import { terrainPreset } from '@threedog/terrain-noise';
|
|
14
19
|
|
|
15
20
|
const engine = createEngine({ canvas: document.getElementById('view'), lights: false, saveKey: 'range' });
|
|
16
|
-
engine.use(openWorld({ seed: 7, terrain: terrainPreset(), camera: 'firstPerson' }), hud());
|
|
21
|
+
engine.use(openWorld({ seed: 7, terrain: terrainPreset(), camera: 'firstPerson' }), hud()); // camera (required): 'follow' | 'firstPerson' | 'rts' | 'fixed', or pass a module like firstPersonCamera({ height: 1.7 })
|
|
17
22
|
engine.use(createPicture());
|
|
18
23
|
const { picture } = engine;
|
|
19
|
-
engine.input.
|
|
20
|
-
engine.characters.
|
|
24
|
+
engine.input.define('shoot', { label: 'Shoot', keys: ['Mouse0', 'KeyF'] }); // the left mouse button is a key too (Mouse0 / Mouse1 / Mouse2); either it or KeyF works
|
|
25
|
+
engine.characters.addPlayer({ ...presets.player.aim, spawn: engine.characters.findSpawn([0, 0, 0], { minH: 3, maxH: 14 }) });
|
|
21
26
|
Object.assign(window, { engine, picture });
|
|
22
|
-
await engine.start();
|
|
27
|
+
await engine.start(); // place targets after the terrain is generated
|
|
23
28
|
|
|
24
29
|
// Targets: ordinary three.js objects. Put your own data in target.userData; managing them with a Map / Set is faster than traversing the scene
|
|
25
30
|
const targets = [];
|
|
@@ -33,16 +38,16 @@ const p0 = engine.player.position;
|
|
|
33
38
|
for (let i = 0; i < 6; i++) addTarget(p0.x + (i - 2.5) * 3, p0.z - 15);
|
|
34
39
|
|
|
35
40
|
let score = 0;
|
|
36
|
-
engine.hud.
|
|
37
|
-
engine.describe.add('range', () => ({ score, targets: targets.length }));
|
|
41
|
+
engine.hud.addCounter('score', { label: 'Hits', value: 0 });
|
|
42
|
+
engine.describe.add('range', () => ({ score, targets: targets.length })); // dev bridge: threedog describe range; in code the part sits under its name: engine.describe('range').range.score
|
|
38
43
|
|
|
39
|
-
engine.onFixed(() => {
|
|
40
|
-
if (!engine.input.pressed('shoot')) return;
|
|
41
|
-
const hit = engine.pick(0, 0, { targets });
|
|
44
|
+
engine.onFixed(() => { // firing is gameplay: read it in fixed so the result is independent of frame rate
|
|
45
|
+
if (!engine.input.pressed('shoot')) return; // "just pressed" from the fixed-step snapshot; one click counts once
|
|
46
|
+
const hit = engine.pick(0, 0, { targets }); // cast from the screen center; hit.object may be a child mesh of the target, so find the target as below
|
|
42
47
|
const t = hit && targets.find(x => x === hit.object || x.getObjectById(hit.object.id));
|
|
43
48
|
if (!t) return;
|
|
44
49
|
engine.remove(t); targets.splice(targets.indexOf(t), 1);
|
|
45
|
-
engine.hud.
|
|
50
|
+
engine.hud.addCounter('score', { value: ++score }); // calling again with the same id = update
|
|
46
51
|
});
|
|
47
52
|
```
|
|
48
53
|
- **Where fire and reload live**: the engine has no weapon system. In a game with ammo they are the game's ops (`engine.ops.define('weapon.fire', ...)`, recipe 23), so a key, a test and the dev bridge run one path; the fixed step above only calls `engine.ops.run`.
|
|
@@ -56,7 +61,7 @@ engine.onFixed(() => { // firing is gameplay:
|
|
|
56
61
|
- **The first click**: on desktop, first person by default needs one click on the canvas to lock the mouse. That press only locks: it is not delivered
|
|
57
62
|
as `Mouse0` and not as a click, so it cannot fire (every later click after Esc and a re-lock behaves the same). `swallowLockClick: false` on the
|
|
58
63
|
camera delivers it too.
|
|
59
|
-
- **Adding a gamepad button**: `engine.input.
|
|
64
|
+
- **Adding a gamepad button**: `engine.input.define('shoot', { label: 'Shoot', keys: ['Mouse0', 'KeyF', 'PadRT'] })`; the key names go into the settings key table and the
|
|
60
65
|
UI prompts. A touch tap does not count as `Mouse0` (give phones a button: `engine.input.touchButton('shoot', 'Shoot')`).
|
|
61
66
|
- To hit terrain / houses / registered static objects, don't pass `targets` (the default hits what was registered with `rays.addStatic`); to hit rigid
|
|
62
67
|
bodies too, pass `targets: 'all'`.
|
|
@@ -66,13 +71,13 @@ engine.onFixed(() => { // firing is gameplay:
|
|
|
66
71
|
- For bullets with flight time (arcs, enemies dodging): don't use a ray; write `world.add({ kind: 'bullet', ... })` + `world.simulate`, see `18-world.md`.
|
|
67
72
|
- Distance limit: `engine.pick(0, 0, { targets, far: 60 })`.
|
|
68
73
|
- Recoil: `pick` casts from the camera as last drawn, so a `rig.yaw` / `rig.pitch` write reaches it on the next drawn step. For several shots in one step with recoil between them, build the direction from the rig's angles and use `engine.raycast`.
|
|
69
|
-
- Score, ammo: `hud.
|
|
70
|
-
`hud.
|
|
74
|
+
- Score, ammo: `hud.addCounter` / `hud.bar`; numbers that must be saved go in `engine.vars` (`engine.vars.bump('score')`); after changing them call
|
|
75
|
+
`hud.addCounter` again to sync the display.
|
|
71
76
|
|
|
72
77
|
## 3. Testing
|
|
73
78
|
```js fragment
|
|
74
79
|
engine.haltLoop();
|
|
75
|
-
engine.input.simulate('shoot'); engine.step(0.1); engine.input.simulate('shoot', false);
|
|
80
|
+
engine.input.simulate('shoot'); engine.step(0.1); engine.input.simulate('shoot', false); // simulate a click on the action bound to Mouse0 (use your action name)
|
|
76
81
|
// To hit a specific target: first aim the camera at it with engine.cameraRig.lookAt(target), then click
|
|
77
82
|
```
|
|
78
83
|
From the command line: `threedog press Mouse0` (the same as pressing a keyboard key), then look at `describe range`:
|
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
# Content vocabulary, key actions in actions.js, saving and loading at startup
|
|
2
2
|
|
|
3
|
-
**
|
|
4
|
-
|
|
3
|
+
> **Covers:** content words (conditions and effects), content packs, key actions, saving and loading.
|
|
4
|
+
> **Use when:** game rules written as data, or saving progress.
|
|
5
|
+
> **Shortest:** `engine.saves.save('slot1')` / `engine.session.load('slot1')`.
|
|
6
|
+
> **Sections:** 1 Condition words / · 1b Content packs several · 2 actions.js a game's · 3 Interact keys which · 4 Continue and new · 4b Best times and · Save failures and versions · Save format
|
|
5
7
|
|
|
6
8
|
## 1. Condition words / effect words
|
|
7
9
|
The full vocabulary is in the last section of `../api/content.md` (**generated from `modules/content/rules.js`**, so it never goes stale):
|
|
@@ -21,7 +23,7 @@ ops, used from content as `{ op: ['noun.verb', { args }] }` / `{ can: [...] }` (
|
|
|
21
23
|
Register once and the loader, `threedog check` and GAMEMAP all know the file:
|
|
22
24
|
```js
|
|
23
25
|
// content/rules.js
|
|
24
|
-
import { craftOp } from '../crafting.js';
|
|
26
|
+
import { craftOp } from '../crafting.js'; // the game's own code
|
|
25
27
|
export default {
|
|
26
28
|
kinds: {
|
|
27
29
|
recipes: {
|
|
@@ -32,7 +34,7 @@ export default {
|
|
|
32
34
|
check(data, ctx) {
|
|
33
35
|
for (const [id, r] of Object.entries(data)) if (!ctx.data.items?.[r.makes]) ctx.err(`recipe ${id} makes unknown item ${r.makes}`);
|
|
34
36
|
},
|
|
35
|
-
map: data => Object.entries(data).map(([id, r]) => `${id} -> ${r.makes}`),
|
|
37
|
+
map: data => Object.entries(data).map(([id, r]) => `${id} -> ${r.makes}`), // optional GAMEMAP lines
|
|
36
38
|
// optional: the keys of each entry (core/base/params.js format, no default); threedog check reports unknown keys, wrong types, out of range
|
|
37
39
|
fields: { needs: 'object', makes: 'string', seconds: { type: 'number', min: 0, optional: true, desc: 'crafting time' } },
|
|
38
40
|
},
|
|
@@ -43,20 +45,17 @@ export default {
|
|
|
43
45
|
// content/recipes.js
|
|
44
46
|
export default { bread: { needs: { flour: 2 }, makes: 'bread' } };
|
|
45
47
|
```
|
|
46
|
-
Add `recipes` to `content/index.js
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
both say how to register it. A kind may not reuse an engine file name. A file the index does not list is no content, so `threedog check` gives one warning.
|
|
50
|
-
A game's own data that the engine never reads, such as translated story text, belongs outside `content/`: a folder of its own that the game
|
|
51
|
-
imports itself, or `engine.i18n.add()` when it is text the UI fetches with `engine.t`. To have it checked and on the map, register a kind with no `load`.
|
|
48
|
+
Add `recipes` and `rules` to `content/index.js`: the loader knows a kind only from the `rules` it is handed. `load` is optional (the check and the map entry still apply).
|
|
49
|
+
An unregistered name in `content/index.js` or `content.load({ enemies })` is an error saying how to register it; a kind may not reuse an engine file name; a file the index does not list gets one warning.
|
|
50
|
+
Data the engine never reads (translated story text) belongs outside `content/`, or in `engine.i18n.add()` for text fetched with `engine.t`; a kind with no `load` still gets it checked and mapped.
|
|
52
51
|
|
|
53
|
-
**Field tables.** Every content entry has one
|
|
54
|
-
|
|
52
|
+
**Field tables.** Every content entry has one (the engine's own, a template's `fields` (recipes/30-templates.md), a kind's `fields`): `threedog check` validates against it
|
|
53
|
+
(a misspelled `scael` names `scale`), and `engine.content.fields(name)` returns it for tools.
|
|
55
54
|
|
|
56
55
|
## 1b. Content packs: several data sets in one load
|
|
57
56
|
A pack with a `level` commits when its file is here. If a newer `level.load`, save load or unload comes first, the newest level stands and only the pack's `level` gives way: the rest goes in once that load has ended, on the level that won. A place only the pack's level had fails with `content-place`, as any unknown place does, and the pack goes back whole.
|
|
58
57
|
|
|
59
|
-
|
|
58
|
+
Bad data throws on the line. The Promise `content.load` returns resolves once the pack committed and rejects when it failed, after the old level and registrations are back; saves and loads asked meanwhile wait. A load nobody awaits is reported all the same. `err.notRestored` lists why the old level could not come back.
|
|
60
59
|
|
|
61
60
|
```js fragment
|
|
62
61
|
try { await engine.content.load(dlc); }
|
|
@@ -67,9 +66,9 @@ A content pack is the same object `content/index.js` exports (`{ items, template
|
|
|
67
66
|
folder or an npm package: data only, assets by name (never a path or a function; `npm run check` and a dev warning report both). Load several together:
|
|
68
67
|
```js fragment
|
|
69
68
|
import base from './content/index.js';
|
|
70
|
-
import forest from 'forest-content';
|
|
71
|
-
import packs from './assets.js';
|
|
72
|
-
engine.assets.manifest(packs);
|
|
69
|
+
import forest from 'forest-content'; // its props name templates from base and models from the forest asset pack
|
|
70
|
+
import packs from './assets.js'; // export default [forestAssets, ...]: the asset packs ({ name, base, models, textures, sounds, fonts })
|
|
71
|
+
engine.assets.manifest(packs); // the same objects `npm run check` reads the names from
|
|
73
72
|
engine.content.load([base, forest], { places: { home } });
|
|
74
73
|
```
|
|
75
74
|
- Packs load in list order, so a pack may use what an earlier one defines. A pack's own `places` load with it; the `places` option goes on top (a place computed at startup).
|
|
@@ -79,9 +78,8 @@ engine.content.load([base, forest], { places: { home } });
|
|
|
79
78
|
are ids like items (two packs, one name: an error); ambience and music rule lists concatenate.
|
|
80
79
|
|
|
81
80
|
## 2. actions.js: a game's own key actions
|
|
82
|
-
Format of `content/actions.js`: **action name -> { keys: default keys, label: display text }**.
|
|
83
|
-
|
|
84
|
-
are not core keys either: they come from the game (`presets.bindings.*`, this file or `createEngine({ bindings })`).
|
|
81
|
+
Format of `content/actions.js`: **action name -> { keys: default keys, label: display text }**. Engine actions (move...) need not be written; modules
|
|
82
|
+
only declare theirs, and run, jump and interact keys come from the game (`presets.bindings.*`, this file or `createEngine({ bindings })`).
|
|
85
83
|
```js
|
|
86
84
|
// content/actions.js
|
|
87
85
|
export default {
|
|
@@ -90,42 +88,39 @@ export default {
|
|
|
90
88
|
load: { keys: ['KeyL'], label: 'Load' },
|
|
91
89
|
};
|
|
92
90
|
```
|
|
93
|
-
|
|
94
|
-
it (it calls `engine.input.action(name, { label, keys })`). What happens on press is written in main.js, read inside a fixed step so it lands on a tick:
|
|
91
|
+
Add it to `content/index.js` (`export default { ..., actions }`); the load calls `engine.input.define(name, { label, keys })`. The press is read in main.js inside a fixed step:
|
|
95
92
|
`engine.onFixed(() => { if (engine.input.pressed('kick')) engine.ops.run('ball.kick', {}, { source: 'player' }); })` (a gameplay action is an op,
|
|
96
|
-
recipes/23-ops.md). A game that does not use content calls `engine.input.
|
|
93
|
+
recipes/23-ops.md). A game that does not use content calls `engine.input.define('kick', { label: 'Push / kick', keys: ['KeyF'] })` directly.
|
|
97
94
|
|
|
98
|
-
**The
|
|
99
|
-
|
|
100
|
-
Loading a slot to keep playing from it is `engine.session.load`, which leaves nothing of the current playthrough behind:
|
|
95
|
+
**The `save` / `load` actions only register keys**: call the engine yourself after the press. Both are async (`Promise<boolean>`): say "saved" only on `true`
|
|
96
|
+
(on `false` the engine already showed why). Loading a slot to play on is `engine.session.load`, which leaves nothing of the current playthrough:
|
|
101
97
|
```js
|
|
102
98
|
import { toast } from 'threedog';
|
|
103
|
-
engine.onFixed(() => {
|
|
99
|
+
engine.onFixed(() => { // read keys in the fixed step like every gameplay key; the async work runs after it
|
|
104
100
|
if (engine.input.pressed('save')) engine.saves.save('slot1').then(ok => ok && toast(engine, 'Saved'));
|
|
105
101
|
if (engine.input.pressed('load')) engine.session.load('slot1').then(ok => !ok && toast(engine, 'No save yet'));
|
|
106
102
|
});
|
|
107
|
-
engine.saves.autosave(3);
|
|
103
|
+
engine.saves.autosave(3); // autosave to 'auto' every 3 minutes of play (waits while paused, on the title screen and during newGame / load)
|
|
108
104
|
```
|
|
109
105
|
|
|
110
106
|
## 3. Interact keys: which object, and who acts
|
|
111
107
|
`interactions({ pick })` decides what the interact key uses (no default, `[interaction-setup]` names the fix). It takes no key: bind one in `createEngine({ bindings: presets.bindings.interact })`, or with `engine.input.bind`.
|
|
112
|
-
`radius` is measured from the object's origin, not its edge
|
|
113
|
-
object at the spot where it is used.
|
|
108
|
+
`radius` is measured from the object's origin, not its edge: for a large object raise it, or put the interaction on a small marker where it is used.
|
|
114
109
|
|
|
115
110
|
Pick the rule that fits the camera, not the genre default:
|
|
116
111
|
```js
|
|
117
|
-
engine.use(interactions({ ...presets.interactions.nearest }));
|
|
112
|
+
engine.use(interactions({ ...presets.interactions.nearest })); // E, nearest within 2.5 m (top-down, third person)
|
|
118
113
|
engine.use(interactions({ pick: 'facing' })); // only what the actor faces (within 60°): the door behind you stays dark
|
|
119
114
|
engine.use(interactions({ pick: 'aim', radius: 2 })); // closest to the screen-center ray: first person, shooters
|
|
120
|
-
engine.use(interactions({ pick: (list, ctx) => list.find(c => c.id.startsWith('npc')) ?? list[0] }));
|
|
121
|
-
engine.interactions.pickMode = 'aim';
|
|
115
|
+
engine.use(interactions({ pick: (list, ctx) => list.find(c => c.id.startsWith('npc')) ?? list[0] })); // own rule; list = enabled ones in range, nearest first
|
|
116
|
+
engine.interactions.pickMode = 'aim'; // switch at runtime (entering a first-person mode)
|
|
122
117
|
```
|
|
123
118
|
One object with two verbs = two interactions with different key actions; each key picks among its own action, and `engine.interactions.options` lists
|
|
124
119
|
one `{ action, id, label }` per key for a prompt that shows both:
|
|
125
120
|
```js fragment
|
|
126
|
-
engine.input.
|
|
127
|
-
engine.interactions.add(thing, { label: 'Inspect', onUse: inspect });
|
|
128
|
-
engine.interactions.add(thing, { label: 'Take', action: 'take', enabled: () => ready, onUse: take });
|
|
121
|
+
engine.input.define('take', { label: 'Take', keys: ['KeyF'] });
|
|
122
|
+
engine.interactions.add(thing, { label: 'Inspect', onUse: inspect }); // E
|
|
123
|
+
engine.interactions.add(thing, { label: 'Take', action: 'take', enabled: () => ready, onUse: take }); // F
|
|
129
124
|
```
|
|
130
125
|
**Hold and walk-over.** `hold: seconds` makes the key a hold (pump a well, defuse, pick a lock): the engine counts it on fixed steps, interrupts it
|
|
131
126
|
when the key is released, the actor leaves the radius, `enabled()` turns false or input locks (`interaction:hold` / `interaction:interrupt
|
|
@@ -135,13 +130,12 @@ when the key is released, the actor leaves the radius, `enabled()` turns false o
|
|
|
135
130
|
skip the hold; an approach returns `{ approaching }`, a promise of onUse's result).
|
|
136
131
|
```js fragment
|
|
137
132
|
engine.interactions.add(well, { label: 'Pump', hold: 1.5, onUse: fill });
|
|
138
|
-
engine.interactions.add(shell, { id: 'shell-1', label: 'Pick up', once: true, counter: 'shells' });
|
|
133
|
+
engine.interactions.add(shell, { id: 'shell-1', label: 'Pick up', once: true, counter: 'shells' }); // mesh gone after E, counted: recipe 03 "Pick and count"
|
|
139
134
|
engine.interactions.add(clerk, { label: 'Talk', radius: Infinity, approach: true, onUse: talk });
|
|
140
135
|
```
|
|
141
|
-
**Who acts** is `engine.actor` (a world record id, default `'player'`)
|
|
142
|
-
|
|
143
|
-
`engine.
|
|
144
|
-
(rule R17 warns).
|
|
136
|
+
**Who acts** is `engine.actor` (a world record id, default `'player'`): interactions, trigger zones, marker distances, the world simulation center and ops'
|
|
137
|
+
default `ctx.actor` measure from `engine.actorPosition()`. Drive a boat or switch squad members with `engine.actor = 'boat_1'`. Module code reads
|
|
138
|
+
`engine.actorPosition()`, never `engine.player.position` (rule R17).
|
|
145
139
|
The actor is handed down, never assumed: `label / enabled / onUse` get `(object, { actor })` (the actor of `interaction.use`: the local user, a net
|
|
146
140
|
peer, an NPC); trigger callbacks get `(t, who, id)` and the events carry `id` (`who` may list actor ids: `who: () => [e.actor, ...peerIds]`); content
|
|
147
141
|
`has / lacks / give / take` use the bag of the running op's actor (else `engine.actor`), and `engine.content.run(effect, { actor })` /
|
|
@@ -154,26 +148,23 @@ engine.triggers.add({ position: gate, who: () => [engine.actor, ...guards], onEn
|
|
|
154
148
|
## 4. Continue and new game (the engine does not load automatically on start)
|
|
155
149
|
After a page refresh the game is a new run; to "continue last time", load **after** `await engine.start()` through `engine.session`, the standard form:
|
|
156
150
|
```js
|
|
157
|
-
await engine.start();
|
|
158
|
-
if (engine.saves.check('auto') === null) await engine.session.load('auto');
|
|
151
|
+
await engine.start(); // modules and the save index are ready, so saves.list / check are synchronous
|
|
152
|
+
if (engine.saves.check('auto') === null) await engine.session.load('auto'); // continue from the autosave if it can be loaded
|
|
159
153
|
```
|
|
160
|
-
- `engine.session.load(slot)` and `engine.session.newGame()`
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
- A running cutscene and an open conversation are not saved: any load ends them without their remaining steps. Save at a point the game can continue from: a save taken inside a
|
|
164
|
-
cutscene whose last step sets the flag a quest waits for comes back without that flag.
|
|
154
|
+
- `engine.session.load(slot)` and `engine.session.newGame()` return `Promise<boolean>`. `session.load` starts from the new-game state and puts the save on top,
|
|
155
|
+
so a part the save lacks starts fresh. `engine.saves.load(slot)` is a quick load onto the running playthrough; never build Continue from it.
|
|
156
|
+
- A running cutscene and an open conversation are not saved: any load ends them without their remaining steps (a flag their last step sets is missing), so save where the game can continue.
|
|
165
157
|
- Loading restores the player, the view (the camera rig's yaw and pitch: a first-person game needs no save code for it), world data (world changes and deletions), inventory, quests, clock and random state; initial data in content files
|
|
166
158
|
(`initial`) is the same whether it is loaded before or after the save, so ignore the order.
|
|
167
159
|
- A load rebuilds the props and other world records: an Object3D your code kept from before (a door mesh, a lamp) is gone afterwards. Keep the
|
|
168
160
|
record id, not the mesh, and look it up again on `save:loaded`: `engine.world.get(id)` for the record, `engine.world.view(id)` for its model
|
|
169
161
|
now (null while not built or far away).
|
|
170
|
-
-
|
|
171
|
-
"New game" is `await engine.session.newGame()`.
|
|
162
|
+
- Main menu: show "Continue" only when `engine.saves.check(slot) === null`; "New game" is `await engine.session.newGame()`.
|
|
172
163
|
- During development, to jump straight into a save: URL `?save=slot1` (`threedog state` also understands `save=`).
|
|
173
164
|
- In tests, `engine.saves.save('x'); await engine.saves.flush();` writes before reading back.
|
|
174
165
|
|
|
175
166
|
## 4b. Best times and high scores: data that outlives saves
|
|
176
|
-
Best
|
|
167
|
+
Best times, a leaderboard or high scores belong to the player, not one playthrough (a new game would wipe a save part): keep them in `localStorage` under `engine.saves.storageKey(name)`, which shares the game's name and stays out of the slots:
|
|
177
168
|
```js
|
|
178
169
|
const key = engine.saves.storageKey('records');
|
|
179
170
|
const records = () => JSON.parse(localStorage.getItem(key) ?? '{ "laps": [] }');
|
|
@@ -187,7 +178,8 @@ const addLap = time => { const r = records(); r.laps.push(time); localStorage.se
|
|
|
187
178
|
running game and the stored save stay as they were. Ask first with `engine.saves.check(slot)` → `null | 'missing' | 'corrupt' | 'tooNew' | 'migrate'`.
|
|
188
179
|
- A part whose `save()` throws makes the whole save fail (`false`, the slot keeps its previous save); a part whose `load()` throws rolls the game back
|
|
189
180
|
to how it was before the load (`false`). So does a listener of an event the load emits (`world:load`) or a module's `afterLoad` that throws. Both go
|
|
190
|
-
through the error tiers (`engine.error` in dev, code `save-part-threw` / `save-load-threw
|
|
181
|
+
through the error tiers (`engine.error` in dev and in release, code `save-part-threw` / `save-load-threw`; dev freezes the game on it).
|
|
182
|
+
- A rollback that cannot put a part back (no restorable `save()`, no new-game state, or a content `undo` that throws) warns `rollback-incomplete`: reload the page.
|
|
191
183
|
- One replacement at a time: `saves.apply`, `saves.load` and `session.newGame` / `load` / `quit` wait their turn in the order asked, so the end state is
|
|
192
184
|
always one whole save, and a load that fails rolls back to the whole state before it. Idle, a save with only synchronous parts applies at once. While
|
|
193
185
|
a replacement runs ops return `'loading'`.
|
|
@@ -208,12 +200,12 @@ const addLap = time => { const r = records(); r.laps.push(time); localStorage.se
|
|
|
208
200
|
## Save format
|
|
209
201
|
A save is one envelope; `engine.saves.collect()` returns it and `export` / `exportFile` carry it unchanged:
|
|
210
202
|
```js fragment
|
|
211
|
-
{ format: 1,
|
|
212
|
-
savedAt: 1730000000000,
|
|
213
|
-
versions: { world: 5, quests: 2, clock: 1 },
|
|
214
|
-
parts: { world: {...}, quests: {...}, clock: {...}, vars: {...} } }
|
|
203
|
+
{ format: 1, // the envelope's own version: a save with a higher format is refused as tooNew (none = 1)
|
|
204
|
+
savedAt: 1730000000000, // real time of the save
|
|
205
|
+
versions: { world: 5, quests: 2, clock: 1 }, // each part's version (none = 1)
|
|
206
|
+
parts: { world: {...}, quests: {...}, clock: {...}, vars: {...} } } // each saves.define part's data, by key
|
|
215
207
|
```
|
|
216
|
-
- **Parts and versions**: each `engine.saves.
|
|
208
|
+
- **Parts and versions**: each `engine.saves.define(key, { version, migrate, save, load })` owns one part. `load` takes one argument, the data: `load: data => …`, never `load(engine, data)`, the shape of a module hook (`npm run check` warns, rule R33). When `save()` changes shape, raise
|
|
217
209
|
`version` by 1 and add `migrate[oldVersion] = data => newData`; load runs the steps in order on a copy, so `load` only sees the current shape.
|
|
218
210
|
This is how a game's own saved data migrates across its releases (there is no other system): keep one saved file per released game version, never edit it, and load each in a test with `engine.saves.apply(sample)` (the engine does the same for its own parts in `tests/specs/save-compat.mjs`).
|
|
219
211
|
- **Parts nobody owns are kept**: a part in the loaded save whose module is not installed in this run (a feature turned off for a version) is written
|
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
# Camera: first / third person, top-down strategy, fixed shots, switched at runtime
|
|
2
2
|
|
|
3
|
-
**
|
|
4
|
-
|
|
5
|
-
|
|
3
|
+
> **Covers:** the four cameras (follow, first person, strategy, fixed), switching, framing, limits.
|
|
4
|
+
> **Use when:** choosing or tuning how the player sees the game.
|
|
5
|
+
> **Shortest:** `openWorld({ camera: 'firstPerson' })`.
|
|
6
|
+
> **Sections:** 1 Press V to · 2 What the engine · 3 Other common things · 4 Over the shoulder · 4b Looking up, ground · 4c Chase camera behind · 5 Take over the · 6 Orthographic view, and · 7 Your own camera
|
|
6
7
|
|
|
7
8
|
Four cameras; the kind names are always: `'follow'` third-person follow · `'firstPerson'` first person · `'rts'` top-down strategy · `'fixed'` fixed shots.
|
|
8
9
|
Pick one at the start: `openWorld({ camera: 'firstPerson' })`, or by hand `engine.use(followCamera({ distance: 10 }))` /
|
|
@@ -11,25 +12,20 @@ Pick one at the start: `openWorld({ camera: 'firstPerson' })`, or by hand `engin
|
|
|
11
12
|
|
|
12
13
|
## 1. Press V to switch between first and third person (copy it)
|
|
13
14
|
```js
|
|
14
|
-
engine.input.
|
|
15
|
-
engine.onFrame(() => {
|
|
15
|
+
engine.input.define('toggleView', { label: 'Switch view', keys: ['KeyV'] });
|
|
16
|
+
engine.onFrame(() => { // UI-type actions read pressed in onFrame
|
|
16
17
|
if (!engine.input.pressed('toggleView')) return;
|
|
17
|
-
engine.setCamera(engine.cameraRig.kind === 'follow' ? 'firstPerson' : 'follow');
|
|
18
|
+
engine.setCamera(engine.cameraRig.kind === 'follow' ? 'firstPerson' : 'follow'); // kind is the current kind
|
|
18
19
|
});
|
|
19
20
|
```
|
|
20
21
|
Starting in first person and switching later: `openWorld({ camera: 'firstPerson' })` can still `setCamera('follow')`; you don't need to install two cameras.
|
|
21
22
|
|
|
22
23
|
## 2. What the engine does for you when switching
|
|
23
|
-
- **Target and heading carry over
|
|
24
|
-
|
|
25
|
-
- **
|
|
26
|
-
|
|
27
|
-
- **
|
|
28
|
-
it. No lock on phones.
|
|
29
|
-
- **Field of view (fov)**: switching away returns to the value from when the camera was installed; the first-person / strategy cameras each set it
|
|
30
|
-
from their own `fov` option.
|
|
31
|
-
- **Settings are kept**: the camera you switched away from is kept, so switching back keeps the zoom distance and pitch. To use a different set of
|
|
32
|
-
parameters pass options (that camera is rebuilt with the new parameters):
|
|
24
|
+
- **Target and heading carry over** (the followed character and `yaw`; pitch is not, it means different things per camera).
|
|
25
|
+
- **First person hides the body but keeps the shadow**: the model moves to `hideLayer` (default 30), which the shadow camera still sees; a model loaded later too. A light the player carries (within one body width of the body) leaves the hidden body out of its shadow: recipe 34.
|
|
26
|
+
- **Mouse lock**: switching to first person by a key press locks the mouse, Esc leaves, switching away releases it. No lock on phones.
|
|
27
|
+
- **Field of view**: switching away returns to the value from install; first-person and strategy cameras set their own `fov` option.
|
|
28
|
+
- **Settings are kept**: switching back keeps the zoom and pitch; pass options to rebuild that camera with new ones:
|
|
33
29
|
```js
|
|
34
30
|
engine.setCamera('firstPerson', { height: 1.7, fov: 80 });
|
|
35
31
|
engine.setCamera('follow', { distance: 8, pitch: 0.3 });
|
|
@@ -37,30 +33,26 @@ engine.setCamera('follow', { distance: 8, pitch: 0.3 });
|
|
|
37
33
|
- A wrong kind name throws and lists the valid ones; a wrong option name gets the closest name suggested in development.
|
|
38
34
|
|
|
39
35
|
## 3. Other common things
|
|
40
|
-
- **
|
|
41
|
-
|
|
36
|
+
- **Which way yaw points**: first person and follow, yaw 0 looks toward -z, `Math.PI / 2` toward -x, `Math.PI` toward +z (forward = -(sin yaw, cos yaw)). Facing +z: `engine.cameraRig.yaw = Math.PI` (recipe 63 §7).
|
|
37
|
+
- **Cycling**: find `engine.cameraRig.kind` in a list of kinds, `setCamera` the next.
|
|
42
38
|
- **A fixed camera needs shots first**: `engine.setCamera('fixed', { shots: { hall: { position: [0, 6, 12], lookAt: [0, 0, 0] } }, start: 'hall' })`. A shot stays where it was placed; a view that pans at a fixed angle is the follow camera (section 6).
|
|
43
39
|
- **Camera-specific methods** exist only after switching: `engine.cameraRig.lookAt(position)` (first person), `cut('name')` (fixed shots),
|
|
44
40
|
`screenToGround(...)` (rts). Check `kind` before calling.
|
|
45
|
-
- **Teleport, then lookAt**: `await engine.stream.teleport(p); engine.cameraRig.lookAt(target);`
|
|
46
|
-
|
|
47
|
-
- **Saves and new games**: a save holds the view (`yaw`, `pitch`), and `session.load` / `saves.load` put it back. A new playthrough rebuilds the installed camera on the same object, so a kept `const rig = engine.cameraRig` stays valid (one from `setCamera` with options does not). A kind switched to with `setCamera` is not restored: only the heading carries, so call `setCamera` again on `session:start` if the game keeps that choice.
|
|
48
|
-
- **Player movement direction follows the camera**: `engine.cameraRig.forward()` / `right()` change automatically after switching.
|
|
41
|
+
- **Teleport, then lookAt**: `await engine.stream.teleport(p); engine.cameraRig.lookAt(target);` in that order: `lookAt` aims once from the body's current position.
|
|
42
|
+
- **Saves and new games**: a save holds the view (`yaw`, `pitch`), and `session.load` / `saves.load` put it back. A new playthrough rebuilds the installed camera on the same object: a kept `engine.cameraRig` stays valid (one from `setCamera` with options does not). A kind switched to with `setCamera` is not restored (only the heading carries): call `setCamera` again on `session:start` to keep the choice.
|
|
49
43
|
- **Cutscene takeover**: while anyone holds `engine.takeCamera(owner)` (`engine.cameraOverride` is not null) the camera module leaves the camera alone; see [the engine API](../api/engine.md).
|
|
50
|
-
- **Shooting games**: bind first-person firing to a mouse-button action, see `19-shooting-picking.md`.
|
|
51
44
|
|
|
52
45
|
## 4. Over the shoulder, lock-on framing, mouse lock (follow camera)
|
|
53
46
|
```js fragment
|
|
54
|
-
engine.use(followCamera({ distance: 3, shoulder: 0.7, pitch: 0.15, pointerLock: true }));
|
|
55
|
-
engine.cameraRig.shoulder = -0.7;
|
|
56
|
-
engine.cameraRig.frame(enemy.root);
|
|
47
|
+
engine.use(followCamera({ distance: 3, shoulder: 0.7, pitch: 0.15, pointerLock: true })); // shooter / action-adventure view
|
|
48
|
+
engine.cameraRig.shoulder = -0.7; // switch shoulders at any time (plain property)
|
|
49
|
+
engine.cameraRig.frame(enemy.root); // lock-on: turn to "behind the player, looking at the enemy"; frame(null) lets go
|
|
57
50
|
```
|
|
58
51
|
- **`shoulder`**: meters the aim point (and so the camera) moves to the right along `right()`; negative = left, 0 = centered (default).
|
|
59
|
-
- **`pointerLock`** (default false): a click on the canvas locks the mouse, so moving it turns the view with no dragging; Esc releases, and `engine.page.releaseLock()` releases from code without opening the pause menu. Not on phones. If the browser refuses the lock the camera falls back to dragging; `describe().camera.pointerLock`
|
|
52
|
+
- **`pointerLock`** (default false): a click on the canvas locks the mouse, so moving it turns the view with no dragging; Esc releases, and `engine.page.releaseLock()` releases from code without opening the pause menu. Not on phones. If the browser refuses the lock the camera falls back to dragging; `describe().camera.pointerLock` has `state` (`off` / `unsupported` / `waiting-click` / `requesting` / `locked` / `refused`), `covered` (what sits on the canvas centre and eats the click), `cameraOverride` (a takeover blocks locking) and `lastFailure { reason, agoSec }`; the text line shows the same.
|
|
60
53
|
The press that locks is swallowed (no `Mouse0`, no click) so it cannot attack or fire; `swallowLockClick: false` delivers it.
|
|
61
54
|
Leave it off when the mouse buttons are for UI or clicking the ground.
|
|
62
|
-
- **`yaw`
|
|
63
|
-
`forward() = -(sin yaw, cos yaw)`. To make it look toward a direction, negate it; better not to compute it at all and use `frame(target)`.
|
|
55
|
+
- **`yaw` is which side of the player the camera is on**: `camera = focus + (sin yaw, cos yaw) * distance`, looking along `forward() = -(sin yaw, cos yaw)`; prefer `frame(target)` to computing it.
|
|
64
56
|
- **`frame(target, { strength = 6 })`**: `target` is an Object3D or `{ x, z }`; call it once when the lock starts, not every frame. While framing,
|
|
65
57
|
mouse / stick yaw is ignored and a `yaw` you write directly is pulled back, because `frame()` owns the heading; `frame(null)` hands it back.
|
|
66
58
|
`forward()` turns with it, so camera-relative movement strafes around the target.
|
|
@@ -68,8 +60,8 @@ engine.cameraRig.frame(enemy.root); // lock-on: turn to "behind the player, lo
|
|
|
68
60
|
|
|
69
61
|
## 4b. Looking up, ground and walls, driving the view yourself (follow camera)
|
|
70
62
|
```js
|
|
71
|
-
engine.use(followCamera(presets.camera.thirdPersonAction));
|
|
72
|
-
engine.use(followCamera({ minPitch: -0.9, ground: 'shorten' }));
|
|
63
|
+
engine.use(followCamera(presets.camera.thirdPersonAction)); // locked mouse, look up ~60° and down, ground shortens the arm, walls pull in
|
|
64
|
+
engine.use(followCamera({ minPitch: -0.9, ground: 'shorten' })); // or the same idea on your own options
|
|
73
65
|
```
|
|
74
66
|
- **Pitch sign**: positive = the camera is above the look point looking down; **negative = looking up**. Looking up needs `minPitch < 0`.
|
|
75
67
|
- **`ground`** decides what happens when the camera would go below the ground:
|
|
@@ -79,10 +71,9 @@ engine.use(followCamera({ minPitch: -0.9, ground: 'shorten' })); // or the sam
|
|
|
79
71
|
Default: `'shorten'` when `minPitch < 0`, otherwise `'raise'`.
|
|
80
72
|
- **Walls** (with `collision()` installed) pull the arm in at once and let it out slowly; the shortest arm is `collision({ cameraMin })` (default 1.5 m).
|
|
81
73
|
**What blocks by default**: every `addCircle` / `addBox` / `addSegment` collider, over its footprint and up to its height, and every mesh registered
|
|
82
|
-
with `engine.rays.addStatic(mesh, { occluder: true })` (`level()` registers its buildings and `col_` meshes). A mesh alone blocks nothing
|
|
83
|
-
crown or an eave that reaches past its collider lets the camera inside. Register that mesh: it stops the arm and adds no gameplay collider (it does
|
|
74
|
+
with `engine.rays.addStatic(mesh, { occluder: true })` (`level()` registers its buildings and `col_` meshes). A mesh alone blocks nothing (a crown or eave past its collider lets the camera in): registering it stops the arm without a gameplay collider (it does
|
|
84
75
|
join `engine.raycast`). `collision({ cameraOcclusion: 'colliders' })` tests colliders only.
|
|
85
|
-
A content prop or template with `collide` blocks with its whole mesh, crown and eaves included, with no game code. A hand-written mesh stays opt-in: `addStatic(mesh, { occluder: true })`. In a level, `userData.occluder = false` on a node (or a parent)
|
|
76
|
+
A content prop or template with `collide` blocks with its whole mesh, crown and eaves included, with no game code. A hand-written mesh stays opt-in: `addStatic(mesh, { occluder: true })`. In a level, `userData.occluder = false` on a node (or a parent) stops it blocking; a hidden mesh does not block (`col_` meshes do). `addStatic` skips `InstancedMesh` and `SkinnedMesh` (dev warns once; rays do not hit them): give them a collider or a plain stand-in mesh.
|
|
86
77
|
Give the colliders the camera may pass through `occluder: false`
|
|
87
78
|
(`engine.collision.addCircle(tree, { radius: 0.4, occluder: false })`, or `collide: { circle: 0.4, occluder: false }` / `occluder: false` on a content prop or template): walkers are still stopped, the arm ignores them. A dense forest of
|
|
88
79
|
blocking trunks collapses the camera onto the player; `collision({ canopyHeight })` covers only the terrain's own trees.
|
|
@@ -97,16 +88,16 @@ engine.use(followCamera({ minPitch: -0.9, ground: 'shorten' })); // or the sam
|
|
|
97
88
|
```js fragment
|
|
98
89
|
let yaw = null;
|
|
99
90
|
engine.onFrame(dt => {
|
|
100
|
-
const q = car.body.rotation();
|
|
101
|
-
const want = Math.atan2(2 * (q.x * q.z + q.w * q.y), 1 - 2 * (q.x * q.x + q.y * q.y)) + Math.PI;
|
|
91
|
+
const q = car.body.rotation(); // car: what addWheeled returned
|
|
92
|
+
const want = Math.atan2(2 * (q.x * q.z + q.w * q.y), 1 - 2 * (q.x * q.x + q.y * q.y)) + Math.PI; // a car drives along its +z; the view looks along -z at yaw 0
|
|
102
93
|
yaw ??= want;
|
|
103
|
-
yaw += Math.atan2(Math.sin(want - yaw), Math.cos(want - yaw)) * Math.min(1, 5 * dt);
|
|
94
|
+
yaw += Math.atan2(Math.sin(want - yaw), Math.cos(want - yaw)) * Math.min(1, 5 * dt); // the shortest way round, catching up at 5 per second
|
|
104
95
|
engine.cameraRig.setView({ yaw });
|
|
105
96
|
});
|
|
106
97
|
```
|
|
107
98
|
|
|
108
99
|
## 5. Take over the player: your own movement, facing and lock-on
|
|
109
|
-
The engine has no default here: `
|
|
100
|
+
The engine has no default here: `addPlayer` needs `control` (a preset such as `presets.player.thirdPerson` gives keys relative to the camera, Shift
|
|
110
101
|
run, Space jump, turning toward where it walks and `cameraFollow: true`). Each piece below replaces one part and keeps the rest (world record, saving,
|
|
111
102
|
`describe().player`).
|
|
112
103
|
```js fragment
|
|
@@ -114,21 +105,21 @@ import { pickTarget, switchTarget } from 'threedog';
|
|
|
114
105
|
|
|
115
106
|
// how the input steers the player: 'camera' (keys relative to the camera) | (player, input, dt) => ({ x, z, run? }) | null (stand still)
|
|
116
107
|
let lock = null, hitStun = 0, knockX = 0, knockZ = 0;
|
|
117
|
-
const player = engine.characters.
|
|
118
|
-
engine.input.bind({ lockOn: ['KeyQ'], switchTarget: ['KeyR'] });
|
|
108
|
+
const player = engine.characters.addPlayer({ cameraFollow: true, faceMode: 'manual', control: steer }); // moveInput().run reads the bound 'run' action
|
|
109
|
+
engine.input.bind({ lockOn: ['KeyQ'], switchTarget: ['KeyR'] }); // no module binds a key by itself
|
|
119
110
|
const enemies = () => engine.world.query({ kind: 'enemy', near: player.position, radius: 20 });
|
|
120
111
|
|
|
121
|
-
function steer(player, input, dt) {
|
|
122
|
-
const m = engine.characters.moveInput();
|
|
123
|
-
if (engine.input.pressed('lockOn')) {
|
|
112
|
+
function steer(player, input, dt) { // called once per fixed step while the input is in charge of the player
|
|
113
|
+
const m = engine.characters.moveInput(); // the 'camera' key direction as a value, relative to the camera (a reused object: copy x / z if you keep it)
|
|
114
|
+
if (engine.input.pressed('lockOn')) { // pick what is in view; press again to let go
|
|
124
115
|
lock = lock ? null : pickTarget(player, engine.cameraRig.forward(), enemies(), { radius: 15 });
|
|
125
116
|
engine.cameraRig.frame(lock ? engine.world.view(lock.id) : null);
|
|
126
117
|
}
|
|
127
118
|
if (lock && engine.input.pressed('switchTarget')) lock = switchTarget(player, engine.cameraRig.forward(), lock, enemies(), 1) ?? lock;
|
|
128
|
-
player.faceMode = lock ? 'target' : 'move';
|
|
119
|
+
player.faceMode = lock ? 'target' : 'move'; // 'move' toward velocity | 'camera' along the camera | 'target' toward faceTarget | 'manual' only face() turns it
|
|
129
120
|
player.faceTarget = lock ? engine.world.view(lock.id) : null;
|
|
130
|
-
if (hitStun > 0) { hitStun -= dt; player.push(knockX, knockZ, dt); return null; }
|
|
131
|
-
return m;
|
|
121
|
+
if (hitStun > 0) { hitStun -= dt; player.push(knockX, knockZ, dt); return null; } // knockback / roll: fixed velocity, never turns
|
|
122
|
+
return m; // the engine calls player.move() with it (one move per step)
|
|
132
123
|
}
|
|
133
124
|
```
|
|
134
125
|
- **`control`** is how the input steers the player: `'camera'` or a function. A function keeps jump and vehicles and only replaces direction
|
|
@@ -157,14 +148,14 @@ The default stays perspective. On resize the view height stays `size` and the wi
|
|
|
157
148
|
```js fragment
|
|
158
149
|
// one fixed isometric shot (shorthand for a single shot named 'main')
|
|
159
150
|
engine.setCamera('fixed', { position: [14, 14, 14], lookAt: [0, 0, 0], projection: 'orthographic', size: 16 });
|
|
160
|
-
// per shot: shots: { hall: { position, lookAt, projection: 'orthographic', size: 12 }, yard: { position, lookAt } }
|
|
151
|
+
// per shot: shots: { hall: { position, lookAt, projection: 'orthographic', size: 12 }, yard: { position, lookAt } } // yard stays perspective
|
|
161
152
|
// follow the player from a fixed angle
|
|
162
153
|
engine.setCamera('follow', { pitch: 0.6, yaw: 0.8, distance: 20, projection: 'orthographic', size: 14, mouseLook: false, ground: 'none' });
|
|
163
154
|
```
|
|
164
155
|
**A view that pans at a fixed angle** (isometric, tactics, city builders) is that follow camera, not a fixed shot. `mouseLook: false` stops the drag and the wheel from moving the view, and `ground: 'none'` stops hills from tilting it. It follows the player, or with no player any object the game moves:
|
|
165
156
|
```js fragment
|
|
166
|
-
const view = new THREE.Object3D();
|
|
167
|
-
engine.cameraRig.follow(view);
|
|
157
|
+
const view = new THREE.Object3D(); // the point the view is centered on
|
|
158
|
+
engine.cameraRig.follow(view); // again on 'session:start': a new playthrough follows the player or nothing
|
|
168
159
|
engine.onFrame(dt => { view.position.x += engine.input.axis.x * 12 * dt; view.position.z -= engine.input.axis.y * 12 * dt; });
|
|
169
160
|
```
|
|
170
161
|
`smoothing` sets how tightly the view keeps up (higher is tighter).
|
|
@@ -181,11 +172,11 @@ Several holders can take it (a cutscene, then a named view on top): the latest i
|
|
|
181
172
|
|
|
182
173
|
```js fragment
|
|
183
174
|
let t = 0;
|
|
184
|
-
const cam = engine.takeCamera('my-orbit', { focus: engine.player.position });
|
|
175
|
+
const cam = engine.takeCamera('my-orbit', { focus: engine.player.position }); // focus (optional): where the world loads around
|
|
185
176
|
const frame = engine.onFrame(dt => {
|
|
186
177
|
t += dt; engine.camera.position.set(Math.cos(t) * 12, 8, Math.sin(t) * 12); engine.camera.lookAt(0, 1, 0);
|
|
187
178
|
});
|
|
188
|
-
// done: frame.remove(); cam.remove();
|
|
179
|
+
// done: frame.remove(); cam.remove(); // the rig resumes from its own state
|
|
189
180
|
```
|
|
190
181
|
|
|
191
182
|
To draw through your own three.js camera, assign it. A real `THREE.PerspectiveCamera` or `THREE.OrthographicCamera` is taken as it is, and any other class, a subclass too, is refused:
|
|
@@ -194,12 +185,12 @@ To draw through your own three.js camera, assign it. A real `THREE.PerspectiveCa
|
|
|
194
185
|
const original = engine.camera;
|
|
195
186
|
const ortho = new THREE.OrthographicCamera(-16, 16, 9, -9, 0.1, 500);
|
|
196
187
|
ortho.position.set(10, 10, 10); ortho.lookAt(0, 0, 0);
|
|
197
|
-
engine.camera = ortho;
|
|
188
|
+
engine.camera = ortho; // rendering, post, picking, shadows, audio and the camera module go on with it
|
|
198
189
|
// give it back: engine.camera = original;
|
|
199
190
|
```
|
|
200
191
|
|
|
201
192
|
The aspect follows the canvas, on assignment and on every resize: an orthographic camera keeps its height and its width follows. `engine.autoView.manual('aspect')` before assigning keeps your own frustum. The engine leaves `far` and `fov` of a real orthographic camera alone.
|
|
202
|
-
A camera module goes on placing the camera you assigned, and
|
|
193
|
+
A camera module goes on placing the camera you assigned, and one assigned during a shot stays until the next view is asked for. `projection: 'orthographic', size` sets the height of a real orthographic camera; on a real perspective one the rig's own orthographic camera stands in until the next perspective view brings yours back. `pixelSnap` writes the height it needs. A chain taken with `engine.post.own()` is yours to point at the new camera; a `pixelGrid` you made keeps the camera you gave it.
|
|
203
194
|
|
|
204
195
|
**Side view (side-scroller).** `presets.player.sideScroller` moves the player along world X only (A / D, `z` stays) and turns it toward the move. Face the camera along -Z with `yaw: 0`, so +X is screen right (`yaw: Math.PI` looks from the far side and flips left and right), on `followCamera`:
|
|
205
196
|
```js fragment
|
|
@@ -208,6 +199,6 @@ engine.use(followCamera({ projection: 'orthographic', size: 15, yaw: 0, pitch: 0
|
|
|
208
199
|
|
|
209
200
|
## 7. Your own camera module
|
|
210
201
|
Everything else in the engine reads only what `modules/camera/contract.js` lists from `engine.cameraRig`: `forward()` / `right()` (control: 'camera',
|
|
211
|
-
faceMode 'camera', targeting), `follow(object, opts?)` (
|
|
202
|
+
faceMode 'camera', targeting), `follow(object, opts?)` (addPlayer, getting in and out of a vehicle), `focusPoint()` (photo, where the world loads)
|
|
212
203
|
and `screenToGround(ndcX, ndcY)` (click-to-move, placing things; every built-in kind has it). A module named `cameraRig` with those five methods
|
|
213
204
|
replaces the built-in cameras: `tests/contract/fakeCamera.js` in the engine repository is one in ~35 lines and the player walks with it.
|