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/docs/recipes/52-look.md
CHANGED
|
@@ -2,6 +2,8 @@
|
|
|
2
2
|
|
|
3
3
|
Every look part lives at `engine.look.<part>` and is changed with the same verbs. The style pack gives the starting values; the game changes them on top.
|
|
4
4
|
|
|
5
|
+
Exits, in order: `set` params → `patch` (your own GLSL at a named hook) → textures in the material spec (`map`, `normalMap`) → `replace` (your own material or object) → plain three.js (recipe 40 §8). When two rounds of tuning params do not reach the reference, take the next exit instead of tuning on.
|
|
6
|
+
|
|
5
7
|
```js
|
|
6
8
|
const cave = engine.look.tone.set({ exposure: 0.6 }, { owner: 'cave' }); // only the keys you give; null drops a key
|
|
7
9
|
engine.look.lights.set({ sun: { intensity: 0.5 } }, { owner: 'cave' });
|
|
@@ -33,16 +35,17 @@ engine.look.shadow.set({ type: 'vsm', radius: 3, cascades: 3, maxFar: 150 });
|
|
|
33
35
|
- `fog` shows `enabled` and `far` (fog reaches full strength at `engine.fogFar`, starting at 0.3 x that) as the visible defaults; turn off with `set({ enabled: false })`. Color, density, near, far, enabled and linear <-> exp2 are live. Kind `'exp'` / `'height'`, `height`, `falloff` and the `'fog'` hook replace three's shared fog shader chunks, so they only work before the first frame (style, `sky({ fog })`, or right after `createEngine`); later they throw and say so.
|
|
34
36
|
- `sky`: `clouds.*` are live uniforms of the dome (they only draw when `clouds.coverage` > 0). A hook change recompiles the dome material once. Style `layers` arrays are named by their `name` key, else `layer0`, `layer1`.
|
|
35
37
|
- `shadow`: no `patch` (the cascade patch is internal) and no `replace` (to own the shadows, light with your own lights: `sky({ sun: false })`).
|
|
38
|
+
- Fog kinds and the fog hook in detail, and taking lights or fog away from the sky entirely (`sky({ sun: 'manual' | false })`, `look.fog.replace('manual')`): [recipe 38](38-environment-look-hooks.md).
|
|
36
39
|
|
|
37
40
|
## Surface parts: `materials`, `surface`, `ground`, `wind`
|
|
38
41
|
|
|
39
|
-
A change to these parts reaches the materials made **after** it, with one exception: `look.materials.set` of the plain properties `color`, `emissive`, `emissiveIntensity`, `roughness`, `metalness`, `opacity`, `envMapIntensity`, `shininess` and `specular` also changes the materials already made for that role (no recompile; clearing the layer goes back to the style's value). Shader-changing keys (`type`, `steps`, `ramp`, `soften`, `repeat`, `wrap`, `detail`, `lighting`, `patch`, `replace`) and all of `look.surface` are for new materials only (a Material already handed out, or cloned by your game, is not touched; catalog and describe say so as `appliesTo`, and a debug override warns). `engine.look.<part>.object` is the three.js object behind a part; for `materials` it is a function: `engine.look.materials.object('
|
|
42
|
+
A change to these parts reaches the materials made **after** it, with one exception: `look.materials.set` of the plain properties `color`, `emissive`, `emissiveIntensity`, `roughness`, `metalness`, `opacity`, `envMapIntensity`, `shininess` and `specular` also changes the materials already made for that role (no recompile; clearing the layer goes back to the style's value). Shader-changing keys (`type`, `steps`, `ramp`, `soften`, `repeat`, `wrap`, `detail`, `lighting`, `patch`, `replace`) and all of `look.surface` are for new materials only (a Material already handed out, or cloned by your game, is not touched; catalog and describe say so as `appliesTo`, and a debug override warns). `engine.look.<part>.object` is the three.js object behind a part; for `materials` it is a function: `engine.look.materials.object('cloth')` is the last Material made for that role, `object()` all of them.
|
|
40
43
|
|
|
41
44
|
```js
|
|
42
45
|
const L = engine.look;
|
|
43
|
-
L.materials.set({
|
|
44
|
-
L.materials.patch('dim', { glsl: { fragment: { color_fragment: 'diffuseColor.rgb *= 0.8;' } } }, { roles: ['
|
|
45
|
-
L.materials.replace('
|
|
46
|
+
L.materials.set({ cloth: { roughness: 0.4, color: 0xf2ece0 } }, { owner: 'shop' }); // merged into style.materials.cloth; any role name
|
|
47
|
+
L.materials.patch('dim', { glsl: { fragment: { color_fragment: 'diffuseColor.rgb *= 0.8;' } } }, { roles: ['metal'] }); // a ShaderPatch on those roles
|
|
48
|
+
L.materials.replace('glass', new THREE.MeshPhysicalMaterial({ transmission: 1 })); // the role is this Material (or (params, purpose, engine) => Material)
|
|
46
49
|
L.surface.set({ lighting: { wrap: 0.3, shadowTint: { color: '#4a5a9a', strength: 0.5 } }, detail: { noise: 'grain', strength: 0.15 } });
|
|
47
50
|
L.surface.set({ ramp: [0.35, 0.7, 1], soften: 0.2 }); // every toon material's ramp
|
|
48
51
|
L.surface.patch('lighting', glsl); // your threedogLighting(...), see recipe 43
|
|
@@ -70,7 +73,7 @@ engine.look.water.replace((engine, { uniforms, waves, surface }) => myMaterial);
|
|
|
70
73
|
|
|
71
74
|
engine.look.weather.set({ 'rain.speed': 10, 'snow.size': 8, 'lightning.brightness': 0.5, overcastColor: '#667' }); // rebuilds that field's particles once
|
|
72
75
|
engine.look.weather.patch('rain.fragment', wholeFragmentShaderText); // rain|snow . vertex|fragment: the WHOLE shader text, not a function
|
|
73
|
-
engine.look.weather.replace({ ash: { shape: 'soft', color: 0x555555 }, rain: { create } }); //
|
|
76
|
+
engine.look.weather.replace({ ash: { shape: 'soft', color: 0x555555 }, rain: { create } }); // null gives the fields back
|
|
74
77
|
|
|
75
78
|
engine.look.post.set({ bloom: { strength: 0.6 }, vignette: false }); // keys: '<effect>.<param>', '<effect>.enabled'
|
|
76
79
|
engine.look.post.patch('tint', { glsl: 'color.rgb *= vec3(1.0, 0.9, 0.8);', slot: 'ldr', order: 5 }); // generates a fuse effect named 'tint'; patch('tint', null) removes it
|
|
@@ -83,11 +86,45 @@ engine.look.post.replace([bloom(), grain()]);
|
|
|
83
86
|
- Post: `look.post.set` writes the `game` layer (keys `<effect>.<param>` and `<effect>.enabled`); style effects (bloom, ao ...) are the style layer; `engine.post.get(name)` only reads an effect. MSAA is `engine.post.setAntialias(on)`. Costly effects start off on low-tier devices: `look.post` lists `<effect>.enabled` with `why` and `off`. `postAdd` / `postRemove` stay style-pack parts (they edit the list before the engine exists).
|
|
84
87
|
- `describe().render.post` reads the same records (`by`: style, game, debug).
|
|
85
88
|
|
|
89
|
+
## Post effect chain
|
|
90
|
+
|
|
91
|
+
Post-processing is an ordered list of named effects (`style.post`, then `look.post`). Each runs in a slot, then by `order` (low first):
|
|
92
|
+
`scene` (replaces the scene render, one at a time, e.g. pixelation) -> `hdr` (linear color: outline, AO, bloom) -> tone mapping -> `ldr` (sRGB: LUT,
|
|
93
|
+
palette, grain, vignette) -> `final` (FXAA / SMAA). An effect is `{ name, slot, order, params, create(ctx) => pass, update?(pass, params) }`; under
|
|
94
|
+
WebGL the pass is any three.js postprocessing Pass, built the first time it is on.
|
|
95
|
+
```js
|
|
96
|
+
import { bloom, outline, vignette, lut } from '@threedog/post-effects'; // never from another style pack: packs do not depend on each other
|
|
97
|
+
import { LUTPass } from 'three/addons/postprocessing/LUTPass.js';
|
|
98
|
+
const myStyle = { post: [outline({ enabled: true, thickness: 1.5 }), bloom({ strength: 0.2 }), vignette(), lut({ saturation: 1.1 }),
|
|
99
|
+
{ name: 'myLut', slot: 'ldr', params: { lut: myLut }, create: ({ params }) => new LUTPass({ lut: params.lut }) }] };
|
|
100
|
+
```
|
|
101
|
+
- The engine ships no effects. `@threedog/post-effects` (import only what you use) has `bloom`, `ao`, `outline`, `dof` (all `hdr`; outline and dof
|
|
102
|
+
read depth) and `lut` (contrast / saturation / warm-cool / optional 3D LUT), `grain`, `vignette`, `chromatic` (`ldr`). `lut`, `grain`, `vignette`,
|
|
103
|
+
`chromatic`, `dof`, `ao` and `outline` are off until `enabled: true`. To add to or trim a pack's list without replacing it: `postAdd(...effects)` /
|
|
104
|
+
`postRemove(...names)` ([recipe 09](09-style-pack.md), 0b).
|
|
105
|
+
- Depth: an effect that reads scene depth (`needsDepth: true`, e.g. `outline`) must run before any pass that swaps buffers (a `ShaderPass`, a
|
|
106
|
+
scene-slot pixelation pass, the tone-mapping output). A chain that breaks this throws when the effect is added or enabled, naming both effects;
|
|
107
|
+
give the depth reader a lower `order`. `dof` keeps the scene depth (`pass.keepsDepth = true`), so `dof` and `outline` can both be on while `dof`
|
|
108
|
+
has the lower `order` (default: dof 5, outline 10). `threedog style check` reports the other order as an error.
|
|
109
|
+
- `createEngine({ post: { bloom: false } })` overrides an effect's startup on/off; `costly: true` effects start off on low-tier devices. MSAA
|
|
110
|
+
(`antialias`) works with every effect on. The settings menu shows `bloom` / `ao` toggles only when the style registers effects with those names.
|
|
111
|
+
- `fuse`: a light color effect can skip its own fullscreen pass by carrying a GLSL snippet instead of `create()`:
|
|
112
|
+
`fuse: { uniforms: { uMyAmount: 'float' }, values: p => ({ uMyAmount: p.amount }), glsl: 'color.rgb *= 1.0 - uMyAmount * length(vUv - 0.5);' }`.
|
|
113
|
+
Fused effects that are on and next to each other in one slot (never `scene`) compile into one shader and draw in one pass, in `order`. The
|
|
114
|
+
snippet edits `vec4 color` and may use `vUv`, `tDiffuse`, `uTime`, `uResolution`, `fxHash(vec2)`; uniform names are shared by the group, so prefix
|
|
115
|
+
them with the effect name. A snippet that samples `tDiffuse` elsewhere (blur, color fringe) sets `reads: true` and starts a new group.
|
|
116
|
+
`look.post.patch(name, { glsl })` builds such an effect for you.
|
|
117
|
+
- Outline: `outline({ mode: 'depth' | 'normal' | 'both' })`: `depth` (default, silhouettes), `normal` (creases; draws the scene once more with
|
|
118
|
+
normals, so it is `costly`), `both`. `fadeWithDistance: false` keeps lines at any distance; `wobble: 1.5` jitters lines by up to 1.5 px at 8 steps a
|
|
119
|
+
second. To exempt objects: `outline({ offLayer: OUTLINE_OFF_LAYER })` and `mesh.layers.enable(OUTLINE_OFF_LAYER)` (one extra render of just
|
|
120
|
+
those objects; nothing when `offLayer` is `null`).
|
|
121
|
+
|
|
86
122
|
## sky.modify vs look.lights
|
|
87
123
|
|
|
88
124
|
Two ways to make the light darker or brighter; pick by what you want to keep.
|
|
89
125
|
- `engine.sky.modify('cave', { sun: 0.3, ambient: 0.4, fog: 0.5, tint, tintAmount })` is a **multiplier layer** on what the sky produces each frame (keyframes, weather, season). The time of day keeps moving underneath, layers from different owners multiply, `modify('cave', null)` removes yours, and `sky.modifiers` shows the combined result (read-only). Use it for "darker in the cave" or "ash over the ground" (`groundCover`, `coverAmount`).
|
|
90
126
|
- `engine.look.lights.set({ sun: { intensity: 0.5 } }, { owner: 'cave' })` is an **override layer** on the part's own values: the key you give replaces what the style or the keyframes said, whatever the hour. Use it for "the sun is exactly this".
|
|
127
|
+
|
|
91
128
|
## Renamed in 0.2 (old call → new call)
|
|
92
129
|
|
|
93
130
|
The old calls below now throw `renamed-api` and the message names the new call (the list is `RENAMED` in `core/renamed.js`; rule R39 keeps the old names out of the repo).
|
|
@@ -104,5 +141,6 @@ The old calls below now throw `renamed-api` and the message names the new call (
|
|
|
104
141
|
| `engine.cameraOverride = { owner }` | `const cam = engine.takeCamera('owner', { focus })`; `cam.remove()` releases it |
|
|
105
142
|
| `engine.views.define(name, { pos })` | `engine.views.define(name, { position: [x, y, z] })` |
|
|
106
143
|
| failure `result.reason` (`ops.run` / `can` / `undo`) | `result.code` (reading `reason` throws) |
|
|
144
|
+
| `style.character.create` / `.model` / `.colors` (a body from the style pack) | bodies are assets: `createPlayer({ model: 'humanoid' })` with a pack's `assets` registered, a GLB asset name, or `{ rig }`; part colors are material roles `cloth` / `skin` / `trousers` / `hair`, or `{ colors }` per character ([13-animation](13-animation.md)) |
|
|
107
145
|
|
|
108
146
|
Not renamed (still the way to do it): per-call `makeMaterial(role, params)` keys win for that one material; `applyEffects(mat, { patches })` is the low-level form of `look.materials.patch(name, spec, { roles })`; `style.terrain.*`, `style.wind.*` and `style.lighting` are the style layer of `look.ground` / `look.wind` / `look.surface`.
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
# The ground up close: options and diagnosis
|
|
2
|
+
|
|
3
|
+
Not a standard recipe. Several looks are right for different games, and none is the default. **Decide from the reference images first**: is the
|
|
4
|
+
ground flat color shapes, a painted surface, a photographic texture, or a few lit polygons? Then pick a row. If the ground already looks wrong,
|
|
5
|
+
jump to the symptoms.
|
|
6
|
+
|
|
7
|
+
## Approaches (pick by the look you want)
|
|
8
|
+
| Look | How | Typical values |
|
|
9
|
+
|---|---|---|
|
|
10
|
+
| Flat color blocks, no detail (minimal, flat illustration; on purpose) | `shading: 'flat'` or `'smooth'`, `colors` / `biomeColors`, no `detail`; a few `variation.patches` with `levels` | `resolution: 16`; `patches: { size: 90, levels: 3, strength: 0.15 }` |
|
|
11
|
+
| Color map + detail layer + near grass (soft variation, crisp borders) | `terrain({ shading: 'texture', colorResolution })`, `style.terrain.detail`, grass with `vegetation.add(name, { nearOnly: true })` | `colorResolution: 128`; `detail: { noise: 'dabs', scale: 0.5, strength: 0.25, normal: 0.03 }` |
|
|
12
|
+
| Tiling or triplanar textures (your own painted, photographed or generated images) | material spec `map` + `repeat`, or `detail: { texture: 'name' }` (`projection: 'triplanar'` on slopes and rocks) | `repeat: 8`; `detail: { texture, scale: 0.5, strength: 0.6 }` |
|
|
13
|
+
| Vertex color + toon lighting | vertex colors from `colors` and `variation.jitter`, `type: 'toon'` with a `ramp`; detail optional | `jitter: { size: 2, min: 0.9, range: 0.15 }`; `ramp: [0.4, 0.75, 1]` |
|
|
14
|
+
| Your own shader or plain three.js | `terrain({ material })`, or recipe 40 section 8 (what you give up) | any |
|
|
15
|
+
|
|
16
|
+
Detail noises (recipe 43): `grain` fine speckle, `paper` fibres, `stroke` directional streaks (stretched on purpose), `dabs` soft oval dabs with
|
|
17
|
+
no direction. `fade` (on by default) removes the detail where its pattern is smaller than a pixel. At run time: `look.ground.set`,
|
|
18
|
+
`look.surface.set({ detail })`, `look.surface.patch('detail', glsl)` (recipe 52).
|
|
19
|
+
|
|
20
|
+
Where each key is defined: `variation` (blend, jitter, patches) recipe 36; `shading`, `colorResolution`, `normals`, `normalFn`, heights from a
|
|
21
|
+
grid recipe 37; `detail` keys recipe 43; run-time changes `look.ground` recipe 52; terrain basics recipe 28.
|
|
22
|
+
|
|
23
|
+
## Symptom, causes, options
|
|
24
|
+
**Brushed metal at grazing angles.** Cause: `stroke` stretches one axis (`stretch` 6) and `world` projection looks straight down, so a flat
|
|
25
|
+
ground seen at a low angle shows the stretch as long streaks. Options: `noise: 'dabs'` or `'grain'` (no stretch); `stretch: 1`; a smaller
|
|
26
|
+
`strength`; `projection: 'triplanar'` only on slopes; no detail at all if the reference is flat.
|
|
27
|
+
|
|
28
|
+
**Slopes show terraces or creases.** Causes: heights from sparse data with linear (bilinear) interpolation show the data grid as kinks along
|
|
29
|
+
its cell lines (`terrain({ heightmap })` always reads its image bilinearly; `sampleGrid` defaults to `interp: 'linear'`); a coarse mesh
|
|
30
|
+
`resolution` (16 per 64 m chunk = one height every 4 m); `shading: 'flat'`, which lights each triangle on its own so every facet shows.
|
|
31
|
+
Options, any of them: more height samples (a larger image or table), or the data smoothed before the terrain reads it; `sampleGrid(...,
|
|
32
|
+
{ interp: 'cubic' })` for smooth heights everywhere outside the terrain module (placement, gameplay; recipe 37 section 7; a terrain `height`
|
|
33
|
+
function runs in a worker and cannot capture a sampler); a finer `resolution` (more triangles, collision and edit cells); `shading: 'smooth'`,
|
|
34
|
+
or `normals: 'smooth'` with `shading: 'texture'`; `diagonal: 'adaptive'` against zigzag ridges; or noise in the `height` function (`n.fbm`; ridges from
|
|
35
|
+
folding it) instead of a sparse table. Terraces can also be the look you want: `interp: 'nearest'`, or a stepped `height`.
|
|
36
|
+
|
|
37
|
+
**Blurry up close.** Cause: the color map is `colorResolution + 2` pixels per 64 m chunk side; 128 is 0.5 m per pixel, which is soft when the
|
|
38
|
+
camera is within a few meters. It does not depend on the mesh `resolution`. On a `low` tier the default is 64 (twice as coarse) unless you set
|
|
39
|
+
it. Options: `colorResolution: 256` (0.25 m; four times the image memory and worker time); a detail layer on top (it is computed per screen
|
|
40
|
+
pixel, so it stays sharp); near grass over the ground; or accept soft color and let a texture carry the fine part.
|
|
41
|
+
|
|
42
|
+
**One flat green.** Cause: not resolution. Color comes from `colors` / `biomeColors` per ground type (`groundType`), `variation.blend`
|
|
43
|
+
(wavelength and `strength` of the two-color noise) and `steep`. One color with no `biomeColors` and a flat blend is one green. Options: two
|
|
44
|
+
colors in `biomeColors` for the type; `blend.strength` 1.5; `variation.patches` with a `tint`; more ground types.
|
|
45
|
+
|
|
46
|
+
**Dark blotches.** Cause: usually cloud shadows (`style.clouds.shadow` above 0), not texture; they drift with `speed`, and bigger clouds mean
|
|
47
|
+
bigger blotches. Test by setting `clouds.shadow: 0` (live: `look.cloudShadow`); if they vanish, lower it or change `scale`. Blotches that
|
|
48
|
+
never move are `variation.patches` or a strong `detail`.
|
|
49
|
+
|
|
50
|
+
**Shimmer far away.** Cause: a pattern smaller than a pixel aliases. `detail.fade` (default) fades it out; `fade: false` keeps it. In your own
|
|
51
|
+
`glsl`, read `threedogDetailFootprint` (one pixel in pattern units; 1 = one cell per pixel) and fade yourself. A `variation.jitter.size` below a
|
|
52
|
+
pixel shimmers the same way; use a few meters, or `shading: 'texture'` (mipmapped).
|
|
53
|
+
|
|
54
|
+
**Near-only vegetation fades out by distance.** Any `nearOnly` species (grass, flowers, pebbles, twigs, snow tufts, debris ...) is placed per chunk ring
|
|
55
|
+
(`maxRing`), whose edge would be a visible line. By default instances shrink toward their base over a band that ends at `maxRing x chunk size` from the
|
|
56
|
+
player (start at 65% of it), so nothing pops per chunk. Tune with `fade: { start: 20, end: 45 }` (metres), or `fade: false` for a hard edge
|
|
57
|
+
(e.g. a species hidden in fog anyway). It is part of the species' own material (no extra draw call or program), keeps wind sway and shadows in step, and is skipped
|
|
58
|
+
when `effects: false`. A larger `maxRing`, fog, or a ground color near the species' base color still help for stylized looks with strong silhouettes.
|
|
@@ -29,7 +29,7 @@ Content: actions 4 · audio 1 · items 1 · places 1 · props 8 (from templates
|
|
|
29
29
|
- settings: `node_modules/threedog/docs/recipes/26-ui-parts.md` · `node_modules/threedog/docs/api/settings.md`
|
|
30
30
|
- interactions: `node_modules/threedog/docs/recipes/20-content-actions-save.md` · `node_modules/threedog/docs/api/interactions.md`
|
|
31
31
|
- inventory: `node_modules/threedog/docs/recipes/03-items-pickups.md` · `node_modules/threedog/docs/api/inventory.md`
|
|
32
|
-
- content: `node_modules/threedog/docs/recipes/
|
|
32
|
+
- content: `node_modules/threedog/docs/recipes/01-new-game.md` · `node_modules/threedog/docs/api/content.md`
|
|
33
33
|
- hud: `node_modules/threedog/docs/recipes/04-quests.md` · `node_modules/threedog/docs/api/hud.md`
|
|
34
34
|
|
|
35
35
|
Not used yet (check these before writing the system yourself):
|
|
@@ -52,7 +52,7 @@ content/*.js is content data: how to write it in `node_modules/threedog/docs/rec
|
|
|
52
52
|
| content/templates.js | 11 | |
|
|
53
53
|
| content/views.js | 7 | |
|
|
54
54
|
| look.js | 6 | This example's look, as a style part merged over the lowpoly pack (createEngine({ style: [lowpoly, … |
|
|
55
|
-
| main.js |
|
|
55
|
+
| main.js | 139 | @ts-check Action example: one room, one player, one slime, one drop. Shows how an action game wires… |
|
|
56
56
|
| models.js | 26 | Models this example builds in code (floor, wall, pillar, enemy), registered by name in main.js and … |
|
|
57
57
|
|
|
58
58
|
## NPCs (content/npcs.js)
|
package/examples/action/main.js
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
// main.js holds rules only: modules, ops (attack, damage, enemy attack, death), fixed-step logic, presentation. The room, the slime and its stats are
|
|
4
4
|
// content (content/templates.js + props.js, rule R33). The engine has no health, damage or death: all of that is below, as plain game state and ops.
|
|
5
5
|
import { createEngine, openWorld, followCamera, presets, interactions, inventory, content, hud, toast } from '../../index.js';
|
|
6
|
-
import lowpoly from '@threedog/style-lowpoly'; // optional style pack; ?style=none runs with the engine's gray placeholders
|
|
6
|
+
import lowpoly, { assets as lowpolyAssets } from '@threedog/style-lowpoly'; // optional style pack + its asset pack (the humanoid body); ?style=none runs with the engine's gray placeholders
|
|
7
7
|
import look from './look.js';
|
|
8
8
|
import data from './content/index.js';
|
|
9
9
|
import { models } from './models.js';
|
|
@@ -30,7 +30,8 @@ engine.use(openWorld({ camera: followCamera({ ...presets.camera.overShoulder, ya
|
|
|
30
30
|
const m = models(engine); // the names content/templates.js uses, written out so `npm run check` can see them
|
|
31
31
|
engine.assets.manifest({ name: 'action', models: { floor: m.floor, wall: m.wall, pillar: m.pillar, enemy: m.enemy } });
|
|
32
32
|
engine.audio.register('blip', (a, p, out) => { a.tone({ freq: (p.freq ?? 440) * p.pitch, dur: 0.12, out }); return 0.12; }); // content/audio.js names it
|
|
33
|
-
engine.
|
|
33
|
+
if (style) engine.assets.manifest(lowpolyAssets); // the 'humanoid' body; style=none keeps the gray capsule
|
|
34
|
+
engine.characters.createPlayer({ ...presets.player.aim, model: style ? 'humanoid' : null, spawn: TUNE.spawn }); // face where the camera looks: a swing goes where you aim
|
|
34
35
|
engine.content.load(data, { places: { room: { x: 0, z: 0 } } });
|
|
35
36
|
|
|
36
37
|
// ---------- Game state: plain values, described and saved (one player, so it is not keyed by actor) ----------
|
|
@@ -25,7 +25,7 @@ None yet, write them in `DESIGN.md` (why it is designed this way, what not to ch
|
|
|
25
25
|
- collision: `node_modules/threedog/docs/recipes/12-navmesh.md` · `node_modules/threedog/docs/api/collision.md`
|
|
26
26
|
- characters: `node_modules/threedog/docs/recipes/12-navmesh.md` · `node_modules/threedog/docs/api/characters.md`
|
|
27
27
|
- settings: `node_modules/threedog/docs/recipes/26-ui-parts.md` · `node_modules/threedog/docs/api/settings.md`
|
|
28
|
-
- content: `node_modules/threedog/docs/recipes/
|
|
28
|
+
- content: `node_modules/threedog/docs/recipes/01-new-game.md` · `node_modules/threedog/docs/api/content.md`
|
|
29
29
|
|
|
30
30
|
Not used yet (check these before writing the system yourself):
|
|
31
31
|
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
export default {
|
|
3
3
|
guide: {
|
|
4
4
|
name: 'Guide',
|
|
5
|
-
colors: { body: 0x4f6d8f, legs: 0x5b4a3a, hair: 0xd8d4cc },
|
|
5
|
+
model: 'humanoid', colors: { body: 0x4f6d8f, legs: 0x5b4a3a, hair: 0xd8d4cc },
|
|
6
6
|
start: { place: 'stage', x: 2.5, z: 4 }, behavior: 'wander', mind: { radius: 0 },
|
|
7
7
|
},
|
|
8
8
|
};
|
|
@@ -42,7 +42,7 @@ engine.use(openWorld({ camera: fixedCamera(), seed: SEED, terrain: terrainPreset
|
|
|
42
42
|
|
|
43
43
|
engine.assets.manifest(lowpolyAssets);
|
|
44
44
|
engine.assets.manifest({ name: 'styletest', models: { woodBlock, stoneBlock, metalBall, glassPanes, shadowStage, room } }); // the names content/templates.js uses
|
|
45
|
-
engine.characters.createPlayer({ ...presets.player.thirdPerson, spawn: { x: stage.x + 0.5, z: stage.z + 6 } });
|
|
45
|
+
engine.characters.createPlayer({ ...presets.player.thirdPerson, model: params.style === 'none' ? null : 'humanoid', spawn: { x: stage.x + 0.5, z: stage.z + 6 } }); // style=none: the gray capsule
|
|
46
46
|
engine.content.load(data, { places: { stage, water } });
|
|
47
47
|
if (params.env) { engine.look.env.replace('sky'); engine.look.env.set({ intensity: 0.8 }); engine.sky.modify('env', { ambient: 0.6 }); } // soft ambient from the sky: lower the hemisphere ambient so shadows stay
|
|
48
48
|
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
export default {
|
|
3
3
|
fisher: {
|
|
4
4
|
name: '老渔夫',
|
|
5
|
-
colors: { body: 0x4f6d8f, legs: 0x5b4a3a, hair: 0xd8d4cc },
|
|
5
|
+
model: 'humanoid', colors: { body: 0x4f6d8f, legs: 0x5b4a3a, hair: 0xd8d4cc },
|
|
6
6
|
start: { place: 'home', x: 1, z: 5 },
|
|
7
7
|
schedule: [
|
|
8
8
|
{ at: '06:00', place: 'river' }, // go to the riverside
|
package/examples/world/main.js
CHANGED
|
@@ -48,7 +48,7 @@ engine.onFrame(() => {
|
|
|
48
48
|
});
|
|
49
49
|
|
|
50
50
|
// ---------- 3. Player + content (vegetation, items, pickups, NPCs, dialogues, quests, key actions, templates, props, physics props, custom conditions) ----------
|
|
51
|
-
engine.characters.createPlayer({ ...presets.player.thirdPerson, spawn: { x: home.x + 4, z: home.z + 7 } });
|
|
51
|
+
engine.characters.createPlayer({ ...presets.player.thirdPerson, model: 'humanoid', spawn: { x: home.x + 4, z: home.z + 7 } }); // body: lowpoly's humanoid asset
|
|
52
52
|
engine.content.load(data, { places: { home, river, water: waterSpot } }); // content names models only; the asset packs above resolve them
|
|
53
53
|
|
|
54
54
|
// Show the film count at the top left (hud counter)
|
package/index.d.ts
CHANGED
|
@@ -66,10 +66,10 @@ export * as THREE from 'three';
|
|
|
66
66
|
export function createEngine(opts: EngineOptions): Engine;
|
|
67
67
|
/**
|
|
68
68
|
* A style part that adds post effects to the ones before it (a plain { post: [...] } would replace the whole list); an effect with the same name
|
|
69
|
-
* replaces that one in place. Style parts with it: createEngine({ style: [
|
|
69
|
+
* replaces that one in place. Style parts with it: createEngine({ style: [basePack, postAdd(myGrain, bloom({ strength: 0.6 }))] })
|
|
70
70
|
*/
|
|
71
71
|
export function postAdd(...effects: PostEffect[]): Style;
|
|
72
|
-
/** A style part that removes post effects by name from the ones before it: createEngine({ style: [
|
|
72
|
+
/** A style part that removes post effects by name from the ones before it: createEngine({ style: [basePack, postRemove('ao', 'outline')] }) */
|
|
73
73
|
export function postRemove(...names: string[]): Style;
|
|
74
74
|
|
|
75
75
|
/** One openWorld part: false leaves the module out, true / omitted uses defaults, an object is that module's own options */
|
|
@@ -219,6 +219,12 @@ export { hud } from './types/generated/modules/hud/index';
|
|
|
219
219
|
export function screenToGround(engine: Engine, ndcX: number, ndcY: number, opts?: { maxDistance?: number }): Vector3 | null;
|
|
220
220
|
/** All easing functions: name -> function */
|
|
221
221
|
export const EASINGS: Record<EaseName, (t: number) => number>;
|
|
222
|
+
/**
|
|
223
|
+
* A grid of numbers (height, moisture, density, walkable...) as a function (x, z) -> value. data[j * width + i] sits at origin + (i, j) * cell.
|
|
224
|
+
* interp 'nearest' = flat steps, 'linear' (default) = bilinear, 'cubic' = smooth (clamp: true avoids overshoot). Outside: edge value, or `outside`.
|
|
225
|
+
*/
|
|
226
|
+
export function sampleGrid(data: ArrayLike<number>, opts: { width: number; height: number; cellSize?: number | [number, number]; size?: [number, number];
|
|
227
|
+
origin?: [number, number]; interp?: 'nearest' | 'linear' | 'cubic'; clamp?: boolean; outside?: number }): (x: number, z: number) => number;
|
|
222
228
|
/** Name or function -> easing function */
|
|
223
229
|
export function ease(e: Ease): (t: number) => number;
|
|
224
230
|
/**
|
package/index.js
CHANGED
|
@@ -5,10 +5,10 @@
|
|
|
5
5
|
//
|
|
6
6
|
// import { createEngine, terrain, vegetation, sky, weather, water, collision, rigid,
|
|
7
7
|
// followCamera, characters, interactions, dialogue, inventory, quests, photo, ambience, debug } from 'threedog';
|
|
8
|
-
// import
|
|
8
|
+
// import basePack from 'your-style-pack'; // optional: the engine itself ships no art (your own pack or a published one)
|
|
9
9
|
// import { terrainPreset } from '@threedog/terrain-noise'; // optional: nor a terrain generator
|
|
10
10
|
//
|
|
11
|
-
// const engine = createEngine({ canvas, style:
|
|
11
|
+
// const engine = createEngine({ canvas, style: basePack }); // without a style pack: neutral gray placeholders
|
|
12
12
|
// engine.use(terrain({ seed: 7, ...terrainPreset() }), vegetation(), sky(), weather(), water(), collision(), followCamera(), characters());
|
|
13
13
|
// engine.start();
|
|
14
14
|
//
|
|
@@ -58,6 +58,7 @@ export { terrain, vegetation, sky, weather, water, collision, rigid, followCamer
|
|
|
58
58
|
export { net, fakeNetwork, webSocket } from './modules/net/index.js';
|
|
59
59
|
export { screenToGround } from './core/screenToGround.js';
|
|
60
60
|
export { EASINGS, ease } from './core/easing.js';
|
|
61
|
+
export { sampleGrid } from './core/grid.js'; // a grid of numbers (height, moisture, density, walkable) as a function (x, z) -> value; assets.gridFromImage reads one from an image. 'threedog/grid' is the same file without three.js (workers, tests)
|
|
61
62
|
export { checkOptions };
|
|
62
63
|
export { defineLookPart } from './core/look/part.js'; // a module's own look part: engine.look.<id> with set / patch / replace, catalog and describe (recipes/52)
|
|
63
64
|
export { readParams } from './core/params.js'; // params schema for game-made modules: validated, defaults filled, shown by engine.catalog() // for game-made modules (recipes/14): the package exposes no core/* deep paths
|
package/llms.txt
CHANGED
|
@@ -28,7 +28,7 @@ Reading order: docs/AI.md (the index: one line per task) -> the recipe for the t
|
|
|
28
28
|
- [15-perf](docs/recipes/15-perf.md): Performance investigation (F3, budget, profile, describe().perf)
|
|
29
29
|
- [16-dev-bridge](docs/recipes/16-dev-bridge.md): Dev bridge: operate the running game from the terminal (npx threedog describe / step / press / op...)
|
|
30
30
|
- [18-world](docs/recipes/18-world.md): World data: things that must be saved, grow, and keep changing while far away
|
|
31
|
-
- [19-shooting-picking](docs/recipes/19-shooting-picking.md): Shooting and picking (
|
|
31
|
+
- [19-shooting-picking](docs/recipes/19-shooting-picking.md): Shooting and picking (cast a ray from the screen center or the mouse position, with any camera)
|
|
32
32
|
- [20-content-actions-save](docs/recipes/20-content-actions-save.md): Content vocabulary, key actions in actions.js, saving and loading at startup
|
|
33
33
|
- [21-camera](docs/recipes/21-camera.md): Camera: first / third person, top-down strategy, fixed shots, switched at runtime
|
|
34
34
|
- [22-shop-gold](docs/recipes/22-shop-gold.md): Shop and gold: buy, sell / consign, gold HUD, saving
|
|
@@ -36,7 +36,7 @@ Reading order: docs/AI.md (the index: one line per task) -> the recipe for the t
|
|
|
36
36
|
- [26-ui-parts](docs/recipes/26-ui-parts.md): UI parts: replace or turn off any piece of the engine's screen UI
|
|
37
37
|
- [27-net](docs/recipes/27-net.md): Co-op multiplayer: net() (host authority + state sync)
|
|
38
38
|
- [28-terrain](docs/recipes/28-terrain.md): Terrain: your own generator, digging, raising and painting the ground
|
|
39
|
-
- [29-grid](docs/recipes/29-grid.md): Grid placement:
|
|
39
|
+
- [29-grid](docs/recipes/29-grid.md): Grid placement: towers, furniture, buildings, crops
|
|
40
40
|
- [30-templates](docs/recipes/30-templates.md): Templates: reusable objects, definition vs instance state
|
|
41
41
|
- [31-audio](docs/recipes/31-audio.md): Sound: buses, sounds by name, ambience rules, music, footsteps, ducking
|
|
42
42
|
- [32-action-game](docs/recipes/32-action-game.md): Action game wiring: hp, attacks, enemy AI, drops and death without engine combat rules
|
|
@@ -44,18 +44,19 @@ Reading order: docs/AI.md (the index: one line per task) -> the recipe for the t
|
|
|
44
44
|
- [34-environment-lighting](docs/recipes/34-environment-lighting.md): Environment lighting
|
|
45
45
|
- [35-style-from-reference](docs/recipes/35-style-from-reference.md): Making a new look from a reference picture
|
|
46
46
|
- [36-sky-ground-plant-looks](docs/recipes/36-sky-ground-plant-looks.md): Sky, ground and plant looks: what a style can change
|
|
47
|
-
- [37-terrain-look-hooks](docs/recipes/37-terrain-look-hooks.md):
|
|
48
|
-
- [38-environment-look-hooks](docs/recipes/38-environment-look-hooks.md):
|
|
47
|
+
- [37-terrain-look-hooks](docs/recipes/37-terrain-look-hooks.md): Crisp ground color borders, terrain normals, height from a grid
|
|
48
|
+
- [38-environment-look-hooks](docs/recipes/38-environment-look-hooks.md): Owning lights, fog and exposure yourself
|
|
49
49
|
- [40-scene](docs/recipes/40-scene.md): Scene: what is in the world, where, and what a save keeps
|
|
50
50
|
- [41-thing-registry](docs/recipes/41-thing-registry.md): Things: what is in the scene, who manages it, what a save keeps (engine.thing)
|
|
51
51
|
- [42-terrain-shape](docs/recipes/42-terrain-shape.md): Terrain outline: islands, floating rocks, a world that ends
|
|
52
52
|
- [43-shader-patches-surface-looks](docs/recipes/43-shader-patches-surface-looks.md): Writing shader patches and surface looks
|
|
53
|
-
- [44-water-weather-look-hooks](docs/recipes/44-water-weather-look-hooks.md): Water and
|
|
53
|
+
- [44-water-weather-look-hooks](docs/recipes/44-water-weather-look-hooks.md): Water and rain/snow looks: depth color, foam, reflections, particles, lightning
|
|
54
54
|
- [45-cascaded-shadows](docs/recipes/45-cascaded-shadows.md): Cascaded shadows
|
|
55
|
-
- [46-blender-art-route](docs/recipes/46-blender-art-route.md):
|
|
56
|
-
- [47-island-snow-backdrop](docs/recipes/47-island-snow-backdrop.md):
|
|
55
|
+
- [46-blender-art-route](docs/recipes/46-blender-art-route.md): Blender to game (GLB) route
|
|
56
|
+
- [47-island-snow-backdrop](docs/recipes/47-island-snow-backdrop.md): Snow cover, flat backdrop, rounded terrain rim
|
|
57
57
|
- [48-make-material](docs/recipes/48-make-material.md): 48. `engine.makeMaterial(role, spec)`: which keys work, who wins
|
|
58
|
-
- [49-game-module-contract](docs/recipes/49-game-module-contract.md): Writing a game system module (
|
|
58
|
+
- [49-game-module-contract](docs/recipes/49-game-module-contract.md): Writing a game system module (a smelter, a recharging turret, growing crops) that plugs into the engine's contracts
|
|
59
59
|
- [50-own-renderer](docs/recipes/50-own-renderer.md): Bring your own renderer: `createEngine({ renderer })`
|
|
60
60
|
- [51-capability-catalog](docs/recipes/51-capability-catalog.md): Capability catalog: ask what the game can do before reading docs
|
|
61
61
|
- [52-look](docs/recipes/52-look.md): 52 Change any look: `engine.look`
|
|
62
|
+
- [53-ground-up-close](docs/recipes/53-ground-up-close.md): The ground up close: options and diagnosis
|
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
// Character: procedural rig
|
|
1
|
+
// Character: a body from a model asset (procedural rig from an asset pack, or a glTF model; gray capsule without one) + procedural animation (walk, run, swim, idle breathing)
|
|
2
2
|
// + movement control (ground snap, collision, slope limit, swimming).
|
|
3
|
-
// Used by both player and NPCs
|
|
3
|
+
// Used by both player and NPCs; a skeletal glTF body takes model + clips (or an animation state machine config), control logic stays the same.
|
|
4
4
|
// The mover owns position: only the mover (movers/) changes a character's position inside move(); other systems (pathfinding, triggers, vehicles, loading)
|
|
5
5
|
// request movement via placeAt (teleport), move (direction), enter / exit (vehicles).
|
|
6
6
|
// Characters backed by a world record (the player, recordId = 'player') write position and motion state back to the record after every move / placeAt / enter / exit;
|
|
7
7
|
// the record is saved, world splits near/far by it, the model is just its look.
|
|
8
8
|
// Radius and step height default to engine.movement (the single source of "can walk through" parameters); passing radius / stepHeight overrides it for this character only.
|
|
9
9
|
// How to walk is decided by the mover (movers/: 'simple' default, 'rapier' character controller); feel parameters are identical for both.
|
|
10
|
-
// The procedural body (capsule,
|
|
10
|
+
// The procedural body (capsule, rig read from a model asset, limb swing) is in proceduralRig.js; loading a body by asset name in assetModel.js.
|
|
11
11
|
import * as THREE from 'three';
|
|
12
12
|
import { xzOf } from '../../core/math.js';
|
|
13
13
|
import { placeY } from '../../core/ground.js';
|
|
@@ -15,14 +15,13 @@ import { warnOnce, warnMissing } from '../../core/validate.js';
|
|
|
15
15
|
import { reportError } from '../../core/errors.js';
|
|
16
16
|
import { simpleMover } from './movers/simple.js';
|
|
17
17
|
import { rapierMover } from './movers/rapier.js';
|
|
18
|
-
import { loadAssetModel } from './assetModel.js';
|
|
19
|
-
import { NO_CHARACTER, capsule, useRig, animateRig } from './proceduralRig.js';
|
|
18
|
+
import { loadAssetModel, buildNow, checkStyleCharacter } from './assetModel.js';
|
|
19
|
+
import { NO_CHARACTER, capsule, useRig, animateRig, rigFromObject, tintParts } from './proceduralRig.js';
|
|
20
20
|
import { walkTo } from './walkTo.js';
|
|
21
21
|
import { useModel } from './useModel.js';
|
|
22
22
|
|
|
23
23
|
const STRINGS = { noClip: 'character has no skeletal animation; playAction(\'{name}\') skipped (the model needs this action)' };
|
|
24
24
|
const MOVERS = { simple: simpleMover, rapier: rapierMover };
|
|
25
|
-
// Default action names for the clips shorthand (character state -> glTF action name)
|
|
26
25
|
|
|
27
26
|
// Options Character understands (shared by player and NPC)
|
|
28
27
|
export const CHARACTER_KEYS = ['colors', 'speed', 'runSpeed', 'radius', 'canSwim', 'swimDepth', 'swimSpeed', 'turnSpeed', 'acceleration', 'gravity',
|
|
@@ -32,7 +31,9 @@ const FACE_MODES = ['move', 'camera', 'target', 'manual'];
|
|
|
32
31
|
export class Character {
|
|
33
32
|
/**
|
|
34
33
|
* @param engine
|
|
35
|
-
* @param o
|
|
34
|
+
* @param o model: the body, one path for all: a model asset name (a procedural builder from an asset pack, or a GLB name), or what
|
|
35
|
+
* engine.assets.model() returned; without model and rig a gray capsule (warned once). rig: a ready body (proceduralRig.js format)
|
|
36
|
+
* colors: { body, skin, legs, hair } per-character part colors (meshes marked userData.part); the style tints parts by material role
|
|
36
37
|
* speed walk speed, runSpeed run speed (m/s), radius collision radius
|
|
37
38
|
* canSwim whether it can swim (false: never enters water), swimDepth water depth at which swimming starts, swimSpeed swim speed multiplier
|
|
38
39
|
* turnSpeed how fast it turns, acceleration how fast it starts/stops
|
|
@@ -41,13 +42,11 @@ export class Character {
|
|
|
41
42
|
* model + clips: optional glTF model and action-name map { idle, walk, run, swim, jump, fall, drive } (shorthand for animation)
|
|
42
43
|
* animation: animation state machine config (see core/Animator.js), state names are character state names;
|
|
43
44
|
* without walk/run, move (blend tree, param speed) is used
|
|
44
|
-
* rig: a ready body in the format style.character.create returns (proceduralRig.js), used instead of the style pack's (hand-built guard / pet)
|
|
45
45
|
* mover: 'simple' (default) | 'rapier' (Rapier character controller, needs the rigid module)
|
|
46
46
|
* faceMode which way it turns each move: 'move' (default, toward its velocity) | 'camera' (along cameraRig.forward(), over-the-shoulder aiming)
|
|
47
47
|
* | 'target' (toward faceTarget: Object3D / Vector3 / { x, z }, lock-on strafing) | 'manual' (only face() turns it);
|
|
48
48
|
* both are plain properties, change them at any time
|
|
49
|
-
*
|
|
50
|
-
* without model: style pack style.character.create(engine, colors) may return a custom procedural character (rig format below), else a gray capsule
|
|
49
|
+
* a file model name shows the capsule until it loads, then is swapped in (assetModel.js)
|
|
51
50
|
*/
|
|
52
51
|
constructor(engine, { colors = {}, speed = 4.5, runSpeed = 7, radius = engine.movement.radius, canSwim = true, swimDepth = 1.0, swimSpeed = 0.45,
|
|
53
52
|
turnSpeed = 10, acceleration = 12, gravity = -24, jumpSpeed = 8, stepHeight = engine.movement.stepHeight, airControl = 0.35, coyoteTime = 0.12,
|
|
@@ -76,18 +75,21 @@ export class Character {
|
|
|
76
75
|
if (!MOVERS[mover]) warnMissing('mover', mover, Object.keys(MOVERS));
|
|
77
76
|
const simple = simpleMover(this);
|
|
78
77
|
this.mover = mover === 'rapier' ? rapierMover(this, simple) : simple;
|
|
79
|
-
//
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
model
|
|
83
|
-
if (
|
|
84
|
-
// style-pack procedural character: the rig format is in proceduralRig.js
|
|
85
|
-
rig ??= engine.style.character?.create?.(engine, c);
|
|
78
|
+
checkStyleCharacter(engine); // bodies are assets now: an old style.character.create / model / colors throws renamed-api
|
|
79
|
+
this._colors = colors;
|
|
80
|
+
// one path for every body: an object, a procedural builder built now (joints exist at once), or a file asset loaded behind a capsule
|
|
81
|
+
const now = typeof model === 'string' ? buildNow(engine, model) : model;
|
|
82
|
+
if (now) { this._useModel(now, clips, animation); return; }
|
|
86
83
|
if (!rig && !model) warnOnce(NO_CHARACTER);
|
|
87
|
-
useRig(this, rig || capsule(
|
|
84
|
+
useRig(this, rig || capsule(colors.body ?? 0x8a8a8a, engine));
|
|
88
85
|
if (model) this._whenReady = loadAssetModel(this, model, m => this._useModel(m, clips, animation));
|
|
89
86
|
}
|
|
90
|
-
|
|
87
|
+
/** A model object with userData.rig is a procedural body (limb swing); anything else animates by its clips */
|
|
88
|
+
_useModel(model, clips, animation) {
|
|
89
|
+
const r = rigFromObject(model);
|
|
90
|
+
if (r) useRig(this, r); else useModel(this, model, clips, animation);
|
|
91
|
+
tintParts(model, this._colors);
|
|
92
|
+
}
|
|
91
93
|
|
|
92
94
|
/**
|
|
93
95
|
* Walk to a point along characters.findPath on fixed steps (turn rate, skips passed points, re-plans when stuck). Returns a promise of
|
|
@@ -1,18 +1,46 @@
|
|
|
1
|
-
// Character
|
|
2
|
-
// A
|
|
3
|
-
//
|
|
4
|
-
//
|
|
1
|
+
// Character body named by asset (Character({ model: 'humanoid' | 'hero' })): construction is synchronous, loading is not.
|
|
2
|
+
// A procedural builder (manifest models: { humanoid: fn }, an asset pack's models) is built right here (buildNow), so its joints exist as soon as the
|
|
3
|
+
// character does and no placeholder frame shows. A file model already loaded is swapped in at once (engine.assets.modelNow); otherwise the
|
|
4
|
+
// character keeps its gray capsule until engine.assets.model(name) resolves, then the copy (SkeletonUtils clone, so many characters share one
|
|
5
|
+
// asset) replaces the body under the same root: position, facing, state and every reference to the character or its root (collision,
|
|
6
|
+
// interactions, world view) stay valid.
|
|
7
|
+
import * as THREE from 'three';
|
|
5
8
|
import { warnOnce } from '../../core/validate.js';
|
|
6
9
|
import { fmt } from '../../core/opsCheck.js';
|
|
10
|
+
import { renamed } from '../../core/errorHints.js';
|
|
11
|
+
import { makeMaterial } from '../../render/materials.js';
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Bodies are assets, not style (0.2): a style pack that still gives style.character.create / model / colors throws renamed-api at once,
|
|
15
|
+
* instead of silently getting gray capsules. style.character.animation (default fade) stays: it is a look of motion, not a body.
|
|
16
|
+
*/
|
|
17
|
+
export function checkStyleCharacter(engine) {
|
|
18
|
+
const sc = engine.style.character;
|
|
19
|
+
if (sc && ('create' in sc || 'model' in sc || 'colors' in sc)) renamed('characterBody');
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Build a procedural model asset now (synchronously) when `name` is a registered builder; null when it is a file model, unknown, or the
|
|
24
|
+
* builder is async (those load through loadAssetModel). The builder gets this = { palette: style.palette, engine } like engine.assets.cached.
|
|
25
|
+
*/
|
|
26
|
+
export function buildNow(engine, name) {
|
|
27
|
+
const build = engine.assets.builder(name);
|
|
28
|
+
if (!build) return null;
|
|
29
|
+
const v = build.call({ palette: engine.style.palette, engine });
|
|
30
|
+
if (!v || typeof v.then === 'function') return null;
|
|
31
|
+
if (v.isBufferGeometry) return new THREE.Mesh(v, makeMaterial('character', { vertexColors: !!v.attributes.color }, engine));
|
|
32
|
+
if (!v.name) v.name = name;
|
|
33
|
+
return v;
|
|
34
|
+
}
|
|
7
35
|
|
|
8
36
|
const STRINGS = {
|
|
9
|
-
unknown: 'Character model "{name}" is not a registered model asset (registered: {list}). Fix: use one of those names, or register it first: engine.assets.manifest({ models: { {name}: \'/models/{name}.glb\' } })',
|
|
37
|
+
unknown: 'Character model "{name}" is not a registered model asset (registered: {list}). Fix: use one of those names, or register it first: engine.assets.manifest({ models: { {name}: \'/models/{name}.glb\' } }). A procedural body is a generator in an asset pack (engine.assets.manifest(yourAssets)); without a model the player is a gray capsule',
|
|
10
38
|
failed: 'Character model "{name}" did not load ({why}); the character keeps its placeholder body. Registered models: {list}; engine.loading has the error',
|
|
11
39
|
};
|
|
12
40
|
|
|
13
41
|
/**
|
|
14
42
|
* Start loading the asset model for ch; returns the promise stored as ch.whenReady (never rejects).
|
|
15
|
-
* Throws at once when
|
|
43
|
+
* Throws at once when no model asset has the name (paths with / or . load as files).
|
|
16
44
|
* @param {import('./Character.js').Character} ch
|
|
17
45
|
* @param {string} name
|
|
18
46
|
* @param {(model: any) => void} use builds the model and Animator on ch
|
|
@@ -21,7 +49,7 @@ export function loadAssetModel(ch, name, use) {
|
|
|
21
49
|
const e = ch.engine, A = e.assets;
|
|
22
50
|
const names = [...A.entries].filter(([, x]) => x.type === 'model' && x.named).map(([n]) => n);
|
|
23
51
|
const list = names.join(', ') || 'none; register them with engine.assets.manifest({ models })';
|
|
24
|
-
if (
|
|
52
|
+
if (!names.includes(name) && !/[/.]/.test(name)) throw new Error(fmt(STRINGS.unknown, { name, list }));
|
|
25
53
|
const fail = why => warnOnce(fmt(STRINGS.failed, { name, why, list }));
|
|
26
54
|
const swap = m => {
|
|
27
55
|
if (ch._disposed || e.disposed) { e.remove(m); return; } // removed before loading finished: never reaches the scene, the copy is released
|
|
@@ -1,16 +1,50 @@
|
|
|
1
|
-
// The procedural body of a Character (split out of Character.js): the gray capsule used when
|
|
2
|
-
// and the limb swing / body bob used
|
|
3
|
-
// A rig is { root, body?, head?, joints?: { name: Group }, limbs: [{ joint, offset: 0 | Math.PI, amp, kind: 'arm' | 'leg', side? }] }
|
|
1
|
+
// The procedural body of a Character (split out of Character.js): the gray capsule used when no model gives a body, attaching a rig, reading a rig
|
|
2
|
+
// out of a model asset (a pack's humanoid), per-character part colors, and the limb swing / body bob used without skeletal animation.
|
|
3
|
+
// A rig is { root, body?, head?, joints?: { name: Group }, limbs: [{ joint, offset: 0 | Math.PI, amp, kind: 'arm' | 'leg', side? }] }.
|
|
4
|
+
// A model asset carries the same thing as plain data by object NAME in root.userData.rig: names, not references, because userData survives
|
|
5
|
+
// clone and GLB export and object references do not; so a procedural builder and a baked / hand-made GLB with those names animate the same way.
|
|
4
6
|
import * as THREE from 'three';
|
|
5
7
|
import { makeMaterial } from '../../render/materials.js';
|
|
6
8
|
import { warnOnce } from '../../core/validate.js';
|
|
7
9
|
|
|
8
|
-
/** Warned once when no
|
|
9
|
-
export const NO_CHARACTER = 'characters: no
|
|
10
|
-
+ "
|
|
11
|
-
+ "
|
|
10
|
+
/** Warned once when no model gives the character a body */
|
|
11
|
+
export const NO_CHARACTER = 'characters: no model given, so characters are gray capsules (a placeholder). Character bodies are assets: '
|
|
12
|
+
+ "register a pack's models (engine.assets.manifest(yourAssets)) and pass createPlayer({ model: 'yourBody' }), "
|
|
13
|
+
+ "a GLB asset name ({ model: 'hero' }), or a ready body ({ rig })";
|
|
12
14
|
|
|
13
|
-
/**
|
|
15
|
+
/**
|
|
16
|
+
* The rig a model asset describes in root.userData.rig ({ body, head, joints: [names], limbs: [{ joint: name, offset, amp, kind, side }] }), names
|
|
17
|
+
* resolved to this copy's objects; null without rig data (a skinned GLB animates by clips instead).
|
|
18
|
+
* @param {THREE.Object3D} root
|
|
19
|
+
*/
|
|
20
|
+
export function rigFromObject(root) {
|
|
21
|
+
const d = root?.userData?.rig;
|
|
22
|
+
if (!d) return null;
|
|
23
|
+
const get = n => {
|
|
24
|
+
const o = n ? root.getObjectByName(n) : null;
|
|
25
|
+
if (n && !o) warnOnce(`character model "${root.name || 'model'}": userData.rig names "${n}", but the model has no object with that name`);
|
|
26
|
+
return o || null;
|
|
27
|
+
};
|
|
28
|
+
const joints = {};
|
|
29
|
+
for (const n of d.joints || []) { const o = get(n); if (o) joints[n] = o; }
|
|
30
|
+
const limbs = (d.limbs || []).map(L => ({ ...L, joint: get(L.joint) })).filter(L => L.joint);
|
|
31
|
+
return { root, body: get(d.body), head: get(d.head), joints, limbs };
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Per-character part colors ({ colors: { body: 0x4f6d8f } }): meshes marked userData.part get their own copy of the material in that color.
|
|
36
|
+
* A copy, because asset copies share materials: recoloring in place would recolor every character using the model.
|
|
37
|
+
*/
|
|
38
|
+
export function tintParts(root, colors) {
|
|
39
|
+
if (!colors || !Object.keys(colors).length) return;
|
|
40
|
+
root.traverse(o => {
|
|
41
|
+
const c = o.isMesh ? colors[o.userData.part] : null;
|
|
42
|
+
if (c == null || !o.material?.color) return;
|
|
43
|
+
o.material = o.material.clone(); o.material.color.set(c);
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Neutral placeholder when no model gives a body: one gray capsule, no limbs (body shapes belong to asset packs) */
|
|
14
48
|
export function capsule(color, engine) {
|
|
15
49
|
const body = new THREE.Group(); body.position.y = 0.85;
|
|
16
50
|
const m = new THREE.Mesh(new THREE.CapsuleGeometry(0.3, 1.0, 4, 12).translate(0, -0.05, 0), makeMaterial('character', { color }, engine));
|
|
@@ -21,11 +55,12 @@ export function capsule(color, engine) {
|
|
|
21
55
|
|
|
22
56
|
/** Put a rig under the character root and remember its parts */
|
|
23
57
|
export function useRig(ch, rig) {
|
|
24
|
-
ch.root.add(rig.root);
|
|
58
|
+
if (rig.root.parent !== ch.root) ch.root.add(rig.root);
|
|
59
|
+
ch._rig = rig;
|
|
25
60
|
ch.hips = rig.body || rig.root; ch.head = rig.head || null;
|
|
26
61
|
ch.bodyBase = ch.hips.position.y;
|
|
27
62
|
ch.limbs = rig.limbs || [];
|
|
28
|
-
// named joints (
|
|
63
|
+
// named joints (a humanoid rig: armL armR legL legR) become properties so game poses can grab them; never shadow a Character field
|
|
29
64
|
for (const k in rig.joints || {}) {
|
|
30
65
|
if (!(k in ch)) ch[k] = rig.joints[k];
|
|
31
66
|
else if (ch[k] !== rig.joints[k]) warnOnce(`character rig: joint "${k}" has the same name as the Character field ch.${k}, so ch.${k} stays the field; use rig.joints.${k} (or rename the joint)`);
|
package/modules/content/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// Content loader: hands the plain data in the game's content/*.js to the engine (items, pickups, vegetation, NPCs, dialogues, quests, key actions, trigger
|
|
2
2
|
// zones, props).
|
|
3
3
|
// engine.use(content());
|
|
4
|
-
// engine.assets.manifest(
|
|
4
|
+
// engine.assets.manifest(yourAssets); // models content names (an asset pack; content never holds paths or code)
|
|
5
5
|
// engine.content.load(data, { places: { home: { x, z } } }); // or several packs at once: load([base, dlc, level]) (packs.js)
|
|
6
6
|
// Condition/effect vocabulary is in rules.js. Games add condition words (content/rules.js, or content.condition(name, { test }) in code);
|
|
7
7
|
// a game's own actions are ops, called from content with { op: ['noun.verb', args] } and tested with { can: [...] }.
|