threedog 0.1.0 → 0.2.1

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.
Files changed (244) hide show
  1. package/README.md +4 -4
  2. package/core/Animator.js +1 -0
  3. package/core/Assets.js +28 -0
  4. package/core/DebugOverrides.js +143 -0
  5. package/core/Describe.js +14 -3
  6. package/core/Engine.js +44 -72
  7. package/core/Events.js +59 -1
  8. package/core/I18n.js +2 -2
  9. package/core/Inspect.js +12 -32
  10. package/core/InspectScene.js +7 -3
  11. package/core/MaterialInfo.js +32 -0
  12. package/core/Ops.js +43 -59
  13. package/core/Saves.js +5 -4
  14. package/core/UrlState.js +3 -2
  15. package/core/Vars.js +1 -0
  16. package/core/Views.js +49 -0
  17. package/core/actor.js +2 -2
  18. package/core/assetReport.js +83 -0
  19. package/core/catalog.js +169 -0
  20. package/core/checks.js +67 -0
  21. package/core/claims.js +51 -0
  22. package/core/debugView.js +76 -0
  23. package/core/describeRender.js +51 -0
  24. package/core/describeText.js +11 -4
  25. package/core/errorCodes.js +33 -0
  26. package/core/errorHints.js +6 -1
  27. package/core/grid.js +127 -0
  28. package/core/gridLoad.js +19 -0
  29. package/core/holds.js +106 -0
  30. package/core/lifecycle.js +1 -0
  31. package/core/lightWatch.js +23 -3
  32. package/core/look/coreParts.js +112 -0
  33. package/core/look/layers.js +136 -0
  34. package/core/look/part.js +173 -0
  35. package/core/look/report.js +79 -0
  36. package/core/look/write.js +86 -0
  37. package/core/loop.js +22 -16
  38. package/core/modules.js +19 -5
  39. package/core/opsAtomic.js +31 -0
  40. package/core/opsCheck.js +25 -14
  41. package/core/opsFail.js +20 -0
  42. package/core/opsHistory.js +6 -6
  43. package/core/opsRun.js +77 -0
  44. package/core/params.js +132 -0
  45. package/core/renamed.js +22 -0
  46. package/core/saveApply.js +2 -2
  47. package/core/sceneMethods.js +9 -34
  48. package/core/services.js +73 -0
  49. package/core/startup.js +3 -1
  50. package/core/styleParts.js +11 -9
  51. package/core/thingExplain.js +68 -0
  52. package/core/thingOps.js +35 -24
  53. package/core/things.js +15 -1
  54. package/core/util.js +11 -0
  55. package/core/validate.js +23 -7
  56. package/docs/AI.md +93 -114
  57. package/docs/API.md +8 -9
  58. package/docs/CODEMAP.md +67 -53
  59. package/docs/COMMANDS.md +21 -7
  60. package/docs/CONVENTIONS.md +22 -11
  61. package/docs/THREE.md +3 -3
  62. package/docs/api/assets.md +3 -0
  63. package/docs/api/characters.md +5 -2
  64. package/docs/api/collision.md +4 -0
  65. package/docs/api/content.md +1 -0
  66. package/docs/api/engine.md +23 -14
  67. package/docs/api/events.md +5 -1
  68. package/docs/api/post.md +5 -4
  69. package/docs/api/saves.md +2 -1
  70. package/docs/api/sky.md +3 -3
  71. package/docs/api/style.md +8 -8
  72. package/docs/api/tools.md +5 -2
  73. package/docs/api/vegetation.md +1 -0
  74. package/docs/api/weather.md +1 -1
  75. package/docs/recipes/01-new-game.md +41 -43
  76. package/docs/recipes/02-npc.md +38 -22
  77. package/docs/recipes/03-items-pickups.md +4 -4
  78. package/docs/recipes/04-quests.md +23 -23
  79. package/docs/recipes/05-props-bake.md +5 -5
  80. package/docs/recipes/06-clock-events.md +13 -0
  81. package/docs/recipes/07-flow-scenes-pause.md +6 -2
  82. package/docs/recipes/08-weather-sky.md +6 -6
  83. package/docs/recipes/09-style-pack.md +35 -100
  84. package/docs/recipes/12-navmesh.md +22 -0
  85. package/docs/recipes/13-animation.md +25 -6
  86. package/docs/recipes/14-custom-module.md +6 -7
  87. package/docs/recipes/15-perf.md +9 -1
  88. package/docs/recipes/16-dev-bridge.md +52 -18
  89. package/docs/recipes/18-world.md +5 -2
  90. package/docs/recipes/19-shooting-picking.md +9 -8
  91. package/docs/recipes/20-content-actions-save.md +10 -10
  92. package/docs/recipes/21-camera.md +51 -2
  93. package/docs/recipes/22-shop-gold.md +16 -16
  94. package/docs/recipes/23-ops.md +46 -10
  95. package/docs/recipes/27-net.md +3 -3
  96. package/docs/recipes/28-terrain.md +2 -2
  97. package/docs/recipes/29-grid.md +47 -27
  98. package/docs/recipes/34-environment-lighting.md +11 -10
  99. package/docs/recipes/35-style-from-reference.md +41 -46
  100. package/docs/recipes/36-sky-ground-plant-looks.md +22 -20
  101. package/docs/recipes/37-terrain-look-hooks.md +34 -13
  102. package/docs/recipes/38-environment-look-hooks.md +49 -42
  103. package/docs/recipes/40-scene.md +29 -0
  104. package/docs/recipes/41-thing-registry.md +29 -0
  105. package/docs/recipes/42-terrain-shape.md +1 -1
  106. package/docs/recipes/43-shader-patches-surface-looks.md +37 -20
  107. package/docs/recipes/44-water-weather-look-hooks.md +11 -9
  108. package/docs/recipes/45-cascaded-shadows.md +2 -2
  109. package/docs/recipes/46-blender-art-route.md +26 -4
  110. package/docs/recipes/47-island-snow-backdrop.md +4 -3
  111. package/docs/recipes/48-make-material.md +70 -0
  112. package/docs/recipes/49-game-module-contract.md +71 -0
  113. package/docs/recipes/50-own-renderer.md +12 -0
  114. package/docs/recipes/51-capability-catalog.md +63 -0
  115. package/docs/recipes/52-look.md +146 -0
  116. package/docs/recipes/53-ground-up-close.md +58 -0
  117. package/examples/action/GAMEMAP.md +7 -7
  118. package/examples/action/content/index.js +2 -1
  119. package/examples/action/content/views.js +6 -0
  120. package/examples/action/main.js +3 -2
  121. package/examples/sheepisland/GAMEMAP.md +3 -4
  122. package/examples/styletest/GAMEMAP.md +3 -3
  123. package/examples/styletest/content/npcs.js +1 -1
  124. package/examples/styletest/main.js +2 -2
  125. package/examples/styletest/panel.js +3 -3
  126. package/examples/world/GAMEMAP.md +3 -3
  127. package/examples/world/content/npcs.js +1 -1
  128. package/examples/world/main.js +1 -1
  129. package/index.d.ts +35 -2
  130. package/index.js +6 -3
  131. package/llms.txt +13 -7
  132. package/modules/ambience/Ambience.js +5 -2
  133. package/modules/camera/FirstPersonCamera.js +3 -5
  134. package/modules/camera/FixedCamera.js +19 -12
  135. package/modules/camera/FollowCamera.js +14 -8
  136. package/modules/camera/RtsCamera.js +3 -5
  137. package/modules/camera/common.js +40 -10
  138. package/modules/camera/index.js +1 -1
  139. package/modules/camera/projection.js +34 -0
  140. package/modules/characters/Character.js +45 -31
  141. package/modules/characters/assetModel.js +35 -7
  142. package/modules/characters/astar.js +14 -7
  143. package/modules/characters/index.js +6 -3
  144. package/modules/characters/movers/simple.js +6 -1
  145. package/modules/characters/npcSim.js +8 -2
  146. package/modules/characters/pathAsync.js +12 -6
  147. package/modules/characters/pathJob.js +2 -1
  148. package/modules/characters/proceduralRig.js +50 -11
  149. package/modules/characters/useModel.js +22 -0
  150. package/modules/characters/walkTo.js +58 -0
  151. package/modules/collision/Collision.js +102 -4
  152. package/modules/content/explain.js +13 -0
  153. package/modules/content/index.js +3 -1
  154. package/modules/content/loader.js +3 -0
  155. package/modules/content/rules.js +1 -0
  156. package/modules/debug/DebugPanel.js +11 -5
  157. package/modules/entities/Entities.js +6 -2
  158. package/modules/flow/index.js +5 -2
  159. package/modules/gameplay/Dialogue.js +5 -2
  160. package/modules/gameplay/Interactions.js +12 -2
  161. package/modules/gameplay/Inventory.js +21 -11
  162. package/modules/gameplay/Quests.js +13 -3
  163. package/modules/gameplay/pickups.js +6 -4
  164. package/modules/grid/Layer.js +1 -1
  165. package/modules/grid/index.js +1 -1
  166. package/modules/grid/tiles.js +9 -5
  167. package/modules/hlod/index.js +5 -2
  168. package/modules/hud/index.js +5 -2
  169. package/modules/level/index.js +5 -3
  170. package/modules/lights/index.js +5 -2
  171. package/modules/music/Music.js +6 -2
  172. package/modules/nav/index.js +5 -3
  173. package/modules/net/Client.js +4 -3
  174. package/modules/net/Host.js +2 -2
  175. package/modules/net/index.js +5 -3
  176. package/modules/particles/Particles.js +1 -1
  177. package/modules/photo/Photo.js +10 -7
  178. package/modules/rigid/RigidBodies.js +5 -2
  179. package/modules/settings/Settings.js +6 -3
  180. package/modules/settings/apply.js +2 -1
  181. package/modules/sky/Sky.js +21 -19
  182. package/modules/sky/cascades.js +6 -6
  183. package/modules/sky/domeLayers.js +1 -1
  184. package/modules/sky/environment.js +39 -13
  185. package/modules/sky/fog.js +9 -6
  186. package/modules/sky/frame.js +4 -3
  187. package/modules/sky/look.js +3 -2
  188. package/modules/sky/lookFog.js +80 -0
  189. package/modules/sky/lookShadow.js +50 -0
  190. package/modules/sky/lookSky.js +108 -0
  191. package/modules/sky/shader.js +2 -2
  192. package/modules/sky/shadow.js +4 -10
  193. package/modules/sky/skyModule.js +4 -3
  194. package/modules/terrain/ChunkManager.js +2 -33
  195. package/modules/terrain/chunkLevels.js +40 -0
  196. package/modules/terrain/index.js +10 -2
  197. package/modules/terrain/lookGround.js +61 -0
  198. package/modules/timeline/Timeline.js +7 -3
  199. package/modules/timeline/Tween.js +3 -7
  200. package/modules/timeline/shots.js +6 -4
  201. package/modules/triggers/index.js +9 -2
  202. package/modules/vegetation/Vegetation.js +17 -4
  203. package/modules/vegetation/index.js +7 -4
  204. package/modules/vegetation/lookWind.js +37 -0
  205. package/modules/vegetation/nearFade.js +39 -0
  206. package/modules/water/Water.js +19 -3
  207. package/modules/water/look.js +80 -0
  208. package/modules/weather/Weather.js +22 -31
  209. package/modules/weather/look.js +75 -0
  210. package/modules/weather/particles.js +1 -1
  211. package/modules/weather/strings.js +15 -0
  212. package/modules/world/explain.js +11 -0
  213. package/modules/world/index.js +11 -4
  214. package/modules/world/thingSource.js +44 -0
  215. package/package.json +2 -1
  216. package/render/PostFX.js +48 -51
  217. package/render/detail.js +39 -15
  218. package/render/effects.js +4 -2
  219. package/render/fuse.js +12 -0
  220. package/render/lights.js +4 -2
  221. package/render/lookSurface.js +161 -0
  222. package/render/materials.js +27 -10
  223. package/render/postLook.js +86 -0
  224. package/render/surface.js +3 -1
  225. package/types/core.d.ts +223 -29
  226. package/types/gameplay.d.ts +22 -6
  227. package/types/generated/core/DebugOverrides.d.ts +52 -0
  228. package/types/generated/core/Events.d.ts +43 -0
  229. package/types/generated/core/Ops.d.ts +62 -21
  230. package/types/generated/core/Saves.d.ts +1 -0
  231. package/types/generated/core/Views.d.ts +33 -0
  232. package/types/generated/modules/debug/DebugPanel.d.ts +2 -2
  233. package/types/generated/modules/grid/Layer.d.ts +1 -0
  234. package/types/generated/modules/sky/Sky.d.ts +10 -17
  235. package/types/generated/modules/weather/Weather.d.ts +5 -15
  236. package/types/generated/render/PostFX.d.ts +20 -23
  237. package/types/generated/render/materials.d.ts +10 -0
  238. package/types/physics.d.ts +8 -0
  239. package/types/style.d.ts +35 -20
  240. package/types/world.d.ts +7 -1
  241. package/ui/Parts.js +6 -2
  242. package/ui/UI.js +1 -1
  243. package/ui/defaults.js +1 -1
  244. package/docs/api/debug.md +0 -10
