roamwright 0.54.0 → 0.56.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.
Files changed (40) hide show
  1. package/examples/animals.js +27 -15
  2. package/examples/crowds.js +28 -18
  3. package/examples/effects.js +13 -11
  4. package/examples/figure-motion.js +17 -5
  5. package/examples/figure.js +12 -8
  6. package/examples/fliers.js +16 -12
  7. package/examples/fortification.js +31 -18
  8. package/examples/house-kit.js +17 -10
  9. package/examples/island.js +25 -12
  10. package/examples/land.js +14 -8
  11. package/examples/props-and-plants.js +21 -32
  12. package/examples/rooms.js +2 -2
  13. package/examples/ships.js +33 -15
  14. package/examples/small-world-land.js +3 -3
  15. package/examples/small-world-life.js +13 -5
  16. package/examples/small-world-town.js +8 -11
  17. package/examples/small-world.js +26 -19
  18. package/examples/soundscape.js +18 -18
  19. package/examples/stage-kits.js +5 -133
  20. package/examples/stage.js +1 -324
  21. package/examples/towns.js +25 -18
  22. package/examples/viaduct-landscape.js +1 -1
  23. package/examples/viaduct.js +3 -4
  24. package/geometry/builder.js +8 -18
  25. package/geometry/plant-broadleaf.js +10 -4
  26. package/geometry/plant-trees.js +15 -9
  27. package/geometry/still-mesh.js +35 -0
  28. package/index.js +11 -1
  29. package/motion/cast-actors.js +379 -0
  30. package/motion/cast-manager.js +321 -0
  31. package/motion/figure-mount.js +1 -0
  32. package/package.json +20 -1
  33. package/rendering/cast-stage.js +299 -0
  34. package/rendering/crowd-system.js +239 -0
  35. package/rendering/daylight-sky.js +212 -0
  36. package/rendering/house-kit-meshes.js +65 -16
  37. package/rendering/nameplate-groups.js +84 -0
  38. package/rendering/nameplates.js +386 -0
  39. package/rendering/orbit-camera.js +216 -0
  40. package/rendering/water-simple.js +112 -0
