threedog 0.2.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 (80) hide show
  1. package/README.md +4 -4
  2. package/core/Assets.js +12 -0
  3. package/core/Engine.js +13 -4
  4. package/core/describeRender.js +7 -1
  5. package/core/grid.js +127 -0
  6. package/core/gridLoad.js +19 -0
  7. package/core/loop.js +7 -2
  8. package/core/renamed.js +1 -0
  9. package/core/styleParts.js +9 -7
  10. package/docs/AI.md +28 -23
  11. package/docs/API.md +3 -3
  12. package/docs/CODEMAP.md +5 -3
  13. package/docs/COMMANDS.md +5 -3
  14. package/docs/CONVENTIONS.md +6 -6
  15. package/docs/api/assets.md +1 -0
  16. package/docs/api/characters.md +3 -2
  17. package/docs/api/engine.md +3 -3
  18. package/docs/api/style.md +7 -7
  19. package/docs/api/tools.md +3 -2
  20. package/docs/api/vegetation.md +1 -0
  21. package/docs/recipes/01-new-game.md +41 -43
  22. package/docs/recipes/02-npc.md +24 -24
  23. package/docs/recipes/03-items-pickups.md +4 -4
  24. package/docs/recipes/04-quests.md +23 -23
  25. package/docs/recipes/05-props-bake.md +5 -5
  26. package/docs/recipes/07-flow-scenes-pause.md +2 -2
  27. package/docs/recipes/08-weather-sky.md +5 -5
  28. package/docs/recipes/09-style-pack.md +35 -100
  29. package/docs/recipes/13-animation.md +22 -6
  30. package/docs/recipes/14-custom-module.md +6 -7
  31. package/docs/recipes/15-perf.md +8 -0
  32. package/docs/recipes/16-dev-bridge.md +7 -7
  33. package/docs/recipes/18-world.md +5 -2
  34. package/docs/recipes/19-shooting-picking.md +9 -8
  35. package/docs/recipes/20-content-actions-save.md +10 -10
  36. package/docs/recipes/22-shop-gold.md +16 -16
  37. package/docs/recipes/23-ops.md +2 -2
  38. package/docs/recipes/27-net.md +2 -2
  39. package/docs/recipes/28-terrain.md +2 -2
  40. package/docs/recipes/29-grid.md +47 -27
  41. package/docs/recipes/34-environment-lighting.md +2 -2
  42. package/docs/recipes/35-style-from-reference.md +41 -46
  43. package/docs/recipes/36-sky-ground-plant-looks.md +22 -20
  44. package/docs/recipes/37-terrain-look-hooks.md +34 -13
  45. package/docs/recipes/38-environment-look-hooks.md +47 -42
  46. package/docs/recipes/42-terrain-shape.md +1 -1
  47. package/docs/recipes/43-shader-patches-surface-looks.md +35 -20
  48. package/docs/recipes/44-water-weather-look-hooks.md +5 -5
  49. package/docs/recipes/45-cascaded-shadows.md +1 -1
  50. package/docs/recipes/46-blender-art-route.md +4 -4
  51. package/docs/recipes/47-island-snow-backdrop.md +4 -3
  52. package/docs/recipes/48-make-material.md +2 -2
  53. package/docs/recipes/49-game-module-contract.md +25 -25
  54. package/docs/recipes/51-capability-catalog.md +2 -2
  55. package/docs/recipes/52-look.md +43 -5
  56. package/docs/recipes/53-ground-up-close.md +58 -0
  57. package/examples/action/GAMEMAP.md +2 -2
  58. package/examples/action/main.js +3 -2
  59. package/examples/sheepisland/GAMEMAP.md +1 -1
  60. package/examples/styletest/content/npcs.js +1 -1
  61. package/examples/styletest/main.js +1 -1
  62. package/examples/world/content/npcs.js +1 -1
  63. package/examples/world/main.js +1 -1
  64. package/index.d.ts +8 -2
  65. package/index.js +3 -2
  66. package/llms.txt +9 -8
  67. package/modules/characters/Character.js +21 -19
  68. package/modules/characters/assetModel.js +35 -7
  69. package/modules/characters/proceduralRig.js +45 -10
  70. package/modules/content/index.js +1 -1
  71. package/modules/gameplay/pickups.js +1 -1
  72. package/modules/vegetation/Vegetation.js +15 -3
  73. package/modules/vegetation/index.js +1 -1
  74. package/modules/vegetation/nearFade.js +39 -0
  75. package/package.json +2 -1
  76. package/render/detail.js +39 -15
  77. package/types/core.d.ts +7 -5
  78. package/types/gameplay.d.ts +12 -6
  79. package/types/style.d.ts +20 -15
  80. package/types/world.d.ts +7 -1
@@ -10,7 +10,7 @@ Large repeated areas (forests, grass) don't use this; use `content/vegetation.js
10
10
  `games/<game>/content/props.js` (a list; remember to add it to `content/index.js`):
11
11
  ```js
12
12
  export default [
13
- { model: 'pine', place: 'home', x: -8, z: -6, scale: 1.2, collide: 'circle' }, // an asset name (here a generator of the lowpoly asset pack)
13
+ { model: 'pine', place: 'home', x: -8, z: -6, scale: 1.2, collide: 'circle' }, // an asset name (here a generator from an asset pack)
14
14
  { model: ['flower', 0xf2d16b], place: 'home', x: 1.6, z: 3.4 }, // a generator with arguments, use an array: flower(0xf2d16b)
15
15
  { model: 'rock', x: 120, z: -40, rot: 0.6, scale: 0.8, collide: 'box' }, // no place = world coordinates; rot in radians
16
16
  { model: 'well', place: 'home', x: 4, z: -4, y: 0, collide: 'box' }, // a file asset: assets.model('well')
@@ -25,8 +25,8 @@ interaction, container and saved state (recipe 30).
25
25
  A model is always an **asset name**, never a path or a function (`npm run check` reports both): register it in a manifest or asset pack first. A
26
26
  generator entry is built through `engine.assets.cached` (params from the array), a file entry through `engine.assets.model`:
27
27
  ```js
28
- import { assets as lowpolyAssets } from '@threedog/style-lowpoly';
29
- engine.assets.manifest(lowpolyAssets); // pine, rock, ['flower', color]...
28
+ import { assets } from './assets.js'; // your asset pack (or a published one)
29
+ engine.assets.manifest(assets); // pine, rock, ['flower', color]...
30
30
  engine.assets.manifest({ name: 'props', models: { well: '/models/well.glb' } });
31
31
  ```
32
32
  Props with the same model share one prototype (geometry and material are built once); each spot gets a clone.
@@ -134,11 +134,11 @@ import forest from 'forest-assets';
134
134
  engine.assets.manifest(forest); // content and code now say 'oak', 'creek'
135
135
  engine.assets.manifest({ name: 'mine', models: { oak: '/models/my-oak.glb' } }); // a later pack replaces a name it shares
136
136
  ```
137
- A generator function is also an entry (`models: { pine: () => geometry }`): the lowpoly package exports its procedural models this way as `assets`.
137
+ A generator function is also an entry (`models: { pine: () => geometry }`): an asset pack exports its procedural models this way.
138
138
 
139
139
  Fonts are entries too, and a style names them instead of holding the file (a style is looks only):
140
140
  ```js
141
- const engine = createEngine({ canvas, style: [lowpoly, { ui: { fonts: ['pixel', 'pixelBold'], font: '"pixel", system-ui' } }] });
141
+ const engine = createEngine({ canvas, style: [basePack, { ui: { fonts: ['pixel', 'pixelBold'], font: '"pixel", system-ui' } }] });
142
142
  engine.assets.manifest({ name: 'ui-fonts', base: '/fonts/', fonts: { pixel: 'pixel.woff2', pixelBold: { url: 'pixel-bold.woff2', family: 'pixel', weight: 700 } } });
143
143
  ```
