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.
- package/README.md +4 -4
- package/core/Assets.js +12 -0
- package/core/Engine.js +13 -4
- package/core/describeRender.js +7 -1
- package/core/grid.js +127 -0
- package/core/gridLoad.js +19 -0
- package/core/loop.js +7 -2
- package/core/renamed.js +1 -0
- package/core/styleParts.js +9 -7
- package/docs/AI.md +28 -23
- package/docs/API.md +3 -3
- package/docs/CODEMAP.md +5 -3
- package/docs/COMMANDS.md +5 -3
- package/docs/CONVENTIONS.md +6 -6
- package/docs/api/assets.md +1 -0
- package/docs/api/characters.md +3 -2
- package/docs/api/engine.md +3 -3
- package/docs/api/style.md +7 -7
- package/docs/api/tools.md +3 -2
- package/docs/api/vegetation.md +1 -0
- package/docs/recipes/01-new-game.md +41 -43
- package/docs/recipes/02-npc.md +24 -24
- package/docs/recipes/03-items-pickups.md +4 -4
- package/docs/recipes/04-quests.md +23 -23
- package/docs/recipes/05-props-bake.md +5 -5
- package/docs/recipes/07-flow-scenes-pause.md +2 -2
- package/docs/recipes/08-weather-sky.md +5 -5
- package/docs/recipes/09-style-pack.md +35 -100
- package/docs/recipes/13-animation.md +22 -6
- package/docs/recipes/14-custom-module.md +6 -7
- package/docs/recipes/15-perf.md +8 -0
- package/docs/recipes/16-dev-bridge.md +7 -7
- package/docs/recipes/18-world.md +5 -2
- package/docs/recipes/19-shooting-picking.md +9 -8
- package/docs/recipes/20-content-actions-save.md +10 -10
- package/docs/recipes/22-shop-gold.md +16 -16
- package/docs/recipes/23-ops.md +2 -2
- package/docs/recipes/27-net.md +2 -2
- package/docs/recipes/28-terrain.md +2 -2
- package/docs/recipes/29-grid.md +47 -27
- package/docs/recipes/34-environment-lighting.md +2 -2
- package/docs/recipes/35-style-from-reference.md +41 -46
- package/docs/recipes/36-sky-ground-plant-looks.md +22 -20
- package/docs/recipes/37-terrain-look-hooks.md +34 -13
- package/docs/recipes/38-environment-look-hooks.md +47 -42
- package/docs/recipes/42-terrain-shape.md +1 -1
- package/docs/recipes/43-shader-patches-surface-looks.md +35 -20
- package/docs/recipes/44-water-weather-look-hooks.md +5 -5
- package/docs/recipes/45-cascaded-shadows.md +1 -1
- package/docs/recipes/46-blender-art-route.md +4 -4
- package/docs/recipes/47-island-snow-backdrop.md +4 -3
- package/docs/recipes/48-make-material.md +2 -2
- package/docs/recipes/49-game-module-contract.md +25 -25
- package/docs/recipes/51-capability-catalog.md +2 -2
- package/docs/recipes/52-look.md +43 -5
- package/docs/recipes/53-ground-up-close.md +58 -0
- package/examples/action/GAMEMAP.md +2 -2
- package/examples/action/main.js +3 -2
- package/examples/sheepisland/GAMEMAP.md +1 -1
- package/examples/styletest/content/npcs.js +1 -1
- package/examples/styletest/main.js +1 -1
- package/examples/world/content/npcs.js +1 -1
- package/examples/world/main.js +1 -1
- package/index.d.ts +8 -2
- package/index.js +3 -2
- package/llms.txt +9 -8
- package/modules/characters/Character.js +21 -19
- package/modules/characters/assetModel.js +35 -7
- package/modules/characters/proceduralRig.js +45 -10
- package/modules/content/index.js +1 -1
- package/modules/gameplay/pickups.js +1 -1
- package/modules/vegetation/Vegetation.js +15 -3
- package/modules/vegetation/index.js +1 -1
- package/modules/vegetation/nearFade.js +39 -0
- package/package.json +2 -1
- package/render/detail.js +39 -15
- package/types/core.d.ts +7 -5
- package/types/gameplay.d.ts +12 -6
- package/types/style.d.ts +20 -15
- package/types/world.d.ts +7 -1
package/README.md
CHANGED
|
@@ -5,28 +5,28 @@ A web 3D game engine on three.js 0.187: **core** (rendering, main loop, input, a
|
|
|
5
5
|
## Install
|
|
6
6
|
```sh
|
|
7
7
|
npm install threedog three@~0.187.0
|
|
8
|
-
npm install @threedog/style-lowpoly # optional: the low-poly style pack (the engine ships no art)
|
|
9
8
|
npm install @threedog/terrain-noise # optional: the noise terrain generator terrainPreset() (without one the ground is flat)
|
|
10
9
|
npm install -D vite @threedog/tools # optional: the vite preset and the threedog command line
|
|
11
10
|
```
|
|
11
|
+
Or let it set up the folder: `npx threedog init` (flags: `--example` for a small gameplay sample, `--style empty|<path-or-package>`; the default is a clean start with an empty style pack in `style/`) writes index.html, main.js, vite.config.js, content/, CLAUDE.md and `.mcp.json` (Claude Code then starts the threedog MCP server by itself), never overwriting a file you have.
|
|
12
12
|
`three` is a peer dependency: your game and the engine share one copy. Types for three come with the engine (`@types/three`, same version), so `// @ts-check` JS and TypeScript both see real three.js types.
|
|
13
13
|
|
|
14
14
|
## Minimal usage
|
|
15
15
|
```js
|
|
16
16
|
import { createEngine, presets, openWorld } from 'threedog';
|
|
17
|
-
import lowpoly from '@threedog/style-lowpoly'; // optional style pack (npm install @threedog/style-lowpoly)
|
|
18
17
|
import { terrainPreset } from '@threedog/terrain-noise'; // optional terrain generator (npm install @threedog/terrain-noise)
|
|
19
18
|
|
|
20
|
-
const engine = createEngine({ canvas: document.getElementById('view')
|
|
19
|
+
const engine = createEngine({ canvas: document.getElementById('view') }); // no style pack: gray placeholders
|
|
21
20
|
engine.use(openWorld({ camera: 'follow', seed: 7, terrain: terrainPreset() }));
|
|
22
21
|
engine.characters.createPlayer({ ...presets.player.thirdPerson });
|
|
23
22
|
engine.start();
|
|
24
23
|
```
|
|
24
|
+
A look is a style pack you pass in (yours or a published one): `createEngine({ canvas, style: yourPack })`.
|
|
25
25
|
`vite.config.js` with the preset: `import { gameConfig } from '@threedog/tools/vite'; export default gameConfig(import.meta.dirname);`
|
|
26
26
|
|
|
27
27
|
## Entry points
|
|
28
28
|
- `threedog`: the whole public API (`THREE` is re-exported, so `import { THREE } from 'threedog'` is the same three instance).
|
|
29
|
-
- Style packs are separate packages: the engine ships no art
|
|
29
|
+
- Style packs are separate packages (yours or published): the engine ships no art (visuals only; the noise terrain generator `terrainPreset()` is `@threedog/terrain-noise`); without a style pack everything is a neutral gray placeholder.
|
|
30
30
|
- `threedog/error-hints`: the developer error hint table (used by `@threedog/tools`).
|
|
31
31
|
|
|
32
32
|
Nothing else is a public path; files under `core/`, `modules/` etc. may move between versions.
|
package/core/Assets.js
CHANGED
|
@@ -33,6 +33,7 @@ import { codedError, coded } from './errorHints.js';
|
|
|
33
33
|
import { Animator } from './Animator.js';
|
|
34
34
|
import { fetchEntry, freeEntry, preloadEntries } from './assetEntry.js';
|
|
35
35
|
import { registerManifest } from './assetManifest.js';
|
|
36
|
+
import { loadGrid } from './gridLoad.js';
|
|
36
37
|
|
|
37
38
|
const STRINGS = {
|
|
38
39
|
noFont: 'assets.font(\'{name}\'): no font named {name}{known}. Register the file in an asset pack: engine.assets.manifest({ fonts: { {name}: \'/fonts/{name}.woff2\' } })',
|
|
@@ -181,6 +182,17 @@ export class Assets {
|
|
|
181
182
|
return this._fetch(v);
|
|
182
183
|
}
|
|
183
184
|
|
|
185
|
+
/**
|
|
186
|
+
* An image as grid data for sampleGrid (height map, moisture, density, walkable mask...): { data: Float32Array, width, height, bits }. Name or path.
|
|
187
|
+
* PNG is read at full precision (8 or 16 bits, grayscale or color); jpg / webp give 8 bits. channel: 'r' (default) 'g' 'b' 'a' or 0-3.
|
|
188
|
+
* range: [min, max] the pixel values map to (default [0, 1]; pass world units, e.g. [-5, 60] meters). bits: 8 reads only the high byte of a 16-bit file.
|
|
189
|
+
* @example const g = await engine.assets.gridFromImage('/maps/height.png', { range: [-5, 60] }); const h = sampleGrid(g.data, { ...g, size: [512, 512] });
|
|
190
|
+
* @param {string} nameOrUrl
|
|
191
|
+
* @param {{ channel?: 'r' | 'g' | 'b' | 'a' | number, range?: [number, number], bits?: 8 | 16 }} [opts]
|
|
192
|
+
* @returns {Promise<{ data: Float32Array, width: number, height: number, bits: number }>}
|
|
193
|
+
*/
|
|
194
|
+
gridFromImage(nameOrUrl, opts = {}) { return loadGrid(this.entries.get(nameOrUrl)?.url ?? nameOrUrl, opts); }
|
|
195
|
+
|
|
184
196
|
/**
|
|
185
197
|
* Release an asset and return its GPU memory (reloaded on next use). A texture is released together with all its opts variants.
|
|
186
198
|
* A model with copies still in the scene is not released yet; it is freed when the last copy is engine.remove'd (copies in use are never broken)
|
package/core/Engine.js
CHANGED
|
@@ -26,7 +26,7 @@ import { createMovement } from './movement.js';
|
|
|
26
26
|
import { moduleMethods } from './modules.js';
|
|
27
27
|
import { skipMethods } from './skip.js';
|
|
28
28
|
import { checkMethods } from './checks.js';
|
|
29
|
-
import { styleFrom, NO_STYLE } from './styleParts.js';
|
|
29
|
+
import { styleFrom, NO_STYLE, styleIsEmpty } from './styleParts.js';
|
|
30
30
|
import { canvasBox, placeUI, resizeMethods } from './canvasBox.js';
|
|
31
31
|
import { sceneMethods } from './sceneMethods.js';
|
|
32
32
|
import { recordRender } from './describeRender.js';
|
|
@@ -37,6 +37,15 @@ const ENGINE_OPTIONS = ['canvas', 'style', 'shadows', 'shadowType', 'antialias',
|
|
|
37
37
|
'fov', 'near', 'fogFar',
|
|
38
38
|
'locale', 'strings', 'bindings', 'saveKey', 'joystick', 'padBindings', 'headless', 'validate', 'decoders', 'budget', 'urlState', 'seed', 'movement', 'threads', 'pauseOnBlur', 'batching', 'lights', 'renderer'];
|
|
39
39
|
|
|
40
|
+
/**
|
|
41
|
+
* Default render scale. High tier: the display scale up to 1.5. Low tier: at least 0.75 x display scale (1.5 on a 2x screen; a fixed 1 there
|
|
42
|
+
* would be an upscaled blurry picture), never above 1.5 or the display scale.
|
|
43
|
+
*/
|
|
44
|
+
export function defaultPixelRatio(dpr, tier) {
|
|
45
|
+
const cap = Math.min(dpr, 1.5);
|
|
46
|
+
return tier === 'low' ? Math.min(cap, Math.max(1, +(0.75 * dpr).toFixed(2))) : cap;
|
|
47
|
+
}
|
|
48
|
+
|
|
40
49
|
export class Engine {
|
|
41
50
|
/**
|
|
42
51
|
* @param o createEngine options: each option, its default and meaning is documented once on EngineOptions (types/core.d.ts).
|
|
@@ -53,12 +62,12 @@ export class Engine {
|
|
|
53
62
|
const canvas = canvasIn ?? rendererIn?.domElement;
|
|
54
63
|
this.movement = createMovement(movement); // character radius / height / slope / step height: the single copy shared by collision, physics and nav
|
|
55
64
|
const style = this.style = styleFrom(styleIn); // a list of parts is deep-merged (styleParts.js); one object is used as is
|
|
56
|
-
if (
|
|
65
|
+
if (styleIsEmpty(opts.style)) warnOnce(NO_STYLE);
|
|
57
66
|
// a game-supplied renderer is used as is: the engine configures (pixel ratio, size, tone mapping, shadows) only a renderer it created itself
|
|
58
67
|
const owned = !rendererIn;
|
|
59
68
|
const r = this.renderer = rendererIn ?? new THREE.WebGLRenderer({ canvas, antialias: false, powerPreference: 'high-performance' });
|
|
60
69
|
this.tier = detectTier(r); // 'low' | 'high': device tier, decides default quality
|
|
61
|
-
if (owned || pixelRatio != null) r.setPixelRatio(pixelRatio ??
|
|
70
|
+
if (owned || pixelRatio != null) r.setPixelRatio(pixelRatio ?? defaultPixelRatio(devicePixelRatio || 1, this.tier));
|
|
62
71
|
this._autoSize = undefined; // decided once the canvas is in the page (sizeMode): true = no CSS size, the engine sizes it to the window
|
|
63
72
|
const box = canvasBox(this);
|
|
64
73
|
if (owned) r.setSize(box.w, box.h, !!this._autoSize);
|
|
@@ -135,7 +144,7 @@ export class Engine {
|
|
|
135
144
|
defineCoreParts(this);
|
|
136
145
|
this.ui.get('loading')?.show({});
|
|
137
146
|
this.adaptive = { paused: false, on: adaptiveResolution && !headless, target: targetFps, min: 0.6, max: r.getPixelRatio(),
|
|
138
|
-
t: 0, n: 0, good: 0, cooldown: 0 };
|
|
147
|
+
t: 0, n: 0, good: 0, cooldown: 0, lowered: false, from: null };
|
|
139
148
|
// follow the canvas's own CSS box, not the window: a canvas in a page section or editor panel renders at its own size.
|
|
140
149
|
// The window event stays for a canvas outside the page (no box, falls back to the window) and for moves that do not resize the canvas
|
|
141
150
|
addEventListener('resize', () => this._resize(), { signal: this.signal });
|
package/core/describeRender.js
CHANGED
|
@@ -41,5 +41,11 @@ export function describeRender(e) {
|
|
|
41
41
|
const dv0 = e.debug?.viewState?.(), dv = dv0 && dv0.mode !== 'off' ? dv0 : null;
|
|
42
42
|
if (dv) text = `DEBUG VIEW "${dv.mode}" (by ${dv.owner}) is ON: ${dv.what}. This is NOT the real look; the debug view 'off' restores it.
|
|
43
43
|
` + text;
|
|
44
|
-
|
|
44
|
+
// render scale: the canvas resolution against the display. auto: the adaptive resolution lowered it at some point (it raises it back when frames are fast)
|
|
45
|
+
const dpr = (typeof devicePixelRatio === 'number' && devicePixelRatio) || 1, cur = r.getPixelRatio(), ad = e.adaptive;
|
|
46
|
+
const scale = { current: Math.round(cur * 100) / 100, devicePixelRatio: dpr, upscaled: cur < dpr - 0.01, autoLowered: !!ad?.lowered && cur < (ad.max ?? cur) - 0.01,
|
|
47
|
+
adaptive: !!ad?.on, floor: ad?.min ?? null, max: ad?.max ?? null };
|
|
48
|
+
text += `
|
|
49
|
+
render scale: ${scale.current} of device pixel ratio ${dpr}${scale.upscaled ? ' (picture is upscaled, softer than the screen)' : ''}${scale.autoLowered ? ` (auto-lowered by adaptive resolution, floor ${scale.floor}; adaptiveResolution: false turns it off)` : ''}`;
|
|
50
|
+
return { debugView: dv, scale, toneMapping: tone, exposure, shadows, post, lights, text };
|
|
45
51
|
}
|
package/core/grid.js
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
// 2D grid fields: sampleGrid turns an array of numbers laid out on a regular grid into a function (x, z) -> value, and gridFromPixels / decodePng read
|
|
2
|
+
// an image into such an array. A grid can hold any field of the ground plane: height, moisture, ground-type weight, density, a walkable mask, danger, cost.
|
|
3
|
+
// No three.js and no DOM here (DecompressionStream exists in browsers and Node), so it runs in tests and workers alike.
|
|
4
|
+
|
|
5
|
+
const CHANNELS = { r: 0, g: 1, b: 2, a: 3 };
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Turn grid data into a function (x, z) -> value in world units.
|
|
9
|
+
* data[j * width + i] is the value at world (origin[0] + i * cell, origin[1] + j * cell): samples sit on the grid nodes, so a grid of
|
|
10
|
+
* `width` samples spans (width - 1) cells. Give the node spacing as cellSize (a number, or [sx, sz]) or the whole extent as size [sx, sz].
|
|
11
|
+
* Outside the grid the nearest edge value is used, or `outside` when given (a number, e.g. a sea-floor height or 0 for "not walkable").
|
|
12
|
+
*
|
|
13
|
+
* interp picks the look of the field between nodes (none of them is the right one; they suit different looks):
|
|
14
|
+
* 'nearest' flat steps, one value per cell: blocky or terraced ground, tile-like masks, ids stored as numbers
|
|
15
|
+
* 'linear' (default) plain bilinear blend: smooth enough for most fields, cheap, never leaves the range of the four corners
|
|
16
|
+
* 'cubic' Catmull-Rom bicubic: smooth slopes without visible cell creases; it can overshoot near sharp steps, clamp: true keeps the result
|
|
17
|
+
* inside the range of the four corner samples
|
|
18
|
+
* @param {ArrayLike<number>} data
|
|
19
|
+
* @param {{ width: number, height: number, cellSize?: number | [number, number], size?: [number, number], origin?: [number, number],
|
|
20
|
+
* interp?: 'nearest' | 'linear' | 'cubic', clamp?: boolean, outside?: number }} opts
|
|
21
|
+
* @returns {(x: number, z: number) => number}
|
|
22
|
+
* @example const wet = sampleGrid(moisture, { width: 64, height: 64, size: [256, 256], origin: [-128, -128] }); wet(12, -40)
|
|
23
|
+
*/
|
|
24
|
+
export function sampleGrid(data, opts = {}) {
|
|
25
|
+
const { width, height, interp = 'linear', clamp = false, outside } = opts;
|
|
26
|
+
if (!data || !(width >= 1) || !(height >= 1) || !Number.isInteger(width) || !Number.isInteger(height)) throw new Error('sampleGrid(data, { width, height }): width and height are whole numbers >= 1');
|
|
27
|
+
if (data.length < width * height) throw new Error(`sampleGrid: data has ${data.length} values, but width * height is ${width * height}`);
|
|
28
|
+
if (!['nearest', 'linear', 'cubic'].includes(interp)) throw new Error(`sampleGrid: interp '${interp}' is not one of 'nearest', 'linear', 'cubic'`);
|
|
29
|
+
const [ox, oz] = opts.origin || [0, 0];
|
|
30
|
+
let cx, cz;
|
|
31
|
+
if (opts.size) { cx = opts.size[0] / Math.max(1, width - 1); cz = opts.size[1] / Math.max(1, height - 1); }
|
|
32
|
+
else if (Array.isArray(opts.cellSize)) [cx, cz] = opts.cellSize;
|
|
33
|
+
else if (opts.cellSize != null) cx = cz = opts.cellSize;
|
|
34
|
+
else throw new Error('sampleGrid: give cellSize (node spacing in world units) or size: [sx, sz] (the whole extent)');
|
|
35
|
+
if (!(cx > 0) || !(cz > 0)) throw new Error('sampleGrid: cellSize / size must be greater than 0');
|
|
36
|
+
const W = width, H = height, at = (i, j) => data[(j < 0 ? 0 : j >= H ? H - 1 : j) * W + (i < 0 ? 0 : i >= W ? W - 1 : i)];
|
|
37
|
+
const hasOut = typeof outside === 'number';
|
|
38
|
+
// Catmull-Rom weights through p0..p3 at t in [0, 1] (passes through p1 at 0 and p2 at 1)
|
|
39
|
+
const cr = (a, b, c, d, t) => b + 0.5 * t * (c - a + t * (2 * a - 5 * b + 4 * c - d + t * (3 * (b - c) + d - a)));
|
|
40
|
+
return (x, z) => {
|
|
41
|
+
const gx = (x - ox) / cx, gz = (z - oz) / cz;
|
|
42
|
+
if (hasOut && (gx < 0 || gz < 0 || gx > W - 1 || gz > H - 1)) return outside;
|
|
43
|
+
if (interp === 'nearest') return at(Math.round(gx), Math.round(gz));
|
|
44
|
+
const fx = Math.floor(gx), fz = Math.floor(gz), tx = gx - fx, tz = gz - fz;
|
|
45
|
+
const a = at(fx, fz), b = at(fx + 1, fz), c = at(fx, fz + 1), d = at(fx + 1, fz + 1);
|
|
46
|
+
if (interp === 'linear') return (a + (b - a) * tx) * (1 - tz) + (c + (d - c) * tx) * tz;
|
|
47
|
+
const row = j => cr(at(fx - 1, j), at(fx, j), at(fx + 1, j), at(fx + 2, j), tx);
|
|
48
|
+
const v = cr(row(fz - 1), row(fz), row(fz + 1), row(fz + 2), tz);
|
|
49
|
+
return clamp ? Math.min(Math.max(v, Math.min(a, b, c, d)), Math.max(a, b, c, d)) : v;
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Channel name or index -> index (r g b a, or 0-3) */
|
|
54
|
+
function channelIndex(channel) {
|
|
55
|
+
const i = typeof channel === 'string' ? CHANNELS[channel.toLowerCase()] : channel;
|
|
56
|
+
if (!Number.isInteger(i) || i < 0 || i > 3) throw new Error(`gridFromImage: channel '${channel}' is not 'r', 'g', 'b', 'a' or 0-3`);
|
|
57
|
+
return i;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Pixels -> grid data. samples is the interleaved channel array of an image (Uint8Array, or Uint16Array for 16-bit), channels per pixel as given.
|
|
62
|
+
* Values map linearly from 0..maxValue to range [min, max] (default [0, 1]).
|
|
63
|
+
* @param {{ samples: ArrayLike<number>, width: number, height: number, channels: number, bitDepth: number }} img
|
|
64
|
+
* @param {{ channel?: 'r' | 'g' | 'b' | 'a' | number, range?: [number, number], bits?: 8 | 16 }} [opts]
|
|
65
|
+
* @returns {{ data: Float32Array, width: number, height: number, bits: number }}
|
|
66
|
+
*/
|
|
67
|
+
export function gridFromPixels(img, { channel = 0, range = [0, 1], bits } = {}) {
|
|
68
|
+
const ch = channelIndex(channel), n = img.width * img.height, bd = img.bitDepth;
|
|
69
|
+
if (ch >= img.channels) throw new Error(`gridFromImage: the image has ${img.channels} channel(s), so channel ${ch} does not exist`);
|
|
70
|
+
const want = bits ?? (bd === 16 ? 16 : 8);
|
|
71
|
+
if (want !== 8 && want !== 16) throw new Error('gridFromImage: bits is 8 or 16');
|
|
72
|
+
const [lo, hi] = range, data = new Float32Array(n);
|
|
73
|
+
// asking for 8 bits from a 16-bit image keeps only the high byte (the stepped look of an 8-bit file); asking for 16 from 8 bits just stretches it
|
|
74
|
+
const shift = bd === 16 && want === 8 ? 8 : 0, max = want === 16 ? 65535 : 255, src = img.samples;
|
|
75
|
+
for (let i = 0; i < n; i++) {
|
|
76
|
+
let v = src[i * img.channels + ch];
|
|
77
|
+
if (shift) v >>= shift; else if (bd === 8 && want === 16) v *= 257;
|
|
78
|
+
data[i] = lo + (v / max) * (hi - lo);
|
|
79
|
+
}
|
|
80
|
+
return { data, width: img.width, height: img.height, bits: want };
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
async function inflate(bytes) {
|
|
84
|
+
const s = new Blob([bytes]).stream().pipeThrough(new DecompressionStream('deflate'));
|
|
85
|
+
return new Uint8Array(await new Response(s).arrayBuffer());
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Decode a PNG (not interlaced; grayscale, gray+alpha, RGB, RGBA, 8 or 16 bits). Browsers' canvas flattens 16-bit images to 8, so height maps that
|
|
90
|
+
* need the full 16 bits are read here. Palette images and interlaced files throw with the way out.
|
|
91
|
+
* @param {Uint8Array | ArrayBuffer} input
|
|
92
|
+
* @returns {Promise<{ samples: Uint8Array | Uint16Array, width: number, height: number, channels: number, bitDepth: number }>}
|
|
93
|
+
*/
|
|
94
|
+
export async function decodePng(input) {
|
|
95
|
+
const b = input instanceof Uint8Array ? input : new Uint8Array(input), dv = new DataView(b.buffer, b.byteOffset, b.byteLength);
|
|
96
|
+
if (b.length < 33 || dv.getUint32(0) !== 0x89504e47) throw new Error('decodePng: not a PNG file');
|
|
97
|
+
let width = 0, height = 0, bitDepth = 0, colorType = 0, interlace = 0, p = 8;
|
|
98
|
+
const idat = [];
|
|
99
|
+
while (p + 8 <= b.length) {
|
|
100
|
+
const len = dv.getUint32(p), type = String.fromCharCode(b[p + 4], b[p + 5], b[p + 6], b[p + 7]), d = p + 8;
|
|
101
|
+
if (type === 'IHDR') { width = dv.getUint32(d); height = dv.getUint32(d + 4); bitDepth = b[d + 8]; colorType = b[d + 9]; interlace = b[d + 12]; }
|
|
102
|
+
else if (type === 'IDAT') idat.push(b.subarray(d, d + len));
|
|
103
|
+
else if (type === 'IEND') break;
|
|
104
|
+
p = d + len + 4;
|
|
105
|
+
}
|
|
106
|
+
if (interlace) throw new Error('decodePng: interlaced PNG is not supported; save it without interlacing');
|
|
107
|
+
if (colorType === 3) throw new Error('decodePng: palette PNG is not supported; save it as grayscale or RGB');
|
|
108
|
+
if (bitDepth !== 8 && bitDepth !== 16) throw new Error(`decodePng: ${bitDepth}-bit PNG is not supported; use 8 or 16 bits per channel`);
|
|
109
|
+
const channels = { 0: 1, 2: 3, 4: 2, 6: 4 }[colorType];
|
|
110
|
+
if (!channels) throw new Error(`decodePng: color type ${colorType} is not supported`);
|
|
111
|
+
const all = new Uint8Array(idat.reduce((s, c) => s + c.length, 0));
|
|
112
|
+
let o = 0; for (const c of idat) { all.set(c, o); o += c.length; }
|
|
113
|
+
const raw = await inflate(all), bpp = channels * bitDepth / 8, stride = width * bpp, out = new Uint8Array(stride * height);
|
|
114
|
+
for (let y = 0; y < height; y++) {
|
|
115
|
+
const f = raw[y * (stride + 1)], s = y * (stride + 1) + 1, r = y * stride;
|
|
116
|
+
for (let x = 0; x < stride; x++) {
|
|
117
|
+
const a = x >= bpp ? out[r + x - bpp] : 0, up = y ? out[r - stride + x] : 0, c = x >= bpp && y ? out[r - stride + x - bpp] : 0, v = raw[s + x];
|
|
118
|
+
let add = 0;
|
|
119
|
+
if (f === 1) add = a; else if (f === 2) add = up; else if (f === 3) add = (a + up) >> 1;
|
|
120
|
+
else if (f === 4) { const pp = a + up - c, pa = Math.abs(pp - a), pb = Math.abs(pp - up), pc = Math.abs(pp - c); add = pa <= pb && pa <= pc ? a : pb <= pc ? up : c; }
|
|
121
|
+
out[r + x] = (v + add) & 255;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
let samples = out;
|
|
125
|
+
if (bitDepth === 16) { samples = new Uint16Array(width * height * channels); for (let i = 0; i < samples.length; i++) samples[i] = (out[i * 2] << 8) | out[i * 2 + 1]; }
|
|
126
|
+
return { samples, width, height, channels, bitDepth };
|
|
127
|
+
}
|
package/core/gridLoad.js
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
// Load an image file as grid data (assets.gridFromImage). PNG is decoded by decodePng (full 8 or 16 bits); other formats (jpg, webp) go through a
|
|
2
|
+
// canvas, which gives 8 bits per channel. Kept apart from grid.js because it needs fetch / DOM, grid.js does not.
|
|
3
|
+
import { decodePng, gridFromPixels } from './grid.js';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* @param {string} url
|
|
7
|
+
* @param {{ channel?: 'r' | 'g' | 'b' | 'a' | number, range?: [number, number], bits?: 8 | 16 }} [opts]
|
|
8
|
+
*/
|
|
9
|
+
export async function loadGrid(url, opts = {}) {
|
|
10
|
+
const res = await fetch(url);
|
|
11
|
+
if (!res.ok) throw new Error(`gridFromImage: could not load ${url} (${res.status})`);
|
|
12
|
+
const bytes = new Uint8Array(await res.arrayBuffer());
|
|
13
|
+
if (bytes[0] === 0x89 && bytes[1] === 0x50) return gridFromPixels(await decodePng(bytes), opts);
|
|
14
|
+
const bmp = await createImageBitmap(new Blob([bytes]));
|
|
15
|
+
const c = new OffscreenCanvas(bmp.width, bmp.height), g = c.getContext('2d');
|
|
16
|
+
g.drawImage(bmp, 0, 0);
|
|
17
|
+
const samples = g.getImageData(0, 0, bmp.width, bmp.height).data;
|
|
18
|
+
return gridFromPixels({ samples, width: bmp.width, height: bmp.height, channels: 4, bitDepth: 8 }, opts);
|
|
19
|
+
}
|
package/core/loop.js
CHANGED
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
// Determinism: in engine.step() and headless loading frames, jobs ignore the real-time budget and drain the queue (see Jobs.js),
|
|
14
14
|
// and stream's synchronous builds are attached to the scene before step returns: same input and same seed (engine.random) give the same result.
|
|
15
15
|
import { reportError } from './errors.js';
|
|
16
|
-
import { DEV } from './validate.js';
|
|
16
|
+
import { DEV, warnOnce } from './validate.js';
|
|
17
17
|
import { codedError } from './errorHints.js';
|
|
18
18
|
import { watchLights } from './lightWatch.js';
|
|
19
19
|
|
|
@@ -192,7 +192,12 @@ export const loopMethods = {
|
|
|
192
192
|
if (a.t < 1) return;
|
|
193
193
|
const fps = a.n / a.t; a.t = 0; a.n = 0;
|
|
194
194
|
const pr = this.renderer.getPixelRatio();
|
|
195
|
-
if (fps < a.target - 5 && pr > a.min + 0.01) {
|
|
195
|
+
if (fps < a.target - 5 && pr > a.min + 0.01) {
|
|
196
|
+
const to = Math.max(a.min, +(pr - 0.1).toFixed(2));
|
|
197
|
+
// never silent: the picture gets softer, and the game or an AI should know why (dev warning once; describe().render.scale keeps the facts)
|
|
198
|
+
if (!a.lowered) { a.lowered = true; a.from = pr; if (DEV) warnOnce(`render scale ${pr} -> ${to} because fps ${fps.toFixed(0)} is under ${a.target}; adaptive resolution lowers it down to ${a.min}. Turn off with createEngine({ adaptiveResolution: false }) or engine.adaptive.on = false; see describe().render.scale`); }
|
|
199
|
+
this.setPixelRatio(to); a.good = 0; a.cooldown = 5;
|
|
200
|
+
}
|
|
196
201
|
else if (fps >= a.target + 3 && pr < a.max - 0.01 && a.cooldown <= 0) {
|
|
197
202
|
if (++a.good >= 4) { this.setPixelRatio(Math.min(a.max, +(pr + 0.05).toFixed(2))); a.good = 0; }
|
|
198
203
|
} else a.good = 0;
|
package/core/renamed.js
CHANGED
|
@@ -17,5 +17,6 @@ export const RENAMED = {
|
|
|
17
17
|
lookClouds: { old: 'engine.look.clouds', now: 'engine.look.cloudShadow', find: '\\blook\\.clouds\\b' },
|
|
18
18
|
cameraOverride: { old: 'engine.cameraOverride = {...}', now: "const cam = engine.takeCamera('owner', { focus }); cam.remove() releases it", find: '\\bcameraOverride\\s*=(?!=)' },
|
|
19
19
|
viewsPos: { old: "views.define(name, { pos })", now: 'views.define(name, { position: [x, y, z] })', find: null },
|
|
20
|
+
characterBody: { old: 'style.character.create / .model / .colors (a character body or tint from the style pack)', now: "character bodies are assets: createPlayer({ model: 'yourBody' }) (a generator from an asset pack via engine.assets.manifest(yourAssets)), any GLB asset name, or { rig } for a ready body; part colors are the style's material roles skin / cloth / trousers / hair, or { colors } per character", find: '\\bstyle\\.character\\??\\.(create|model|colors)\\b|\\bcharacter:\\s*\\{[^}]*\\b(create|colors):' },
|
|
20
21
|
reason: { old: 'result.reason (ops.run / can / undo failures), ops.recent() / catalog(op).last / net:result .reason', now: 'result.code (the same name in history, catalog and net:result)', find: null },
|
|
21
22
|
};
|
package/core/styleParts.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
// A style built from parts: createEngine({ style: [
|
|
1
|
+
// A style built from parts: createEngine({ style: [basePack, { sky: mySky }, toonMaterials] }) merges the parts left to right into engine.style.
|
|
2
2
|
// Why parts and not one object: a look is often borrowed piecemeal (one pack's materials, another's sky, the game's own UI colors), and a
|
|
3
|
-
// spread `{ ...
|
|
3
|
+
// spread `{ ...basePack, sky }` loses basePack's other sky fields; a deep merge keeps them. Rules (one place; recipes/09-style-pack.md "Composing"):
|
|
4
4
|
// - parts merge left to right, later wins; nested arrays are flattened (a pack may itself be a list of parts); null / undefined / false parts are skipped
|
|
5
5
|
// - plain objects ({ } literals) merge key by key, recursively: { sky: { sunSize: 600 } } changes only sunSize
|
|
6
6
|
// - anything else replaces whole: arrays (sky.keyframes, post, terrain.steep), functions, numbers, strings, three.js objects and class instances
|
|
@@ -20,7 +20,7 @@ const edit = fn => ({ post: Object.assign(fn, { [EDIT]: true }) });
|
|
|
20
20
|
/**
|
|
21
21
|
* 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 as
|
|
22
22
|
* an earlier one replaces it in place; names are the effects' own ('bloom', 'ao', 'outline', or your own).
|
|
23
|
-
* @example createEngine({ style: [
|
|
23
|
+
* @example createEngine({ style: [basePack, postAdd(myGrain, bloom({ strength: 0.6 }))] }) // grain added, the pack's bloom swapped for yours
|
|
24
24
|
* @param {...import('../render/PostFX.js').PostEffect} effects
|
|
25
25
|
* @returns {{ post: any }}
|
|
26
26
|
*/
|
|
@@ -34,7 +34,7 @@ export function postAdd(...effects) {
|
|
|
34
34
|
|
|
35
35
|
/**
|
|
36
36
|
* A style part that removes post effects by name from the ones before it.
|
|
37
|
-
* @example createEngine({ style: [
|
|
37
|
+
* @example createEngine({ style: [basePack, postRemove('ao', 'outline')] })
|
|
38
38
|
* @param {...string} names
|
|
39
39
|
* @returns {{ post: any }}
|
|
40
40
|
*/
|
|
@@ -91,6 +91,8 @@ function checkStyleLooks(style) {
|
|
|
91
91
|
}
|
|
92
92
|
|
|
93
93
|
// Dev warning when createEngine gets no style pack (shown once from Engine.js)
|
|
94
|
-
export const NO_STYLE = 'createEngine():
|
|
95
|
-
+ 'directional light, no shadows, no tone mapping), gray background, ground, capsule characters and box props. This is not a look. '
|
|
96
|
-
+
|
|
94
|
+
export const NO_STYLE = 'createEngine(): the style pack is missing or empty, so everything is a neutral gray placeholder: plain lights (one white hemisphere + one neutral '
|
|
95
|
+
+ 'directional light, no shadows, no tone mapping), gray background, ground, capsule characters and box props. This is not a look and not an error. '
|
|
96
|
+
+ 'Fill your own pack (style/index.js in a new game; recipes/09-style-pack.md, recipes/52-look.md) or pass a published one';
|
|
97
|
+
/** true when createEngine got no style, or only empty parts ({} / [{}, {}]): the game has no look yet */
|
|
98
|
+
export const styleIsEmpty = st => !st || (Array.isArray(st) ? st.every(styleIsEmpty) : typeof st === 'object' && Object.keys(st).every(k => k === 'name')); // a name alone (the new-game empty pack) is still empty
|
package/docs/AI.md
CHANGED
|
@@ -14,7 +14,7 @@ This file is the index for the AI that builds a game on the engine. Paths are re
|
|
|
14
14
|
- Changing a look by editing `renderer` / `scene.fog` / materials directly, or in logic: `engine.look.<part>` (recipe 52), values in the style pack.
|
|
15
15
|
- Putting game content (dialogue, quests, items, layout) inside the engine package: it lives in the game's `content/`.
|
|
16
16
|
- Editing generated docs (GAMEMAP, API.md, api/, CODEMAP, `types/generated/`): change the code, run `npm run map`.
|
|
17
|
-
- Guessing a name: look it up in `api/<module>.md`;
|
|
17
|
+
- Guessing a name: look it up in `api/<module>.md`; engine errors carry `err.code` / `fix` / `docs`.
|
|
18
18
|
|
|
19
19
|
## What to read, in order (stop when you have enough)
|
|
20
20
|
1. This file: find the task in the entry table below.
|
|
@@ -23,8 +23,6 @@ This file is the index for the AI that builds a game on the engine. Paths are re
|
|
|
23
23
|
4. The game's own `GAMEMAP.md` (generated): what this game has, and "Read for this game".
|
|
24
24
|
5. When needed: `CODEMAP.md` · `THREE.md` (what the engine lacks: use three.js) · `PERF.md` · `COMMANDS.md` · `CONVENTIONS.md`.
|
|
25
25
|
|
|
26
|
-
What can I do here: `threedog catalog`, `threedog how "<task>"` (ranks these rows and recipes for a task in your own words).
|
|
27
|
-
|
|
28
26
|
## One thing, one entry point (don't build another)
|
|
29
27
|
Three outward concepts: **Scene** (what is in the world; content packs are part of it), **Assets** (models, textures, sounds, fonts),
|
|
30
28
|
**Style** (the look; material roles are labels inside it). Patches, ops and world records are the scene's inner machinery.
|
|
@@ -42,9 +40,11 @@ Three outward concepts: **Scene** (what is in the world; content packs are part
|
|
|
42
40
|
| Saved / far-away objects, the player record, stream in, teleport | `engine.world`, `player.placeAt()`, `engine.stream.add / teleport / source` | `recipes/18-world.md` |
|
|
43
41
|
| Blender level, grass and trees without terrain | `engine.level`, `npm run assets -- check`, `vegetation({ area })`, `engine.vegetation.rebuild()` | `recipes/10-blender-level.md` |
|
|
44
42
|
| Terrain generator, ground height, terrain editing | `terrain({ height, groundType })`, `terrainPreset()`, `engine.surface(x, z)`, `engine.ground`, `engine.terrain.edit()` | `recipes/28-terrain.md` |
|
|
43
|
+
| Ground up close: blurry ground, brush detail, near grass and its distance fade, blurry render scale (options, diagnosis) | `detail`, `colorResolution`, `fade`, `describe().render.scale` | `recipes/53-ground-up-close.md` |
|
|
45
44
|
| Ground color borders, mesh cut, lighting normals | `terrain({ shading: 'texture', colorResolution, normals, diagonal })` | `recipes/37-terrain-look-hooks.md` |
|
|
46
45
|
| Island, floating rock, world with an edge | `terrain({ shape: { mask, edge, side, bottom } })`, `engine.ground.has`, event `terrain:void` | `recipes/42-terrain-shape.md` |
|
|
47
|
-
| Grid placement,
|
|
46
|
+
| Grid placement, tile grid, player-changed ground, plots, dig, build on cells | `engine.grids.add / define`, `terrain.edit`, ops `grid.place / move / remove` | `recipes/29-grid.md` |
|
|
47
|
+
| Grid field as a function (height, moisture, density, walkable), read a grid from an image (PNG 8/16-bit) | `sampleGrid(data, { width, height, cellSize, origin, interp })`, `await engine.assets.gridFromImage(nameOrUrl, { channel, range, bits })` | `recipes/37-terrain-look-hooks.md` §7 |
|
|
48
48
|
| Collision, fences, rivers, physics, vehicles | `engine.collision` (`addSegment`, `addBlocked`, `lineClear`), `engine.rigid` | `recipes/11-vehicles.md` |
|
|
49
49
|
| Pathfinding, navmesh, "can walk there" | `engine.characters.findPath`, `engine.nav`, `createEngine({ movement })` | `recipes/12-navmesh.md` |
|
|
50
50
|
| Interaction prompts (talk, pick up, open a door or chest), trigger zones | `engine.interactions`, `interactions({ ...presets.interactions.nearest })`, `engine.triggers` | `recipes/20-content-actions-save.md` |
|
|
@@ -52,7 +52,7 @@ Three outward concepts: **Scene** (what is in the world; content packs are part
|
|
|
52
52
|
| NPCs and what they do, dialogue | content `npcs` (`behavior`), `engine.npcs.behavior`, content `dialogues`, `engine.dialogue` | `recipes/02-npc.md` |
|
|
53
53
|
| Items, pickups, inventory, chests, shops, gold | content `items` / `pickups`, `engine.inventory` (`container`, `transfer`), currency item + ops | `recipes/03-items-pickups.md`, `22-shop-gold.md` |
|
|
54
54
|
| Quests, objective markers | content `quests`, `engine.quests`, `engine.hud.marker()` | `recipes/04-quests.md` |
|
|
55
|
-
| Player and characters | `engine.player`, `
|
|
55
|
+
| Player and characters (bodies are assets) | `engine.player`, `createPlayer({ ...presets.player.thirdPerson, model: 'humanoid' })` (a generator from an asset pack; a GLB name; `{ rig }`; none = gray capsule) | `recipes/13-animation.md` |
|
|
56
56
|
| Camera, orthographic camera | `openWorld({ camera })` (required), `engine.setCamera(...)`, `engine.cameraRig`, `engine.takeCamera` | `recipes/21-camera.md` |
|
|
57
57
|
| Action game: hp, attacks, enemy AI, drops | your ops + `world.simulate` + `inventory.spawnPickup`; `examples/action/` | `recipes/32-action-game.md` |
|
|
58
58
|
| Use three.js directly, own renderer, no default lights | `engine.scene / renderer / camera`, `createEngine({ lights: false, renderer })` | `recipes/40-scene.md` §8, `50-own-renderer.md` |
|
|
@@ -69,13 +69,13 @@ Three outward concepts: **Scene** (what is in the world; content packs are part
|
|
|
69
69
|
| To do | Use | Recipe |
|
|
70
70
|
|---|---|---|
|
|
71
71
|
| Change any look at run time: tone, lights, fog, sky, clouds, shadow, wind, ground, water, weather, post | `engine.look.<part>.set / patch / replace` (`engine.catalog('look')`); own plain three.js: when to | `recipes/52-look.md`, `40-scene.md` §8 |
|
|
72
|
-
| Set the starting look: pack, materials, mixing packs, exposure, sky layers | style pack (`style: [
|
|
73
|
-
| Material and lighting shader patches, toon ramp, wind, fog hooks | `applyEffects`, `look.surface.patch`, `look.wind.patch`, `look.fog.patch` | `recipes/43-shader-patches-surface-looks.md`, `38-environment-look-hooks.md` |
|
|
72
|
+
| Set the starting look: pack, materials, mixing packs, exposure, sky layers | style pack (`style: [basePack, { sky }]`), `engine.makeMaterial('role', {...})`, `style.palette`, `postAdd` / `postRemove` | `recipes/09-style-pack.md`, `36-sky-ground-plant-looks.md`, `48-make-material.md` |
|
|
73
|
+
| Material and lighting shader patches, toon ramp, surface detail (grain, paper, strokes, dabs, texture, own glsl), colored shadows (shadowTint, rim, wrap), wind, fog hooks | `applyEffects`, `look.surface.patch`, `look.wind.patch`, `look.fog.patch` | `recipes/43-shader-patches-surface-looks.md`, `38-environment-look-hooks.md` |
|
|
74
74
|
| Water depth / foam, rain and snow shapes, own weather particles, snow cover, backdrop | `look.water`, `look.weather`, `style.weather.snow.cover`, `style.sky.backdrop` | `recipes/44-water-weather-look-hooks.md`, `47-island-snow-backdrop.md` |
|
|
75
75
|
| Shadows too blurry near the camera; shadow type | `look.shadow.set({ cascades: 3, type })` | `recipes/45-cascaded-shadows.md`, `15-perf.md` |
|
|
76
|
-
| Environment lighting (PBR reflections, HDR) | `look.env.replace('sky'
|
|
77
|
-
| Color grading, grain, vignette, DOF, outline, bloom | `@threedog/post-effects`, `postAdd(vignette())`, `engine.post`, `look.post.set` | `recipes/
|
|
78
|
-
| Many lights (torches, lamps, muzzle flashes) | `lightPool({ point })`, `engine.lightPool.add(obj, { color, intensity, distance, flicker })` | `recipes/09-style-pack.md` |
|
|
76
|
+
| Environment lighting (PBR reflections, HDR) | `look.env.replace('sky' \| asset \| false)`, `look.env.set({ intensity, rotation })` | `recipes/34-environment-lighting.md` |
|
|
77
|
+
| Color grading, grain, vignette, DOF, outline, bloom | `@threedog/post-effects`, `postAdd(vignette())`, `engine.post`, `look.post.set` | `recipes/52-look.md#post-effect-chain` |
|
|
78
|
+
| Many lights (torches, lamps, muzzle flashes) | `lightPool({ point })`, `engine.lightPool.add(obj, { color, intensity, distance, flicker })` | `recipes/09-style-pack.md` §1b |
|
|
79
79
|
| Day, night, seasons, sky, weather, water, isDay | `engine.sky` (`at / between / daily / onSeason`), `engine.weather`, `engine.water` | `recipes/08-weather-sky.md` |
|
|
80
80
|
| Who set tone / post / lights; why does it look like this | `engine.describe().look` (value, by, at), `describe().render`, `debug.view('albedo'\|'lighting'\|'shadow'\|'normals')` | `recipes/52-look.md`, `16-dev-bridge.md` |
|
|
81
81
|
| New style from a reference image | `threedog style palette <image>`, `npm run new-style`, `style check`, `style compare <ref> <shot>` | `recipes/35-style-from-reference.md` |
|
|
@@ -89,7 +89,7 @@ Three outward concepts: **Scene** (what is in the world; content packs are part
|
|
|
89
89
|
| Story flags, counters | `engine.vars` (`setFlag / flag / bump / counter`, saved) | `recipes/20-content-actions-save.md` |
|
|
90
90
|
| Saves: save game, load game, progress, slot, autosave, 存档 | `engine.saves.register(key, { save, load })`, `saves.autosave(minutes)` | `recipes/20-content-actions-save.md` |
|
|
91
91
|
| New game / continue / back to title / retry | `await engine.session.newGame() / load(slot)`, `quit()`, `session.track(h)` | `recipes/07-flow-scenes-pause.md` |
|
|
92
|
-
| Scene flow, fades, pausing, cutscenes, tweens | `engine.flow`, `fadeScreen(engine, to, s)`, `engine.
|
|
92
|
+
| Scene flow, fades, pausing, cutscenes, tweens | `engine.flow`, `fadeScreen(engine, to, s)`, flow `'paused'` (`engine.freeze(owner)`; not `engine.pause`, which stops rendering), `engine.timeline.tween` | `recipes/07-flow-scenes-pause.md` |
|
|
93
93
|
| Time, timers, skipping time | `engine.clock` (`after / every`), `await engine.skip({ to: '06:00' })`, `checkSkip`, `checkSave` | `recipes/06-clock-events.md` |
|
|
94
94
|
| Events, cause chain, randomness | `engine.events.on / emit`, `engine.random` (saved), `events.trace(name)`, `traceFocus(id)` | `recipes/06-clock-events.md` |
|
|
95
95
|
| Keys, input contexts, open / interact key; text and languages (`engine.t`, `engine.i18n`) | `input.define('action', keys, label)`, `engine.input.push('menu')`, `input.simulate` | `recipes/26-ui-parts.md` |
|
|
@@ -98,26 +98,31 @@ Three outward concepts: **Scene** (what is in the world; content packs are part
|
|
|
98
98
|
| Fixed camera views, same shot before / after | `engine.views.define`, `shot --view name --compare` | `recipes/46-blender-art-route.md` |
|
|
99
99
|
| Drive the game from an MCP client | `claude mcp add threedog -- npx threedog mcp` | `recipes/16-dev-bridge.md` §10 |
|
|
100
100
|
| Will a save keep it; hide / recolor on screen only | `engine.add(obj, { id })`, `engine.thing(id)`, ops `thing.set / remove`, `debug.override(owner, id, {...})` | `recipes/41-thing-registry.md` |
|
|
101
|
-
| Your own module, own game system (
|
|
101
|
+
| Your own module, own game system (crafting, spawner, machine, crop growth) | `{ name, install, fixed, frame, describe, afterLoad }`, `engine.use`; `before` / `after`, `critical`; save, `skip` hook, ops `can` | `recipes/14-custom-module.md`, `49-game-module-contract.md` |
|
|
102
102
|
| Heavy loops, workers; performance budget, debug panel | `engine.jobs.add`, `engine.threads.lane`, `engine.commits`, `engine.budget`, `engine.debug.panel`, `threedog capture` | `recipes/15-perf.md` |
|
|
103
103
|
| Co-op multiplayer | `engine.use(net({ role, transport }))`, `engine.net` | `recipes/27-net.md` |
|
|
104
104
|
|
|
105
|
-
##
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
105
|
+
## When something happens -> which tool
|
|
106
|
+
Tools via MCP or `node node_modules/@threedog/tools/bin/threedog.mjs <cmd>` (not npx: +2.5 s a call); every command is in `COMMANDS.md`. Order: `npm run map` -> `npm run check` (each change) -> related tests (`npm test -- name`). Errors: `.threedog/errors.log`, **read first when something breaks**.
|
|
107
|
+
- Not sure the engine has X -> `threedog how "<task in English>"`, `threedog catalog [id]`.
|
|
108
|
+
- What is this object / why can't I click it -> `thing(id).explain()`.
|
|
109
|
+
- An action failed -> the failure's `code`, `facts`, `nextActions`; `engine.explain({ op })` for what blocks it.
|
|
110
|
+
- The picture looks wrong -> `engine.debug.view('albedo' | 'lighting' | 'shadow' | 'normals')`, `describe().look`.
|
|
111
|
+
- Matching a reference image -> `style palette <ref>`, `style compare <ref> <shot>`, `shot --view name --compare`.
|
|
112
|
+
- The game seems stuck -> `runState`, `describe().time.heldBy`.
|
|
113
|
+
- What caused this -> `events.trace(name)`, `traceFocus(id)`.
|
|
114
|
+
- Verifying a change -> `describeText()` for logic, screenshots only for looks; `threedog js --file steps.js` with asserts; `threedog verify <scenario>` (read its "not proven" part).
|
|
115
|
+
- Saves or time skips broken -> `checkSave`, `checkSkip`.
|
|
116
|
+
- Move a placed thing for good -> `threedog content set <id> x=12` (edits `content/*.js`; bridge ops last this session only).
|
|
117
|
+
- Swapped a model -> `threedog assets check new.glb --against old.glb`.
|
|
118
|
+
- Commands slow -> plain node, or `threedog session`.
|
|
114
119
|
|
|
115
120
|
## Conventions (detailed in `CONVENTIONS.md`)
|
|
116
121
|
- **A position is one argument** (Vector3, Object3D, `[x, y, z]` or `{ x, z }`); sizes and counts go in the options object after it.
|
|
117
122
|
- **Registrations return a handle**; `h.remove()` undoes it. **Ready is the boolean `ready`**. **Event names are `noun:action`**.
|
|
118
123
|
- **Fixed step vs frame**: `onFixed` runs game time (damage, AI, timers); `onFrame` is presentation (animation, camera feel, HUD).
|
|
119
|
-
- **The engine owns** sky lights, fog and the camera every frame
|
|
124
|
+
- **The engine owns** sky lights, fog and the camera every frame (CONVENTIONS "Adjusting sky brightness").
|
|
120
125
|
- **Units** are meters, Y up, north -Z; characters face +Z. **Errors say how to fix it**: an old form throws with the fix.
|
|
121
126
|
|
|
122
127
|
## Stability
|
|
123
|
-
|
|
128
|
+
May change before 1.0: `net()` · `engine.threads` · `grids()` · `terrain.edit` · `world.simulate({ worker })` · `look.post.add` · `stream.source` · `hlod()` · `ops.guard / allow`.
|
package/docs/API.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# Engine API index (generated, do not edit by hand; produced by npm run map)
|
|
2
2
|
|
|
3
|
-
> **To do something, first look at the recipe in `recipes/` whose file name matches** (it has a ready-made pattern, faster than browsing the API): 01-new-game · 02-npc · 03-items-pickups · 04-quests · 05-props-bake · 06-clock-events · 07-flow-scenes-pause · 08-weather-sky · 09-style-pack · 10-blender-level · 11-vehicles · 12-navmesh · 13-animation · 14-custom-module · 15-perf · 16-dev-bridge · 18-world · 19-shooting-picking · 20-content-actions-save · 21-camera · 22-shop-gold · 23-ops · 26-ui-parts · 27-net · 28-terrain · 29-grid · 30-templates · 31-audio · 32-action-game · 33-stream-sources · 34-environment-lighting · 35-style-from-reference · 36-sky-ground-plant-looks · 37-terrain-look-hooks · 38-environment-look-hooks · 40-scene · 41-thing-registry · 42-terrain-shape · 43-shader-patches-surface-looks · 44-water-weather-look-hooks · 45-cascaded-shadows · 46-blender-art-route · 47-island-snow-backdrop · 48-make-material · 49-game-module-contract · 50-own-renderer · 51-capability-catalog · 52-look
|
|
3
|
+
> **To do something, first look at the recipe in `recipes/` whose file name matches** (it has a ready-made pattern, faster than browsing the API): 01-new-game · 02-npc · 03-items-pickups · 04-quests · 05-props-bake · 06-clock-events · 07-flow-scenes-pause · 08-weather-sky · 09-style-pack · 10-blender-level · 11-vehicles · 12-navmesh · 13-animation · 14-custom-module · 15-perf · 16-dev-bridge · 18-world · 19-shooting-picking · 20-content-actions-save · 21-camera · 22-shop-gold · 23-ops · 26-ui-parts · 27-net · 28-terrain · 29-grid · 30-templates · 31-audio · 32-action-game · 33-stream-sources · 34-environment-lighting · 35-style-from-reference · 36-sky-ground-plant-looks · 37-terrain-look-hooks · 38-environment-look-hooks · 40-scene · 41-thing-registry · 42-terrain-shape · 43-shader-patches-surface-looks · 44-water-weather-look-hooks · 45-cascaded-shadows · 46-blender-art-route · 47-island-snow-backdrop · 48-make-material · 49-game-module-contract · 50-own-renderer · 51-capability-catalog · 52-look · 53-ground-up-close
|
|
4
4
|
> The api pages are generated too, do not edit them by hand; `?` in a signature means optional, what follows `→` is the return value; the full types are in `types/*.d.ts`.
|
|
5
5
|
> With no matching recipe: read this page first: the core everyday API + one line per core object / module (listing method names). For the one you need, **read only that page** `api/<name>.md` (methods, parameters, properties and data structures are all in it).
|
|
6
6
|
> Paths are relative to the package (`node_modules/threedog/`). Entry: `import { createEngine, openWorld, … } from 'threedog'` (the engine package's own examples use relative paths); a module that is not installed is undefined, so use `engine.xxx?.method()`.
|
|
@@ -35,7 +35,7 @@
|
|
|
35
35
|
- [`engine.clock`](api/clock.md) game seconds and "after how long / every how long": after every
|
|
36
36
|
- [`engine.vars`](api/vars.md) story flags and counters (autosaved): flag setFlag counter bump
|
|
37
37
|
- [`engine.saves`](api/saves.md) engine.saves handles saving: register queue flush collect check apply save load list remove export import exportFile importFile …
|
|
38
|
-
- [`engine.assets`](api/assets.md) Assets: manifest builder preload font model modelNow geometry texture release trim users forget cached
|
|
38
|
+
- [`engine.assets`](api/assets.md) Assets: manifest builder preload font model modelNow geometry gridFromImage texture release trim users forget cached …
|
|
39
39
|
- [`engine.audio`](api/audio.md) buses: addBus setVolume duck register condition measure value matches volumeOf sfx noiseBurst tone load play
|
|
40
40
|
- [`engine.i18n`](api/i18n.md) string tables: add setLocale has t
|
|
41
41
|
- [`engine.rays`](api/rays.md) engine.rays is the ray registry…: addStatic forget addProvider cast pick
|
|
@@ -80,4 +80,4 @@
|
|
|
80
80
|
|
|
81
81
|
## Other
|
|
82
82
|
- [Style pack Style](api/style.md): all look options (sky, weather, water, terrain, UI, materials, particles, sound, models)
|
|
83
|
-
- [Utility functions](api/tools.md): postAdd postRemove presets world net fakeNetwork webSocket grids screenToGround EASINGS ease checkOptions readParams defineLookPart createTerrain terrainMaterial mergeColored applyEffects MATERIAL_PURPOSES makeMaterial materialPatches toast makeWindow
|
|
83
|
+
- [Utility functions](api/tools.md): postAdd postRemove presets world net fakeNetwork webSocket grids screenToGround EASINGS sampleGrid ease checkOptions readParams defineLookPart createTerrain terrainMaterial mergeColored applyEffects MATERIAL_PURPOSES makeMaterial materialPatches toast makeWindow …
|
package/docs/CODEMAP.md
CHANGED
|
@@ -83,6 +83,8 @@ Requires, optional, stage, run order, params, ops, saves and time model of each
|
|
|
83
83
|
- errorHints.js: Error hints: a table of "message pattern -> likely cause + …
|
|
84
84
|
- errors.js: Error tiers: what to do when a module hook, onFixed / onFra…
|
|
85
85
|
- events.generated.js: Generated, do not edit by hand: npm run map generates it fr…
|
|
86
|
+
- grid.js: 2D grid fields: sampleGrid turns an array of numbers laid o…
|
|
87
|
+
- gridLoad.js: Load an image file as grid data (assets.gridFromImage)
|
|
86
88
|
- ground.js: Ground API (part of Engine, mixed into Engine.prototype): w…
|
|
87
89
|
- holds.js: Who holds the engine still: pause / resume, freeze / unfree…
|
|
88
90
|
- inputContext.js: Input contexts (like Unity's Action Maps): a stack of named…
|
|
@@ -126,7 +128,7 @@ Requires, optional, stage, run order, params, ops, saves and time model of each
|
|
|
126
128
|
- startup.js: Startup (part of Engine, mixed into Engine.prototype): star…
|
|
127
129
|
- streamCells.js: Per-chunk view of stream sources for loaders that sync whol…
|
|
128
130
|
- streamSources.js: Stream sources (internal half of engine.stream): the places…
|
|
129
|
-
- styleParts.js: A style built from parts: createEngine({ style: [
|
|
131
|
+
- styleParts.js: A style built from parts: createEngine({ style: [basePack, …
|
|
130
132
|
- targeting.js: Target selection: pure functions (no camera, input or engin…
|
|
131
133
|
- thingExplain.js: engine.thing(id).explain(): everything known about one id i…
|
|
132
134
|
- thingOps.js: engine.thing and the two built-in ops on things (thing.set …
|
|
@@ -163,7 +165,7 @@ Requires, optional, stage, run order, params, ops, saves and time model of each
|
|
|
163
165
|
- terrain/ Terrain module: chunked, streamed ground built from a height function (or a hei… — ChunkManager.js, chunkJob.js, chunkLevels.js, chunkQueries.js, chunkWorker.js, index.js, lookGround.js, mountTerrain.js, terrainColorMap.js, terrainDefaults.js, terrainEdit.js, terrainGen.js, terrainIsland.js, terrainMesh.js, terrainShape.js, terrainShapeMain.js, terrainTexture.js
|
|
164
166
|
- timeline/ Timeline: cutscenes, camera moves, scripted movement — Timeline.js, Tween.js, letterbox.js, shots.js
|
|
165
167
|
- triggers/ Trigger zone module: invisible regions in the world that notify you when the pl… — index.js
|
|
166
|
-
- vegetation/ Vegetation module factory: engine.use(vegetation(...)) — Vegetation.js, groundChunks.js, index.js, lookWind.js, modelGeometry.js
|
|
168
|
+
- vegetation/ Vegetation module factory: engine.use(vegetation(...)) — Vegetation.js, groundChunks.js, index.js, lookWind.js, modelGeometry.js, nearFade.js
|
|
167
169
|
- water/ Water module: draws the global water plane (sea, big lakes; snaps to a grid fol… — Water.js, look.js, surface.js
|
|
168
170
|
- weather/ Weather: the game's table of weather types (weather({ types })); without one on… — Weather.js, look.js, particles.js, shaders.js, strings.js
|
|
169
171
|
- world/ world() module: installed as engine.world (world data, see World.js) — World.js, cells.js, explain.js, index.js, persist.js, pos.js, records.js, sim.js, simFar.js, state.js, thingSource.js, views.js
|
|
@@ -333,7 +335,7 @@ Requires, optional, stage, run order, params, ops, saves and time model of each
|
|
|
333
335
|
| grid | grid |
|
|
334
336
|
| lighting | render/lookSurface.js |
|
|
335
337
|
| materials | render/lookSurface.js |
|
|
336
|
-
| palette | core/Assets.js, core/assetLoad.js |
|
|
338
|
+
| palette | core/Assets.js, core/assetLoad.js, characters |
|
|
337
339
|
| particles | particles |
|
|
338
340
|
| pickup | gameplay |
|
|
339
341
|
| seasons | sky |
|
package/docs/COMMANDS.md
CHANGED
|
@@ -32,7 +32,8 @@ export const specs = [{
|
|
|
32
32
|
```
|
|
33
33
|
Tests run against the built bundle (not the dev server): main.js must set `window.engine = engine;` before `await engine.start()`, otherwise the
|
|
34
34
|
test waits for the engine until timeout (the error explains why).
|
|
35
|
-
- New game: `npm run new-game name
|
|
35
|
+
- New game: `npm run new-game -- name [--example] [--style empty|<path-or-package>]` (clean start by default; `--example` adds the old sample; see `recipes/01-new-game.md`).
|
|
36
|
+
- Game in your own folder (outside this repo): after `npm install threedog three@~0.187.0 @threedog/tools`, run `npx threedog init [name] [--example] [--style empty|<path-or-package>]`: it copies the new-game template without overwriting anything, merges package.json and writes `.mcp.json`, so Claude Code opened in that folder starts the threedog MCP server by itself.
|
|
36
37
|
|
|
37
38
|
> Git Bash (MSYS) rewrites arguments that start with `/` (`/styletest.html` turns into a Windows path). Write `shot styletest`, or set `MSYS_NO_PATHCONV=1`, or use PowerShell.
|
|
38
39
|
|
|
@@ -41,6 +42,7 @@ export const specs = [{
|
|
|
41
42
|
|---|---|
|
|
42
43
|
| `npm run dev` | Development. Browser errors are sent automatically to the terminal and to the workspace's `.threedog/errors.log` (e.g. `games/my-game/.threedog/errors.log`): read that file first when something breaks, before taking screenshots. Known error classes carry `Possible cause: …` and `Read: recipes/…` lines (table `core/errorHints.js`) |
|
|
43
44
|
| `npm run check` | Run after every change (order: if the docs need regenerating `map` -> `check` -> related tests; otherwise `check` -> related tests): hard rules + rule checks (`packages/tools/rules/`; detection and allowlists are at the top of each file; the save round trip is in npm test) + types + content validation + generated docs up to date. `-- --rule R4` runs one rule, `-- --all` lists every warning, `-- -w game` (or `npx threedog check -w game`) checks one game only: its content validation and GAMEMAP freshness (not the engine rules/types; run plain `check` before committing engine changes) |
|
|
45
|
+
| R40 bypass hints (part of `check`, warnings only) | Game code that hand-rolls timers, `Math.random`, an inventory, grid/height blending or materials is pointed to the engine system that already does it. Off per line `// hint-off(kind)`, per file `// hint-off-file(kind)`, per project `package.json "threedog": { "hints": false | { "kind": false } }`, per run `THREEDOG_HINTS=off`. A deliberate choice goes in DESIGN.md Systems |
|
|
44
46
|
| `npm run types` | Type check only (does game code misuse the engine API) |
|
|
45
47
|
| `npm test` | Full browser tests (slow). Normally `npm test -- name` runs only the related ones (matched by test-name substring, e.g. `-- HLOD`), `-- -w game` tests one game. `-- --update-snapshots` makes tests that use `expectDescribe` write their describe baselines (`tests/snapshots/*.describe.json`) instead of comparing. `npm test -- pack` (the build test): after a real build of each game, open only dist from a static server and check that the engine is ready, no 4xx resources, no console errors |
|
|
46
48
|
| `npx threedog snap-describe save|diff name [--only a,b]` | Describe snapshot instead of a screenshot: baseline of the gameplay part of `describe()` (see recipes/16-dev-bridge.md section 7); in tests one line `expectDescribe({ check, ev }, name, { only, tolerance })` from `@threedog/tools/describe-snapshot` |
|
|
@@ -50,7 +52,7 @@ export const specs = [{
|
|
|
50
52
|
| `threedog js --file steps.js [--verbose]` | A script that calls `assert(cond, msg)` or `expect(v).toBe/toEqual/toBeCloseTo/toBeGreaterThan(x, msg)` runs as checks in ONE call: globals `engine`, `step(seconds)`, `log(...)`; failed checks are recorded and the script goes on, a throw stops it. Output: `✓ 7 checks passed`, or the failures then `✗ 2 of 7 checks failed`; exit code 1 on failure. `--verbose` adds passes, `log` lines and the return value. A script without those calls is the plain eval |
|
|
51
53
|
| `threedog verify scenario` | Run `tests/scenarios/<scenario>.json` on the running page and print PASS / FAIL, **Tested** (ops with outcomes, describe sections compared, time advanced), **Not tested** (ops never run, sections never compared, steps skipped after a failure, key path, picture), a `Layers:` line (steps by layer: direct = op/describe call, simulated-input = bridge press; real-browser-input is always 0 and printed as not verified, visual 0 because scenario snapshots are describe, not pixels), tests that mention an error code seen, and the `threedog test` command to re-run. A page error during the run fails it. JSON adds `layers` / `layerCounts` / `evidence` (per-check layers, notProven, ops / modules coverage; text: Evidence, NOT proven, Coverage: ops ran/total with refused ones marked, modules tested / indirect / untested, lists capped with "+N more"). `threedog scenario` prints its pass line plus the same Coverage block |
|
|
52
54
|
| `threedog catalog [id] [--find word] [--json]` | What this game can do: modules, ops (args, failure codes, last attempt), saves, time. `recipes/51-capability-catalog.md` |
|
|
53
|
-
| `threedog how "<task>"` | Ranks the AI.md task rows and recipe headings for a task in your own words
|
|
55
|
+
| `threedog how "<task>"` | Ranks the AI.md task rows and recipe headings for a task in your own words. `recipes/51-capability-catalog.md` section 5 |
|
|
54
56
|
| `threedog explain op shop.buy shop=bakery` / `explain quest first-light` | Why an op cannot run now, or what a quest waits on (`engine.explain`). `recipes/23-ops.md` |
|
|
55
57
|
| `threedog thing <id>` | Everything about one id: definition file:line, model, materials, state, ops, save tier, how to change it (`thing.explain()`). `recipes/41-thing-registry.md` section 6 |
|
|
56
58
|
| `threedog content set <id> <field> <json> [--in props] [--dry]` (or `<id> x=12 place=home …`: several fields, one write, one check, all-or-nothing) | Write a permanent change into the content entry. `recipes/41-thing-registry.md` |
|
|
@@ -96,7 +98,7 @@ export const specs = [{
|
|
|
96
98
|
- `modules/` modules, one folder each, installed with `engine.use`; list in `CODEMAP.md`.
|
|
97
99
|
- `render/ ui/` material factory, post-processing; UI basics (windows, UI focus stack, toast, fadeScreen, worldToScreen).
|
|
98
100
|
- `index.js index.d.ts types/` entry and API declarations (`types/generated/` is generated from source JSDoc, never edited by hand).
|
|
99
|
-
- `packages/styles/lowpoly/` (`@threedog/style-lowpoly`,
|
|
101
|
+
- `packages/styles/lowpoly/` (`@threedog/style-lowpoly`, private, example-only: not published, not a recommended look) the pack the bundled examples, tests and older games use: `index.js` holds the style pack (all
|
|
100
102
|
look parameters) and exports the asset pack `assets`, `models.js` the procedural models in it, `shapes.js` the default humanoid and pickup shapes,
|
|
101
103
|
The bloom / outline / ao effects are in `packages/post-effects/` (`@threedog/post-effects`). The terrain preset `terrainPreset()` is a separate package, `packages/terrain-noise/` (`@threedog/terrain-noise`).
|
|
102
104
|
- `examples/world/` is the engine example (open world `/`, content-only placement). The small city (level, no terrain, no style pack, top-down) and
|