@@ -0,0 +1,239 @@
1
+ /**
2
+ * High-level crowd system facade wiring figure assembly, instanced crowd batches, pose texture,
3
+ * herd skins and rendering, street beasts, frustum visibility, alarms, and per-frame updating
4
+ * from one call.
5
+ * @module
6
+ */
7
+
8
+ import * as THREE from 'three';
9
+ import { geometryOf } from '../geometry/builder.js';
10
+ import { farCrowdFigure } from '../geometry/crowd-far.js';
11
+ import { createCrowdLookBuilder } from '../geometry/crowd-look.js';
12
+ import { createFigureBuilder } from '../geometry/figure-body.js';
13
+ import { createCrowdAlarms } from '../motion/crowd-alarms.js';
14
+ import { createStreetBeasts } from '../motion/crowd-beasts.js';
15
+ import { createCrowdPoser } from '../motion/crowd-pose.js';
16
+ import { createCrowdBatches } from './crowd-batches.js';
17
+ import { createHerdRenderer, createHerdSkins } from './crowd-herd.js';
18
+ import { createCrowdUpdater, registerCrowd } from './crowd-update.js';
19
+ import { createCrowdVisibility } from './crowd-visibility.js';
20
+ import { createFigureAssembler } from './figure-skeleton.js';
21
+
22
+ /**
23
+ * Wires figure builders, instanced crowd batches, pose texture, herd skins, ambient street beasts,
24
+ * frustum/shadow visibility, alarms, and the per-frame crowd updater from one call.
25
+ *
26
+ * When `getTime` and `getLightDir` are supplied, the updater is created immediately and available
27
+ * through `updater`, `updateCrowds()`, and `orderLooksAround()`. Callers that create lights later
28
+ * may call `createUpdater({ getTime, getFrame, getLightDir, ... })` afterward.
29
+ *
30
+ * @param {object} config
31
+ * @param {THREE.Object3D} config.scene Scene or world group receiving instanced crowd and herd meshes.
32
+ * @param {THREE.PerspectiveCamera} config.camera Active camera for frustum culling and LOD promotion.
33
+ * @param {THREE.WebGLRenderer|null} [config.renderer=null] Optional renderer for shadow-map checks.
34
+ * @param {(x: number, z: number) => number} [config.groundAt] Ground height sampler (metres); defaults to flat `0`.
35
+ * @param {{ worldSpace: object, steer?: Function }|null} [config.spaceKit=null] Optional space kit from `createSpaces` supplying `worldSpace` and `steer`.
36
+ * @param {object|null} [config.space=null] Optional active space record (`{ id, ground }`); defaults to `spaceKit.worldSpace` or `{ id: 'world', ground: groundAt }`.
37
+ * @param {() => object} [config.getSpace] Returns the active space each frame; overrides `space`.
38
+ * @param {Function} [config.steer] Steering helper for alarm flight; defaults to `spaceKit?.steer`.
39
+ * @param {object[]} [config.crowds] Optional existing crowd array to populate.
40
+ * @param {() => THREE.Material} [config.figureMaterial] Material factory for assembled figure rigs.
41
+ * @param {() => THREE.Material} [config.createColourMaterial] Base colour material factory for instanced crowd batches.
42
+ * @param {() => THREE.Material} [config.herdMaterial] Material factory for instanced herd meshes.
43
+ * @param {Function} [config.buildFigure] Custom figure builder overriding the default `createFigureBuilder` + `createFigureAssembler`.
44
+ * @param {Function} [config.buildCrowdLook] Custom synchronous crowd-look builder.
45
+ * @param {Function|null} [config.orderCrowdLook=null] Optional worker look orderer.
46
+ * @param {Function} [config.crowdPose] Custom crowd poser; defaults to `createCrowdPoser()`.
47
+ * @param {object} [config.herdSkins] Custom herd skin registry; defaults to `createHerdSkins()`.
48
+ * @param {object} [config.herdRenderer] Custom herd renderer; defaults to `createHerdRenderer(...)`.
49
+ * @param {object} [config.visibility] Custom visibility tester; defaults to `createCrowdVisibility()`.
50
+ * @param {object} [config.alarms] Custom alarm controller; defaults to `createCrowdAlarms({ steer })`.
51
+ * @param {Array<[string, object]>} [config.looks] Crowd look table forwarded to `createCrowdBatches`.
52
+ * @param {number[]} [config.skins] Skin tone hex palette forwarded to `createCrowdBatches`.
53
+ * @param {number[]} [config.hair] Hair tone hex palette forwarded to `createCrowdBatches`.
54
+ * @param {(x: number, y: number, salt?: number) => number} [config.hash] Seeded 2D hash forwarded to `createCrowdBatches` and `registerCrowd`.
55
+ * @param {Function} [config.pickLook] Custom look picker forwarded to `createCrowdBatches`.
56
+ * @param {Function|null} [config.pickSkinHair] Custom skin/hair picker forwarded to `createCrowdBatches`.
57
+ * @param {Function} [config.hasFirewood] Firewood predicate forwarded to `createCrowdBatches`.
58
+ * @param {Function} [config.carryBendOf] Carry-bend resolver forwarded to `createCrowdBatches`.
59
+ * @param {Record<string, object>} [config.beastKinds] Custom street-beast kind table forwarded to `createStreetBeasts`.
60
+ * @param {() => number} [config.getTime] Optional elapsed time source (seconds) to wire the updater immediately.
61
+ * @param {() => number} [config.getFrame] Optional frame counter source.
62
+ * @param {() => { x: number, y: number, z: number }} [config.getLightDir] Optional directional light vector source.
63
+ * @param {() => boolean} [config.getShadowsEnabled] Optional shadow-enabled predicate.
64
+ * @param {number} [config.shadowRange=120] Default shadow frustum half-extent (metres).
65
+ * @param {number} [config.shadowFar=320] Default shadow frustum far depth (metres).
66
+ * @param {object} [config.updaterOptions] Additional options forwarded to `createCrowdUpdater`.
67
+ * @returns {object} Crowd system handle with `crowds`, `addCrowd`, `batches`, `poseTexture`, `herdSkins`, `herdRenderer`, `streetBeasts`, `beastsAbout`, `alarms`, `visibility`, `crowdPose`, `build`, `createUpdater`, `updater`, `updateCrowds`, `orderLooksAround`, and `dispose`.
68
+ */
69
+ export function createCrowdSystem({
70
+ scene,
71
+ camera,
72
+ renderer = null,
73
+ groundAt = () => 0,
74
+ spaceKit = null,
75
+ space = null,
76
+ getSpace = null,
77
+ steer = spaceKit?.steer,
78
+ crowds = [],
79
+ figureMaterial = () => new THREE.MeshStandardMaterial({ vertexColors: true, roughness: 0.88, side: THREE.DoubleSide }),
80
+ createColourMaterial,
81
+ herdMaterial = () => new THREE.MeshStandardMaterial({ vertexColors: true, roughness: 0.9 }),
82
+ buildFigure = null,
83
+ buildCrowdLook = null,
84
+ orderCrowdLook = null,
85
+ crowdPose = createCrowdPoser(),
86
+ herdSkins = createHerdSkins(),
87
+ herdRenderer = null,
88
+ visibility = createCrowdVisibility(),
89
+ alarms = null,
90
+ looks,
91
+ skins,
92
+ hair,
93
+ hash,
94
+ pickLook,
95
+ pickSkinHair,
96
+ hasFirewood,
97
+ carryBendOf,
98
+ beastKinds,
99
+ getTime = null,
100
+ getFrame = () => 0,
101
+ getLightDir = null,
102
+ getShadowsEnabled = () => (renderer ? !!renderer.shadowMap?.enabled : true),
103
+ shadowRange = 120,
104
+ shadowFar = 320,
105
+ updaterOptions = {},
106
+ }) {
107
+ const defaultSpace = space ?? spaceKit?.worldSpace ?? { id: 'world', ground: groundAt };
108
+ const resolveSpace = getSpace ?? (() => defaultSpace);
109
+
110
+ let figureBuilder = buildFigure;
111
+ let lookBuilder = buildCrowdLook;
112
+ if (!figureBuilder || !lookBuilder) {
113
+ const { buildBody, kit } = createFigureBuilder();
114
+ if (!figureBuilder) {
115
+ const { assembleFigure } = createFigureAssembler({ material: figureMaterial, holds: kit.holds });
116
+ figureBuilder = (look, lookSeed, _near, bodies) => {
117
+ const far = bodies?.[0] || buildBody(look, lookSeed, 1);
118
+ return assembleFigure(look, 'human', { ...far, geo: geometryOf(far.parts) }, null);
119
+ };
120
+ }
121
+ if (!lookBuilder) lookBuilder = createCrowdLookBuilder({ buildBody });
122
+ }
123
+
124
+ const batchConfig = {
125
+ scene,
126
+ buildFigure: figureBuilder,
127
+ buildCrowdLook: lookBuilder,
128
+ orderCrowdLook,
129
+ crowdPose,
130
+ };
131
+ if (createColourMaterial) batchConfig.createColourMaterial = createColourMaterial;
132
+ if (looks) batchConfig.looks = looks;
133
+ if (skins) batchConfig.skins = skins;
134
+ if (hair) batchConfig.hair = hair;
135
+ if (hash) batchConfig.hash = hash;
136
+ if (pickLook) batchConfig.pickLook = pickLook;
137
+ if (pickSkinHair) batchConfig.pickSkinHair = pickSkinHair;
138
+ if (hasFirewood) batchConfig.hasFirewood = hasFirewood;
139
+ if (carryBendOf) batchConfig.carryBendOf = carryBendOf;
140
+
141
+ const batches = createCrowdBatches(batchConfig);
142
+ const resolvedHerdRenderer =
143
+ herdRenderer ??
144
+ createHerdRenderer({
145
+ scene,
146
+ material: herdMaterial,
147
+ herdPoses: herdSkins.herdPoses,
148
+ });
149
+ const resolvedAlarms = alarms ?? createCrowdAlarms(steer ? { steer } : {});
150
+
151
+ const groundForCrowd = (_spaceId, x, z) => groundAt(x, z);
152
+ function addCrowd(list, tones, cx, cz, range, kind, beasts = null, sp = defaultSpace.id) {
153
+ return registerCrowd(crowds, list, tones, cx, cz, range, kind, {
154
+ beasts,
155
+ space: sp,
156
+ groundAt: groundForCrowd,
157
+ ...(hash ? { hash } : {}),
158
+ });
159
+ }
160
+
161
+ const { streetBeasts, beastsAbout } = createStreetBeasts({
162
+ addCrowd,
163
+ herdLook: herdSkins.herdLook,
164
+ ...(beastKinds ? { kinds: beastKinds } : {}),
165
+ });
166
+
167
+ function build(fars = [farCrowdFigure('distant'), farCrowdFigure('remote')]) {
168
+ return batches.buildCrowdBatches(fars, crowds);
169
+ }
170
+
171
+ let activeUpdater = null;
172
+ function createUpdater(overrides = {}) {
173
+ const {
174
+ shadowRange: range = shadowRange,
175
+ shadowFar: far = shadowFar,
176
+ getShadowRange = () => range,
177
+ getShadowFar = () => far,
178
+ ...rest
179
+ } = overrides;
180
+ activeUpdater = createCrowdUpdater({
181
+ camera,
182
+ renderer,
183
+ getTime,
184
+ getFrame,
185
+ getShadowsEnabled,
186
+ getLightDir,
187
+ getShadowRange,
188
+ getShadowFar,
189
+ getSpace: resolveSpace,
190
+ crowds,
191
+ batches,
192
+ visibility,
193
+ alarms: resolvedAlarms,
194
+ crowdPose,
195
+ herds: { ...resolvedHerdRenderer, orderHerd: herdSkins.orderHerd },
196
+ ...updaterOptions,
197
+ ...rest,
198
+ });
199
+ return activeUpdater;
200
+ }
201
+
202
+ if (getTime && getLightDir) createUpdater();
203
+
204
+ function updateCrowds() {
205
+ if (activeUpdater) activeUpdater.updateCrowds();
206
+ }
207
+
208
+ function orderLooksAround(land, x, z) {
209
+ if (activeUpdater) activeUpdater.orderLooksAround(land, x, z);
210
+ }
211
+
212
+ function dispose() {
213
+ batches.dropCrowdBatches();
214
+ }
215
+
216
+ return {
217
+ crowds,
218
+ addCrowd,
219
+ batches,
220
+ get poseTexture() {
221
+ return batches.poseTexture;
222
+ },
223
+ herdSkins,
224
+ herdRenderer: resolvedHerdRenderer,
225
+ streetBeasts,
226
+ beastsAbout,
227
+ alarms: resolvedAlarms,
228
+ visibility,
229
+ crowdPose,
230
+ build,
231
+ createUpdater,
232
+ get updater() {
233
+ return activeUpdater;
234
+ },
235
+ updateCrowds,
236
+ orderLooksAround,
237
+ dispose,
238
+ };
239
+ }
@@ -0,0 +1,212 @@
1
+ /**
2
+ * Procedural equirectangular sky panoramas and a one-call daylight sky facade that sets up
3
+ * background sky texture, directional sun light with shadows, hemisphere fill, and exponential fog.
4
+ * @module
5
+ */
6
+
7
+ import * as THREE from 'three';
8
+ import { createNoise } from '../math/noise.js';
9
+
10
+ /**
11
+ * Wraps an RGBA pixel buffer into an equirectangular sky `THREE.DataTexture`.
12
+ *
13
+ * @param {Uint8Array} pixels Flat RGBA bytes (`width * height * 4`).
14
+ * @param {number} width Texture width in pixels.
15
+ * @param {number} height Texture height in pixels.
16
+ * @returns {THREE.DataTexture}
17
+ */
18
+ export function createSkyTexture(pixels, width, height) {
19
+ const sky = new THREE.DataTexture(pixels, width, height);
20
+ sky.colorSpace = THREE.SRGBColorSpace;
21
+ sky.mapping = THREE.EquirectangularReflectionMapping;
22
+ sky.minFilter = sky.magFilter = THREE.LinearFilter;
23
+ sky.needsUpdate = true;
24
+ return sky;
25
+ }
26
+
27
+ /**
28
+ * Paints an equirectangular sky `THREE.DataTexture` with horizon-to-zenith gradient, wispy high
29
+ * clouds, sun glow, and optional stars for dusk or night skies.
30
+ *
31
+ * @param {{ fbm: Function, vnoise: Function }} [noise] Seeded noise generator (`createNoise`); defaults to `createNoise(42)`.
32
+ * @param {object} [options]
33
+ * @param {[number, number, number]} [options.zenith=[0.27, 0.49, 0.72]] Linear-range zenith sky tint.
34
+ * @param {[number, number, number]} [options.horizon=[0.82, 0.86, 0.84]] Horizon sky tint.
35
+ * @param {[number, number, number]} [options.ground=[0.55, 0.56, 0.5]] Below-horizon tint.
36
+ * @param {[number, number, number]} [options.cloudColor=[0.99, 0.95, 0.87]] High-cloud veil tint.
37
+ * @param {[number, number, number]} [options.sunGlow=[1.0, 0.84, 0.58]] Solar halo tint.
38
+ * @param {[number, number, number]} [options.sunDir=[-0.72, 0.28, -0.63]] Direction toward the sun or moon.
39
+ * @param {number} [options.cloudCover=0.53] Cloud noise threshold in `[0, 1]`.
40
+ * @param {number} [options.stars=0] Starfield brightness multiplier (`0` disables stars).
41
+ * @param {number} [options.width=512] Panorama width in pixels.
42
+ * @param {number} [options.height=256] Panorama height in pixels.
43
+ * @returns {THREE.DataTexture}
44
+ */
45
+ export function createSkyPanorama(
46
+ noise = createNoise(42),
47
+ {
48
+ zenith = [0.27, 0.49, 0.72],
49
+ horizon = [0.82, 0.86, 0.84],
50
+ ground = [0.55, 0.56, 0.5],
51
+ cloudColor = [0.99, 0.95, 0.87],
52
+ sunGlow = [1.0, 0.84, 0.58],
53
+ sunDir = [-0.72, 0.28, -0.63],
54
+ cloudCover = 0.53,
55
+ stars = 0,
56
+ width = 512,
57
+ height = 256,
58
+ } = {},
59
+ ) {
60
+ const pixels = new Uint8Array(width * height * 4);
61
+ const sun = new THREE.Vector3(...sunDir).normalize();
62
+ for (let y = 0; y < height; y++) {
63
+ const lat = Math.PI * ((y + 0.5) / height - 0.5);
64
+ const up = Math.sin(lat),
65
+ ring = Math.cos(lat);
66
+ const skyMix = THREE.MathUtils.smoothstep(up, -0.04, 0.74);
67
+ const belowMix = THREE.MathUtils.smoothstep(-up, 0.0, 0.35);
68
+ for (let x = 0; x < width; x++) {
69
+ const lon = 2 * Math.PI * ((x + 0.5) / width - 0.5);
70
+ const ex = ring * Math.cos(lon),
71
+ ez = ring * Math.sin(lon);
72
+ const air = Math.max(0.09, up);
73
+ const cNoise = noise.fbm((ex / air) * 1.25, (ez / air) * 2.4, 4, 71);
74
+ const veil = THREE.MathUtils.smoothstep(cNoise, cloudCover, cloudCover + 0.24) * THREE.MathUtils.smoothstep(up, 0.01, 0.16);
75
+ const sd = Math.max(0, ex * sun.x + up * sun.y + ez * sun.z);
76
+ const glow = Math.pow(sd, 18) * 0.26 + Math.pow(sd, 140) * 0.65;
77
+ let r = horizon[0] + (zenith[0] - horizon[0]) * skyMix;
78
+ let g = horizon[1] + (zenith[1] - horizon[1]) * skyMix;
79
+ let b = horizon[2] + (zenith[2] - horizon[2]) * skyMix;
80
+ if (up < 0) {
81
+ r += (ground[0] - r) * belowMix;
82
+ g += (ground[1] - g) * belowMix;
83
+ b += (ground[2] - b) * belowMix;
84
+ }
85
+ r = r * (1 - veil) + cloudColor[0] * veil + sunGlow[0] * glow;
86
+ g = g * (1 - veil) + cloudColor[1] * veil + sunGlow[1] * glow;
87
+ b = b * (1 - veil) + cloudColor[2] * veil + sunGlow[2] * glow;
88
+ if (stars > 0 && up > 0.05) {
89
+ const twinkle = noise.vnoise(ex * 95 + 11, ez * 95 + up * 73, 19);
90
+ if (twinkle > 0.945) {
91
+ const s = ((twinkle - 0.945) / 0.055) * stars * THREE.MathUtils.smoothstep(up, 0.05, 0.3) * (1 - veil);
92
+ r += s * 0.9;
93
+ g += s * 0.94;
94
+ b += s;
95
+ }
96
+ }
97
+ const i = (y * width + x) * 4;
98
+ pixels[i] = Math.min(255, Math.max(0, Math.round(r * 255)));
99
+ pixels[i + 1] = Math.min(255, Math.max(0, Math.round(g * 255)));
100
+ pixels[i + 2] = Math.min(255, Math.max(0, Math.round(b * 255)));
101
+ pixels[i + 3] = 255;
102
+ }
103
+ }
104
+ return createSkyTexture(pixels, width, height);
105
+ }
106
+
107
+ /**
108
+ * Sets up a daylight sky backdrop, directional sun light with shadow frustum, hemisphere ambient
109
+ * fill, and exponential distance fog on `scene` in one call.
110
+ *
111
+ * @param {object} options
112
+ * @param {THREE.Scene} options.scene Scene receiving background, fog, sun, and hemisphere light.
113
+ * @param {THREE.WebGLRenderer} [options.renderer] Optional renderer whose shadow map is enabled and configured.
114
+ * @param {{ fbm: Function, vnoise: Function }} [options.noise] Seeded noise for the sky panorama; defaults to `createNoise(seed)`.
115
+ * @param {number} [options.seed=42] Fallback seed when `noise` is not provided.
116
+ * @param {object|THREE.Texture|false} [options.sky={}] Options passed to `createSkyPanorama`, a prebuilt `THREE.Texture`, or `false` to skip `scene.background`.
117
+ * @param {[number, number, number]} [options.sunPosition=[-65, 38, 48]] World position of the directional sun light (metres).
118
+ * @param {number} [options.sunColor=0xffe2b8] Directional sun light colour (sRGB hex).
119
+ * @param {number} [options.sunIntensity=2.6] Directional sun light intensity.
120
+ * @param {number} [options.skyColor=0xddeaf5] Hemisphere sky colour (sRGB hex).
121
+ * @param {number} [options.groundColor=0x6b6752] Hemisphere ground bounce colour (sRGB hex).
122
+ * @param {number} [options.hemiIntensity=1.25] Hemisphere light intensity.
123
+ * @param {boolean} [options.castShadow=true] Whether the directional sun casts shadows.
124
+ * @param {number} [options.shadowRadius=70] Half-extent of the orthographic shadow frustum (metres).
125
+ * @param {number} [options.shadowFar=240] Far plane of the orthographic shadow frustum (metres).
126
+ * @param {number} [options.shadowMapSize=2048] Shadow map resolution in pixels (square).
127
+ * @param {number} [options.normalBias=0.045] Shadow normal bias (metres).
128
+ * @param {boolean} [options.staticShadows=false] When true, renders the shadow map once instead of every frame.
129
+ * @param {number} [options.fogColor=0xd4ded9] Exponential fog colour (sRGB hex).
130
+ * @param {number} [options.fogDensity=0.002] Exponential fog density (`0` omits fog).
131
+ * @returns {{ sky: THREE.Texture|null, sun: THREE.DirectionalLight, hemi: THREE.HemisphereLight, fog: THREE.FogExp2|null, lightDir: THREE.Vector3, dispose: () => void }}
132
+ */
133
+ export function createDaylightSky({
134
+ scene,
135
+ renderer = null,
136
+ noise = null,
137
+ seed = 42,
138
+ sky: skyOptions = {},
139
+ sunPosition = [-65, 38, 48],
140
+ sunColor = 0xffe2b8,
141
+ sunIntensity = 2.6,
142
+ skyColor = 0xddeaf5,
143
+ groundColor = 0x6b6752,
144
+ hemiIntensity = 1.25,
145
+ castShadow = true,
146
+ shadowRadius = 70,
147
+ shadowFar = 240,
148
+ shadowMapSize = 2048,
149
+ normalBias = 0.045,
150
+ staticShadows = false,
151
+ fogColor = 0xd4ded9,
152
+ fogDensity = 0.002,
153
+ } = {}) {
154
+ let sky = null;
155
+ let ownsSky = false;
156
+ if (skyOptions && skyOptions.isTexture) {
157
+ sky = skyOptions;
158
+ scene.background = sky;
159
+ } else if (skyOptions !== false) {
160
+ sky = createSkyPanorama(noise ?? createNoise(seed), skyOptions);
161
+ ownsSky = true;
162
+ scene.background = sky;
163
+ }
164
+
165
+ let fog = null;
166
+ if (fogDensity > 0) {
167
+ fog = new THREE.FogExp2(fogColor, fogDensity);
168
+ scene.fog = fog;
169
+ }
170
+
171
+ if (renderer && castShadow) {
172
+ renderer.shadowMap.enabled = true;
173
+ renderer.shadowMap.type = THREE.PCFShadowMap;
174
+ }
175
+
176
+ const hemi = new THREE.HemisphereLight(skyColor, groundColor, hemiIntensity);
177
+ scene.add(hemi);
178
+
179
+ const sun = new THREE.DirectionalLight(sunColor, sunIntensity);
180
+ sun.position.set(...sunPosition);
181
+ sun.castShadow = castShadow;
182
+ if (castShadow) {
183
+ sun.shadow.mapSize.set(shadowMapSize, shadowMapSize);
184
+ Object.assign(sun.shadow.camera, {
185
+ left: -shadowRadius,
186
+ right: shadowRadius,
187
+ top: shadowRadius,
188
+ bottom: -shadowRadius,
189
+ near: 1,
190
+ far: shadowFar,
191
+ });
192
+ sun.shadow.camera.updateProjectionMatrix();
193
+ sun.shadow.normalBias = normalBias;
194
+ }
195
+ scene.add(sun);
196
+
197
+ if (renderer && castShadow && staticShadows) {
198
+ renderer.shadowMap.autoUpdate = false;
199
+ renderer.shadowMap.needsUpdate = true;
200
+ }
201
+
202
+ const lightDir = sun.position.clone().normalize();
203
+
204
+ function dispose() {
205
+ if (ownsSky && sky) sky.dispose();
206
+ scene.remove(sun, hemi);
207
+ sun.dispose();
208
+ hemi.dispose();
209
+ }
210
+
211
+ return { sky, sun, hemi, fog, lightDir, dispose };
212
+ }
@@ -4,27 +4,76 @@ import * as THREE from 'three';
4
4
  import { geometryOf } from '../geometry/builder.js';
