threedog 0.1.0 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/core/Animator.js +1 -0
- package/core/Assets.js +16 -0
- package/core/DebugOverrides.js +143 -0
- package/core/Describe.js +14 -3
- package/core/Engine.js +32 -69
- package/core/Events.js +59 -1
- package/core/I18n.js +2 -2
- package/core/Inspect.js +12 -32
- package/core/InspectScene.js +7 -3
- package/core/MaterialInfo.js +32 -0
- package/core/Ops.js +43 -59
- package/core/Saves.js +5 -4
- package/core/UrlState.js +3 -2
- package/core/Vars.js +1 -0
- package/core/Views.js +49 -0
- package/core/actor.js +2 -2
- package/core/assetReport.js +83 -0
- package/core/catalog.js +169 -0
- package/core/checks.js +67 -0
- package/core/claims.js +51 -0
- package/core/debugView.js +76 -0
- package/core/describeRender.js +45 -0
- package/core/describeText.js +11 -4
- package/core/errorCodes.js +33 -0
- package/core/errorHints.js +6 -1
- package/core/holds.js +106 -0
- package/core/lifecycle.js +1 -0
- package/core/lightWatch.js +23 -3
- package/core/look/coreParts.js +112 -0
- package/core/look/layers.js +136 -0
- package/core/look/part.js +173 -0
- package/core/look/report.js +79 -0
- package/core/look/write.js +86 -0
- package/core/loop.js +15 -14
- package/core/modules.js +19 -5
- package/core/opsAtomic.js +31 -0
- package/core/opsCheck.js +25 -14
- package/core/opsFail.js +20 -0
- package/core/opsHistory.js +6 -6
- package/core/opsRun.js +77 -0
- package/core/params.js +132 -0
- package/core/renamed.js +21 -0
- package/core/saveApply.js +2 -2
- package/core/sceneMethods.js +9 -34
- package/core/services.js +73 -0
- package/core/startup.js +3 -1
- package/core/styleParts.js +2 -2
- package/core/thingExplain.js +68 -0
- package/core/thingOps.js +35 -24
- package/core/things.js +15 -1
- package/core/util.js +11 -0
- package/core/validate.js +23 -7
- package/docs/AI.md +83 -109
- package/docs/API.md +7 -8
- package/docs/CODEMAP.md +63 -51
- package/docs/COMMANDS.md +17 -5
- package/docs/CONVENTIONS.md +17 -6
- package/docs/THREE.md +3 -3
- package/docs/api/assets.md +2 -0
- package/docs/api/characters.md +2 -0
- package/docs/api/collision.md +4 -0
- package/docs/api/content.md +1 -0
- package/docs/api/engine.md +20 -11
- package/docs/api/events.md +5 -1
- package/docs/api/post.md +5 -4
- package/docs/api/saves.md +2 -1
- package/docs/api/sky.md +3 -3
- package/docs/api/style.md +3 -3
- package/docs/api/tools.md +2 -0
- package/docs/api/weather.md +1 -1
- package/docs/recipes/02-npc.md +16 -0
- package/docs/recipes/03-items-pickups.md +1 -1
- package/docs/recipes/06-clock-events.md +13 -0
- package/docs/recipes/07-flow-scenes-pause.md +4 -0
- package/docs/recipes/08-weather-sky.md +1 -1
- package/docs/recipes/09-style-pack.md +5 -5
- package/docs/recipes/12-navmesh.md +22 -0
- package/docs/recipes/13-animation.md +3 -0
- package/docs/recipes/15-perf.md +1 -1
- package/docs/recipes/16-dev-bridge.md +51 -17
- package/docs/recipes/21-camera.md +51 -2
- package/docs/recipes/23-ops.md +45 -9
- package/docs/recipes/27-net.md +1 -1
- package/docs/recipes/29-grid.md +1 -1
- package/docs/recipes/34-environment-lighting.md +9 -8
- package/docs/recipes/38-environment-look-hooks.md +8 -6
- package/docs/recipes/40-scene.md +29 -0
- package/docs/recipes/41-thing-registry.md +29 -0
- package/docs/recipes/43-shader-patches-surface-looks.md +2 -0
- package/docs/recipes/44-water-weather-look-hooks.md +6 -4
- package/docs/recipes/45-cascaded-shadows.md +1 -1
- package/docs/recipes/46-blender-art-route.md +22 -0
- package/docs/recipes/48-make-material.md +70 -0
- package/docs/recipes/49-game-module-contract.md +71 -0
- package/docs/recipes/50-own-renderer.md +12 -0
- package/docs/recipes/51-capability-catalog.md +63 -0
- package/docs/recipes/52-look.md +108 -0
- package/examples/action/GAMEMAP.md +5 -5
- package/examples/action/content/index.js +2 -1
- package/examples/action/content/views.js +6 -0
- package/examples/sheepisland/GAMEMAP.md +2 -3
- package/examples/styletest/GAMEMAP.md +3 -3
- package/examples/styletest/main.js +1 -1
- package/examples/styletest/panel.js +3 -3
- package/examples/world/GAMEMAP.md +3 -3
- package/index.d.ts +27 -0
- package/index.js +3 -1
- package/llms.txt +5 -0
- package/modules/ambience/Ambience.js +5 -2
- package/modules/camera/FirstPersonCamera.js +3 -5
- package/modules/camera/FixedCamera.js +19 -12
- package/modules/camera/FollowCamera.js +14 -8
- package/modules/camera/RtsCamera.js +3 -5
- package/modules/camera/common.js +40 -10
- package/modules/camera/index.js +1 -1
- package/modules/camera/projection.js +34 -0
- package/modules/characters/Character.js +29 -17
- package/modules/characters/astar.js +14 -7
- package/modules/characters/index.js +6 -3
- package/modules/characters/movers/simple.js +6 -1
- package/modules/characters/npcSim.js +8 -2
- package/modules/characters/pathAsync.js +12 -6
- package/modules/characters/pathJob.js +2 -1
- package/modules/characters/proceduralRig.js +5 -1
- package/modules/characters/useModel.js +22 -0
- package/modules/characters/walkTo.js +58 -0
- package/modules/collision/Collision.js +102 -4
- package/modules/content/explain.js +13 -0
- package/modules/content/index.js +2 -0
- package/modules/content/loader.js +3 -0
- package/modules/content/rules.js +1 -0
- package/modules/debug/DebugPanel.js +11 -5
- package/modules/entities/Entities.js +6 -2
- package/modules/flow/index.js +5 -2
- package/modules/gameplay/Dialogue.js +5 -2
- package/modules/gameplay/Interactions.js +12 -2
- package/modules/gameplay/Inventory.js +21 -11
- package/modules/gameplay/Quests.js +13 -3
- package/modules/gameplay/pickups.js +5 -3
- package/modules/grid/Layer.js +1 -1
- package/modules/grid/index.js +1 -1
- package/modules/grid/tiles.js +9 -5
- package/modules/hlod/index.js +5 -2
- package/modules/hud/index.js +5 -2
- package/modules/level/index.js +5 -3
- package/modules/lights/index.js +5 -2
- package/modules/music/Music.js +6 -2
- package/modules/nav/index.js +5 -3
- package/modules/net/Client.js +4 -3
- package/modules/net/Host.js +2 -2
- package/modules/net/index.js +5 -3
- package/modules/particles/Particles.js +1 -1
- package/modules/photo/Photo.js +10 -7
- package/modules/rigid/RigidBodies.js +5 -2
- package/modules/settings/Settings.js +6 -3
- package/modules/settings/apply.js +2 -1
- package/modules/sky/Sky.js +21 -19
- package/modules/sky/cascades.js +6 -6
- package/modules/sky/domeLayers.js +1 -1
- package/modules/sky/environment.js +39 -13
- package/modules/sky/fog.js +9 -6
- package/modules/sky/frame.js +4 -3
- package/modules/sky/look.js +3 -2
- package/modules/sky/lookFog.js +80 -0
- package/modules/sky/lookShadow.js +50 -0
- package/modules/sky/lookSky.js +108 -0
- package/modules/sky/shader.js +2 -2
- package/modules/sky/shadow.js +4 -10
- package/modules/sky/skyModule.js +4 -3
- package/modules/terrain/ChunkManager.js +2 -33
- package/modules/terrain/chunkLevels.js +40 -0
- package/modules/terrain/index.js +10 -2
- package/modules/terrain/lookGround.js +61 -0
- package/modules/timeline/Timeline.js +7 -3
- package/modules/timeline/Tween.js +3 -7
- package/modules/timeline/shots.js +6 -4
- package/modules/triggers/index.js +9 -2
- package/modules/vegetation/Vegetation.js +2 -1
- package/modules/vegetation/index.js +6 -3
- package/modules/vegetation/lookWind.js +37 -0
- package/modules/water/Water.js +19 -3
- package/modules/water/look.js +80 -0
- package/modules/weather/Weather.js +22 -31
- package/modules/weather/look.js +75 -0
- package/modules/weather/particles.js +1 -1
- package/modules/weather/strings.js +15 -0
- package/modules/world/explain.js +11 -0
- package/modules/world/index.js +11 -4
- package/modules/world/thingSource.js +44 -0
- package/package.json +1 -1
- package/render/PostFX.js +48 -51
- package/render/effects.js +4 -2
- package/render/fuse.js +12 -0
- package/render/lights.js +4 -2
- package/render/lookSurface.js +161 -0
- package/render/materials.js +27 -10
- package/render/postLook.js +86 -0
- package/render/surface.js +3 -1
- package/types/core.d.ts +216 -24
- package/types/gameplay.d.ts +10 -0
- package/types/generated/core/DebugOverrides.d.ts +52 -0
- package/types/generated/core/Events.d.ts +43 -0
- package/types/generated/core/Ops.d.ts +62 -21
- package/types/generated/core/Saves.d.ts +1 -0
- package/types/generated/core/Views.d.ts +33 -0
- package/types/generated/modules/debug/DebugPanel.d.ts +2 -2
- package/types/generated/modules/grid/Layer.d.ts +1 -0
- package/types/generated/modules/sky/Sky.d.ts +10 -17
- package/types/generated/modules/weather/Weather.d.ts +5 -15
- package/types/generated/render/PostFX.d.ts +20 -23
- package/types/generated/render/materials.d.ts +10 -0
- package/types/physics.d.ts +8 -0
- package/types/style.d.ts +16 -6
- package/ui/Parts.js +6 -2
- package/ui/UI.js +1 -1
- package/ui/defaults.js +1 -1
- package/docs/api/debug.md +0 -10
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
// look.ground: how the terrain looks (colors, variation, shading, detail layer, material). Registered by the terrain module.
|
|
2
|
+
// set({ colors, biomeColors, steep, variation, shading, detail })
|
|
3
|
+
// colors / biomeColors / steep / variation / shading are baked into the chunks by the workers: a change rebuilds every chunk (cost 'rebuild';
|
|
4
|
+
// edits stay). colors / biomeColors / steep are given whole (they replace the style's table), variation / detail are objects (style.terrain.*).
|
|
5
|
+
// patch('detail', glsl) the detail layer's `vec4 threedogDetailSample(vec2 p)` (render/detail.js); a detail object must be set too
|
|
6
|
+
// replace(Material | (engine) => Material) the ground material (terrain({ material }) / style.terrain.material is the first one); null gives it back
|
|
7
|
+
// Why not in ChunkManager.js: that file is at its size cap, and every ground option below already reached it as config before; this only
|
|
8
|
+
// writes the same config again when a verb changes it.
|
|
9
|
+
import { defineLookPart, REPLACE } from '../../core/look/part.js';
|
|
10
|
+
import { terrainMaterial } from '../../render/materials.js';
|
|
11
|
+
|
|
12
|
+
const GEN = ['colors', 'biomeColors', 'steep', 'variation', 'shading'];
|
|
13
|
+
const isObj = v => (v && typeof v === 'object' ? null : 'must be an object');
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* @param {any} e @param {any} w the ChunkManager
|
|
17
|
+
* @param {{ cfg: () => any, setCfg: (c: any) => void, game: Record<string, any> }} h the module's current terrain config, and what terrain({...}) itself passed (written as owner 'terrain()')
|
|
18
|
+
*/
|
|
19
|
+
export function defineGroundLook(e, w, h) {
|
|
20
|
+
const st = e.style.terrain ?? {}, cfg0 = h.cfg();
|
|
21
|
+
const rebuild = 'rebuild';
|
|
22
|
+
const part = defineLookPart(e, {
|
|
23
|
+
id: 'ground', group: 'surface', module: 'terrain', object: () => w.terrainMat, applyAtStart: false, docs: ['recipes/52-look.md'],
|
|
24
|
+
params: {
|
|
25
|
+
colors: { type: 'any', default: {}, neutral: true, cost: rebuild, check: isObj, desc: 'palette name -> color; the whole table (a ground type without a color is neutral gray)' },
|
|
26
|
+
biomeColors: { type: 'any', default: {}, neutral: true, cost: rebuild, check: isObj, desc: 'ground type -> palette name(s); the whole table' },
|
|
27
|
+
steep: { type: 'array', default: [], neutral: true, cost: rebuild, desc: 'slope colors [{ maxNormalY, colors }]' },
|
|
28
|
+
variation: { type: 'any', default: null, neutral: true, cost: rebuild, check: isObj, desc: '{ blend, jitter, patches } color variation (style.terrain.variation); null = none' },
|
|
29
|
+
shading: { type: 'string', values: ['smooth', 'flat', 'texture'], default: 'smooth', cost: rebuild,
|
|
30
|
+
why: 'terrain colors are blended per grid point (smooth) so the ground has no visible facets', off: "look.ground.set({ shading: 'flat' }) for one color per triangle, or 'texture' for a per-chunk color map" },
|
|
31
|
+
detail: { type: 'any', default: null, neutral: true, cost: 'recompile', check: isObj, desc: '{ texture | noise | glsl, scale, strength ... } detail layer over the ground (style.terrain.detail); null = none' },
|
|
32
|
+
},
|
|
33
|
+
style: () => ({ colors: st.colors, biomeColors: st.biomeColors, steep: st.steep, variation: st.variation, shading: st.config?.shading, detail: st.detail, [REPLACE]: st.material }),
|
|
34
|
+
read: () => ({}),
|
|
35
|
+
hooks: { detail: { signature: 'vec4 threedogDetailSample(vec2 p) // rgb + height 0-1', scope: ['fragment'], example: "engine.look.ground.patch('detail', glsl)" } },
|
|
36
|
+
replace: { accepts: 'a Material, or (engine) => Material; null gives the style\'s back', loses: ['the style\'s terrain material (cloud shadows and season tint are added to the new one)'] },
|
|
37
|
+
applyReplace: () => material(), applyHook: () => material(),
|
|
38
|
+
apply(v, changed) {
|
|
39
|
+
if (changed.has('detail')) material();
|
|
40
|
+
if (!GEN.some(k => changed.has(k))) return;
|
|
41
|
+
const next = { ...h.cfg() };
|
|
42
|
+
for (const k of GEN) if (changed.has(k)) { if (v[k] == null) delete next[k]; else next[k] = v[k]; }
|
|
43
|
+
if (!next.shading) next.shading = cfg0.shading;
|
|
44
|
+
h.setCfg(next);
|
|
45
|
+
const species = {}; for (const sp of e.vegetation?.list() || []) species[sp.name] = sp.rule;
|
|
46
|
+
w.reinit(next, species);
|
|
47
|
+
},
|
|
48
|
+
});
|
|
49
|
+
// what terrain({ colors, shading, material ... }) itself was given sits on the game layer under the owner 'terrain()', so describe shows it
|
|
50
|
+
const given = {};
|
|
51
|
+
for (const k of GEN) if (h.game[k] !== undefined) given[k] = h.game[k];
|
|
52
|
+
if (h.game.material !== undefined) given[REPLACE] = h.game.material;
|
|
53
|
+
if (Object.keys(given).length) part.write('terrain()', given);
|
|
54
|
+
/** Rebuild the ground material from the resolved replace / detail, then every chunk picks it up */
|
|
55
|
+
function material() {
|
|
56
|
+
const impl = part.value(REPLACE) ?? null;
|
|
57
|
+
w.terrainMat = terrainMaterial(typeof impl === 'function' ? impl(e) : impl, e);
|
|
58
|
+
w.rebuild();
|
|
59
|
+
}
|
|
60
|
+
return part;
|
|
61
|
+
}
|
|
@@ -18,7 +18,7 @@
|
|
|
18
18
|
// Space, which is dialogue "continue"), or click the hint on the letterbox.
|
|
19
19
|
// While frozen (engine.freeze / flow 'paused') wait, tweens, camera and paths do not advance; they resume after unfreezing.
|
|
20
20
|
// On skip all running tweens jump to their end and the remaining steps finish instantly (do steps still run, so state matches a normal playthrough).
|
|
21
|
-
// Camera takeover: a camera step
|
|
21
|
+
// Camera takeover: a camera step takes the camera (engine.takeCamera, see camera/common.js) and releases its claim and restores the view after the whole run; the camera
|
|
22
22
|
// module then resumes.
|
|
23
23
|
// To hand the camera back midway: { camera: { release: true } }
|
|
24
24
|
// General tween (usable anywhere in a game): await engine.timeline.tween(mesh, { 'position.y': 2, 'material.opacity': 0 }, 1, 'outCubic')
|
|
@@ -29,6 +29,7 @@ import { fadeScreen, uiFocus } from '../../ui/UI.js';
|
|
|
29
29
|
import { cameraStep, pathStep, releaseCamera } from './shots.js';
|
|
30
30
|
import { buildLetterbox } from './letterbox.js';
|
|
31
31
|
import { checkOptions } from '../../core/validate.js';
|
|
32
|
+
import { readParams, keysSchema } from '../../core/params.js';
|
|
32
33
|
/** @import { ModuleDef } from '../../types/core' */
|
|
33
34
|
/** @import { Ease } from '../../types/common' */
|
|
34
35
|
/** @import { TimelineStep, TimelinePlayOptions, TimelineOptions, TweenTo, TweenPromise } from '../../types/gameplay' */
|
|
@@ -217,6 +218,8 @@ const STRINGS = {
|
|
|
217
218
|
en: { 'timeline.skip': '{key:skip} Skip', 'timeline.skipAction': 'Skip cutscene' },
|
|
218
219
|
};
|
|
219
220
|
|
|
221
|
+
const TIMELINE_PARAMS = keysSchema(['skipKeys']);
|
|
222
|
+
|
|
220
223
|
/**
|
|
221
224
|
* Timeline (cutscenes, tweens) -> engine.timeline.
|
|
222
225
|
* timeline({ skipKeys: ['Escape', 'Backspace'] })(timeline({ skipKeys: ['Escape', 'Backspace'] }) (Esc is the back key, dispatched by the UI focus stack)
|
|
@@ -225,11 +228,12 @@ const STRINGS = {
|
|
|
225
228
|
* @returns {ModuleDef<Timeline>}
|
|
226
229
|
*/
|
|
227
230
|
export function timeline(opts = {}) {
|
|
231
|
+
readParams('timeline', TIMELINE_PARAMS, opts);
|
|
228
232
|
let t = null;
|
|
229
233
|
return {
|
|
230
|
-
name: 'timeline', label: 'Timeline', stage: 'control', before: ['cameraRig'], // before the camera, so the takeover applies on the same frame
|
|
234
|
+
name: 'timeline', params: TIMELINE_PARAMS, options: opts, label: 'Timeline', stage: 'control', before: ['cameraRig'], // before the camera, so the takeover applies on the same frame
|
|
231
235
|
install(e) {
|
|
232
|
-
|
|
236
|
+
e.i18n.add(STRINGS); t = new Timeline(e, opts);
|
|
233
237
|
// a running cutscene ends with its playthrough (session waits one macrotask for its steps to settle)
|
|
234
238
|
e.events.on('session:end', () => { if (t.runs.size) t.skip(); });
|
|
235
239
|
return t;
|
|
@@ -9,18 +9,14 @@
|
|
|
9
9
|
import * as THREE from 'three';
|
|
10
10
|
import { ease as easing } from '../../core/easing.js';
|
|
11
11
|
import { allowOwned } from '../../core/validate.js';
|
|
12
|
+
import { getPath } from '../../core/util.js';
|
|
12
13
|
|
|
13
14
|
const COMPS = ['x', 'y', 'z', 'w'];
|
|
14
15
|
|
|
15
16
|
/** 'material.color' → { obj: target.material, key: 'color' } */
|
|
16
17
|
function resolve(target, path) {
|
|
17
|
-
const
|
|
18
|
-
|
|
19
|
-
for (let i = 0; i < parts.length - 1; i++) {
|
|
20
|
-
obj = obj?.[parts[i]];
|
|
21
|
-
if (obj == null) return null;
|
|
22
|
-
}
|
|
23
|
-
return { obj, key: parts[parts.length - 1] };
|
|
18
|
+
const i = path.lastIndexOf('.'), obj = i < 0 ? target : getPath(target, path.slice(0, i));
|
|
19
|
+
return obj == null ? null : { obj, key: path.slice(i + 1) };
|
|
24
20
|
}
|
|
25
21
|
|
|
26
22
|
/** Build an interpolator for a property: returns k => apply progress k (0..1) */
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// Timeline camera and path steps (helper of Timeline.js): a shot takes the camera over
|
|
1
|
+
// Timeline camera and path steps (helper of Timeline.js): a shot takes the camera over with engine.takeCamera (core/holds.js) and gives it back when the run ends;
|
|
2
2
|
// a path moves any object (a character, the camera) along a spline. Each function takes the Timeline as `t`.
|
|
3
3
|
import * as THREE from 'three';
|
|
4
4
|
import { vec3 as v3 } from '../../core/math.js';
|
|
@@ -36,8 +36,10 @@ export function cameraStep(t, c, run) {
|
|
|
36
36
|
function takeCamera(t, run) {
|
|
37
37
|
const e = t.engine;
|
|
38
38
|
if (!run.cam) {
|
|
39
|
-
|
|
40
|
-
|
|
39
|
+
// a claim of its own (engine.takeCamera): a named view or a game holding the camera keeps its claim and gets the camera back afterwards.
|
|
40
|
+
// The owner carries the run id so two overlapping runs are two holders, not one overwriting the other.
|
|
41
|
+
const override = { owner: 'timeline:' + run.id, id: run.id, focus: e.focus.clone() };
|
|
42
|
+
run.cam = { fov: e.camera.fov, look: new THREE.Vector3(), override, hold: e.takeCamera(override.owner, override) };
|
|
41
43
|
}
|
|
42
44
|
return run.cam;
|
|
43
45
|
}
|
|
@@ -46,7 +48,7 @@ export function releaseCamera(t, run) {
|
|
|
46
48
|
const st = run.cam; if (!st) return;
|
|
47
49
|
run.cam = null;
|
|
48
50
|
const e = t.engine;
|
|
49
|
-
|
|
51
|
+
st.hold.remove();
|
|
50
52
|
if (e.camera.fov !== st.fov) { e.camera.fov = st.fov; e.camera.updateProjectionMatrix(); }
|
|
51
53
|
}
|
|
52
54
|
|
|
@@ -32,6 +32,7 @@
|
|
|
32
32
|
// In dev builds F4 (action triggersDebug, rebindable) toggles the display; release builds bind no key unless triggers({ keys }) names one.
|
|
33
33
|
import * as THREE from 'three';
|
|
34
34
|
import { checkOptions, DEV } from '../../core/validate.js';
|
|
35
|
+
import { readParams } from '../../core/params.js';
|
|
35
36
|
|
|
36
37
|
// Zones are indexed by the grid cells their bounding box covers, so a step looks at the zones near the actor instead of every zone. A zone with its own `who`
|
|
37
38
|
// (any position, unknown until it runs) or one covering more than MAX_CELLS cells goes to the always-checked `_global` list.
|
|
@@ -238,13 +239,19 @@ export class Triggers {
|
|
|
238
239
|
}
|
|
239
240
|
}
|
|
240
241
|
|
|
242
|
+
const TRIGGER_PARAMS = {
|
|
243
|
+
debug: { type: 'bool', default: false, desc: 'draw all zones as wireframes from the start' },
|
|
244
|
+
action: { type: 'string', default: 'triggersDebug', desc: 'input action that toggles the debug display' },
|
|
245
|
+
keys: { type: 'array', optional: true, desc: "keys for that toggle (default ['F4'] in dev builds, none in release)" },
|
|
246
|
+
};
|
|
247
|
+
|
|
241
248
|
/** Trigger zone module. Provides engine.triggers once installed. Optional dependency: level (used by fromMarkers) */
|
|
242
249
|
export function triggers(opts = {}) {
|
|
250
|
+
const o = readParams('triggers', TRIGGER_PARAMS, opts);
|
|
243
251
|
let tr = null;
|
|
244
252
|
return {
|
|
245
|
-
name: 'triggers', label: 'Triggers', optional: ['level'], stage: 'gameplay', after: ['interactions'],
|
|
253
|
+
name: 'triggers', label: 'Triggers', params: TRIGGER_PARAMS, options: o, noSkip: 'zone enter/exit is re-evaluated on the next fixed step', optional: ['level'], stage: 'gameplay', after: ['interactions'],
|
|
246
254
|
install(e) {
|
|
247
|
-
checkOptions('triggers()', opts, ['debug', 'action', 'keys']);
|
|
248
255
|
tr = new Triggers(e, opts);
|
|
249
256
|
// audio rule condition { zone: 'cave' | ['cave', 'mine'] }: some trigger zone with that tag is occupied
|
|
250
257
|
e.audio.condition('zone', v => [].concat(v).some(tag => tr.byTag(tag).some(t => t.inside)));
|
|
@@ -6,6 +6,7 @@ import { makeMaterial, applyEffects } from '../../render/materials.js';
|
|
|
6
6
|
import { checkOptions, checkOptionsArg, warnMissing } from '../../core/validate.js';
|
|
7
7
|
import { xzOf } from '../../core/math.js';
|
|
8
8
|
import { GroundChunks } from './groundChunks.js';
|
|
9
|
+
import { swayOf } from './lookWind.js';
|
|
9
10
|
// parameters read by vegetation.add(); keys inside rule (sent to the worker thread)
|
|
10
11
|
const ADD_KEYS = ['geometry', 'model', 'lodGeometry', 'rule', 'wind', 'nearOnly', 'maxRing', 'lodRing', 'castShadow', 'shadowRing', 'receiveShadow', 'material', 'effects', 'doubleSided'];
|
|
11
12
|
const RULE_KEYS = ['perChunk', 'chance', 'minHeight', 'maxHeight', 'maxSlope', 'cluster', 'scale', 'stretch', 'sink', 'tintJitter', 'tints', 'biomes', 'collider', 'avoidFlat', 'salt'];
|
|
@@ -78,7 +79,7 @@ export class Vegetation {
|
|
|
78
79
|
add(name, o) {
|
|
79
80
|
checkOptions(`vegetation.add('${name}')`, o, ADD_KEYS);
|
|
80
81
|
checkOptions(`vegetation.add('${name}').rule`, o.rule, RULE_KEYS);
|
|
81
|
-
const sw = this.engine
|
|
82
|
+
const sw = swayOf(this.engine), wind = o.wind && sw ? { amplitude: o.wind, glsl: sw.glsl, uniforms: sw.uniforms } : o.wind; // look.wind 'sway' (style.wind.glsl or a game's patch) replaces the sway shape
|
|
82
83
|
const fx = m => o.effects === false ? m : applyEffects(m, { wind, season: 'foliage' });
|
|
83
84
|
const mdl = o.model && fromModel(o.model, `vegetation.add('${name}')`);
|
|
84
85
|
let lod = o.lodGeometry?.isObject3D ? fromModel(o.lodGeometry, `vegetation.add('${name}').lodGeometry`).geometry : o.lodGeometry || null;
|
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
// Vegetation module factory: engine.use(vegetation(...)). The class and its chunk plumbing are in Vegetation.js.
|
|
2
|
-
import {
|
|
2
|
+
import { readParams, keysSchema } from '../../core/params.js';
|
|
3
3
|
import { Vegetation } from './Vegetation.js';
|
|
4
|
+
import { defineWindLook } from './lookWind.js';
|
|
4
5
|
|
|
5
6
|
const OPTS = ['chunkSize', 'viewChunks', 'density', 'area', 'seed'];
|
|
7
|
+
const VEG_PARAMS = keysSchema(OPTS, { chunkSize: 32, viewChunks: 3, density: 1, seed: 1 }); // defaults of the own-chunks mode (without terrain)
|
|
6
8
|
/**
|
|
7
9
|
* Vegetation module. Provides engine.vegetation.add(name, {...}) once installed.
|
|
8
10
|
* With terrain() installed first it grows on the terrain chunks and takes no options (density and view distance are terrain options).
|
|
@@ -18,10 +20,11 @@ const OPTS = ['chunkSize', 'viewChunks', 'density', 'area', 'seed'];
|
|
|
18
20
|
* engine.vegetation.add('grass', { geometry, nearOnly: true, rule: { perChunk: 400, biomes: { lawn: 1 } } }); // only on 'lawn' surfaces
|
|
19
21
|
*/
|
|
20
22
|
export function vegetation(opts = {}) {
|
|
21
|
-
|
|
23
|
+
readParams('vegetation', VEG_PARAMS, opts);
|
|
22
24
|
let v = null, own = null, cols = null, ready = null;
|
|
23
|
-
return { name: 'vegetation', label: 'Vegetation', stage: 'world', after: ['terrain', 'level'], optional: ['terrain', 'level'],
|
|
25
|
+
return { name: 'vegetation', label: 'Vegetation', params: VEG_PARAMS, options: opts, stage: 'world', after: ['terrain', 'level'], optional: ['terrain', 'level'],
|
|
24
26
|
install(e) {
|
|
27
|
+
defineWindLook(e); // look.wind
|
|
25
28
|
v = new Vegetation(e, opts);
|
|
26
29
|
if (v.host !== e.terrain) {
|
|
27
30
|
own = v.host;
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
// look.wind: how plants sway. Registered by the vegetation module (it is the one that adds wind patches to its species' materials).
|
|
2
|
+
// set({ frequency, amplitude }) uniforms: live on every wind patch (trees already planted too)
|
|
3
|
+
// patch('sway', glsl) a threedogWind function (style.wind.glsl is the style layer); read when a species is ADDED, so patch before vegetation.add
|
|
4
|
+
// No replace: the sway patch already is the whole motion; weather's gusts (uWind) still scale it.
|
|
5
|
+
import { defineLookPart } from '../../core/look/part.js';
|
|
6
|
+
import { codedError } from '../../core/errorHints.js';
|
|
7
|
+
import { windCustom } from '../../render/materials.js';
|
|
8
|
+
|
|
9
|
+
const asObj = v => (typeof v === 'string' ? { glsl: v } : v);
|
|
10
|
+
/** The custom sway { glsl, uniforms } to give a new wind patch, or null for the built-in sway */
|
|
11
|
+
export function swayOf(e) { const v = e.look?.wind?.value('hook:sway'); return v ? asObj(v) : null; }
|
|
12
|
+
|
|
13
|
+
/** @param {any} e */
|
|
14
|
+
export function defineWindLook(e) {
|
|
15
|
+
if (e.look?.wind) return;
|
|
16
|
+
const u = e.uniforms, w = e.style.wind ?? {};
|
|
17
|
+
const part = defineLookPart(e, {
|
|
18
|
+
id: 'wind', group: 'motion', module: 'vegetation', object: () => u, docs: ['recipes/52-look.md'],
|
|
19
|
+
params: {
|
|
20
|
+
frequency: { type: 'number', default: 1, min: 0, neutral: true, cost: 'uniform', desc: 'sway speed multiplier (style.wind.frequency)' },
|
|
21
|
+
amplitude: { type: 'number', default: 1, min: 0, neutral: true, cost: 'uniform', desc: "multiplies every species' wind amplitude; 0 = plants stand still" },
|
|
22
|
+
},
|
|
23
|
+
style: () => ({ frequency: w.frequency, ...(w.glsl ? { 'hook:sway': { glsl: w.glsl, uniforms: w.uniforms } } : {}) }),
|
|
24
|
+
read: () => ({ frequency: u.uWindFreq.value, amplitude: u.uWindAmp.value }),
|
|
25
|
+
apply(v, changed) {
|
|
26
|
+
if (changed.has('frequency')) u.uWindFreq.value = v.frequency;
|
|
27
|
+
if (changed.has('amplitude')) u.uWindAmp.value = v.amplitude;
|
|
28
|
+
},
|
|
29
|
+
hooks: { sway: { signature: 'void threedogWind(inout vec3 transformed, vec3 ip, vec3 position)', scope: ['vertex'], example: 'engine.look.wind.patch("sway", glsl) // or { glsl, uniforms }' } },
|
|
30
|
+
noReplace: 'the sway patch already is the whole motion; patch("sway", glsl) rewrites it, set({ amplitude: 0 }) stops it',
|
|
31
|
+
});
|
|
32
|
+
const patch = part.patch.bind(part);
|
|
33
|
+
part.patch = (name, glsl, o) => { // a wrong sway function throws here, not later inside vegetation.add
|
|
34
|
+
if (glsl != null) { try { windCustom(asObj(glsl)); } catch (err) { throw codedError('look-param', `look.wind.patch('${name}'): ${err.message}`); } }
|
|
35
|
+
return patch(name, glsl, o);
|
|
36
|
+
};
|
|
37
|
+
}
|
package/modules/water/Water.js
CHANGED
|
@@ -14,20 +14,24 @@ import * as THREE from 'three';
|
|
|
14
14
|
import { makeMaterial } from '../../render/materials.js';
|
|
15
15
|
import { placeholderTexture } from '../../render/effects.js';
|
|
16
16
|
import { patchMaterial } from '../../render/patches.js';
|
|
17
|
-
import {
|
|
17
|
+
import { warnOnce } from '../../core/validate.js';
|
|
18
|
+
import { readParams, keysSchema } from '../../core/params.js';
|
|
18
19
|
import { waterLook, wavesPatch, surfacePatch } from './surface.js';
|
|
20
|
+
import { defineWaterLook } from './look.js';
|
|
19
21
|
/** @import { ModuleDef } from '../../types/core' */
|
|
20
22
|
/** @import { Object3D, Material, Vector3 } from '../../types/common' */
|
|
21
23
|
/** @import { WaterBody, WaterOptions } from '../../types/world' */
|
|
22
24
|
// Options accepted by water(): sea / level + any appearance item that overrides the style pack's style.water
|
|
23
25
|
const WATER_OPTIONS = ['sea', 'level', 'color', 'opacity', 'flat', 'waveHeight', 'waveScale', 'waveSpeed', 'fresnel', 'size', 'segments', 'normalMap',
|
|
24
26
|
'normalScale', 'normalRepeat', 'normalSpeed', 'shininess', 'specular', 'material', 'depthColor', 'foam', 'glsl', 'uniforms'];
|
|
27
|
+
const WATER_PARAMS = keysSchema(WATER_OPTIONS);
|
|
25
28
|
|
|
26
29
|
/** engine.water */
|
|
27
30
|
export class Water {
|
|
28
31
|
/** @internal */
|
|
29
32
|
constructor(engine, opts = {}) {
|
|
30
33
|
/** @internal */ this.engine = engine;
|
|
34
|
+
/** @internal */ this.opts = opts;
|
|
31
35
|
/** @internal */ this.st = { color: 0x888888, opacity: 0.85, flat: true, waveHeight: 1, waveScale: 1, waveSpeed: 1, fresnel: 0.5,
|
|
32
36
|
size: 900, segments: 150, normalScale: 0.4, normalRepeat: 0.05, normalSpeed: [0.01, 0.006], ...(engine.style.water || {}), ...opts };
|
|
33
37
|
const st = this.st;
|
|
@@ -57,6 +61,7 @@ export class Water {
|
|
|
57
61
|
this.sea = null;
|
|
58
62
|
/** @internal */ this._seaChecked = st.sea === false; // global water is built on the first frame: terrain (water level) is installed by then, so no dependence on install order
|
|
59
63
|
for (const b of engine.waterBodies) this._addBody(b);
|
|
64
|
+
defineWaterLook(this); // look.water: the style's values are its style layer, water({...}) options its 'game' layer
|
|
60
65
|
engine.events.on('water:add', b => this._addBody(b));
|
|
61
66
|
// material is shared by all bodies, so not engine.remove (which would dispose it); its ray registration goes too
|
|
62
67
|
engine.events.on('water:remove', b => { const m = this.bodies.get(b); if (m) { engine.detach(m); engine.rays.forget(m); m.geometry.dispose(); this.bodies.delete(b); } });
|
|
@@ -70,6 +75,7 @@ export class Water {
|
|
|
70
75
|
// normal-map scroll running; the built-in look (role 'water', waves, fresnel) is skipped. waves (and surface, when depthColor / foam /
|
|
71
76
|
// glsl.surface ask for one; it needs waves before it) are offered for applyEffects({ patches })
|
|
72
77
|
if (st.material) {
|
|
78
|
+
this._u = waves.uniforms;
|
|
73
79
|
const own = st.material(e, { uniforms: waves.uniforms, waves, surface, normalMap: this.normalMap });
|
|
74
80
|
if (!own?.isMaterial) throw new Error('style.water.material must return a three.js Material, e.g. material: (engine, { uniforms }) => new THREE.ShaderMaterial({ uniforms, vertexShader, fragmentShader })');
|
|
75
81
|
return own;
|
|
@@ -81,15 +87,24 @@ export class Water {
|
|
|
81
87
|
}
|
|
82
88
|
const grey = new THREE.Color(0xcccccc);
|
|
83
89
|
const patches = surface ? [waves, surface] : [waves];
|
|
90
|
+
const uFresnel = { value: st.fresnel };
|
|
91
|
+
this._u = { ...waves.uniforms, uFresnel }; // the live uniforms look.water.set writes
|
|
84
92
|
// grazing-angle reflection: the flatter the view, the closer to the fog (horizon) color; the getter follows whatever fog exists at draw time.
|
|
85
93
|
// Basic material has no normal/view variables, so it gets no reflection
|
|
86
94
|
if (!('isMeshBasicMaterial' in m)) patches.push({ name: 'fresnel',
|
|
87
|
-
uniforms: { uFresnel
|
|
95
|
+
uniforms: { uFresnel, uFresnelColor: { get value() { return e.scene.fog?.color ?? grey; } } },
|
|
88
96
|
glsl: { fragment: { pars: 'uniform float uFresnel; uniform vec3 uFresnelColor;', opaque_fragment: { before: `
|
|
89
97
|
float threedogFres = pow(1.0 - abs(dot(normalize(vViewPosition), normal)), 3.0) * uFresnel;
|
|
90
98
|
outgoingLight = mix(outgoingLight, uFresnelColor, clamp(threedogFres, 0.0, 1.0));` } } } });
|
|
91
99
|
return patchMaterial(m, patches, { strict: false });
|
|
92
100
|
}
|
|
101
|
+
/** Build the shared material again (look.water changed something structural) and hand it to every water mesh @internal */
|
|
102
|
+
_rebuild() {
|
|
103
|
+
const old = this.material;
|
|
104
|
+
this.material = this._material();
|
|
105
|
+
for (const m of [this.sea, ...this.bodies.values()]) if (m) m.material = this.material;
|
|
106
|
+
old.dispose();
|
|
107
|
+
}
|
|
93
108
|
/** @internal */
|
|
94
109
|
_prep(mesh, size) {
|
|
95
110
|
mesh.receiveShadow = true; mesh.renderOrder = 1;
|
|
@@ -139,6 +154,7 @@ export class Water {
|
|
|
139
154
|
* @returns {ModuleDef<Water>}
|
|
140
155
|
*/
|
|
141
156
|
export function water(opts = {}) {
|
|
157
|
+
readParams('water', WATER_PARAMS, opts);
|
|
142
158
|
let w = null;
|
|
143
|
-
return { name: 'water', label: 'Water', stage: 'environment', after: ['sky'], install(e) {
|
|
159
|
+
return { name: 'water', label: 'Water', params: WATER_PARAMS, options: opts, stage: 'environment', after: ['sky'], install(e) { w = new Water(e, opts); return w; }, frame(dt, e) { w.update(e.focus, dt); } };
|
|
144
160
|
}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
// look.water: the water's look as a look part (recipes/52-look.md).
|
|
2
|
+
// set({ color, opacity, waveHeight, waveScale, waveSpeed, fresnel }) live: uniforms and material fields, no recompile
|
|
3
|
+
// set({ depthColor, foam }) structural: the shared material is rebuilt once (one recompile)
|
|
4
|
+
// patch('wave' | 'surface', glsl) the GLSL hooks of style.water.glsl (recipes/44)
|
|
5
|
+
// replace((engine, { uniforms, waves, surface, normalMap }) => Material) the whole surface (style.water.material)
|
|
6
|
+
// The style layer is style.water; the options of water({...}) are the game's own layer ('game'). Why a rebuild and not a patch of the old
|
|
7
|
+
// material: depthColor / foam / hooks decide which GLSL exists, and the shader is part of the material program.
|
|
8
|
+
import { defineLookPart, REPLACE } from '../../core/look/part.js';
|
|
9
|
+
import { waterLook } from './surface.js';
|
|
10
|
+
|
|
11
|
+
const WHY = 'the water module draws a plain gray, mostly opaque sea when the style gives none';
|
|
12
|
+
const OFF = "engine.use(water({ sea: false })) for no global water, or look.water.set({ opacity: 0 }) to hide the surface";
|
|
13
|
+
const KEYS = ['color', 'opacity', 'waveHeight', 'waveScale', 'waveSpeed', 'fresnel', 'depthColor', 'foam'];
|
|
14
|
+
const UN = { waveHeight: 'uWave', waveScale: 'uWaveScale', waveSpeed: 'uWaveSpeed', fresnel: 'uFresnel' }; // the uniforms behind the live keys
|
|
15
|
+
const STRUCT = ['depthColor', 'foam'];
|
|
16
|
+
const validate = (w, k) => v => { try { waterLook({ ...w.st, [k]: v }); return null; } catch (err) { return err.message; } };
|
|
17
|
+
|
|
18
|
+
/** @param {any} w the Water module */
|
|
19
|
+
export function defineWaterLook(w) {
|
|
20
|
+
const e = w.engine, st = w.st, g = st.glsl ?? {};
|
|
21
|
+
const pick = o => Object.fromEntries(KEYS.filter(k => o[k] !== undefined).map(k => [k, o[k]]));
|
|
22
|
+
const built = { sig: '', material: undefined };
|
|
23
|
+
const sig = () => JSON.stringify([st.depthColor ?? null, st.foam ?? null, st.glsl ?? null]);
|
|
24
|
+
built.sig = sig(); built.material = st.material;
|
|
25
|
+
const live = (k, v) => {
|
|
26
|
+
const m = w.material, u = w._u;
|
|
27
|
+
if (k === 'color' && !st.material && m.color) m.color.set(v);
|
|
28
|
+
else if (k === 'opacity' && !st.material) { const t = v < 1; m.opacity = v; if (m.transparent !== t) { m.transparent = t; m.needsUpdate = true; } }
|
|
29
|
+
else if (u?.[UN[k]]) u[UN[k]].value = v;
|
|
30
|
+
};
|
|
31
|
+
const rebuild = () => {
|
|
32
|
+
const now = sig();
|
|
33
|
+
if (now === built.sig && st.material === built.material) return; // the same structure again (e.g. the game layer repeating the style): nothing to do
|
|
34
|
+
built.sig = now; built.material = st.material;
|
|
35
|
+
w._rebuild();
|
|
36
|
+
};
|
|
37
|
+
const p = defineLookPart(e, {
|
|
38
|
+
id: 'water', group: 'surface', module: 'water', object: () => ({ material: w.material, sea: w.sea }), docs: ['recipes/52-look.md'], applyAtStart: false,
|
|
39
|
+
params: {
|
|
40
|
+
color: { type: 'any', default: 0x888888, cost: 'uniform', why: WHY, off: OFF, desc: 'base color (any THREE.Color input)' },
|
|
41
|
+
opacity: { type: 'number', default: 0.85, min: 0, max: 1, cost: 'uniform', why: WHY, off: OFF },
|
|
42
|
+
waveHeight: { type: 'number', default: 1, min: 0, neutral: true, cost: 'uniform', desc: 'multiplies the wave function (0 = flat)' },
|
|
43
|
+
waveScale: { type: 'number', default: 1, min: 0, neutral: true, cost: 'uniform', desc: 'world position scale fed to the wave function' },
|
|
44
|
+
waveSpeed: { type: 'number', default: 1, min: 0, neutral: true, cost: 'uniform', desc: 'time scale fed to the wave function' },
|
|
45
|
+
fresnel: { type: 'number', default: 0.5, min: 0, max: 1, cost: 'uniform', why: 'grazing angles blend toward the fog (horizon) color', off: 'look.water.set({ fresnel: 0 })' },
|
|
46
|
+
depthColor: { type: 'any', default: null, neutral: true, cost: 'recompile', desc: '{ shallow, deep, by: "view" | "wave", curve } or null; rebuilds the water material once', check: validate(w, 'depthColor') },
|
|
47
|
+
foam: { type: 'any', default: null, neutral: true, cost: 'recompile', desc: 'true | { color, start, end, opacity } or null; rebuilds the water material once', check: validate(w, 'foam') },
|
|
48
|
+
},
|
|
49
|
+
style: () => ({ ...pick(e.style.water ?? {}), ...(g.wave ? { 'hook:wave': g.wave } : {}), ...(g.surface ? { 'hook:surface': g.surface } : {}),
|
|
50
|
+
...(e.style.water?.material ? { [REPLACE]: e.style.water.material } : {}) }),
|
|
51
|
+
read: () => ({ opacity: !st.material && w.material.opacity !== undefined ? w.material.opacity : undefined }),
|
|
52
|
+
apply(v, changed) {
|
|
53
|
+
for (const k of changed) { st[k] = v[k]; live(k, v[k]); }
|
|
54
|
+
if (STRUCT.some(k => changed.has(k))) rebuild();
|
|
55
|
+
},
|
|
56
|
+
hooks: {
|
|
57
|
+
wave: { signature: 'float threedogWaterWave(vec3 p, float t)', scope: ['uTime'], example: 'float threedogWaterWave(vec3 p, float t) { return sin(p.x + t) * 0.2; }' },
|
|
58
|
+
surface: { signature: 'vec4 threedogWaterSurface(vec4 base, float wave, float facing, vec3 worldPos, float time)', scope: ['uTime'],
|
|
59
|
+
example: 'vec4 threedogWaterSurface(vec4 base, float wave, float facing, vec3 worldPos, float time) { return vec4(base.rgb * (0.8 + wave), base.a); }' },
|
|
60
|
+
},
|
|
61
|
+
applyHook(name, glsl) {
|
|
62
|
+
const was = st.glsl;
|
|
63
|
+
st.glsl = { ...was, [name]: glsl ?? undefined };
|
|
64
|
+
try { waterLook(st); rebuild(); } catch (err) { st.glsl = was; throw err; }
|
|
65
|
+
},
|
|
66
|
+
replace: { accepts: '(engine, { uniforms, waves, surface, normalMap }) => THREE.Material', loses: ['built-in role "water" material, fresnel, color and opacity (your material owns them)', 'depthColor / foam unless your material uses surface'] },
|
|
67
|
+
// checked before any layer is written: the replace slot is a function, a GLSL hook builds (waterLook compiles it on a copy of the state)
|
|
68
|
+
validate: (k, v) => k === REPLACE ? (typeof v === 'function' ? null : 'is (engine, { uniforms, waves, surface, normalMap }) => THREE.Material')
|
|
69
|
+
: k.startsWith('hook:') ? validate(w, 'glsl')({ ...w.st.glsl, [k.slice(5)]: v }) : null,
|
|
70
|
+
applyReplace(impl) {
|
|
71
|
+
st.material = impl ?? undefined; rebuild();
|
|
72
|
+
},
|
|
73
|
+
});
|
|
74
|
+
// water({...}) options are the game's layer
|
|
75
|
+
const o = w.opts ?? {}, mine = pick(o);
|
|
76
|
+
if (Object.keys(mine).length) p.set(mine);
|
|
77
|
+
if (o.glsl) for (const k of ['wave', 'surface']) if (o.glsl[k]) p.patch(k, o.glsl[k]);
|
|
78
|
+
if (o.material) p.replace(o.material);
|
|
79
|
+
return p;
|
|
80
|
+
}
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
// Seven temperate ones are an opt-in preset: weather(presets.weather.temperate), extend with types: { ...presets.weather.temperate.types, dust: {...} }.
|
|
3
3
|
// All fields blend smoothly on change.
|
|
4
4
|
// Affects: cloud shadows, sky color, sun intensity, fog distance, wind (plants sway), rain/snow particles, lightning, ambience.
|
|
5
|
-
// Particle and lightning looks: style.weather.rain / snow / lightning, engine.weather.
|
|
5
|
+
// Particle and lightning looks: style.weather.rain / snow / lightning, engine.look.weather.replace (particles.js, recipes/44).
|
|
6
6
|
//
|
|
7
7
|
// engine.weather.set('rain', 20) // turn to rain over 20 seconds
|
|
8
8
|
// engine.weather.setAuto(true) // change weather at random (uses engine.random, so step/tests are reproducible and saved)
|
|
@@ -10,29 +10,21 @@
|
|
|
10
10
|
// i18n.add.
|
|
11
11
|
import * as THREE from 'three';
|
|
12
12
|
import { checkOptions, warnMissing, warnOnce } from '../../core/validate.js';
|
|
13
|
+
import { readParams, keysSchema } from '../../core/params.js';
|
|
13
14
|
import { makeSystem, updateSystem, dropSystem, RAIN, SNOW } from './particles.js';
|
|
15
|
+
import { STRINGS, ERR } from './strings.js';
|
|
16
|
+
import { defineWeatherLook } from './look.js';
|
|
17
|
+
import { renamed } from '../../core/errorHints.js';
|
|
14
18
|
/** @import { ModuleDef } from '../../types/core' */
|
|
15
19
|
/** @import { WeatherName, WeatherPreset, WeatherOptions } from '../../types/world' */
|
|
16
20
|
|
|
17
21
|
// The table when the game gives none: one calm type, so engine.weather works without assuming rain, snow or storms exist
|
|
18
22
|
const ONLY_CLEAR = { clear: {} };
|
|
19
|
-
const STRINGS = {
|
|
20
|
-
'zh-CN': { 'weather.clear': '晴', 'weather.cloudy': '多云', 'weather.overcast': '阴', 'weather.rain': '雨', 'weather.storm': '暴雨',
|
|
21
|
-
'weather.snow': '雪', 'weather.fog': '雾', 'weather.auto': '自动变化' },
|
|
22
|
-
en: { 'weather.clear': 'Clear', 'weather.cloudy': 'Cloudy', 'weather.overcast': 'Overcast', 'weather.rain': 'Rain', 'weather.storm': 'Storm',
|
|
23
|
-
'weather.snow': 'Snow', 'weather.fog': 'Fog', 'weather.auto': 'Auto' },
|
|
24
|
-
};
|
|
25
23
|
const STYLE_KEYS = ['area', 'overcastColor', 'lightningBrightness', 'lightning', 'rain', 'snow', 'types'];
|
|
26
24
|
const OPTIONS = ['start', 'auto', 'particles', 'types', 'autoPool', 'autoInterval', 'transition', 'area'];
|
|
25
|
+
const WEATHER_PARAMS = keysSchema(OPTIONS);
|
|
27
26
|
// Fields a type leaves out: calm (no cloud, rain, snow, grey or lightning; normal sun, fog and wind)
|
|
28
27
|
const CALM = { cloud: 0, sun: 1, fog: 1, wind: 1, rain: 0, snow: 0, grey: 0, lightning: 0 };
|
|
29
|
-
const ERR = {
|
|
30
|
-
types: "weather({ types }): the game's weather table, name -> { cloud, sun, fog, wind, rain, snow, grey, lightning } (left-out fields are calm), at least one; got {got}. Seven temperate ones: weather(presets.weather.temperate) with presets from 'threedog'",
|
|
31
|
-
field: "weather type '{k}': field {f} must be a number (every field blends smoothly on change); got {got}",
|
|
32
|
-
start: "weather({ start }): '{got}' is not one of this game's weather types ({list})",
|
|
33
|
-
pool: "weather({ autoPool }): '{got}' is not one of this game's weather types ({list})",
|
|
34
|
-
};
|
|
35
|
-
|
|
36
28
|
/** engine.weather */
|
|
37
29
|
export class Weather {
|
|
38
30
|
/**
|
|
@@ -105,23 +97,16 @@ export class Weather {
|
|
|
105
97
|
/** @internal */ this._cover = { strength: cover.strength ?? 0.8 };
|
|
106
98
|
Object.assign(this._layer, { foliageCover: cover.foliage ?? null, groundCover: cover.ground ?? null, coverAmount: 0 });
|
|
107
99
|
}
|
|
100
|
+
defineWeatherLook(this); // look.weather: the style's rain / snow / lightning values are its style layer
|
|
108
101
|
}
|
|
109
102
|
|
|
110
103
|
/**
|
|
111
|
-
*
|
|
112
|
-
*
|
|
113
|
-
*
|
|
114
|
-
* @
|
|
115
|
-
* engine.weather.define('ash', { shape: 'soft', color: 0x555555, size: 14, speed: 0.8, sway: 3 }); // types: { ashfall: { ash: 1, grey: 0.5 } }
|
|
116
|
-
* @param {string} field
|
|
117
|
-
* @param {import('../../types/style').StyleWeatherParticles} [spec]
|
|
118
|
-
* @returns {{ field: string, object: THREE.Object3D, uniforms: Record<string, { value: any }> | null }}
|
|
104
|
+
* Renamed in 0.2: throws and names the new call, engine.look.weather.replace({ [field]: spec }) (recipes/44-water-weather-look-hooks.md)
|
|
105
|
+
* @param {string} _field
|
|
106
|
+
* @param {import('../../types/style').StyleWeatherParticles} [_spec]
|
|
107
|
+
* @returns {never}
|
|
119
108
|
*/
|
|
120
|
-
define(
|
|
121
|
-
const fields = [...new Set(Object.values(this.types).flatMap(v => Object.keys(v)))];
|
|
122
|
-
if (!fields.includes(field)) throw new Error(`weather.define('${field}'): no weather type has a field '${field}'; add it to a type in weather({ types }) (e.g. ashfall: { ${field}: 1 }), or use one of ${fields.join(', ')}`);
|
|
123
|
-
return this._build(field, spec, field === 'rain' ? RAIN : field === 'snow' ? SNOW : undefined);
|
|
124
|
-
}
|
|
109
|
+
define(_field, _spec) { return renamed('weatherDefine'); }
|
|
125
110
|
|
|
126
111
|
/** @internal */
|
|
127
112
|
_build(field, spec, base) {
|
|
@@ -164,10 +149,11 @@ export class Weather {
|
|
|
164
149
|
/**
|
|
165
150
|
* Advance weather transition, automatic weather and lightning (the module calls this itself every fixed step)
|
|
166
151
|
* @param {number} dt
|
|
152
|
+
* @param {boolean} [quiet] true during engine.skip: same state changes, no lightning event (nobody saw it)
|
|
167
153
|
* @returns {void}
|
|
168
154
|
* @internal
|
|
169
155
|
*/
|
|
170
|
-
tick(dt) {
|
|
156
|
+
tick(dt, quiet = false) {
|
|
171
157
|
const rnd = this.engine.random;
|
|
172
158
|
if (this.t < 1) {
|
|
173
159
|
this.t = Math.min(1, this.t + dt / this.dur);
|
|
@@ -183,7 +169,7 @@ export class Weather {
|
|
|
183
169
|
}
|
|
184
170
|
if (this.current.lightning > 0.5) {
|
|
185
171
|
this.nextBolt -= dt;
|
|
186
|
-
if (this.nextBolt <= 0) { this.flash = 1; this.nextBolt = rnd.range(6, 20); this.engine.events.emit('weather:lightning'); }
|
|
172
|
+
if (this.nextBolt <= 0) { this.flash = 1; this.nextBolt = rnd.range(6, 20); if (!quiet) this.engine.events.emit('weather:lightning'); }
|
|
187
173
|
}
|
|
188
174
|
this.flash = Math.max(0, this.flash - dt * 3);
|
|
189
175
|
}
|
|
@@ -216,11 +202,11 @@ export class Weather {
|
|
|
216
202
|
* @returns {ModuleDef<Weather>}
|
|
217
203
|
*/
|
|
218
204
|
export function weather(opts = {}) {
|
|
205
|
+
readParams('weather', WEATHER_PARAMS, opts);
|
|
219
206
|
let w = null;
|
|
220
207
|
return {
|
|
221
|
-
name: 'weather', label: 'Weather', requires: ['sky'], stage: 'environment', before: ['sky'],
|
|
208
|
+
name: 'weather', label: 'Weather', params: WEATHER_PARAMS, options: opts, requires: ['sky'], stage: 'environment', before: ['sky'],
|
|
222
209
|
install(e) {
|
|
223
|
-
checkOptions('weather()', opts, OPTIONS);
|
|
224
210
|
e.i18n.add(STRINGS);
|
|
225
211
|
w = new Weather(e, opts);
|
|
226
212
|
e.audio.condition('weather', v => [].concat(v).includes(w.name)); // audio rule condition { weather: 'rain' | ['rain', 'storm'] }
|
|
@@ -235,6 +221,11 @@ export function weather(opts = {}) {
|
|
|
235
221
|
return w;
|
|
236
222
|
},
|
|
237
223
|
fixed(dt) { w.tick(dt); },
|
|
224
|
+
// engine.skip: fixed hooks do not run, so the skipped fixed steps are replayed here without events (a bolt nobody saw)
|
|
225
|
+
skip(dt) { // replay the fixed steps (same random draws, same order as stepping, so checkSkip matches); nothing pending = nothing to replay
|
|
226
|
+
if (w.t >= 1 && !w.auto && !(w.current.lightning > 0.5)) return;
|
|
227
|
+
for (let n = Math.round(dt * 60); n > 0; n--) w.tick(1 / 60, true); // 60 = the engine's fixed steps per second
|
|
228
|
+
},
|
|
238
229
|
frame(dt, e) { w.apply(e.camera); },
|
|
239
230
|
// scenario param weather: switch to this weather at once (no transition) and turn off automatic weather, so the scene is reproducible
|
|
240
231
|
applyState(e, { weather: name }) {
|