144
144
  `family` defaults to the asset name; the other keys are FontFace descriptors (`weight`, `style`, `unicodeRange`, ...). `start()` loads the fonts
@@ -16,10 +16,10 @@ engine.flow.define('title', {
16
16
  enter: (e, from) => { titleEl.hidden = false; },
17
17
  exit: (e, to) => { titleEl.hidden = true; },
18
18
  });
19
- engine.flow.define('ending', { freeze: true, lockInput: true, enter: () => toast(engine, '完') });
19
+ engine.flow.define('ending', { freeze: true, lockInput: true, enter: () => toast(engine, 'The end') });
20
20
  startBtn.onclick = () => engine.flow.go('playing');
21
21
 
22
- engine.input.define('pause', ['KeyO'], '暂停'); // read by action name; Esc is the back key (see below); presets.keys / presets.interactions bind P, I, J, E (see the key table in GAMEMAP)
22
+ engine.input.define('pause', ['KeyO'], 'Pause'); // read by action name; Esc is the back key (see below); presets.keys / presets.interactions bind P, I, J, E (see the key table in GAMEMAP)
23
23
  engine.onFrame(() => {
24
24
  if (engine.input.pressedRaw('pause')) engine.flow.go(engine.flow.state === 'paused' ? 'playing' : 'paused'); // paused pushes an opaque input context, so use pressedRaw
25
25
  });
@@ -28,16 +28,16 @@ Fields: `cloud` cloud cover 0-1, `sun` sunlight multiplier, `fog` fog distance m
28
28
  With openWorld the weather module is already installed; pass its options through the preset: `openWorld({ camera: 'follow', weather: { types, autoPool } })`.
29
29
 
30
30
  ## 3. Changing sky colors, sun, stars (style pack)