5
5
  import { KIT_KEYS } from '../geometry/house-kit-frame.js';
6
6
  import { markStill } from './still-casters.js';
7
+ import { createHandOver } from '../runtime/hand-over.js';
8
+
9
+ const SYNC_HAND_OVER = createHandOver({ painted: () => Promise.resolve(), frameShare: () => Infinity });
10
+
11
+ /**
12
+ * Creates a default vertex-coloured `MeshStandardMaterial` map for every house-kit part key
13
+ * (`KIT_KEYS`), suitable for immediate rendering without custom world shaders.
14
+ *
15
+ * @param {object} [options]
16
+ * @param {readonly string[]} [options.keys=KIT_KEYS] Kit material keys to populate.
17
+ * @param {boolean} [options.doubleSide=false] Draw both faces on solid kit parts.
18
+ * @param {number} [options.roughness=0.9] Surface roughness for matte kit parts.
19
+ * @param {number} [options.glassRoughness=0.25] Surface roughness for `glass` when single-sided.
20
+ * @param {number} [options.stainOpacity=0.25] Opacity for transparent ground-contact `stain` decals.
21
+ * @returns {Record<string, THREE.MeshStandardMaterial>}
22
+ */
23
+ export function createHouseKitMaterials({
24
+ keys = KIT_KEYS,
25
+ doubleSide = false,
26
+ roughness = 0.9,
27
+ glassRoughness = 0.25,
28
+ stainOpacity = 0.25,
29
+ } = {}) {
30
+ const solid = doubleSide ? { vertexColors: true, roughness, side: THREE.DoubleSide } : { vertexColors: true, roughness };
31
+ const materials = {};
32
+ for (const key of keys) {
33
+ if (key === 'stain') {
34
+ materials[key] = new THREE.MeshStandardMaterial({
35
+ vertexColors: true,
36
+ transparent: true,
37
+ opacity: stainOpacity,
38
+ depthWrite: false,
39
+ });
40
+ } else if (key === 'glass' && !doubleSide) {
41
+ materials[key] = new THREE.MeshStandardMaterial({ vertexColors: true, roughness: glassRoughness });
42
+ } else if (key === 'cloth') {
43
+ materials[key] = new THREE.MeshStandardMaterial({ vertexColors: true, roughness, side: THREE.DoubleSide });
44
+ } else {
45
+ materials[key] = new THREE.MeshStandardMaterial(solid);
46
+ }
47
+ }
48
+ return materials;
49
+ }
7
50
 