@@ -58,7 +58,7 @@ export async function openPanel(engine, base) {
58
58
  const env = pane.addFolder({ title: `环境照明 (${LIVE})` });
59
59
  const applyEnv = () => {
60
60
  const on = envState.on, opts = { source: 'sky', intensity: envState.intensity };
61
- engine.sky.setEnvironment(on ? opts : null);
61
+ (on ? (engine.look.env.replace('sky'), engine.look.env.set({ intensity: opts.intensity })) : engine.look.env.replace(false));
62
62
  put(['sky', 'environment'], on ? opts : null);
63
63
  };
64
64
  env.addBinding(envState, 'on', { label: '开 on' }).on('change', applyEnv);
@@ -77,11 +77,11 @@ export async function openPanel(engine, base) {
77
77
  for (const { name, enabled } of engine.post.list()) {
78
78
  const h = engine.post.get(name), f = post.addFolder({ title: name, expanded: false });
79
79
  const noteOf = () => notes.get(name) ?? notes.set(name, {}).get(name);
80
- f.addBinding({ enabled }, 'enabled', { label: '开 on' }).on('change', e => { engine.post.enable(name, e.value); noteOf().enabled = e.value; });
80
+ f.addBinding({ enabled }, 'enabled', { label: '开 on' }).on('change', e => { engine.look.post.set({ [name + '.enabled']: e.value }); noteOf().enabled = e.value; });
81
81
  for (const [k, v] of Object.entries(h.params)) {
82
82
  if (typeof v !== 'number' && typeof v !== 'boolean') continue; // lut textures, functions...: not editable here
83
83
  const range = typeof v === 'number' ? { step: Math.abs(v) >= 10 ? 1 : 0.01, min: Math.min(0, v * 2), max: Math.max(1, v * 3) } : {};
84
- f.addBinding({ [k]: v }, k, range).on('change', e => { h.set({ [k]: e.value }); noteOf()[k] = e.value; });
84
+ f.addBinding({ [k]: v }, k, range).on('change', e => { engine.look.post.set({ [name + '.' + k]: e.value }); noteOf()[k] = e.value; });
85
85
  }
86
86
  }
87
87
 
@@ -35,11 +35,11 @@ Content: actions 4 · audio 3 · containers 1 · dialogues 1 · items 4 · npcs
35
35
  - sky: `node_modules/threedog/docs/recipes/08-weather-sky.md` · `node_modules/threedog/docs/api/sky.md`
36
36
  - weather: `node_modules/threedog/docs/recipes/08-weather-sky.md` · `node_modules/threedog/docs/api/weather.md`
37
37
  - water: `node_modules/threedog/docs/recipes/44-water-weather-look-hooks.md` · `node_modules/threedog/docs/api/water.md`
38
- - collision: `node_modules/threedog/docs/recipes/10-blender-level.md` · `node_modules/threedog/docs/api/collision.md`
38
+ - collision: `node_modules/threedog/docs/recipes/12-navmesh.md` · `node_modules/threedog/docs/api/collision.md`
39
39
  - rigid: `node_modules/threedog/docs/recipes/11-vehicles.md` · `node_modules/threedog/docs/api/rigid.md`
40
40
  - characters: `node_modules/threedog/docs/recipes/12-navmesh.md` · `node_modules/threedog/docs/api/characters.md`
41
41
  - ambience: `node_modules/threedog/docs/recipes/31-audio.md` · `node_modules/threedog/docs/api/ambience.md`
42
- - …13 more modules: their pages are in `node_modules/threedog/docs/api/`
42
+ - …12 more modules: their pages are in `node_modules/threedog/docs/api/`
43
43
 
44
44
  Not used yet (check these before writing the system yourself):
45
45
 
@@ -161,7 +161,7 @@ Code that breaks saves or manages world models: none (rule R33).
161
161
  - Save prefix saveKey: default
162
162
  - Save slots: slot1
163
163
  - Autosave: every 3 minutes
164
- - Content-related saves handled by the engine: story flags and counters (engine.vars), inventory, quest progress, timers (clock, after registered by event name), pickups (world), felled trees (vegetation)
164
+ - Saved parts of the engine modules (vars, inventory, quests, timers, world...): `npx threedog catalog` (saves per module)
165
165
 
166
166
  ## Style pack keys
167
167
 
@@ -2,7 +2,7 @@
2
2
  export default {
3
3
  fisher: {
4
4
  name: '老渔夫',
5
- colors: { body: 0x4f6d8f, legs: 0x5b4a3a, hair: 0xd8d4cc },
5
+ model: 'humanoid', colors: { body: 0x4f6d8f, legs: 0x5b4a3a, hair: 0xd8d4cc },
6
6
  start: { place: 'home', x: 1, z: 5 },
7
7
  schedule: [
8
8
  { at: '06:00', place: 'river' }, // go to the riverside
@@ -48,7 +48,7 @@ engine.onFrame(() => {
48
48
  });
49
49
 
50
50
  // ---------- 3. Player + content (vegetation, items, pickups, NPCs, dialogues, quests, key actions, templates, props, physics props, custom conditions) ----------
51
- engine.characters.createPlayer({ ...presets.player.thirdPerson, spawn: { x: home.x + 4, z: home.z + 7 } });
51
+ engine.characters.createPlayer({ ...presets.player.thirdPerson, model: 'humanoid', spawn: { x: home.x + 4, z: home.z + 7 } }); // body: lowpoly's humanoid asset
52
52
  engine.content.load(data, { places: { home, river, water: waterSpot } }); // content names models only; the asset packs above resolve them
53
53
 
54
54
  // Show the film count at the top left (hud counter)
package/index.d.ts CHANGED
@@ -66,10 +66,10 @@ export * as THREE from 'three';
66
66
  export function createEngine(opts: EngineOptions): Engine;
67
67
  /**
68
68
  * A style part that adds post effects to the ones before it (a plain { post: [...] } would replace the whole list); an effect with the same name
69
- * replaces that one in place. Style parts with it: createEngine({ style: [lowpoly, postAdd(myGrain, bloom({ strength: 0.6 }))] })
69
+ * replaces that one in place. Style parts with it: createEngine({ style: [basePack, postAdd(myGrain, bloom({ strength: 0.6 }))] })
70
70
  */
71
71
  export function postAdd(...effects: PostEffect[]): Style;
72
- /** A style part that removes post effects by name from the ones before it: createEngine({ style: [lowpoly, postRemove('ao', 'outline')] }) */
72
+ /** A style part that removes post effects by name from the ones before it: createEngine({ style: [basePack, postRemove('ao', 'outline')] }) */
73
73
  export function postRemove(...names: string[]): Style;
74
74
 
75
75
  /** One openWorld part: false leaves the module out, true / omitted uses defaults, an object is that module's own options */
@@ -219,6 +219,12 @@ export { hud } from './types/generated/modules/hud/index';
219
219
  export function screenToGround(engine: Engine, ndcX: number, ndcY: number, opts?: { maxDistance?: number }): Vector3 | null;
220
220
  /** All easing functions: name -> function */
221
221
  export const EASINGS: Record<EaseName, (t: number) => number>;
222
+ /**
223
+ * A grid of numbers (height, moisture, density, walkable...) as a function (x, z) -> value. data[j * width + i] sits at origin + (i, j) * cell.
224
+ * interp 'nearest' = flat steps, 'linear' (default) = bilinear, 'cubic' = smooth (clamp: true avoids overshoot). Outside: edge value, or `outside`.
225
+ */
226
+ export function sampleGrid(data: ArrayLike<number>, opts: { width: number; height: number; cellSize?: number | [number, number]; size?: [number, number];
227
+ origin?: [number, number]; interp?: 'nearest' | 'linear' | 'cubic'; clamp?: boolean; outside?: number }): (x: number, z: number) => number;
222
228
  /** Name or function -> easing function */
223
229
  export function ease(e: Ease): (t: number) => number;
224
230
  /**
@@ -227,6 +233,33 @@ export function ease(e: Ease): (t: number) => number;
227
233
  * @example checkOptions('stamina()', opts, ['max', 'drain', 'regen']);
228
234
  */
229
235
  export function checkOptions(where: string, opts: object | null | undefined, known: string[], flags?: { loose?: boolean }): void;
236
+ /** One field of a params / op args schema: 'int?' or the full form (default implies optional) */
237
+ export type ParamSpec = string | { type: string, default?: any, min?: number, max?: number, values?: any[], desc?: string, optional?: boolean };
238
+ /**
239
+ * Module options read through a params schema: unknown keys and wrong types throw in dev with the fix, defaults are filled in.
240
+ * Also put params / options on the module definition so engine.catalog(name) shows them (recipes/51-capability-catalog.md).
241
+ * @example const o = readParams('magnet', { radius: { type: 'number', default: 2, min: 0 } }, opts);
242
+ */
243
+ export function readParams<T extends object = any>(where: string, schema: Record<string, ParamSpec>, opts?: object): T;
244
+ /** One look part: engine.look.<id>. set changes parameters for an owner, patch swaps a named GLSL hook, replace takes the whole part over (recipes/52-look.md) */
245
+ export interface LookPart {
246
+ readonly id: string;
247
+ readonly object: any;
248
+ set(params: Record<string, any>, o?: { owner?: string }): { remove(): void };
249
+ patch(name: string, glsl: any, o?: { owner?: string }): { remove(): void };
250
+ replace(impl: any, o?: { owner?: string }): { remove(): void };
251
+ clear(owner: string): void;
252
+ value(key: string): any;
253
+ top(key: string): any;
254
+ }
255
+ /**
256
+ * Register a module's own look part: engine.look.<id> with set / patch / replace, engine.catalog('look.<id>') and describe().look (recipes/52-look.md).
257
+ * Every param needs a default; a default that changes the picture also needs why and off (or neutral: true).
258
+ */
259
+ export function defineLookPart(engine: any, spec: { id: string, group?: string, module?: string, object?: () => any, params?: Record<string, any>,
260
+ style?: () => object, read?: () => object, apply?: (values: any, changed: Set<string>) => void, applyAtStart?: boolean,
261
+ hooks?: Record<string, { signature?: string, scope?: string[], example?: string }>, applyHook?: (name: string, glsl: any) => void, noPatch?: string,
262
+ replace?: { accepts: string, loses?: string[] }, applyReplace?: (impl: any) => void, noReplace?: string, docs?: string[] }): LookPart;
230
263
  // The Character, NPC and Engine classes are exported by the export * above (tweens use engine.timeline.tween, pathfinding uses engine.characters.findPath)
231
264
 
232
265
  /** Pure terrain computation (no engine needed), for previewing heights before start: createTerrain({ seed, ...terrainPreset() }).surface(x, z) */
package/index.js CHANGED
@@ -5,10 +5,10 @@
5
5
  //
6
6
  // import { createEngine, terrain, vegetation, sky, weather, water, collision, rigid,
7
7
  // followCamera, characters, interactions, dialogue, inventory, quests, photo, ambience, debug } from 'threedog';
8
- // import lowpoly from '@threedog/style-lowpoly'; // optional: the engine itself ships no art
8
+ // import basePack from 'your-style-pack'; // optional: the engine itself ships no art (your own pack or a published one)
9
9
  // import { terrainPreset } from '@threedog/terrain-noise'; // optional: nor a terrain generator
10
10
  //
11
- // const engine = createEngine({ canvas, style: lowpoly }); // without a style pack: neutral gray placeholders
11
+ // const engine = createEngine({ canvas, style: basePack }); // without a style pack: neutral gray placeholders
12
12
  // engine.use(terrain({ seed: 7, ...terrainPreset() }), vegetation(), sky(), weather(), water(), collision(), followCamera(), characters());
13
13
  // engine.start();
14
14
  //
@@ -58,7 +58,10 @@ export { terrain, vegetation, sky, weather, water, collision, rigid, followCamer
58
58
  export { net, fakeNetwork, webSocket } from './modules/net/index.js';
59
59
  export { screenToGround } from './core/screenToGround.js';
60
60
  export { EASINGS, ease } from './core/easing.js';
61
- export { checkOptions }; // for game-made modules (recipes/14): the package exposes no core/* deep paths
61
+ export { sampleGrid } from './core/grid.js'; // a grid of numbers (height, moisture, density, walkable) as a function (x, z) -> value; assets.gridFromImage reads one from an image. 'threedog/grid' is the same file without three.js (workers, tests)
62
+ export { checkOptions };
63
+ export { defineLookPart } from './core/look/part.js'; // a module's own look part: engine.look.<id> with set / patch / replace, catalog and describe (recipes/52)
64
+ export { readParams } from './core/params.js'; // params schema for game-made modules: validated, defaults filled, shown by engine.catalog() // for game-made modules (recipes/14): the package exposes no core/* deep paths
62
65
  export { createTerrain } from './modules/terrain/index.js';
63
66
  export { Character, NPC } from './modules/characters/index.js';
64
67
  export { presets } from './presets.js'; // opt-in gameplay presets (weather tables, calendars, player feel, camera): never applied by the engine itself
package/llms.txt CHANGED
@@ -28,7 +28,7 @@ Reading order: docs/AI.md (the index: one line per task) -> the recipe for the t
28
28
  - [15-perf](docs/recipes/15-perf.md): Performance investigation (F3, budget, profile, describe().perf)
29
29
  - [16-dev-bridge](docs/recipes/16-dev-bridge.md): Dev bridge: operate the running game from the terminal (npx threedog describe / step / press / op...)
30
30
  - [18-world](docs/recipes/18-world.md): World data: things that must be saved, grow, and keep changing while far away
31
- - [19-shooting-picking](docs/recipes/19-shooting-picking.md): Shooting and picking (first person; cast a ray from the screen center / mouse position)
31
+ - [19-shooting-picking](docs/recipes/19-shooting-picking.md): Shooting and picking (cast a ray from the screen center or the mouse position, with any camera)
32
32
  - [20-content-actions-save](docs/recipes/20-content-actions-save.md): Content vocabulary, key actions in actions.js, saving and loading at startup
33
33
  - [21-camera](docs/recipes/21-camera.md): Camera: first / third person, top-down strategy, fixed shots, switched at runtime
34
34
  - [22-shop-gold](docs/recipes/22-shop-gold.md): Shop and gold: buy, sell / consign, gold HUD, saving
@@ -36,7 +36,7 @@ Reading order: docs/AI.md (the index: one line per task) -> the recipe for the t
36
36
  - [26-ui-parts](docs/recipes/26-ui-parts.md): UI parts: replace or turn off any piece of the engine's screen UI
37
37
  - [27-net](docs/recipes/27-net.md): Co-op multiplayer: net() (host authority + state sync)
38
38
  - [28-terrain](docs/recipes/28-terrain.md): Terrain: your own generator, digging, raising and painting the ground
39
- - [29-grid](docs/recipes/29-grid.md): Grid placement: farming, furniture, crates, building
39
+ - [29-grid](docs/recipes/29-grid.md): Grid placement: towers, furniture, buildings, crops
40
40
  - [30-templates](docs/recipes/30-templates.md): Templates: reusable objects, definition vs instance state
41
41
  - [31-audio](docs/recipes/31-audio.md): Sound: buses, sounds by name, ambience rules, music, footsteps, ducking
42
42
  - [32-action-game](docs/recipes/32-action-game.md): Action game wiring: hp, attacks, enemy AI, drops and death without engine combat rules
@@ -44,13 +44,19 @@ Reading order: docs/AI.md (the index: one line per task) -> the recipe for the t
44
44
  - [34-environment-lighting](docs/recipes/34-environment-lighting.md): Environment lighting
45
45
  - [35-style-from-reference](docs/recipes/35-style-from-reference.md): Making a new look from a reference picture
46
46
  - [36-sky-ground-plant-looks](docs/recipes/36-sky-ground-plant-looks.md): Sky, ground and plant looks: what a style can change
47
- - [37-terrain-look-hooks](docs/recipes/37-terrain-look-hooks.md): Terrain look open points: shading, color map, triangle cut, normals
48
- - [38-environment-look-hooks](docs/recipes/38-environment-look-hooks.md): Environment look open points: lights, fog, exposure, sky layers
47
+ - [37-terrain-look-hooks](docs/recipes/37-terrain-look-hooks.md): Crisp ground color borders, terrain normals, height from a grid
48
+ - [38-environment-look-hooks](docs/recipes/38-environment-look-hooks.md): Owning lights, fog and exposure yourself
49
49
  - [40-scene](docs/recipes/40-scene.md): Scene: what is in the world, where, and what a save keeps
50
50
  - [41-thing-registry](docs/recipes/41-thing-registry.md): Things: what is in the scene, who manages it, what a save keeps (engine.thing)
51
51
  - [42-terrain-shape](docs/recipes/42-terrain-shape.md): Terrain outline: islands, floating rocks, a world that ends
52
52
  - [43-shader-patches-surface-looks](docs/recipes/43-shader-patches-surface-looks.md): Writing shader patches and surface looks
53
- - [44-water-weather-look-hooks](docs/recipes/44-water-weather-look-hooks.md): Water and weather look open points: depth color, foam, reflections, rain and snow, lightning, own particles
53
+ - [44-water-weather-look-hooks](docs/recipes/44-water-weather-look-hooks.md): Water and rain/snow looks: depth color, foam, reflections, particles, lightning
54
54
  - [45-cascaded-shadows](docs/recipes/45-cascaded-shadows.md): Cascaded shadows
55
- - [46-blender-art-route](docs/recipes/46-blender-art-route.md): Hand-painted art route: from Blender to the game
56
- - [47-island-snow-backdrop](docs/recipes/47-island-snow-backdrop.md): Floating island look: round rim, snow that settles, flat backdrop
55
+ - [46-blender-art-route](docs/recipes/46-blender-art-route.md): Blender to game (GLB) route
56
+ - [47-island-snow-backdrop](docs/recipes/47-island-snow-backdrop.md): Snow cover, flat backdrop, rounded terrain rim
57
+ - [48-make-material](docs/recipes/48-make-material.md): 48. `engine.makeMaterial(role, spec)`: which keys work, who wins
58
+ - [49-game-module-contract](docs/recipes/49-game-module-contract.md): Writing a game system module (a smelter, a recharging turret, growing crops) that plugs into the engine's contracts
59
+ - [50-own-renderer](docs/recipes/50-own-renderer.md): Bring your own renderer: `createEngine({ renderer })`
60
+ - [51-capability-catalog](docs/recipes/51-capability-catalog.md): Capability catalog: ask what the game can do before reading docs
61
+ - [52-look](docs/recipes/52-look.md): 52 Change any look: `engine.look`
62
+ - [53-ground-up-close](docs/recipes/53-ground-up-close.md): The ground up close: options and diagnosis
@@ -18,6 +18,7 @@
18
18
 
19
19
  import * as THREE from 'three';
20
20
  import { checkOptions } from '../../core/validate.js';
21
+ import { readParams, keysSchema } from '../../core/params.js';
21
22
  /** @import { ModuleDef, AmbienceRule } from '../../types/core' */
22
23
  /** @import { AmbienceOptions } from '../../types/gameplay' */
23
24
  const RULE_KEYS = ['sound', 'when', 'volume', 'fade', 'every', 'bus'];
@@ -160,6 +161,8 @@ const SYNTHS = {
160
161
  },
161
162
  };
162
163
 
164
+ const AMBIENCE_PARAMS = keysSchema(['rules', 'interval']);
165
+
163
166
  /**
164
167
  * Ambience -> engine.ambience. Rules come from createEngine({ audio: { ambience: [...] } }) plus opts.rules
165
168
  * @param {AmbienceOptions} [opts]
@@ -167,10 +170,10 @@ const SYNTHS = {
167
170
  * @example engine.use(ambience({ rules: [{ sound: 'hum', when: { zone: 'lab' }, volume: 0.4 }] }));
168
171
  */
169
172
  export function ambience(opts = {}) {
173
+ readParams('ambience', AMBIENCE_PARAMS, opts);
170
174
  let a = null;
171
- return { name: 'ambience', label: 'Ambience', stage: 'late', presentation: true,
175
+ return { name: 'ambience', params: AMBIENCE_PARAMS, options: opts, label: 'Ambience', stage: 'late', presentation: true,
172
176
  install(e) {
173
- checkOptions('ambience()', opts, ['rules', 'interval']);
174
177
  for (const [name, fn] of Object.entries(SYNTHS)) e.audio.register(name, fn, { builtIn: true, bus: 'ambience' });
175
178
  a = new Ambience(e, opts);
176
179
  // measures for data rules (content packs hold no functions). Each reads the listener position itself: music rules call them too,
@@ -3,7 +3,7 @@
3
3
  // - Mobile: drag to turn
4
4
  // - Slight vertical bob while walking (headBob), can be turned off
5
5
  // - hideTarget: hide the followed character from the camera (no seeing inside your own body); the shadow stays
6
- // Cutscene takeover: when engine.cameraOverride is set the camera is left alone (see common.js).
6
+ // Cutscene takeover: while someone holds engine.takeCamera (engine.cameraOverride is not null) the camera is left alone (see common.js).
7
7
  //
8
8
  // engine.use(firstPersonCamera({ height: 1.6, sensitivity: 1, fov: 70, headBob: 0.04, pointerLock: true }));
9
9
  // engine.cameraRig.yaw = Math.PI; // set facing directly
@@ -11,7 +11,6 @@
11
11
  // engine.setCamera('follow'); // switch back to third person at runtime (mouse lock releases, body shows again); see recipes/21-camera.md
12
12
  import * as THREE from 'three';
13
13
  import { rigModule, defineRig, YAW_RIG, clickToLock, releaseLock } from './common.js';
14
- import { checkOptions } from '../../core/validate.js';
15
14
  import { vec3 } from '../../core/math.js';
16
15
 
17
16
  export class FirstPersonCamera {
@@ -127,7 +126,6 @@ Object.assign(FirstPersonCamera.prototype, YAW_RIG); // forward / right / focu
127
126
  */
128
127
  export function firstPersonCamera(opts = {}) { return rigModule('firstPerson', opts); }
129
128
  defineRig('firstPerson', (e, opts) => {
130
- checkOptions('firstPersonCamera()', opts, ['height', 'sensitivity', 'fov', 'headBob', 'bobFrequency', 'hideTarget', 'hideLayer', 'pointerLock', 'yaw', 'pitch',
131
- 'minPitch', 'maxPitch', 'yawLimits', 'smoothing', 'invertY', 'swallowLockClick']);
132
129
  return new FirstPersonCamera(e, opts);
133
- });
130
+ }, ['height', 'sensitivity', 'fov', 'headBob', 'bobFrequency', 'hideTarget', 'hideLayer', 'pointerLock', 'yaw', 'pitch',
131
+ 'minPitch', 'maxPitch', 'yawLimits', 'smoothing', 'invertY', 'swallowLockClick']);
@@ -4,7 +4,7 @@
4
4
  // and a tag 'camera:<shot name>' switches to that shot (triggerBlend decides how)
5
5
  // - A shot can look at a fixed point (lookAt) or turn with the player via track: true
6
6
  // - Movement direction follows the current view: pressing "up" walks into the screen. If a direction key is still held at a shot change, the old direction is kept until release
7
- // Cutscene takeover: when engine.cameraOverride is set the camera is left alone (see common.js).
7
+ // Cutscene takeover: while someone holds engine.takeCamera (engine.cameraOverride is not null) the camera is left alone (see common.js).
8
8
  //
9
9
  // engine.use(fixedCamera({
10
10
  // shots: {
@@ -16,19 +16,23 @@
16
16
  // engine.cameraRig.blend('garden', 1.5);
17
17
  import * as THREE from 'three';
18
18
  import { rigModule, defineRig, viewForward, rightOf } from './common.js';
19
+ import { setProjection } from './projection.js';
19
20
  import { vec3 } from '../../core/math.js';
20
21
  import { ease as easing } from '../../core/easing.js';
21
22
  import { checkOptions, warnMissing } from '../../core/validate.js';
22
23
 
23
24
  export class FixedCamera {
24
25
  /**
25
- * shots { name: { position, lookAt | track: true, fov, at, trackHeight } }; start initial shot;
26
+ * shots { name: { position, lookAt | track: true, fov, at, trackHeight, projection: 'orthographic', size } } (size: world units of view height; default perspective);
27
+ * single-shot shorthand: fixedCamera({ position, lookAt, projection, size }); start initial shot;
26
28
  * auto false | 'nearest' (every autoInterval seconds pick the nearest shot); hysteresis how many meters closer a new shot must be to win (avoids flip-flopping);
27
29
  * triggerBlend transition seconds for trigger-zone switches (0 = hard cut); trackHeight how high on the character a track shot looks; trackSmoothing head-tracking smoothness;
28
30
  * holdDirection keep the direction at a shot change until the key is released (classic fixed-camera controls)
29
31
  */
30
32
  constructor(engine, { shots = {}, start = null, auto = false, autoInterval = 0.25, hysteresis = 2, triggerBlend = 0,
31
- trackHeight = 1.2, trackSmoothing = 8, holdDirection = true, ease = 'inOutCubic' } = {}) {
33
+ trackHeight = 1.2, trackSmoothing = 8, holdDirection = true, ease = 'inOutCubic', ...rest } = {}) {
34
+ if (!Object.keys(shots).length && rest.position) shots = { main: rest }; // setCamera('fixed', { position, lookAt, projection, size })
35
+ else checkOptions('fixedCamera()', rest, []);
32
36
  Object.assign(this, { engine, auto, autoInterval, hysteresis, triggerBlend, trackHeight, trackSmoothing, holdDirection, ease });
33
37
  this.shots = {};
34
38
  for (const [n, s] of Object.entries(shots)) this.add(n, s);
@@ -49,10 +53,11 @@ export class FixedCamera {
49
53
 
50
54
  /** Add or replace a shot */
51
55
  add(name, s) {
52
- checkOptions(`fixedCamera shots.${name}`, s, ['position', 'lookAt', 'track', 'fov', 'at', 'trackHeight']);
56
+ checkOptions(`fixedCamera shots.${name}`, s, ['position', 'lookAt', 'track', 'fov', 'at', 'trackHeight', 'projection', 'size']);
57
+ if (s.projection === 'orthographic' && !(s.size > 0)) throw new Error(`fixedCamera shots.${name}: projection 'orthographic' needs size > 0 (world units of view height)`);
53
58
  this.shots[name] = {
54
59
  position: vec3(s.position), lookAt: s.lookAt ? vec3(s.lookAt) : null, track: !!s.track || !s.lookAt,
55
- fov: s.fov ?? null, at: s.at ? vec3(s.at) : null, trackHeight: s.trackHeight,
60
+ fov: s.fov ?? null, size: s.projection === 'orthographic' ? s.size : null, at: s.at ? vec3(s.at) : null, trackHeight: s.trackHeight,
56
61
  };
57
62
  return this;
58
63
  }
@@ -64,7 +69,7 @@ export class FixedCamera {
64
69
  this.current = name;
65
70
  this._blend?.res(); this._blend = null; // interrupt a running blend: its Promise still resolves (await blend() never hangs)
66
71
  this._lookTarget(s, this._look);
67
- this._place(s.position, this._look, s.fov ?? this._baseFov);
72
+ this._place(s.position, this._look, s.fov ?? this._baseFov, s.size);
68
73
  if (changed) { this._latchDirection(); this.engine.events.emit('camera:shot', { name }); }
69
74
  }
70
75
  /** Blend smoothly to a shot; returns a Promise that resolves when the blend ends */
@@ -74,7 +79,7 @@ export class FixedCamera {
74
79
  const cam = this.engine.camera;
75
80
  return new Promise(res => {
76
81
  this._blend?.res();
77
- this._blend = { from: cam.position.clone(), fromLook: this._look.clone(), fromFov: cam.fov, t: 0, dur: seconds, ease, res };
82
+ this._blend = { from: cam.position.clone(), fromLook: this._look.clone(), fromFov: cam.fov, fromSize: cam.orthoSize || null, t: 0, dur: seconds, ease, res };
78
83
  this.current = name;
79
84
  this._latchDirection();
80
85
  this.engine.events.emit('camera:shot', { name });
@@ -105,12 +110,13 @@ export class FixedCamera {
105
110
  const sh = this.shots[this.current];
106
111
  const pos = (this._bp ??= new THREE.Vector3()).copy(b.from).lerp(sh.position, k), look = (this._bl ??= new THREE.Vector3()).copy(b.fromLook).lerp(want, k);
107
112
  this._look.copy(look);
108
- this._place(pos, look, b.fromFov + (fov - b.fromFov) * k);
113
+ // size blends only between two orthographic shots; a perspective/orthographic mix switches to the target's mode at once
114
+ this._place(pos, look, b.fromFov + (fov - b.fromFov) * k, sh.size && b.fromSize ? b.fromSize + (sh.size - b.fromSize) * k : sh.size);
109
115
  if (b.t >= b.dur) { this._blend = null; b.res(); }
110
116
  } else {
111
117
  if (this.shots[this.current].track) this._look.lerp(want, 1 - Math.exp(-this.trackSmoothing * dt));
112
118
  else this._look.copy(want);
113
- this._place(this.shots[this.current].position, this._look, fov);
119
+ this._place(this.shots[this.current].position, this._look, fov, s.size);
114
120
  }
115
121
  // Direction: release the hold once no direction key is pressed
116
122
  const a = input.axis;
@@ -131,9 +137,10 @@ export class FixedCamera {
131
137
  if (this.target) { out.copy(this.target.position); out.y += s.trackHeight ?? this.trackHeight; return out; }
132
138
  return s.lookAt ? out.copy(s.lookAt) : out.set(s.position.x, s.position.y, s.position.z - 1);
133
139
  }
134
- _place(pos, look, fov) {
140
+ _place(pos, look, fov, size = null) {
135
141
  const cam = this.engine.camera;
136
142
  cam.position.copy(pos); cam.lookAt(look);
143
+ setProjection(cam, size ? 'orthographic' : 'perspective', size);
137
144
  if (Math.abs(cam.fov - fov) > 1e-3) { cam.fov = fov; cam.updateProjectionMatrix(); }
138
145
  }
139
146
  _latchDirection() {
@@ -150,6 +157,6 @@ export class FixedCamera {
150
157
  */
151
158
  export function fixedCamera(opts = {}) { return rigModule('fixed', opts); }
152
159
  defineRig('fixed', (e, opts) => {
153
- checkOptions('fixedCamera()', opts, ['shots', 'start', 'auto', 'autoInterval', 'hysteresis', 'triggerBlend', 'trackHeight', 'trackSmoothing', 'holdDirection', 'ease']);
154
160
  return new FixedCamera(e, opts);
155
- });
161
+ }, ['shots', 'start', 'auto', 'autoInterval', 'hysteresis', 'triggerBlend', 'trackHeight', 'trackSmoothing', 'holdDirection', 'ease',
162
+ 'position', 'lookAt', 'track', 'fov', 'projection', 'size', 'at']); // the last row: setCamera('fixed', { position, lookAt }) is a one-shot form
@@ -2,11 +2,11 @@
2
2
  // optional shoulder offset and lock-on framing.
3
3
  // yaw is which side of the focus the camera sits on: camera = focus + (sin yaw, cos yaw) * distance, so it looks along forward() = -(sin yaw, cos yaw).
4
4
  // To see a character facing angle f from behind, yaw = f + PI.
5
- // Cutscene takeover: when engine.cameraOverride is set the camera is left alone (see common.js).
5
+ // Cutscene takeover: while someone holds engine.takeCamera (engine.cameraOverride is not null) the camera is left alone (see common.js).
6
6
  // Other cameras: firstPersonCamera, fixedCamera, rtsCamera (top-down strategy); all are engine.cameraRig; switch at runtime with engine.setCamera('firstPerson').
7
7
  import * as THREE from 'three';
8
8
  import { rigModule, defineRig, YAW_RIG, clickToLock, releaseLock } from './common.js';
9
- import { checkOptions } from '../../core/validate.js';
9
+ import { setProjection } from './projection.js';
10
10
 
11
11
  export class FollowCamera {
12
12
  /** yaw/pitch initial angles (yaw: see the top of this file); distance (min/max zoom range); height how high on the character to look; smoothing follow smoothness;
@@ -14,7 +14,9 @@ export class FollowCamera {
14
14
  * shoulder meters to the right of the target the camera aims (over-the-shoulder; negative = left shoulder, 0 = centered);
15
15
  * pointerLock click locks the mouse (no dragging; the press that locks is swallowed, swallowLockClick: false delivers it) */
16
16
  constructor(engine, { yaw = 0.8, pitch = 0.42, distance = 13, minDistance = 4, maxDistance = 45, height = 1.4, smoothing = 10,
17
- sensitivity = 1, minPitch = 0.05, maxPitch = 1.35, zoomStep = 0.1, groundClearance = 1.2, invertY = false, shoulder = 0, pointerLock = false, swallowLockClick = true } = {}) {
17
+ sensitivity = 1, minPitch = 0.05, maxPitch = 1.35, zoomStep = 0.1, groundClearance = 1.2, invertY = false, shoulder = 0, pointerLock = false, swallowLockClick = true, projection = 'perspective', size = 20 } = {}) {
18
+ this.projection = projection; this.size = size; // 'orthographic': size = world units of view height (the wheel changes size there, clamped to the min/max distance ratio)
19
+ this.size0 = size; this.distance0 = distance;
18
20
  Object.assign(this, { engine, yaw, pitch, distance, minDistance, maxDistance, height, smoothing, sensitivity, minPitch, maxPitch, zoomStep, groundClearance });
19
21
  Object.assign(this, { invertY, shoulder, pointerLock, swallowLockClick });
20
22
  this.target = null;
@@ -35,7 +37,7 @@ export class FollowCamera {
35
37
  * @example engine.cameraRig.frame(enemy.object); player.faceMode = 'target'; player.faceTarget = enemy.object;
36
38
  */
37
39
  frame(target, { strength = 6 } = {}) { this.framing = target ? { target, strength } : null; }
38
- onEnter(switched) { clickToLock(this, switched); }
40
+ onEnter(switched) { clickToLock(this, switched); setProjection(this.engine.camera, this.projection, this.size); }
39
41
  onExit() { releaseLock(this); }
40
42
  onOverride(on) { if (on) releaseLock(this, true); }
41
43
 
@@ -49,7 +51,12 @@ export class FollowCamera {
49
51
  if (input.enabled) {
50
52
  if (!fr) this.yaw -= input.look.dx * 0.005 * this.sensitivity;
51
53
  if (!this.lockPitch) this.pitch = Math.min(this.maxPitch, Math.max(this.minPitch, this.pitch + input.look.dy * 0.004 * this.sensitivity * (this.invertY ? -1 : 1)));
52
- if (input.look.zoom) this.distance = Math.min(this.maxDistance, Math.max(this.minDistance, this.distance * (1 + input.look.zoom * this.zoomStep)));
54
+ if (input.look.zoom && this.projection === 'orthographic') {
55
+ // distance shows nothing in an orthographic view: zoom `size`, clamped to the same min/max ratio as distance, same wheel feel
56
+ const lo = this.size0 * this.minDistance / this.distance0, hi = this.size0 * this.maxDistance / this.distance0;
57
+ this.size = Math.min(hi, Math.max(lo, this.size * (1 + input.look.zoom * this.zoomStep)));
58
+ cam.orthoSize = this.size; cam.updateProjectionMatrix();
59
+ } else if (input.look.zoom) this.distance = Math.min(this.maxDistance, Math.max(this.minDistance, this.distance * (1 + input.look.zoom * this.zoomStep)));
53
60
  }
54
61
  if (!this.target) return;
55
62
  const want = this.target.position;
@@ -79,7 +86,6 @@ Object.assign(FollowCamera.prototype, YAW_RIG);
79
86
  */
80
87
  export function followCamera(opts = {}) { return rigModule('follow', opts); }
81
88
  defineRig('follow', (e, opts) => {
82
- checkOptions('followCamera()', opts, ['yaw', 'pitch', 'distance', 'minDistance', 'maxDistance', 'height', 'smoothing', 'sensitivity', 'minPitch', 'maxPitch',
83
- 'zoomStep', 'groundClearance', 'invertY', 'lockPitch', 'shoulder', 'pointerLock', 'swallowLockClick']);
84
89
  const c = new FollowCamera(e, opts); if (opts.lockPitch) c.lockPitch = true; return c;
85
- });
90
+ }, ['yaw', 'pitch', 'distance', 'minDistance', 'maxDistance', 'height', 'smoothing', 'sensitivity', 'minPitch', 'maxPitch',
91
+ 'zoomStep', 'groundClearance', 'invertY', 'lockPitch', 'shoulder', 'pointerLock', 'swallowLockClick', 'projection', 'size']);
@@ -5,14 +5,13 @@
5
5
  // - screenToGround(ndcX, ndcY) -> ground point under a screen point (for click-to-move and placing buildings)
6
6
  // - After follow(object) the focus tracks it (done automatically when the player is created) and WASD goes to the character; manual drag/edge pan drops the follow (unless followLock: true)
7
7
  // To not follow: call engine.cameraRig.follow(null) after creating the player, and WASD pans the camera
8
- // Cutscene takeover: when engine.cameraOverride is set the camera is left alone (see common.js).
8
+ // Cutscene takeover: while someone holds engine.takeCamera (engine.cameraOverride is not null) the camera is left alone (see common.js).
9
9
  //
10
10
  // engine.use(rtsCamera({ height: 30, angle: 0.95, panSpeed: 1, edgePan: true, bounds: { minX: -100, maxX: 100, minZ: -100, maxZ: 100 } }));
11
11
  // const p = engine.cameraRig.screenToGround(engine.input.pointer.ndcX, engine.input.pointer.ndcY);
12
12
  // engine.cameraRig.moveTo(position); // move the view somewhere; { instant: true } skips smoothing
13
13
  import * as THREE from 'three';
14
14
  import { rigModule, defineRig, screenToGround, CAMERA_STRINGS, YAW_RIG } from './common.js';
15
- import { checkOptions } from '../../core/validate.js';
16
15
  import { xzOf } from '../../core/math.js';
17
16
  import { surfaceOr } from '../../core/ground.js';
18
17
 
@@ -127,8 +126,7 @@ for (const k of ['forward', 'right']) RtsCamera.prototype[k] = YAW_RIG[k];
127
126
  */
128
127
  export function rtsCamera(opts = {}) { return rigModule('rts', opts); }
129
128
  defineRig('rts', (e, opts) => {
130
- checkOptions('rtsCamera()', opts, ['height', 'minHeight', 'maxHeight', 'angle', 'yaw', 'panSpeed', 'dragPan', 'edgePan', 'edgeSize', 'bounds', 'rotateKeys',
131
- 'rotateSpeed', 'zoomStep', 'smoothing', 'fov', 'followLock', 'start']);
132
129
  e.i18n.add(CAMERA_STRINGS);
133
130
  return new RtsCamera(e, opts);
134
- });
131
+ }, ['height', 'minHeight', 'maxHeight', 'angle', 'yaw', 'panSpeed', 'dragPan', 'edgePan', 'edgeSize', 'bounds', 'rotateKeys',
132
+ 'rotateSpeed', 'zoomStep', 'smoothing', 'fov', 'followLock', 'start']);
@@ -7,14 +7,16 @@
7
7
  // forward() / right() unit directions {x, z} on the XZ plane; player movement uses them
8
8
  // update(dt, input) per-frame camera update
9
9
  //
10
- // Cutscene takeover contract: engine.cameraOverride
11
- // A cutscene (timeline module) that places the camera itself sets engine.cameraOverride = { owner: 'who', focus?: Vector3 }.
12
- // While it is not null the camera module leaves the camera alone; with a focus, engine.focus is set to it (the world loads around it).
13
- // Set it back to null when done; the camera module resumes from its previous state.
10
+ // Cutscene takeover contract: engine.takeCamera(owner, { focus? }) -> { remove() } (core/holds.js); engine.cameraOverride is the holder in charge.
11
+ // A cutscene, a named view or a photo mode that places the camera itself takes it; several can hold it, the latest is in charge.
12
+ // While anyone holds it the camera module leaves the camera alone; with a focus, engine.focus is set to it (the world loads around it).
13
+ // When the last holder removes its claim the camera module resumes from its previous state. cameraOverride itself is read-only.
14
14
  import * as THREE from 'three';
15
15
  import { ownedProps } from '../../core/validate.js';
16
+ import { readParams, keysSchema } from '../../core/params.js';
17
+ import { setProjection } from './projection.js';
16
18
 
17
- const STRINGS = { ownedHint: 'To place the camera yourself, set engine.cameraOverride = { owner: \'me\' } and set it back to null when done' };
19
+ const STRINGS = { ownedHint: 'To place the camera yourself, take it: const cam = engine.takeCamera(\'me\'); ... cam.remove() when done' };
18
20
 
19
21
  /** True during a cutscene takeover, and updates engine.focus from the focus the owner supplied */
20
22
  function applyOverride(e) {
@@ -51,16 +53,38 @@ export function clickToLock(rig, switched) {
51
53
  const e = rig.engine, canvas = e.renderer.domElement;
52
54
  const wouldLock = () => rig.pointerLock && !e.cameraOverride && e.input.enabled
53
55
  && !matchMedia('(pointer: coarse)').matches && document.pointerLockElement !== canvas;
56
+ // Last outcome, shown by describe(): the drag fallback stays, but a refused lock is no longer silent
57
+ const st = rig.lockState = { configured: !!rig.pointerLock, requested: false, locked: document.pointerLockElement === canvas, lastError: null,
58
+ supported: typeof canvas.requestPointerLock === 'function' };
59
+ const fail = err => { st.locked = false; st.lastError = String(err?.message ?? err ?? 'refused'); st.failedAt = e.elapsed; };
54
60
  const lock = () => {
61
+ st.configured = !!rig.pointerLock;
55
62
  if (!wouldLock()) return;
56
- try { const r = canvas.requestPointerLock?.(); r?.catch?.(() => {}); } catch { /* browser refused the lock; fall back to dragging */ }
63
+ st.requested = true;
64
+ try { const r = canvas.requestPointerLock?.(); r?.catch?.(fail); } catch (err) { fail(err); } // browser refused the lock: fall back to dragging
57
65
  };
58
66
  rig._off = new AbortController();
67
+ const sig = { signal: AbortSignal.any([e.signal, rig._off.signal]) };
68
+ document.addEventListener('pointerlockchange', () => { st.locked = document.pointerLockElement === canvas; if (st.locked) st.lastError = null; else st.requested = false; }, sig);
69
+ document.addEventListener('pointerlockerror', () => fail('pointerlockerror (browser refused: needs a user gesture, or the page lost focus)'), sig);
59
70
  const swallow = () => rig.swallowLockClick !== false && wouldLock();
60
71
  e.input.swallowLockClick = swallow; rig._swallow = swallow;
61
- canvas.addEventListener('click', lock, { signal: AbortSignal.any([e.signal, rig._off.signal]) }); // removed on switch-away or engine.dispose()
72
+ canvas.addEventListener('click', lock, sig); // removed on switch-away or engine.dispose()
62
73
  if (switched) lock(); // a runtime switch (a key press counts as a gesture) locks at once
63
74
  }
75
+ /**
76
+ * The pointer-lock state machine for describe(): off (not configured) / unsupported / locked / refused (browser denied) / requesting / waiting-click;
77
+ * plus covered (an element other than the canvas sits at its centre, so a click never reaches it), cameraOverride (a takeover blocks locking) and the last failure
78
+ * @internal
79
+ */
80
+ export function lockView(e, st) {
81
+ if (!st?.configured) return { state: 'off' };
82
+ const state = !st.configured ? 'off' : !st.supported ? 'unsupported' : st.locked ? 'locked' : st.lastError ? 'refused' : st.requested ? 'requesting' : 'waiting-click';
83
+ const c = e.renderer.domElement, r = c.getBoundingClientRect();
84
+ const top = typeof document.elementFromPoint === 'function' ? document.elementFromPoint(r.left + r.width / 2, r.top + r.height / 2) : null;
85
+ return { ...st, state, covered: top && top !== c ? (top.id ? '#' + top.id : top.className ? '.' + String(top.className).split(' ')[0] : top.tagName.toLowerCase()) : null,
86
+ cameraOverride: e.cameraOverride?.owner ?? null, lastFailure: st?.lastError ? { reason: st.lastError, agoSec: Math.round((e.elapsed - st.failedAt) / 100) / 10 } : null };
87
+ }
64
88
  /** Release the mouse lock; stop listening for clicks too when switched away (call from onExit; from onOverride with keepListening) */
65
89
  export function releaseLock(rig, keepListening = false) {
66
90
  if (!keepListening) { rig._off?.abort(); if (rig.engine.input.swallowLockClick === rig._swallow) rig.engine.input.swallowLockClick = null; }
@@ -80,7 +104,9 @@ export { screenToGround } from '../../core/screenToGround.js'; // shared with
80
104
 
81
105
  /** Camera kind table: kind name -> build(engine, opts). Each camera file registers once with defineRig; setCamera switches by name */
82
106
  const RIGS = new Map();
83
- export function defineRig(kind, build) { RIGS.set(kind, build); }
107
+ const RIG_PARAMS = new Map(); // kind -> params schema (the option keys of that camera)
108
+ /** keys: the options that camera takes; they become its params schema (engine.catalog) and a misspelled one throws in dev */
109
+ export function defineRig(kind, build, keys = []) { RIGS.set(kind, build); RIG_PARAMS.set(kind, keysSchema(keys)); }
84
110
 
85
111
  /**
86
112
  * Wrap a camera as a module: handles cutscene takeover, updates engine.focus, and provides runtime switching engine.setCamera(kind, options?).
@@ -93,6 +119,7 @@ export function rigModule(kind, opts) {
93
119
  const make = (k, o) => {
94
120
  const build = RIGS.get(k);
95
121
  if (!build) throw new Error(`setCamera() has no camera kind '${k}'; available: ${[...RIGS.keys()].join(', ')}`);
122
+ readParams(`${k}Camera`, RIG_PARAMS.get(k), o); // also covers setCamera(kind, options)
96
123
  const r = build(engine, o ?? {});
97
124
  r.kind = k; cache.set(k, r);
98
125
  return r;
@@ -101,6 +128,7 @@ export function rigModule(kind, opts) {
101
128
  if (k === c.kind && !o) return c;
102
129
  const old = c, target = old.target;
103
130
  old.onExit?.();
131
+ setProjection(engine.camera); // back to perspective; an orthographic rig sets its own in onEnter / constructor
104
132
  engine.camera.fov = fov0; engine.camera.updateProjectionMatrix(); // fov returns to the value at install; each camera applies its own in onEnter / constructor
105
133
  const next = o || !cache.has(k) ? make(k, o) : cache.get(k);
106
134
  c = engine.cameraRig = next;
@@ -112,7 +140,7 @@ export function rigModule(kind, opts) {
112
140
  return c;
113
141
  }
114
142
  return {
115
- name: 'cameraRig', label: 'Camera', optional: ['collision'], stage: 'control',
143
+ name: 'cameraRig', label: 'Camera', params: RIG_PARAMS.get(kind), options: opts, optional: ['collision'], stage: 'control',
116
144
  install(e) {
117
145
  engine = e; fov0 = e.camera.fov;
118
146
  e.setCamera = setCamera;
@@ -122,6 +150,7 @@ export function rigModule(kind, opts) {
122
150
  e.events.on('session:start', () => {
123
151
  const old = c;
124
152
  old.onExit?.(); cache.clear();
153
+ setProjection(e.camera);
125
154
  e.camera.fov = fov0; e.camera.updateProjectionMatrix();
126
155
  c = e.cameraRig = make(kind, opts);
127
156
  c.onEnter?.(false); c.follow(e.player?.cameraFollow ? e.player.root : null); fresh = true; // follows the player only if the game asked (createPlayer({ cameraFollow }))
@@ -141,7 +170,8 @@ export function rigModule(kind, opts) {
141
170
  e.focus.copy(c.focusPoint()); // decides only where the view (terrain, models) loads; the gameplay simulation center is world.anchor (default the player), so moving the camera away changes nothing
142
171
  owned.mark(); fresh = false;
143
172
  },
144
- describe(e, ctx) { ctx.out.camera.type = c.kind; if (c.current !== undefined) ctx.out.camera.shot = c.current; },
173
+ describe(e, ctx) { ctx.out.camera.type = c.kind; if (c.current !== undefined) ctx.out.camera.shot = c.current;
174
+ ctx.out.camera.pointerLock = lockView(e, c.lockState); },
145
175
  };
146
176
  }
147
177
 
@@ -3,7 +3,7 @@
3
3
  // firstPersonCamera() first person
4
4
  // fixedCamera() fixed shots (camera cuts)
5
5
  // rtsCamera() strategy top-down (pan, zoom, rotate, screen point -> ground)
6
- // Cutscene takeover contract engine.cameraOverride: see common.js.
6
+ // Cutscene takeover contract engine.takeCamera / cameraOverride: see common.js.
7
7
  export { followCamera, FollowCamera } from './FollowCamera.js';
8
8
  export { firstPersonCamera, FirstPersonCamera } from './FirstPersonCamera.js';
9
9
  export { fixedCamera, FixedCamera } from './FixedCamera.js';