31
- `sky.keyframes` in the style pack (lowpoly: its `index.js`):
31
+ `sky.keyframes` in the style pack (your pack's `index.js`):
32
32
  `[time 0-1, zenith color, horizon color (= fog color), sunlight color, sunlight intensity, ambient intensity]`, interpolated by time;
33
- also `sunSize sunGlow moonSize starDensity clouds skybox shadow` (see the comments in lowpoly for what they mean; `hoursPerDay` is timing, so it is a
33
+ also `sunSize sunGlow moonSize starDensity clouds skybox shadow` (see the comments in the style types, `types/style.d.ts`, for what they mean; `hoursPerDay` is timing, so it is a
34
34
  `sky()` option, not a style key). The look of rain and snow is in `style.weather.rain / snow` (shape, density, shaders, the game's own particles: recipe 44).
35
35
 
36
36
  ## 4. Time and brightness (game code)
37
37
  ```js
38
38
  engine.sky.timeOfDay = parseClock('19:30'); // jump to a time (0-1)
39
39
  engine.clock.timeScale = 0; // sky and game seconds stop together (2 = double speed); game seconds per day: sky({ dayLength: 600 }); the three kinds of time are in recipe 06
40
- engine.setFogFar(300); // base fog distance (meters); weather scales it
40
+ engine.look.fog.set({ far: 300 }); // base fog distance (meters); weather scales it. engine.setFogFar(300) sets the same base value directly
41
41
  ```
42
42
  Fixed dusk: `openWorld({ time: 18.5 / 24, ... })` (a 0-1 fraction of the day) and do not pass `sky: presets.calendar.cycle` (the template does; the cycle
43
43
  is what moves the clock). `engine.sky.isDay` is `sunHeight > 0` with `sunHeight = sin((timeOfDay - 0.25) * 2π)`: true strictly between timeOfDay 0.25 and 0.75 (06:00 to 18:00 on the default 24-hour face; with `hoursPerDay: H` the same fractions, 0.25H to 0.75H), false at exactly 06:00 and 18:00, so 18:30 already reads as "night" in `describe().time.isDay`. `daylight` = `max(0, sunHeight)`. Keyframes only change colors, not this flip.
@@ -50,7 +50,7 @@ sky({ seasons: ['spring', 'summer', 'autumn', 'winter'], daysPerSeason: 28, dayL
50
50
  sky({ seasons: [{ name: 'wet', days: 10 }, { name: 'dry', days: 20 }], dayLength: 360 }); // seasons of their own length
51
51
  ```
52
52
  **Don't modify directly** `sky.sun.intensity / color`, `sky.hemi`, `scene.fog`: the sky recomputes them every frame and overwrites your change (the
53
- console warns about it during development).
53
+ console warns about it during development). Use `engine.look.lights` / `look.fog` (recipe 52), or take them over yourself (recipe 38).
54
54
  To darken or tint everything (a cave, a horror segment), write a modifier layer of your own; it stacks with the weather's 'weather' layer without
55
55
  overwriting it (multiplier layers vs `look.lights` overrides: [recipe 52](52-look.md#skymodify-vs-looklights)):
56
56
  ```js
@@ -66,7 +66,7 @@ combined result and is read-only (changing it directly triggers a warning during
66
66
  ## 5. Verify
67
67
  - Text: `npm run shot -- / --time 19:30 --weather dust --wait 2 --describe-only`, then look for "Time: 19:30..." and "Weather: dust (rain 0, snow 0, fog 0.35)".
68
68
  `describe().weather` has `name progress rain snow fog wind cloud`; `describe().time` has `clock day season isDay dayLength timeScale`.
69
- - Take a screenshot only after the look changed: `npm run shot -- / --time 19:30 --weather dust`. Related test: `npm test -- 现场参数`.
69
+ - Take a screenshot only after the look changed: `npm run shot -- / --time 19:30 --weather dust`.
70
70
 
71
71
  ## 6. Day and night in game logic
72
72
  Day and night come only from the sky: test `engine.sky.isDay`, and fade with `engine.sky.daylight` (0-1). Don't decide it from the clock time
@@ -4,26 +4,24 @@
4
4
  plain neutral placeholder (a gray capsule for characters, a gray box for props and pickups, flat gray ground at y = 0, one white hemisphere light plus
5
5
  one neutral directional light without shadows or tone mapping), and the console says once in dev what is missing and how to fix it.
6
6
 
7
- A style pack is a plain object passed in as `createEngine({ style })`. It holds **looks only**: colors, the default character / pickup shapes,
7
+ A style pack is a plain object passed in as `createEngine({ style })`. It holds **looks only**: colors, the default pickup shape,
8
8
  materials and shaders, sky and lighting, post effects, UI look. Not part of it: model / texture / sound files and procedural models content names (an
9
9
  **asset pack**, `engine.assets.manifest`, recipe 05 "Asset packs"), sounds (section 5), gameplay data and timing (a **content pack**, recipe 20;
10
10
  `sky({ hoursPerDay })`). Which key is read by whom is in the "style pack keys" table of `../CODEMAP.md`; the field list is in `../api/style.md`. Every
11
11
  entry can be omitted; omitted entries are the neutral placeholders above (the city example passes no style pack at all). Write it as a plain object literal, no `@type` or `as const`: fields with a fixed set of words (`shading`, `mode`, `type` …) accept any string in the types, and a wrong word is reported by `threedog style check` with the fix.
12
12
 
13
- ## 0. Installing the lowpoly style pack
14
- The low-poly look is an optional package, `@threedog/style-lowpoly` (source in the monorepo: `packages/styles/lowpoly/`):
15
- ```sh
16
- npm install @threedog/style-lowpoly
17
- ```
13
+ ## 0. Using a style pack
14
+ A style pack is a plain object (or a package that exports one): yours in `style/index.js`, a folder you copy, or a published package. Any art direction fits:
15
+ realistic, toon, pixel, painterly, flat, noir. The engine ships none; `threedog new-style` starts an empty one (section 1).
18
16
  ```js
19
17
  import { createEngine, presets, openWorld } from 'threedog';
20
- import lowpoly from '@threedog/style-lowpoly';
21
- import { terrainPreset, terrainStrings } from '@threedog/terrain-noise'; // the world shape is not a look: its own package
22
- const engine = createEngine({ canvas, style: lowpoly, strings: terrainStrings }); // terrainStrings: names of the preset's ground types
23
- engine.use(openWorld({ camera: 'follow', seed: 7, terrain: terrainPreset() })); // noise terrain (hills, rivers, biomes) that lowpoly colors, see recipes/28
18
+ import yourPack from './style/index.js'; // or: import yourPack from 'a-published-pack'
19
+ import { terrainPreset, terrainStrings } from '@threedog/terrain-noise'; // the world shape is not a look: its own package
20
+ const engine = createEngine({ canvas, style: yourPack, strings: terrainStrings }); // terrainStrings: names of the preset's ground types
21
+ engine.use(openWorld({ camera: 'follow', seed: 7, terrain: terrainPreset() })); // noise terrain (hills, rivers, biomes) that your pack colors, see recipes/28
24
22
  ```
25
- Besides the style object it exports `assets` (an asset pack of procedural trees, rocks, grass, flowers: `engine.assets.manifest(assets)`; the same
26
- generators as a plain map are `models`). Its `bloom` / `ao` / `outline` come from `@threedog/post-effects` (style packs never import each other; R34 checks). The terrain generator `terrainPreset` / `riverAt` / `BIOMES` /
23
+ A pack may also export an asset pack (procedural models: `engine.assets.manifest(assets)`). Post effects such as `bloom` / `ao` / `outline` come from
24
+ `@threedog/post-effects` (style packs never import each other; R34 checks). The terrain generator `terrainPreset` / `riverAt` / `BIOMES` /
27
25
  `terrainStrings` is a separate package, `@threedog/terrain-noise`: the shape of the world is gameplay, so a style pack keeps only the colors of its
28
26
  ground types (`terrain.colors`, `biomeColors`).
29
27
 
@@ -31,9 +29,9 @@ ground types (`terrain.colors`, `biomeColors`).
31
29
  `style` may be a list of parts, deep-merged left to right into `engine.style`, so one pack's materials, another pack's sky and the game's own colors
32
30
  mix without copying whole packs:
33
31
  ```js
34
- import lowpoly from '@threedog/style-lowpoly';
32
+ import basePack from './style/index.js';
35
33
  const dusk = { sky: { sunSize: 600, keyframes: myDuskKeyframes } }; // only these two sky fields change
36
- const engine = createEngine({ canvas, style: [lowpoly, dusk, { ui: { accent: '#7fd3ff' }, post: null }] });
34
+ const engine = createEngine({ canvas, style: [basePack, dusk, { ui: { accent: '#7fd3ff' }, post: null }] });
37
35
  ```
38
36
  Rules (`core/styleParts.js`): plain `{ }` objects merge key by key at every depth; everything else replaces whole (arrays such as `sky.keyframes` and
39
37
  `post`, functions, three.js objects); a key set to `null` removes it; `undefined` is ignored; nested lists flatten, so a pack can itself be a list of
@@ -43,16 +41,16 @@ parts; parts are never mutated. One object (not a list) is used as it is.
43
41
  (exported by `threedog`); they are parts too:
44
42
  ```js
45
43
  import { createEngine, postAdd, postRemove } from 'threedog';
46
- import lowpoly from '@threedog/style-lowpoly';
44
+ import basePack from './style/index.js';
47
45
  import { bloom } from '@threedog/post-effects';
48
- createEngine({ canvas, style: [lowpoly, postAdd(myGrain, bloom({ strength: 0.6 })), postRemove('ao')] });
46
+ createEngine({ canvas, style: [basePack, postAdd(myGrain, bloom({ strength: 0.6 })), postRemove('ao')] });
49
47
  ```
50
48
  `postAdd(...effects)` appends; an effect whose `name` is already in the list (`'bloom'`, `'ao'`, `'outline'`) replaces that one in place.
51
49
  `postRemove(...names)` drops effects by name. `{ post: null }` still clears the list; `{ post: [...] }` still replaces it whole.
52
50
 
53
- **Retinting the procedural models.** `style.palette` holds the colors the trees, rocks, grass and flowers are built from (lowpoly: `bark`, `pine`,
54
- `pineLight`, `leaf`, `rock`, `grassBase`, `grassTip`, `bloom`...; the keys are in `lowpoly.palette`). One part changes them all:
55
- `style: [lowpoly, { palette: { pine: 0xa07a2e, leaf: 0xd98a3a } }]` (autumn); keys left out keep the pack's colors. A generator of your own written
51
+ **Retinting the procedural models.** `style.palette` holds the colors the trees, rocks, grass and flowers are built from (the keys are the pack's own, e.g. `bark`, `leaf`, `rock`,
52
+ `grassTip`...; see `basePack.palette`). One part changes them all:
53
+ `style: [basePack, { palette: { leaf: 0xd98a3a } }]` (autumn); keys left out keep the pack's colors. A generator of your own written
56
54
  with `function` (not an arrow) reads `this.palette`; the palette is part of the model cache key, so a changed palette rebuilds. `.glb` files and
57
55
  models baked earlier keep their colors.
58
56
 
@@ -60,13 +58,14 @@ models baked earlier keep their colors.
60
58
  Swapping the style must never change the map or the rules, only how they look. So these are **not** style fields, and a dev run throws an error
61
59
  naming where each goes:
62
60
  - water level, whether there is a sea, the water mesh size: `style.water.level / sea / size` -> `engine.use(water({ level, sea, size }))`
63
- - terrain shape and size (seed, chunk size, resolution, water level, height functions): `style.terrain.config.*` -> `terrain({ ... })`. The one
64
- look in `terrain.config` is `shading: 'flat' | 'smooth'`
61
+ - terrain shape and size (seed, chunk size, resolution, water level, height functions): `style.terrain.config.*` -> `terrain({ ... })`. The looks
62
+ in `terrain.config` are `shading` (`'smooth'` | `'texture'` | `'flat'`), `colorResolution`, `normals` and `normalFn` (recipe 37); at run time
63
+ `engine.look.ground.set({ shading, colors, variation, detail })` (recipe 52)
65
64
  Quality settings are not world state and may stay in a style (shadow `mapSize` and `low` overrides, water `segments`); players can override them in
66
65
  settings. Packs under `packages/styles/**` are also checked by `threedog check` (R34).
67
66
 
68
67
  ## 1. Creating a new style pack
69
- Copy `packages/styles/lowpoly/` to your game (or a new package `@threedog/style-toon`), edit the values in `index.js`, then switch to it in the game:
68
+ Run `threedog new-style` (or copy any pack folder into your game or a package of your own), edit the values in `index.js`, then switch to it in the game:
70
69
  ```js
71
70
  import toon from './style/index.js';
72
71
  const engine = createEngine({ canvas, style: toon });
@@ -80,19 +79,20 @@ Keys you will change most often:
80
79
  |---|---|
81
80
  | `materials` | The material per role. Three forms: a spec `{ default: { type: 'toon', steps: 3 }, water: { type: 'phong', shininess: 90 } }` (lambert / phong / standard / physical / toon / basic; a wrong type throws), any three.js material instance `water: new THREE.MeshMatcapMaterial({ matcap })` (cloned per use), or a function `prop: (params, role) => new THREE.ShaderMaterial({...})`. Style packs may create materials directly; games still go through `makeMaterial` |
82
81
  | `antialias` | `false` for sharp pixel edges; omitted = on for desktop, off for phones (players can switch it in settings) |
83
- | `post` | List of post effects, see 2c (lowpoly: `[outline(), ao(), bloom()]`; `outline({ enabled: true })` for a cartoon look) |
84
- | `sky` `weather` `water` `terrain` `seasons` `clouds` | Sky keyframes (sun color and intensity over the day, fog color, shadows), rain and snow, water, terrain colors (`terrain.colors` palette, `terrain.biomeColors` ground type -> palette names, `terrain.steep` slope colors; a type with no color is gray; `terrain.config.shading: 'flat'` for facets (the only `terrain.config` key; engine default smooth); `terrain.material` swaps the whole ground material, chunks have `uv` = world xz / chunk size; `water.material: (engine, { uniforms, waves, normalMap }) => Material` swaps the whole water surface, e.g. `applyEffects(new THREE.MeshToonMaterial({ color }), { clouds: false, patches: [waves] })` keeps the built-in waves), seasonal tints |
85
- | `character` | Default character colors `colors`; `create(engine, colors)` builds the procedural character (lowpoly: its `shapes.js`; without it a gray capsule); `model` a registered model every character uses |
82
+ | `post` | List of post effects (e.g. `[outline(), ao(), bloom()]`; `outline({ enabled: true })` draws edge lines); slots, the effects package, `fuse`, outline modes: [recipe 52](52-look.md#post-effect-chain) |
83
+ | `sky` `weather` `water` `terrain` `seasons` `clouds` | Sky keyframes (sun color and intensity over the day, fog color, shadows), rain and snow, water, terrain colors (`terrain.colors` palette, `terrain.biomeColors` ground type -> palette names, `terrain.steep` slope colors; a type with no color is gray; `terrain.config`: `shading` `'smooth'` (engine default) | `'texture'` (per-chunk color map) | `'flat'` (facets), `colorResolution`, `normals`, `normalFn`, recipe 37; `terrain.detail` a detail layer, recipe 53; `terrain.material` swaps the whole ground material, chunks have `uv` = world xz / chunk size; `water.material: (engine, { uniforms, waves, normalMap }) => Material` swaps the whole water surface, e.g. `applyEffects(new THREE.MeshToonMaterial({ color }), { clouds: false, patches: [waves] })` keeps the built-in waves), seasonal tints |
84
+ | `character` | `animation.fade`: skeletal animation transition seconds. Bodies are assets, not style: `createPlayer({ model })` with a registered model, a GLB asset name or `{ rig }`; part colors are material roles or `{ colors }` per character (recipe 13). Without a model a gray capsule |
86
85
  | `pickup` `particles` | Items on the ground (`pickup.model(item, { color, size })` returns an Object3D or geometry; without it a plain gray box), particle presets (dust smoke leaves splash sparks...) |
87
86
  | `triggers` `grid` | Tool colors, not art: trigger zone wireframe (`debugColor`), grid placement preview (`ok` / `bad`). The engine has neutral defaults (gray; light = can place, dark = cannot); a pack may recolor them |
88
87
  | `ui` | UI colors, `font` (a CSS font-family list), `fonts` (font asset names to load at start, the files in an asset pack: recipes/05 §3b), extra `css`, `templates` that replace a whole UI piece |
89
88
 
90
- Lights: every engine has `engine.lights = { sun, hemi }`, plain three.js lights. Without a style pack they are a neutral placeholder (white
89
+ ## 1b. Lights and stalls
90
+ Every engine has `engine.lights = { sun, hemi }`, plain three.js lights. Without a style pack they are a neutral placeholder (white
91
91
  hemisphere + neutral directional light, no shadows); the look (sun color and intensity curves, sky colors, fog, shadow softness, exposure, tone
92
- mapping) comes from the style pack's `sky`, `exposure` and `toneMapping`, and the sky module drives the same two lights. For your own lighting hide or
93
- retune them and add three.js lights.
92
+ mapping) comes from the style pack's `sky`, `exposure` and `toneMapping`, and the sky module drives the same two lights. At run time:
93
+ `engine.look.lights.set(...)` (recipe 52); to light the world yourself: recipe 38.
94
94
 
95
- **Lights and stalls.** three.js builds one shader program per material for each light setup. `engine.start()` compiles everything visible behind the
95
+ three.js builds one shader program per material for each light setup. `engine.start()` compiles everything visible behind the
96
96
  loading screen (`engine.startup.compileMs`), but adding or removing a light later, or toggling `visible` on one, changes the setup and compiles again:
97
97
  a frame can freeze for hundreds of milliseconds. Keep the number of lights fixed: create them up front and fade with `intensity` (0 = off, no
98
98
  recompile). In dev the console warns (code `light-recompile`) when programs were compiled in a frame where the lights changed.
@@ -118,7 +118,7 @@ camera. Options and handle: `../api/lightPool.md`.
118
118
  Models are assets, not style keys: content names them, an asset pack maps the names to files or generators. Register a later manifest with the same
119
119
  name to swap one:
120
120
  ```js
121
- engine.assets.manifest(lowpolyAssets); // import { assets as lowpolyAssets } from '@threedog/style-lowpoly': pine, rock, flower... built in code
121
+ engine.assets.manifest(yourAssets); // assets from an asset pack you have: trees, rocks, flowers... built in code
122
122
  engine.assets.manifest({ name: 'mine', models: { pine: () => myPineGeometry(), well: '/models/well.glb' } }); // replaces pine, adds well
123
123
  ```
124
124
  Vegetation takes a geometry (`geometry: await engine.assets.geometry('pine')`, the first mesh in the model) or a whole model with one material per
@@ -143,81 +143,16 @@ A missing `#include` anchor throws. A hand-written `ShaderMaterial` can `#includ
143
143
  `render/effects.js`) with `engine.uniforms` as its uniforms.
144
144
  `material.clone()` does not carry patches (three's `Material.copy` skips `onBeforeCompile`): a pack's Material instance in `materials` is fine
145
145
  (`makeMaterial` keeps its patches); when you clone one yourself, apply the effects to the clone again.
146
-
147
- Patches on one material must agree. Each patch declares what it relies on, and a bad combination throws when it is added (or logs once at compile):
148
- | Field | Meaning | Checked |
149
- |---|---|---|
150
- | `needs.data` | Program inputs the code reads: `'instancing'`, `'instancingColor'`, `'vertexColors'`, `'skinning'`, `'batching'` | when the program compiles (console.error once per material) |
151
- | `needs.patches` | Patches it builds on, e.g. `['world']` for the `vThreedogWorld` varying (world position; `applyEffects` adds `world` itself when a patch needs it) | when added |
152
- | `conflicts` | Patch names it cannot share a material with | when added, both ways |
153
- | `uniforms` | A uniform name belongs to one patch; share `engine.uniforms` (`uTime`, `uWind`, `uCloud`...) instead of making your own `uTime` | when added |
154
- | `shadow` | Render steps: without it the color pass only; `true` also runs its vertex code in the depth (sun / spot shadows) and distance (point-light shadows) passes | - |
155
- | `cacheKey` | Changes whenever the GLSL text changes (defines, branches), never for uniform values; the program key joins every patch's `name=cacheKey` in order | same name + cacheKey with different code throws |
156
- ```js
157
- applyEffects(mat, { wind: 0.03, season: 'foliage', patches: [{ name: 'ripple', needs: { patches: ['world'] }, conflicts: ['wind'],
158
- glsl: { fragment: { color_fragment: 'diffuseColor.rgb *= 0.9 + 0.1 * sin(vThreedogWorld.x);' } } }] }); // throws: 'wind' and 'ripple' cannot be combined
159
- ```
160
-
161
- ## 2c. Post effects (slots)
162
- Post-processing is an ordered list of named effects. Each runs in a slot, then by `order` (low first):
163
- `scene` (replaces the scene render, one at a time, e.g. pixelation) -> `hdr` (linear color: outline, AO, bloom) -> tone mapping -> `ldr` (sRGB: LUT,
164
- palette, grain, vignette) -> `final` (FXAA / SMAA).
165
- An effect is `{ name, slot, order, params, create(ctx) => pass, update?(pass, params) }`; under WebGL the pass is any three.js postprocessing Pass. It
166
- is built the first time it is on.
167
- ```js
168
- import { bloom, outline } from '@threedog/post-effects'; // never from another style pack: packs do not depend on each other
169
- import { LUTPass } from 'three/addons/postprocessing/LUTPass.js';
170
- const toon = { name: 'toon', post: [outline({ enabled: true, thickness: 1.5 }), bloom({ strength: 0.2 }),
171
- { name: 'lut', slot: 'ldr', params: { lut: myLut }, create: ({ params }) => new LUTPass({ lut: params.lut }) }] };
172
- // at runtime (settings, photo mode, a game's own effect):
173
- engine.look.post.set({ 'bloom.strength': 0.6 });
174
- engine.look.post.set({ 'outline.enabled': false }); // MSAA: engine.post.setAntialias(false)
175
- engine.look.post.patch('vignette', { glsl: 'color.rgb *= 0.9;', slot: 'ldr', order: 10 }); // patch('vignette', null) removes it
176
- ```
177
- An effect that reads scene depth (`needsDepth: true`, e.g. `outline`) must run before any pass that swaps buffers (a `ShaderPass`, a scene-slot
178
- `RenderPixelatedPass`, the tone-mapping output): only the buffer the scene render wrote holds scene depth. A chain that breaks this throws when the
179
- effect is added or enabled, naming both effects; give the depth reader a lower `order`. `dof` copies the scene depth into its own output
180
- (`pass.keepsDepth = true`, no extra pass), so `dof` and `outline` can both be on as long as `dof` has the lower `order` (default: dof 5, outline 10;
181
- lines stay sharp over the blur). `threedog style check` reports the other order as an error.
182
- `createEngine({ post: { bloom: false } })` overrides an effect's startup on/off; `costly: true` effects start off on low-tier devices. MSAA
183
- (`antialias`) works with every effect on.
184
- The settings menu shows `bloom` / `ao` toggles only when the style pack registers effects with those names.
185
-
186
- ### Optional post effects package and `fuse`
187
- The engine ships no effects; `@threedog/post-effects` (install it like `@threedog/terrain-noise`, import only what you use) has `bloom`, `ao`,
188
- `outline`, `dof` (all `hdr`; outline and dof read depth) and `lut` (contrast / saturation / warm-cool / optional 3D LUT), `grain`, `vignette`,
189
- `chromatic` (`ldr`). A style pack lists the ones it wants in its own `post`. `lut`, `grain`, `vignette`, `chromatic`, `dof`, `ao` and `outline` are off
190
- until `enabled: true`.
191
- ```js
192
- import { vignette, grain, lut } from '@threedog/post-effects';
193
- createEngine({ canvas, style: [lowpoly, postAdd(lut({ saturation: 1.1, temperature: 0.15 }), vignette(), grain({ amount: 0.04 }))] });
194
- engine.look.post.set({ 'vignette.enabled': true }); // photo mode, settings...
195
- engine.look.post.set({ 'grain.amount': 0.1 }); // updates in place
196
- ```
197
- `fuse` is how a light color effect avoids a fullscreen pass of its own: instead of `create()` it carries a GLSL snippet
198
- `fuse: { uniforms: { uMyAmount: 'float' }, values: p => ({ uMyAmount: p.amount }), glsl: 'color.rgb *= 1.0 - uMyAmount * length(vUv - 0.5);' }`.
199
- Effects with a `fuse` that are on and next to each other in one slot (never `scene`) are compiled into ONE shader and drawn in one pass, in
200
- `order`; turning one off, `set()` or `remove()` recompiles or just updates the uniforms. The snippet edits `vec4 color` and may use `vUv`,
201
- `tDiffuse`, `uTime`, `uResolution`, `fxHash(vec2)`; uniform names are shared by the whole group, so prefix them with the effect name. A snippet that
202
- samples `tDiffuse` at other positions (blur, color fringe) sets `reads: true` and then starts a new group. Four ldr effects: 1 pass instead of 4.
203
- Effects without `fuse` (bloom, outline, `dof`...) stay one pass each.
204
-
205
- ### Outline modes
206
- `outline({ mode: 'depth' | 'normal' | 'both' })`: `depth` (default, silhouettes), `normal` (creases; the scene is drawn once more with normals, so
207
- it is `costly` and off on low-tier devices), `both`. `fadeWithDistance: false` keeps lines at any distance; `wobble: 1.5` jitters the lines by up to 1.5
208
- pixels at 8 steps a second (hand-drawn). To exempt objects: `outline({ offLayer: OUTLINE_OFF_LAYER })` and `mesh.layers.enable(OUTLINE_OFF_LAYER)`
209
- (three.js layers; layer 0 stays on, so the object still renders normally; costs one extra render of just the exempt objects, nothing when
210
- `offLayer` is `null`). Normal mode draws the scene with a plain override material, so wind-animated foliage lines up with its static shape.
211
-
212
- Textures by asset name, grain / paper / strokes (`detail`), shadow tint, rim light, toon ramps and the GLSL exits are all spec keys: recipe 37.
146
+ What a patch declares (`needs`, `conflicts`, `shadow`, `cacheKey`) and the chunk names: recipe 43, exit 2. Textures by asset name, `detail`,
147
+ shadow tint, rim light and toon ramps are material spec keys: recipe 48 (keys), recipe 43 (what they do).
213
148
 
214
149
  ## 3. When the engine gets a new "look parameter"
215
- Hard rule 1: a module only writes a neutral gray fallback and reads `engine.style.xxx ?? fallback`, **and the real value is added to the lowpoly pack
150
+ Hard rule 1: a module only writes a neutral gray fallback and reads `engine.style.xxx ?? fallback`, **and the real value is added to a style pack
216
151
  (its `index.js`) at the same time** (with a one-line comment saying what it means),
217
152
  and the new field gets a doc comment in `types/style.d.ts` (`docs/api/` is generated from there). Materials always go through
218
153
  `makeMaterial('role', { color })`, leaving the surface feel to `style.materials[role]`. Whose style: `engine.makeMaterial('role', { color })` uses that
219
154
  engine's pack; the free `makeMaterial()` uses the first engine created (fine for one engine, a dev warning when two packs run). Engine code and style packs always
220
- go through the engine (`create(engine, colors)`, `pickup.model(item, { color, size }, engine)`, `water.material(engine, ...)`), so two engines never share materials.
155
+ go through the engine (`pickup.model(item, { color, size }, engine)`, `water.material(engine, ...)`), so two engines never share materials.
221
156
  Look parameters only: a field that changes the world (a level, a size, a seed) goes to the module's options, not the style (section 0c).
222
157
 
223
158
  ## 4. Verify
@@ -226,7 +161,7 @@ Look parameters only: a field that changes the world (a level, a size, a seed) g
226
161
  - `npm run map`: the "style pack keys" table in CODEMAP is updated.
227
162
  - Take screenshots only when the look changed, and compare two times of day: `npm run shot -- / --time 12:00`, `npm run shot -- / --time 18:30`
228
163
  (images go to .threedog/shots/).
229
- - It must still run without a style pack: `npm test -- 小城`.
164
+ - It must still run without a style pack: start once with `createEngine({ canvas })` and no `style` (gray placeholders, one console note per missing piece).
230
165
 
231
166
  ## 5. Sounds and music (the game's, not the style pack's)
232
167
  Sounds are game config, passed to `createEngine({ audio: { sounds, ambience, music, footsteps, levels } })` and read back as `engine.audio.config`; a
@@ -59,17 +59,33 @@ engine.characters.createPlayer({ ...presets.player.thirdPerson, model: hero, ani
59
59
  ```
60
60
  The default transition time comes from the style pack's `style.character.animation.fade`.
61
61
 
62
- **By asset name.** `model` also takes the name of a registered model asset, and a style pack can set `style.character.model: 'hero'` as the default
63
- for every character (a per-character `model` wins). The character is built at once with the placeholder body (the style's `create()` or the gray
64
- capsule); when the asset loads, a skeleton-correct copy replaces it under the same root, so position, facing, state, collision and the world view
65
- stay. Then `ready` turns true, `whenReady` settles and `character:model` is emitted. A name missing from a registered manifest throws with the
66
- registered names; a failed load keeps the placeholder and warns once; a character disposed before loading ends never gets the model.
62
+ **By asset name.** `model` also takes the name of a registered model asset: a file model, or a procedural builder. The character is built at once
63
+ with a gray capsule; when the asset loads, a skeleton-correct copy replaces it under the same root, so position, facing, state, collision and the
64
+ world view stay. Then `ready` turns true, `whenReady` settles and `character:model` is emitted. A name no model asset has throws with the registered
65
+ names; a failed load keeps the capsule and warns once; a character disposed before loading ends never gets the model.
67
66
  ```js
68
67
  engine.assets.manifest({ models: { hero: '/models/hero.glb' } });
69
- const p = engine.characters.createPlayer({ ...presets.player.thirdPerson, model: 'hero' }); // placeholder now, the hero once loaded
68
+ const p = engine.characters.createPlayer({ ...presets.player.thirdPerson, model: 'hero' }); // capsule now, the hero once loaded
70
69
  await p.whenReady; // p.anim is set from here (unless the load failed)
71
70
  ```
72
71
 
72
+ ## 3b. Procedural bodies are assets too (`model: 'humanoid'`)
73
+ Character bodies are assets, never style: every character picks one with `model`, the same path for a GLB and a procedural builder. an asset
74
+ pack can supply a code-built humanoid (e.g. box limbs, swung by the engine while walking, running, swimming, jumping); a builder is built at once, so its joints
75
+ (`player.armL`, `legR`...) exist right after `createPlayer`. Without `model` (and without `rig`) a character is a gray capsule, warned once.
76
+ ```js
77
+ import { assets } from './assets.js'; // an asset pack of yours (or a published one) with a 'humanoid' builder
78
+ engine.assets.manifest(assets);
79
+ engine.characters.createPlayer({ ...presets.player.thirdPerson, model: 'humanoid' });
80
+ engine.npcs.add({ id: 'fisher', model: 'humanoid', colors: { body: 0x4f6d8f } }); // per-character part colors
81
+ ```
82
+ - **Colors**: the humanoid's parts use material roles `cloth`, `skin`, `trousers`, `hair`, so any style pack tints every humanoid
83
+ (`style: [basePack, { materials: { cloth: { color: 0x3a6ea5 } } }]`); `colors: { body, skin, legs, hair }` recolors one character.
84
+ - **Your own procedural body**: a builder that returns an Object3D with `root.userData.rig = { body: 'hips', head: 'head', joints: ['armL'],
85
+ limbs: [{ joint: 'legL', offset: 0, amp: 0.9, kind: 'leg' }] }` (object names, so it survives copies and baking) animates like the humanoid; mark
86
+ meshes `userData.part = 'body'` for `colors`. A hand-built one-off passes `{ rig }` instead ([02-npc](02-npc.md)).
87
+ - The old `style.character.create` / `.model` / `.colors` throw `renamed-api` ([52-look](52-look.md#renamed-in-02)).
88
+
73
89
  ## 4. Non-character objects (a dog, a windmill, a door)
74
90
  ```js
75
91
  const dog = await engine.assets.model('dog'); engine.add(dog);
@@ -1,7 +1,8 @@
1
1
  # Custom module
2
2
 
3
- When to write a module: a "mechanic" that has its own state, per-frame logic and saving, and that other games might use too (fishing, farming,
4
- stamina). Something that belongs to one game only goes in `games/<game>/`;
3
+ When to write a module: a "mechanic" that has its own state, per-frame logic and saving (stamina, a heat meter, wave spawning, oxygen, a combo
4
+ counter). The contracts every module should follow (state, game time, skip, describe, ops) and a second copyable module are in
5
+ `49-game-module-contract.md`; this page is the template and the hook cheat sheet. Something that belongs to one game only goes in `games/<game>/`;
5
6
  a general one goes in `modules/<name>/index.js` inside the engine and is exported from the engine's `index.js` (then the three hard rules apply: no
6
7
  hard-coded art or text, no importing another module's internal files).
7
8
 
@@ -20,7 +21,7 @@ export function stamina(opts = {}) {
20
21
  restore(n) { api.value = Math.min(max, api.value + n); },
21
22
  };
22
23
  return {
23
- name: 'stamina', label: '体力', requires: ['characters'], optional: ['hud'], stage: 'gameplay', // once installed, engine.stamina === api
24
+ name: 'stamina', label: 'Stamina', requires: ['characters'], optional: ['hud'], stage: 'gameplay', // once installed, engine.stamina === api
24
25
  install(engine) {
25
26
  e = engine;
26
27
  e.i18n.add({ 'zh-CN': { 'stamina.label': '体力' }, en: { 'stamina.label': 'Stamina' } }); // don't hard-code UI text
@@ -49,7 +50,7 @@ Install it: `engine.use(openWorld({ camera: 'follow', ...}), stamina({ max: 80 }
49
50
  what the loaded state needs nearby, with gameplay frozen until it resolves.
50
51
  - `fixed(dt, e)` movement, timing, gameplay keys (`input.pressed` read in fixed is this step's snapshot, independent of frame rate); `frame(dt, e)`
51
52
  animation, camera, UI (it reads this frame's latest input); `afterRender(dt, e)` after rendering.
52
- - `describe(e, ctx)`: the return value goes into `describe().<module name>`; `ctx.near(object or {x,z}, { name, kind })` reports things nearby.
53
+ - `describe(e, ctx)`: see recipe 49 contract 4; `ctx.near(object or {x,z}, { name, kind })` reports things nearby. `skip(dt, e, done)`: recipe 49 contract 3.
53
54
  - `applyState(e, p)`: called by `engine.applyState` / URL parameters; it only receives the keys `time`, `weather` and `cutscene`.
54
55
  - `stage`: when the hooks run (first -> last): `control` timeline, camera -> `world` terrain, level -> `environment` weather, sky, water -> `gameplay`
55
56
  interactions, dialogue, entities -> `presentation` particles, objective markers -> `late` (the default) characters, physics -> `audio` music. Within
@@ -69,9 +70,7 @@ Install it: `engine.use(openWorld({ camera: 'follow', ...}), stamina({ max: 80 }
69
70
  `document.body`).
70
71
  The `dispose(e)` hook only collects what the core can't, such as Workers, the physics world and real-time timers, and is called in reverse install order.
71
72
  - While frozen (`engine.freeze`, flow pause) `fixed` is skipped entirely and `frame` still runs: check `e.frozen` before gameplay decisions.
72
- - Changing what a saved part looks like: raise its version and add one upgrade step per old version, e.g.
73
- `e.saves.register('stamina', { version: 2, migrate: { 1: v => ({ value: v }) }, save, load })`. `load` only ever sees the current shape; a save
74
- written by a newer build is refused (load returns false, the save is kept).
73
+ - Changing what a saved part looks like: `version` + `migrate` (recipe 49 contract 1). A save written by a newer build is refused (load returns false).
75
74
  - Saved state the module writes joins the ops guard (experimental): `e.ops.guard('stamina.set')` in each writing method (a no-op in production builds,
76
75
  no DEV check needed), `e.ops.allow(fn)` around writes that are allowed anyway (recipe 23 section 5).
77
76
  - **Per-playthrough state** (one hook for every module): state that is not a save part but belongs to the current playthrough (an open dialogue, a
@@ -72,6 +72,14 @@ false = all on the main thread, same results.
72
72
  - `engine.threads.pure(fn)` / `world.simulate(..., { worker: true })`: the function is recompiled from its source, so it cannot capture outside
73
73
  variables or imports; put constants inside it. A bad outside variable is reported by name on the first call.
74
74
 
75
+ ## 4b. Render scale (resolution) is never lowered silently
76
+ - Default render scale: `min(devicePixelRatio, 1.5)`; the low tier uses at least 0.75 x devicePixelRatio (a 2x laptop screen gets 1.5, not 1), never above 1.5.
77
+ - Adaptive resolution (`createEngine({ adaptiveResolution, targetFps })`, default on, floor 0.6) lowers the scale by 0.1 per second under the target fps. The first
78
+ time it does, dev builds warn once: `render scale X -> Y because fps Z ...; turn off with adaptiveResolution: false`. It is the only thing lowered automatically
79
+ (shadows and post are never traded first).
80
+ - `describe().render.scale`: `{ current, devicePixelRatio, upscaled, autoLowered, adaptive, floor, max }`. `upscaled: true` means current < devicePixelRatio, the picture
81
+ is softer than the screen: if that looks wrong in a screenshot, check this before the style. Fixed quality: `pixelRatio: n` plus `adaptiveResolution: false`.
82
+
75
83
  ## 5. Verify (once before and once after, under the same conditions)
76
84
  - `npm run perf` (native vs engine vs per-module cost of openWorld), compared with the tables in `../PERF.md`; differences under 10-30% are noise.
77
85
  - Compare a specific scenario: `npm run shot -- / --pos x,z --time 12:00 --describe-only` to see draw calls and triangles.
@@ -26,11 +26,11 @@ game only advances on step); once you open the page in a browser, commands go to
26
26
  | `press interact` | Press an action name or key once (`KeyE`, `e`, `Escape`). **It advances game time**: 0.1 s held + one rendered frame of 1/60 s, about 0.117 s in total; shorten the hold with `--for 0.02` when timing matters | `✓ Pressed menu (Escape) · … · window open: settings` |
27
27
  | `hold moveForward 1.5` | Hold for 1.5 seconds | `✓ Held moveForward (KeyW) for 1.5 s · player (-0.6, 3.0) …` |
28
28
  | `skip to=06:00` / `skip seconds=600` | Jump the clock like sleeping (`engine.skip`) | `✓ Skipped to 06:00 → 21600 · … 06:00 day 2` |
29
- | `ops` | What the player can do now: every op offer checked with `can` (`recipes/23-ops.md`) | `✓ shop.buy item=bread · ✗ shop.buy item=cake (soldOut)` |
30
- | `op shop.buy shop=bakery item=bread n=2` | Run a game op (source `bridge`, **no time passes**). Values follow the op's `args` shape (`n=2` a number, `position=3,0,-2` an array). **Change state with this, not `js`**: `js` writes skip the op log | `✓ shop.buy → 2 · Bag gold×2 bread×2` / `✗ shop.buy: noMoney (Not enough gold)` |
31
- | `inspect` / `inspect npc_3` / `inspect 10,-4` | What is around the player and which ops it can do now, with reasons (`engine.inspect`, recipes/23-ops.md section 8) | `player at (4, 7) · near: 老渔夫 1 m` / `✗ barter.buy shop=fisher-basket item=feather (soldOut: …)` |
29
+ | `ops` | What the player can do now: every op offer checked with `can` (`recipes/23-ops.md`) | `✓ shop.buy item=medkit · ✗ shop.buy item=ammo (soldOut)` |
30
+ | `op shop.buy shop=trader item=medkit n=2` | Run a game op (source `bridge`, **no time passes**). Values follow the op's `args` shape (`n=2` a number, `position=3,0,-2` an array). **Change state with this, not `js`**: `js` writes skip the op log | `✓ shop.buy → 2 · Bag gold×2 medkit×2` / `✗ shop.buy: noMoney (Not enough gold)` |
31
+ | `inspect` / `inspect npc_3` / `inspect 10,-4` | What is around the player and which ops it can do now, with reasons (`engine.inspect`, recipes/23-ops.md section 8) | `player at (4, 7) · near: guard 1 m` / `✗ shop.buy shop=trader item=ammo (soldOut: …)` |
32
32
  | `pick 480,270` | What is at that screen pixel: record id, kind, template, the content file and line that defines it, its fields (recipes/30-templates.md section 5) | `✓ chest-home (kind chest, template chest) …` / `defined in content/props.js:14: edit it there …` |
33
- | `explain op barter.buy shop=fisher-basket item=berry` / `explain quest first-light` | Why an op cannot run now (the reason and the op's note on fixing it first; `--full` adds the last attempt and events around it), or where a quest is stuck (`engine.explain`) | `✗ barter.buy {...} cannot run now: noFilm (Not enough film)` |
33
+ | `explain op shop.buy shop=trader item=ammo` / `explain quest my-quest` | Why an op cannot run now (the reason and the op's note on fixing it first; `--full` adds the last attempt and events around it), or where a quest is stuck (`engine.explain`) | `✗ shop.buy {...} cannot run now: noMoney (Not enough gold)` |
34
34
  | `scenario barter` | Run `tests/scenarios/barter.json` (recipes/23-ops.md section 7); prints failed checks, leaves it paused | `✓ barter: 6 checks passed` |
35
35
  | `state time=18:30 weather=rain pos=40,-20` | Set the scene (like URL parameters: time weather pos save wait cutscene state) | `✓ Set · 18:30 day 1 · rain` |
36
36
  | `js "engine.sky.timeOfDay"` (alias `eval`) | Evaluate an expression in the page; `engine` is available directly and `await` works inside; multi-line statements need their own `return` (e.g. `js "const p = engine.player.position; return p.x + p.z"`). Long scripts: `js --file script.js` | `✓ 0.77` |
@@ -90,7 +90,7 @@ The same steps as a file: `tests/scenarios/<name>.json` with `{ "press": … }`,
90
90
 
91
91
  ## 3b. Speed, a session, and checks in one call
92
92
 
93
- Why a command used to take seconds: `npx` itself costs about 2.5 s on Windows (npm starts, resolves the bin) before threedog runs at all; threedog added a second node process (about 0.25 s) and a cold first request. Measured on the engine example, per command: `npx threedog describe` 3.2 s; `node node_modules/@threedog/tools/bin/threedog.mjs describe` 0.83 s before, 0.50 s now (one process, lazy imports); with a session 0.4 s (node start alone is 0.27 s).
93
+ Where the time goes: `npx` itself costs about 2.5 s on Windows (npm starts, resolves the bin) before threedog runs. Measured on the engine example, per command: `npx threedog describe` 3.2 s; `node node_modules/@threedog/tools/bin/threedog.mjs describe` 0.5 s; with a session 0.4 s (node start alone is 0.27 s).
94
94
 
95
95
  - For a many-step test call the bin directly (`node node_modules/@threedog/tools/bin/threedog.mjs ...`, or `node_modules/.bin/threedog`) instead of `npx`.
96
96
  - `npx threedog session` starts a background process that serves later commands; it exits after 10 idle minutes (`--minutes N`), `session stop` ends it. Commands behave identically with or without it.
@@ -159,9 +159,9 @@ combination so tests and scenarios reuse it.
159
159
 
160
160
  ## 10. MCP server: Claude Code, Cursor and other MCP clients
161
161
  `npx threedog mcp` runs the dev bridge as an MCP server over stdio. Each command becomes a tool (`play`, `status`, `describe`, `step`, `press`, `hold`, `skip`, `state`, `ops`,
162
- `op`, `catalog`, `inspect`, `scene`, `pick`, `thing`, `explain`, `errors`, `loading`, `snap`, `snap_describe`, `scenario`, `verify`, `reload`, `resume`;
162
+ `op`, `catalog`, `inspect`, `scene`, `pick`, `thing`, `explain`, `errors`, `loading`, `snap`, `snap_describe`, `style_palette`, `style_compare`, `scenario`, `verify`, `reload`, `resume`;
163
163
  tests/mcp.mjs fails when this list and the server's tools differ) and returns the same text as the
164
- command line; `snap` also returns the PNG as an image. It finds the dev server through `.threedog/dev.json` like the CLI; with none running, call the `play` tool (it starts the server and waits for the bridge)
164
+ command line; `snap` also returns the PNG as an image, 480 px wide by default (`size` for more; the full file is saved). `style_palette` and `style_compare` need no game (recipe 35). It finds the dev server through `.threedog/dev.json` like the CLI; with none running, call the `play` tool (it starts the server and waits for the bridge)
165
165
  (or start `npm run dev` yourself; a tool call without a server answers with that fix). It is only a local client of the bridge and opens no port; every check in section 5 still applies. As
166
166
  with the command line, the `op` and `step` tools change the current session and its saves; the level itself changes only by editing content files.
167
167
 
@@ -60,7 +60,7 @@ engine.world.present('crop', {
60
60
  build(rec) {
61
61
  const m = new THREE.Mesh(geo, makeMaterial('prop', { color: 0x6aa84f }));
62
62
  m.castShadow = true;
63
- m.userData.use = engine.interactions.add(m, { label: '收获', radius: 2, enabled: () => growth(rec) >= 1, onUse: () => harvest(rec) }); // can be harvested only when ripe
63
+ m.userData.use = engine.interactions.add(m, { label: 'Harvest', radius: 2, enabled: () => growth(rec) >= 1, onUse: () => harvest(rec) }); // can be harvested only when ripe
64
64
  return m;
65
65
  },
66
66
  update(rec, obj) { // grows bigger, changes color when ripe
@@ -80,6 +80,9 @@ function plant(x, z) { // the player plants one
80
80
  return engine.world.add({ kind: 'crop', position: { x, y: engine.surface(x, z), z }, plantedAt: engine.clock.now });
81
81
  }
82
82
  ```
83
+ The same "store when, derive the rest" pattern fits any timed thing: an enemy camp that respawns (`clearedAt`), a turret or machine cooldown
84
+ (`usedAt`), a door that shuts again (`openedAt`):
85
+ `const ready = rec => engine.clock.now - rec.usedAt >= rec.cooldown; // no per-step counter, correct after skip and load`
83
86
  Test: `plant(2, 2)` -> `engine.step(130)` (fast-forward 130 game seconds) -> the player walks next to it -> `engine.ops.run('interaction.use')` ->
84
87
  `engine.inventory.count('carrot')`.
85
88
 
@@ -157,7 +160,7 @@ function wander(rec, dt) {
157
160
  depend on how fast the machine is.
158
161
  - The owed time and the simulation step count are saved: after loading they are caught up the same way, and the same save gives the same result
159
162
  however many fixed steps run per frame. For things measured by game clock (grows in a few days, respawns at a time), record `engine.clock.now` and compare.
160
- - **Far in workers** (many far records, e.g. thousands of crops): `W.simulate('crop', { far, worker: true })`. Each step's far batch is copied and run
163
+ - **Far in workers** (many far records, e.g. thousands of crops, spawners or machines): `W.simulate('crop', { far, worker: true })`. Each step's far batch is copied and run
161
164
  in `engine.threads` workers, then written back 4 fixed steps later through `engine.commits`; if a reply is late the same function runs on the main
162
165
  thread, so threads on / off / slow give **bit-identical** records. Only fields far changed are written back (gameplay changes to other fields during
163
166
  those 4 steps are kept). `far` must be self-contained: it is recompiled from source and sees only `(rec, dt)` and globals like `Math`; an outside
@@ -1,6 +1,7 @@
1
- # Shooting and picking (first person; cast a ray from the screen center / mouse position)
1
+ # Shooting and picking (cast a ray from the screen center or the mouse position, with any camera)
2
2
 
3
- Requires `openWorld({ camera: 'firstPerson' })` (or `firstPersonCamera()` by hand); a score display needs `hud()`.
3
+ 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
+ use the same ray. The example below is the first-person case; a score display needs `hud()`.
4
5
  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
5
6
  returns the nearest hit `{ point, distance, object, ... }` or null. **If you only want to hit your own targets, pass `targets: [array of objects]`; no
6
7
  ray registration is needed.**
@@ -8,12 +9,12 @@ ray registration is needed.**
8
9
  ## 1. A first-person shooting range (copy it and it runs)
9
10
  ```js
10
11
  import { createEngine, presets, openWorld, hud, THREE, makeMaterial } from 'threedog';
11
- import lowpoly from '@threedog/style-lowpoly';
12
+ import style from './style/index.js'; // the game's own style pack
12
13
  import { terrainPreset } from '@threedog/terrain-noise';
13
14
 
14
- const engine = createEngine({ canvas: document.getElementById('view'), style: lowpoly, saveKey: 'range' });
15
+ const engine = createEngine({ canvas: document.getElementById('view'), style, saveKey: 'range' });
15
16
  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 })
16
- engine.input.define('shoot', ['Mouse0', 'KeyF'], '开枪'); // the left mouse button is a key too (Mouse0 / Mouse1 / Mouse2); either it or KeyF works
17
+ engine.input.define('shoot', ['Mouse0', 'KeyF'], 'Shoot'); // the left mouse button is a key too (Mouse0 / Mouse1 / Mouse2); either it or KeyF works
17
18
  engine.characters.createPlayer({ ...presets.player.aim, spawn: engine.characters.findSpawn([0, 0, 0], { minH: 3, maxH: 14 }) });
18
19
  await engine.start(); // place targets after the terrain is generated
19
20
 
@@ -29,7 +30,7 @@ const p0 = engine.player.position;
29
30
  for (let i = 0; i < 6; i++) addTarget(p0.x + (i - 2.5) * 3, p0.z - 15);
30
31
 
31
32
  let score = 0;
32
- engine.hud.counter('score', { label: '命中', value: 0 });
33
+ engine.hud.counter('score', { label: 'Hits', value: 0 });
33
34
  engine.describe.add('range', () => ({ score, targets: targets.length })); // visible with the dev bridge: threedog describe range
34
35
 
35
36
  engine.onFixed(() => { // firing is gameplay: read it in fixed so the result is independent of frame rate
@@ -51,8 +52,8 @@ engine.onFixed(() => { // firing is gameplay:
51
52
  - **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
52
53
  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
53
54
  camera delivers it too.
54
- - **Adding a gamepad button**: `engine.input.define('shoot', ['Mouse0', 'KeyF', 'PadRT'], '开枪')`; the key names go into the settings key table and the
55
- UI prompts. A touch tap does not count as `Mouse0` (give phones a button: `engine.input.touchButton('shoot', '开枪')`).
55
+ - **Adding a gamepad button**: `engine.input.define('shoot', ['Mouse0', 'KeyF', 'PadRT'], 'Shoot')`; the key names go into the settings key table and the
56
+ UI prompts. A touch tap does not count as `Mouse0` (give phones a button: `engine.input.touchButton('shoot', 'Shoot')`).
56
57
  - To hit terrain / houses / registered static objects, don't pass `targets` (the default hits what was registered with `rays.addStatic`); to hit rigid
57
58
  bodies too, pass `targets: 'all'`.
58
59