8
51
  /**
9
52
  * Binds a house kit's meshes to a world's materials and its renderer's batches.
10
- * @param {object} o
11
- * @param {Object<string, import('three').Material>} o.materials - A material for each of the kit's kinds (`KIT_KEYS`), read
12
- * when a mesh is made.
13
- * @param {Function} o.PieceBatch - The renderer's batch class (`createPieceBatch`).
14
- * @param {(material: import('three').Material) => import('three').Material} [o.instancedMaterial] - The material an
53
+ * When `materials` or `handOver` are omitted, default vertex-coloured materials
54
+ * (`createHouseKitMaterials`) and a synchronous hand-over are used so small worlds and examples
55
+ * can build kit meshes with one call.
56
+ *
57
+ * @param {object} [o]
58
+ * @param {Object<string, import('three').Material>} [o.materials] A material for each of the kit's kinds (`KIT_KEYS`), read
59
+ * when a mesh is made; defaults to `createHouseKitMaterials()`.
60
+ * @param {Function|null} [o.PieceBatch=null] The renderer's batch class (`createPieceBatch`), required only for `cellPieces`.
61
+ * @param {(material: import('three').Material) => import('three').Material} [o.instancedMaterial] The material an
15
62
  * instanced copy draws with (a twin of the mesh's that reads the instance's matrix); the mesh's own if not given.
16
- * @param {() => boolean} [o.worldDrawn] - Whether the world has been drawn yet: until it has, steps written to the card
63
+ * @param {() => boolean} [o.worldDrawn] Whether the world has been drawn yet: until it has, steps written to the card
17
64
  * run all at once (behind a loading bar) rather than paced.
18
- * @param {object} o.handOver - The renderer's hand-over (`createHandOver`): `paced`, `drain` and `heldBytes`.
19
- * @returns {object} `kitStatic(kit, parent, materialOf)`, a filled kit as meshes (one to a kind with any parts) under parent,
20
- * the kit let go; `kitMeshes(parts, parent, materialOf)`, the same from a kit's arrays (GB.parts, one to each kind);
21
- * `instancedOf(meshes, n, group)`, such meshes as instanced meshes of up to n, none shown until given instances;
22
- * `kitInstanced(kit, n, group)`; `cellPieces(cellsOfKinds, parent, far, detail, materialOf)`, a cut kit's cells as batches,
23
- * a generator of steps each yielding the bytes it wrote (the small parts' cells noted in `detail` with where they stand and
24
- * how far, `far` metres beyond their edge, they are drawn), returning the batches; `pieceSwitch(batch, id)`, a stand-in with
25
- * `visible` for one piece of a batch; `toCard(steps, signal)`, runs such steps paced once the world is drawn.
65
+ * @param {object} [o.handOver] The renderer's hand-over (`createHandOver`): `paced`, `drain` and `heldBytes`; defaults to a synchronous hand-over.
66
+ * @returns {object} `materials` (the resolved material map), `kitStatic(kit, parent, materialOf)`, `kitMeshes(parts, parent, materialOf)`,
67
+ * `instancedOf(meshes, n, group)`, `kitInstanced(kit, n, group)`, `cellPieces(cellsOfKinds, parent, far, detail, materialOf)`,
68
+ * `pieceSwitch(batch, id)`, and `toCard(steps, signal)`.
26
69
  */
27
- export function createHouseKitMeshes({ materials, PieceBatch, instancedMaterial = m => m, worldDrawn = () => true, handOver }) {
70
+ export function createHouseKitMeshes({
71
+ materials = createHouseKitMaterials(),
72
+ PieceBatch = null,
73
+ instancedMaterial = m => m,
74
+ worldDrawn = () => true,
75
+ handOver = SYNC_HAND_OVER,
76
+ } = {}) {
28
77
  const { drain, heldBytes, paced } = handOver,
29
78
  ownMaterial = k => materials[k];
30
79
 
@@ -120,5 +169,5 @@ export function createHouseKitMeshes({ materials, PieceBatch, instancedMaterial
120
169
  };
121
170
  }
122
171
 
123
- return { cellPieces, instancedOf, kitInstanced, kitMeshes, kitStatic, pieceSwitch, toCard };
172
+ return { cellPieces, instancedOf, kitInstanced, kitMeshes, kitStatic, materials, pieceSwitch, toCard };
124
173
  }
@@ -0,0 +1,84 @@
1
+ /**
2
+ * Shared nameplate anchors for crowds, formations, or flocks: each named group attaches
3
+ * one anchor record and offers its members each frame so the nearest visible standing
4
+ * member carries the group's single nameplate.
5
+ * @module
6
+ */
7
+
8
+ const DEFAULT_HEAD_CLEARANCE = 0.35; // metres above member top where the label attaches
9
+
10
+ /**
11
+ * Creates a manager for group nameplate anchors bound to a label fade range, camera, and
12
+ * frame counter. Zero allocations per frame in `considerMember`.
13
+ *
14
+ * @param {object} config
15
+ * @param {{ far: number, selection: () => { accept: Function, distance: Function } }} config.labelRange - Label visibility range (`createLabelRange`).
16
+ * @param {() => THREE.Camera} config.getCamera - Returns the active camera.
17
+ * @param {() => number} config.getFrame - Returns the current frame counter.
18
+ * @param {number} [config.headClearance=0.35] - Vertical offset (metres) above a member's height for frustum testing.
19
+ * @returns {{ groupList: object[], attachGroup: (group: object, def: object) => object, considerMember: (anchor: object, x: number, y: number, z: number, height: number) => void, clearGroups: () => void }}
20
+ */
21
+ export function createNameplateGroups({ labelRange, getCamera, getFrame, headClearance = DEFAULT_HEAD_CLEARANCE }) {
22
+ const groupList = [];
23
+
24
+ /**
25
+ * Attaches a shared nameplate anchor record to `group` using metadata `def` (`{ name, sub, color, plateScale? }`).
26
+ * Stores the anchor on `group.bodyPlate` and registers it in `groupList`.
27
+ *
28
+ * @param {object} group - Crowd or flock object receiving the anchor.
29
+ * @param {object} def - Group nameplate definition.
30
+ * @returns {object} The passed `group` for chaining.
31
+ */
32
+ function attachGroup(group, def) {
33
+ // Keep one monomorphic shape matching cast actor nameplate fields so rendering/nameplates.js shares one hot path.
34
+ const anchor = {
35
+ bodyDef: def,
36
+ range: labelRange.far,
37
+ selection: labelRange.selection(),
38
+ x: 0,
39
+ y: 0,
40
+ z: 0,
41
+ height: 0,
42
+ dist: Infinity,
43
+ sx: 0,
44
+ sy: 0,
45
+ ph: 0,
46
+ want: 0,
47
+ plate: null,
48
+ plateH: 1,
49
+ plateOnCard: false,
50
+ plateA: 0,
51
+ plateBeside: false,
52
+ };
53
+ groupList.push(anchor);
54
+ group.bodyPlate = anchor;
55
+ return group;
56
+ }
57
+
58
+ /**
59
+ * Offers a member's resolved world position to its group's anchor; retains the nearest
60
+ * member whose label point falls inside the camera frustum for the current frame.
61
+ *
62
+ * @param {object} anchor - Group anchor (`group.bodyPlate`).
63
+ * @param {number} x - Member world X (metres).
64
+ * @param {number} y - Member base world Y (metres).
65
+ * @param {number} z - Member world Z (metres).
66
+ * @param {number} height - Member height (metres).
67
+ */
68
+ function considerMember(anchor, x, y, z, height) {
69
+ if (!anchor.selection.accept(getFrame(), getCamera(), x, y + height * 0.5, z, y + height + headClearance)) return;
70
+ anchor.x = x;
71
+ anchor.y = y;
72
+ anchor.z = z;
73
+ anchor.height = height;
74
+ }
75
+
76
+ /**
77
+ * Removes all registered group anchors.
78
+ */
79
+ function clearGroups() {
80
+ groupList.length = 0;
81
+ }
82
+
83
+ return { groupList, attachGroup, considerMember, clearGroups };
84
+ }