roamwright 0.61.17 → 0.61.18

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.
@@ -0,0 +1,80 @@
1
+ /**
2
+ * Crowd prepare-and-batch lifecycle around `createCrowdBatches`: registers crowd groups,
3
+ * caches shared distant/remote walk geometries, bakes their walk textures when the walker rig is
4
+ * ready, and rebuilds instanced batches whenever the registered crowd count changes.
5
+ * @module
6
+ */
7
+
8
+ import { farCrowdFigure } from '../geometry/crowd-far.js';
9
+ import { registerCrowd } from './crowd-update.js';
10
+
11
+ /**
12
+ * Create a page-scoped crowd prepare-and-batch lifecycle bound to a crowd batch manager and list.
13
+ *
14
+ * @param {object} config
15
+ * @param {ReturnType<import('./crowd-batches.js').createCrowdBatches>} config.batchManager - Crowd batch manager holding pose and walk textures.
16
+ * @param {object[]} [config.crowds=[]] - Mutable crowd registry populated by `addCrowd` and batched by `batchCrowds`.
17
+ * @param {object} [config.head] - Optional head profile passed to `farCrowdFigure('distant'|'remote', { head })`.
18
+ * @param {(spaceId: string, x: number, z: number) => number} [config.groundAt] - Ground elevation sampler by space id.
19
+ * @param {(x: number, y: number, salt?: number) => number} [config.hash] - Seeded 2D hash forwarded to `registerCrowd`.
20
+ * @param {string} [config.defaultSpace='world'] - Default space id for `addCrowd`.
21
+ * @returns {{
22
+ * addCrowd: (list: object[], tones: number[], cx: number, cz: number, range: number, kind: string, beasts?: object | null, space?: string) => object,
23
+ * prepareCrowds: () => import('three').BufferGeometry[],
24
+ * prepareWhenReady: (walkerOrdered?: () => Promise<unknown> | null | undefined) => Promise<import('three').BufferGeometry[]> | null,
25
+ * batchCrowds: () => object,
26
+ * clearFarFigures: () => void,
27
+ * }}
28
+ */
29
+ export function createCrowdLifecycle({
30
+ batchManager,
31
+ crowds = [],
32
+ head = undefined,
33
+ groundAt = () => 0,
34
+ hash = undefined,
35
+ defaultSpace = 'world',
36
+ }) {
37
+ let farFigures = null;
38
+
39
+ function addCrowd(list, tones, cx, cz, range, kind, beasts = null, space = defaultSpace) {
40
+ return registerCrowd(crowds, list, tones, cx, cz, range, kind, {
41
+ beasts,
42
+ space,
43
+ groundAt,
44
+ ...(hash ? { hash } : {}),
45
+ });
46
+ }
47
+
48
+ function prepareCrowds() {
49
+ const farOptions = head ? { head } : undefined;
50
+ farFigures ??= [farCrowdFigure('distant', farOptions), farCrowdFigure('remote', farOptions)];
51
+ batchManager.bakeWalksOnce(farFigures);
52
+ return farFigures;
53
+ }
54
+
55
+ function prepareWhenReady(walkerOrdered = () => batchManager.walkerOrdered?.()) {
56
+ const ordered = walkerOrdered();
57
+ if (ordered) return ordered.then(prepareCrowds);
58
+ prepareCrowds();
59
+ return null;
60
+ }
61
+
62
+ function batchCrowds() {
63
+ if (batchManager.batches?.groupCount === crowds.length) return batchManager.batches;
64
+ prepareCrowds();
65
+ const built = batchManager.buildCrowdBatches(
66
+ farFigures.map(f => f.clone()),
67
+ crowds,
68
+ );
69
+ batchManager.setBatches(built);
70
+ return built;
71
+ }
72
+
73
+ function clearFarFigures() {
74
+ if (!farFigures) return;
75
+ for (const geo of farFigures) geo.dispose();
76
+ farFigures = null;
77
+ }
78
+
79
+ return { addCrowd, batchCrowds, clearFarFigures, prepareCrowds, prepareWhenReady };
80
+ }
@@ -0,0 +1,145 @@
1
+ /**
2
+ * Plough team and ploughman assembly: pairs two yoked oxen (`THREE.InstancedMesh`) with timber
3
+ * plough gear (`geometry/prop-plough.js`) and lazily sculpts and poses the ploughman behind the
4
+ * stilts when the camera first approaches within visibility range.
5
+ * @module
6
+ */
7
+
8
+ import * as THREE from 'three';
9
+ import { GB } from '../geometry/builder.js';
10
+ import { TRS, createUnitShapes } from '../geometry/primitives.js';
11
+ import { ploughGear } from '../geometry/prop-plough.js';
12
+
13
+ const _coat = new THREE.Color();
14
+
15
+ /** Default sRGB hex coat tones for the left and right yoked oxen. */
16
+ export const DEFAULT_OX_COATS = Object.freeze([0x96684a, 0xc4a57e]);
17
+
18
+ /** Default camera distance in metres within which the ploughman figure is lazily built. */
19
+ export const PLOUGHMAN_SEEN_DISTANCE = 180;
20
+
21
+ /** Default human look descriptor for a farm ploughman. */
22
+ export const DEFAULT_PLOUGHMAN_LOOK = Object.freeze({
23
+ h: 0.98,
24
+ w: 1.08,
25
+ skin: 0xb48a64,
26
+ hair: 0x4a3a2a,
27
+ garb: 'tunic',
28
+ c1: 0x7c6a48,
29
+ c2: 0x4c4234,
30
+ hairStyle: 'cropped',
31
+ beard: true,
32
+ });
33
+
34
+ /**
35
+ * Mid-stride ploughman pose leaning into the plough stilts with both hands lowered onto the handles
36
+ * (positions in metres, joint rotations in radians).
37
+ */
38
+ export const PLOUGHMAN_STANCE = Object.freeze({
39
+ z: -1.02,
40
+ rootX: 0.14,
41
+ armX: -0.28,
42
+ foreX: -0.8,
43
+ legLX: -0.42,
44
+ legRX: 0.3,
45
+ shinRX: 0.35,
46
+ headX: 0.12,
47
+ });
48
+
49
+ /**
50
+ * Apply the ploughman's mid-stride leaning pose to an assembled figure rig.
51
+ *
52
+ * @param {object} figure - Assembled figure containing `group`, `root`, `armL`, `armR`, `foreL`, `foreR`, `legL`, `legR`, `shinR`, `head`.
53
+ * @param {typeof PLOUGHMAN_STANCE} [stance=PLOUGHMAN_STANCE] - Joint angles and Z offset behind the plough.
54
+ * @returns {THREE.Object3D} The posed `figure.group`.
55
+ */
56
+ export function posePloughman(figure, stance = PLOUGHMAN_STANCE) {
57
+ figure.group.position.set(0, 0, stance.z);
58
+ figure.root.rotation.x = stance.rootX;
59
+ figure.armL.rotation.x = figure.armR.rotation.x = stance.armX;
60
+ figure.foreL.rotation.x = figure.foreR.rotation.x = stance.foreX;
61
+ figure.legL.rotation.x = stance.legLX;
62
+ figure.legR.rotation.x = stance.legRX;
63
+ figure.shinR.rotation.x = stance.shinRX;
64
+ figure.head.rotation.x = stance.headX;
65
+ return figure.group;
66
+ }
67
+
68
+ /**
69
+ * Build and pose a ploughman figure using a caller-supplied figure builder.
70
+ *
71
+ * @param {object} options
72
+ * @param {(look: object, seed: number) => object} options.buildFigure - Figure builder returning a posed-rig handle.
73
+ * @param {object} [options.look=DEFAULT_PLOUGHMAN_LOOK] - Figure look descriptor.
74
+ * @param {number} [options.seed=3587] - Deterministic figure seed.
75
+ * @param {typeof PLOUGHMAN_STANCE} [options.stance=PLOUGHMAN_STANCE] - Joint pose overrides.
76
+ * @returns {THREE.Object3D}
77
+ */
78
+ export function buildPloughman({ buildFigure, look = DEFAULT_PLOUGHMAN_LOOK, seed = 3587, stance = PLOUGHMAN_STANCE }) {
79
+ return posePloughman(buildFigure(look, seed), stance);
80
+ }
81
+
82
+ /**
83
+ * Assemble a yoked two-ox plough team facing `+z` from the returned group's origin, with timber
84
+ * plough gear and an optional lazy-built ploughman sculpted on the first near render.
85
+ *
86
+ * @param {object} options
87
+ * @param {THREE.BufferGeometry} options.oxen - Standing ox geometry facing `+z` on `y = 0`.
88
+ * @param {() => number} [options.random=Math.random] - Deterministic PRNG in `[0, 1)` for plough timber tinting.
89
+ * @param {THREE.Material} [options.oxMaterial] - Material for the instanced oxen pair.
90
+ * @param {THREE.Material} [options.woodMaterial] - Material for the timber plough gear.
91
+ * @param {THREE.Camera | null} [options.camera=null] - Active camera checked against `seenDistance` before building the ploughman.
92
+ * @param {((look: object, seed: number) => object) | null} [options.buildFigure=null] - Figure builder for the ploughman (omit for unmanned team).
93
+ * @param {readonly [number, number]} [options.oxCoats=DEFAULT_OX_COATS] - sRGB hex coat tones for the two oxen.
94
+ * @param {object} [options.ploughmanLook=DEFAULT_PLOUGHMAN_LOOK] - Look descriptor passed to `buildFigure`.
95
+ * @param {number} [options.ploughmanSeed=3587] - Seed passed to `buildFigure`.
96
+ * @param {typeof PLOUGHMAN_STANCE} [options.ploughmanStance=PLOUGHMAN_STANCE] - Stance angles for the ploughman.
97
+ * @param {number} [options.seenDistance=PLOUGHMAN_SEEN_DISTANCE] - Camera distance in metres at which the ploughman is built (`0` builds immediately).
98
+ * @param {object} [options.shapes] - Unit shapes passed to `ploughGear` (defaults to `createUnitShapes()`).
99
+ * @param {number | null} [options.layer=1] - Render layer index for gear and oxen (`null` leaves default layer 0).
100
+ * @returns {THREE.Group}
101
+ */
102
+ export function createPloughTeam({
103
+ oxen,
104
+ random = Math.random,
105
+ oxMaterial = new THREE.MeshStandardMaterial({ vertexColors: true, roughness: 0.9 }),
106
+ woodMaterial = new THREE.MeshStandardMaterial({ vertexColors: true, roughness: 0.92 }),
107
+ camera = null,
108
+ buildFigure = null,
109
+ oxCoats = DEFAULT_OX_COATS,
110
+ ploughmanLook = DEFAULT_PLOUGHMAN_LOOK,
111
+ ploughmanSeed = 3587,
112
+ ploughmanStance = PLOUGHMAN_STANCE,
113
+ seenDistance = PLOUGHMAN_SEEN_DISTANCE,
114
+ shapes = createUnitShapes(),
115
+ layer = 1,
116
+ }) {
117
+ const team = new THREE.Group();
118
+ const builder = new GB();
119
+ const pair = new THREE.InstancedMesh(oxen, oxMaterial, 2);
120
+ [-1, 1].forEach((side, i) => {
121
+ pair.setMatrixAt(i, TRS(side * 0.62, 0, 3.3, 1.04, 1.04, 1.04, side * -0.03));
122
+ pair.setColorAt(i, _coat.setHex(oxCoats[i]));
123
+ });
124
+ pair.castShadow = pair.receiveShadow = true;
125
+ ploughGear(builder, random, shapes);
126
+ const gear = builder.mesh(woodMaterial, team);
127
+ if (layer !== null) {
128
+ gear.layers.set(layer);
129
+ pair.layers.set(layer);
130
+ }
131
+ team.add(pair);
132
+ if (buildFigure) {
133
+ const mount = () => team.add(buildPloughman({ buildFigure, look: ploughmanLook, seed: ploughmanSeed, stance: ploughmanStance }));
134
+ if (seenDistance <= 0 || !camera) {
135
+ mount();
136
+ } else {
137
+ gear.onBeforeRender = () => {
138
+ if (team.position.distanceTo(camera.position) > seenDistance) return;
139
+ gear.onBeforeRender = () => {};
140
+ mount();
141
+ };
142
+ }
143
+ }
144
+ return team;
145
+ }
@@ -0,0 +1,190 @@
1
+ /**
2
+ * Flowering and wind-swaying grass tuft material and pressed-cover wiring: opens flower petals and
3
+ * grain ears from `aFlower` instance attributes, sways blades with `WIND_SWAY_GLSL`, presses grass
4
+ * flat inside active scene discs, and fades tufts smoothly at single- or multi-ring patch edges.
5
+ * @module
6
+ */
7
+
8
+ import * as THREE from 'three';
9
+ import { DEFAULT_FLOWER_LOOKS, FLOWER_KINDS, TUFT_SHAPE, tuftGeometry as buildTuftGeometry } from '../geometry/plant-tuft.js';
10
+ import { WIND_SWAY_GLSL } from '../motion/wind.js';
11
+ import { clearInstancesInDiscs, createPressedDiscs, pressedDiscsPars, pressedStandingGLSL } from './pressed-cover.js';
12
+ import { thinSurfaceLight } from './surface-light.js';
13
+
14
+ /**
15
+ * Default shader tuning constants for {@link createTuftMaterial} and {@link createGrassTuft}.
16
+ */
17
+ export const TUFT_SHADER = Object.freeze({
18
+ /** Narrowed stem width as a fraction of the blade it came from. */
19
+ stemNarrow: 0.3,
20
+ /** Camera distance in metres within which flower heads keep true world size. */
21
+ headTrue: 5,
22
+ /** Distance span in metres over which flower heads double in apparent size. */
23
+ headGrow: 8,
24
+ /** Maximum apparent flower-head size multiplier at distance. */
25
+ headMost: 2.5,
26
+ /** Forward-scattering backlit glow strength against a low sun. */
27
+ glow: 1.1,
28
+ /** Default pressed-disc clearing radii for low cover shrubs (`clearInstancesInDiscs`). */
29
+ cleared: Object.freeze({ fromRadii: 1.2, toRadii: 1.7 }),
30
+ });
31
+
32
+ function buildFlowerUniforms(looks, tallest) {
33
+ const table = (fn, size) => looks.map(fn).map(a => (size === 3 ? new THREE.Vector3(...a) : new THREE.Vector4(...a)));
34
+ return {
35
+ uFlowerA: { value: table(k => [k.stem, k.r, k.cup, k.wide], 4) },
36
+ uFlowerB: { value: table(k => [k.petals, k.spread, k.nod, k.over * tallest], 4) },
37
+ uHeart: { value: table(k => k.heart, 3) },
38
+ uRim: { value: table(k => k.tip, 3) },
39
+ };
40
+ }
41
+
42
+ function buildFlowerVertexGLSL(cfg) {
43
+ return /* glsl */ `
44
+ float fKind = floor(aFlower * 0.25 + 0.01), fHeads = aFlower - fKind * 4.0;
45
+ if (fKind > 0.5 && aStem.x > 0.5 && aStem.x < fHeads + 0.5) {
46
+ int k = int(fKind) - 1;
47
+ vec4 fa = uFlowerA[k], fb = uFlowerB[k];
48
+ float sx = length(instanceMatrix[0].xyz), sy = length(instanceMatrix[1].xyz);
49
+ float fh = fract(sin(dot(instanceMatrix[3].xz, vec2(12.9898, 78.233)) + aStem.x * 7.31) * 43758.5453);
50
+ float seen = 1.0 + clamp((length(ip - uCam) - ${cfg.headTrue.toFixed(1)}) / ${cfg.headGrow.toFixed(1)}, 0.0, ${(cfg.headMost - 1).toFixed(1)});
51
+ float lift = max(fa.x / sy, fb.w) * (0.92 + 0.16 * fh) / aStem.y;
52
+ if (aPetal.w < 0.5) {
53
+ transformed.xz = mix(aStem.zw, transformed.xz, ${cfg.stemNarrow.toFixed(2)});
54
+ transformed.y *= lift;
55
+ } else {
56
+ vec2 lean = transformed.xz - aStem.zw; lean /= max(length(lean), 1e-4);
57
+ vec3 up = normalize(vec3(lean.x * fb.z, 1.0, lean.y * fb.z)),
58
+ ax = normalize(cross(up, vec3(0.0, 0.0, 1.0))), bx = cross(up, ax);
59
+ float ang = aPetal.x * (fb.y > 0.0 ? 2.4 : 6.2832 / fb.x) + fh * 6.2832,
60
+ r = aPetal.x < fb.x ? fa.y * (0.85 + 0.3 * fh) : 0.0;
61
+ vec3 dir = cos(ang) * ax + sin(ang) * bx,
62
+ off = r * aPetal.y * (dir * cos(fa.z) + up * sin(fa.z)) + cross(up, dir) * aPetal.z * fa.w * r - up * aPetal.x * fb.y;
63
+ transformed = vec3(transformed.x, transformed.y * lift, transformed.z) + off * seen / vec3(sx, sy, sx);
64
+ vColor.rgb = mix(uHeart[k], uRim[k], smoothstep(0.12, 0.8, aPetal.y)) * (0.85 + 0.3 * fh);
65
+ vTip = 0.33;
66
+ }
67
+ }`;
68
+ }
69
+
70
+ /**
71
+ * Create a flowering, wind-swaying, trodden-aware grass tuft `MeshStandardMaterial` compatible with
72
+ * `createTuftPatch`.
73
+ *
74
+ * @param {{ value: THREE.Vector3 }} uCam - Patch centre / camera position uniform.
75
+ * @param {{ value: number }} uR - Single-ring patch outer radius uniform in metres.
76
+ * @param {boolean} [ringed=false] - When true, reads per-instance `aReach` `[inner, outer]` fade radii.
77
+ * @param {object} [options]
78
+ * @param {{ value: number }} [options.uTime] - Elapsed clock uniform in seconds.
79
+ * @param {{ value: number }} [options.uSunLight] - Sun intensity uniform (`0..1`).
80
+ * @param {{ value: THREE.Vector3 }} [options.uWind] - World wind vector uniform.
81
+ * @param {ReturnType<typeof createPressedDiscs>} [options.pressed] - Shared pressed-cover discs handle.
82
+ * @param {readonly object[]} [options.looks=DEFAULT_FLOWER_LOOKS] - Flower and seed-head descriptor table.
83
+ * @param {number} [options.tallest=TUFT_SHAPE.tallest] - Tallest blade height in tuft-local metres.
84
+ * @param {(sky: number, sun: number, glow: number, where: string) => string} [options.lightThrough] - Backlighting GLSL snippet builder.
85
+ * @param {Partial<typeof TUFT_SHADER>} [options.shader] - Overrides to {@link TUFT_SHADER}.
86
+ * @param {object} [options.flowerUniforms] - Prebuilt flower table uniform map (reused across materials).
87
+ * @returns {THREE.MeshStandardMaterial}
88
+ */
89
+ export function createTuftMaterial(uCam, uR, ringed = false, options = {}) {
90
+ const cfg = options.shader ? { ...TUFT_SHADER, ...options.shader } : TUFT_SHADER;
91
+ const looks = options.looks ?? DEFAULT_FLOWER_LOOKS;
92
+ const tallest = options.tallest ?? TUFT_SHAPE.tallest;
93
+ const flowerU = options.flowerUniforms ?? buildFlowerUniforms(looks, tallest);
94
+ const pressed = options.pressed ?? createPressedDiscs(8);
95
+ const uTime = options.uTime ?? { value: 0 };
96
+ const uSunLight = options.uSunLight ?? { value: 1 };
97
+ const uWind = options.uWind ?? { value: new THREE.Vector3(1, 0, 0) };
98
+ const lightThrough =
99
+ options.lightThrough ??
100
+ ((sky, sun, glow, where) => thinSurfaceLight({ sky, sun, glow, where, sunlight: 'uSunLight', shadowed: false }));
101
+ const kinds = looks.length;
102
+ const flowerVertex = buildFlowerVertexGLSL(cfg);
103
+
104
+ const mat = new THREE.MeshStandardMaterial({ roughness: 1, side: THREE.DoubleSide });
105
+ mat.onBeforeCompile = sh => {
106
+ Object.assign(sh.uniforms, flowerU, pressed.uniforms, { uTime, uSunLight, uWind, uCam, uR });
107
+ sh.vertexShader = sh.vertexShader
108
+ .replace(
109
+ '#include <common>',
110
+ `#include <common>
111
+ uniform float uTime, uR; uniform vec3 uCam, uWind; ${pressedDiscsPars(pressed)} varying float vTip; attribute float aFlower; attribute vec4 aStem, aPetal;${ringed ? ' attribute vec2 aReach;' : ''}
112
+ ${WIND_SWAY_GLSL}
113
+ uniform vec4 uFlowerA[${kinds}], uFlowerB[${kinds}]; uniform vec3 uHeart[${kinds}], uRim[${kinds}];`,
114
+ )
115
+ .replace(
116
+ '#include <begin_vertex>',
117
+ `/* glsl */
118
+ #include <begin_vertex>
119
+ vec3 ip = instanceMatrix[3].xyz; float gd = length((ip - uCam) * vec3(1.0, 1.48, 1.0)); vTip = position.y;${flowerVertex}
120
+ // wind sway: blades lean downwind, more in a gust, and waves run across the grass
121
+ transformed.xz += windSway(ip, transformed.y, 0.05, 0.05, 0.0);
122
+ // trodden: pressed nearly flat where people stand and the camera looks through
123
+ ${pressedStandingGLSL(pressed, 'ip.xz')}
124
+ transformed.y *= mix(0.1, 1.0, stands);
125
+ transformed *= 1.0 - smoothstep(${ringed ? 'aReach.y * 0.55, aReach.y' : 'uR * 0.55, uR'}, gd)${ringed ? ' * (aReach.x > 0.0 ? smoothstep(aReach.x * 0.55, aReach.x, gd) : 1.0)' : ''};`,
126
+ );
127
+ sh.fragmentShader = sh.fragmentShader
128
+ .replace('#include <common>', '#include <common>\nvarying float vTip; uniform float uSunLight;')
129
+ .replace('#include <map_fragment>', 'diffuseColor.rgb *= mix(0.62, 1.34, clamp(vTip * 1.6, 0.0, 1.0));')
130
+ .replace(
131
+ '#include <normal_fragment_begin>',
132
+ '#include <normal_fragment_begin>\n normal = normalize((viewMatrix * vec4(0.0, 1.0, 0.0, 0.0)).xyz);',
133
+ )
134
+ .replace('#include <opaque_fragment>', lightThrough(0, 0, cfg.glow, 'clamp(vTip * 1.6, 0.2, 1.0)'));
135
+ };
136
+ mat.customProgramCacheKey = () => 'grass-one-wind-trodden' + (ringed ? '-ringed' : '');
137
+ return mat;
138
+ }
139
+
140
+ /**
141
+ * Create a world-bound grass tuft toolkit sharing one set of pressed-cover discs, flower uniform
142
+ * tables, wind/time/sun uniforms and low-cover clearing hook.
143
+ *
144
+ * @param {object} [options]
145
+ * @param {number} [options.seed=5] - Deterministic seed for `tuftGeometry()`.
146
+ * @param {readonly object[]} [options.looks=DEFAULT_FLOWER_LOOKS] - Flower and seed-head descriptor table.
147
+ * @param {Partial<typeof TUFT_SHAPE>} [options.shape] - Overrides to `TUFT_SHAPE`.
148
+ * @param {Partial<typeof TUFT_SHADER>} [options.shader] - Overrides to {@link TUFT_SHADER}.
149
+ * @param {number} [options.maxPressed=8] - Maximum pressed-cover discs.
150
+ * @param {{ value: number }} [options.uTime] - Elapsed clock uniform in seconds.
151
+ * @param {{ value: number }} [options.uSunLight] - Sun intensity uniform (`0..1`).
152
+ * @param {{ value: THREE.Vector3 }} [options.uWind] - World wind vector uniform.
153
+ * @param {(sky: number, sun: number, glow: number, where: string) => string} [options.lightThrough] - Backlighting GLSL snippet builder.
154
+ * @returns {{
155
+ * FLOWER: typeof FLOWER_KINDS,
156
+ * pressedDiscs: ReturnType<typeof createPressedDiscs>,
157
+ * pressGrass: (count: number) => THREE.Vector3[],
158
+ * clearedInScenes: <T extends THREE.Material>(mat: T) => T,
159
+ * tuftGeometry: () => THREE.BufferGeometry,
160
+ * tuftMaterial: (uCam: { value: THREE.Vector3 }, uR: { value: number }, ringed?: boolean) => THREE.MeshStandardMaterial,
161
+ * }}
162
+ */
163
+ export function createGrassTuft(options = {}) {
164
+ const looks = options.looks ?? DEFAULT_FLOWER_LOOKS;
165
+ const tallest = options.shape?.tallest ?? TUFT_SHAPE.tallest;
166
+ const cfg = options.shader ? { ...TUFT_SHADER, ...options.shader } : TUFT_SHADER;
167
+ const flowerUniforms = buildFlowerUniforms(looks, tallest);
168
+ const pressedDiscs = options.pressed ?? createPressedDiscs(options.maxPressed ?? 8);
169
+ const cleared = cfg.cleared ?? TUFT_SHADER.cleared;
170
+
171
+ return {
172
+ FLOWER: FLOWER_KINDS,
173
+ pressedDiscs,
174
+ pressGrass: count => pressedDiscs.count(count),
175
+ clearedInScenes: mat => clearInstancesInDiscs(mat, pressedDiscs, cleared),
176
+ tuftGeometry: () => buildTuftGeometry({ seed: options.seed ?? 5, shape: options.shape }),
177
+ tuftMaterial: (uCam, uR, ringed = false) =>
178
+ createTuftMaterial(uCam, uR, ringed, {
179
+ uTime: options.uTime,
180
+ uSunLight: options.uSunLight,
181
+ uWind: options.uWind,
182
+ pressed: pressedDiscs,
183
+ looks,
184
+ tallest,
185
+ lightThrough: options.lightThrough,
186
+ shader: cfg,
187
+ flowerUniforms,
188
+ }),
189
+ };
190
+ }
@@ -0,0 +1,199 @@
1
+ /**
2
+ * Architectural fittings and light/water decals for ruins and courtyards: additive radial ground
3
+ * light pools, dark still water basins, lit brass lamp stands and iron wall lanterns.
4
+ * @module
5
+ */
6
+
7
+ import * as THREE from 'three';
8
+ import { createUnitShapes } from '../geometry/primitives.js';
9
+ import { buildLampStandGeometry, buildWallLanternGeometry } from '../geometry/ruins-masonry.js';
10
+ import { falloffAt, pixelTexture } from './textures.js';
11
+
12
+ /** Default parameters for additive radial ground light pools built by {@link addLightPool}. */
13
+ export const LIGHT_POOL = Object.freeze({
14
+ size: 64,
15
+ falloff: Object.freeze([Object.freeze([0, 1]), Object.freeze([0.35, 0.42]), Object.freeze([1, 0])]),
16
+ hex: 0xffb060,
17
+ strength: 0.75,
18
+ lift: 0.04,
19
+ renderOrder: 4,
20
+ });
21
+
22
+ let defaultPoolTexture = null;
23
+ let fallbackShapes = null;
24
+ const defaultShapes = () => (fallbackShapes ??= createUnitShapes());
25
+
26
+ /**
27
+ * Create a radial white alpha-falloff texture for additive ground light pools.
28
+ *
29
+ * @param {object} [options]
30
+ * @param {number} [options.size=LIGHT_POOL.size] - Texture width and height in pixels.
31
+ * @param {readonly (readonly [number, number])[]} [options.falloff=LIGHT_POOL.falloff] - Radial `[t, alpha]` control stops.
32
+ * @returns {THREE.CanvasTexture}
33
+ */
34
+ export function createLightPoolTexture({ size = LIGHT_POOL.size, falloff = LIGHT_POOL.falloff } = {}) {
35
+ return pixelTexture(
36
+ size,
37
+ (u, v, out) => {
38
+ out[0] = out[1] = out[2] = 255;
39
+ out[3] = 255 * falloffAt(falloff, (Math.hypot(u - 0.5, v - 0.5) * size - 1) / (size / 2 - 2));
40
+ },
41
+ { clamp: true },
42
+ );
43
+ }
44
+
45
+ /**
46
+ * Place a soft additive pool of warm light lying flat on the ground at `(x, y, z)` so unlit street
47
+ * lanterns read warmly without extra dynamic point lights.
48
+ *
49
+ * @param {THREE.Object3D} group - Destination scene or group.
50
+ * @param {number} x - World X position in metres.
51
+ * @param {number} y - Ground elevation in metres.
52
+ * @param {number} z - World Z position in metres.
53
+ * @param {number} radius - Pool radius in metres.
54
+ * @param {object} [options]
55
+ * @param {number} [options.hex=LIGHT_POOL.hex] - Light pool sRGB colour.
56
+ * @param {number} [options.strength=LIGHT_POOL.strength] - Intensity multiplier.
57
+ * @param {number} [options.lift=LIGHT_POOL.lift] - Vertical offset above ground in metres.
58
+ * @param {number} [options.renderOrder=LIGHT_POOL.renderOrder] - Three.js `renderOrder`.
59
+ * @param {boolean} [options.fogFades=false] - Attach `{ FOG_FADES: '' }` define for worlds with custom haze fading.
60
+ * @param {THREE.Texture} [options.texture] - Optional prebuilt radial glow texture.
61
+ * @returns {THREE.Mesh}
62
+ */
63
+ export function addLightPool(group, x, y, z, radius, options = {}) {
64
+ const {
65
+ hex = LIGHT_POOL.hex,
66
+ strength = LIGHT_POOL.strength,
67
+ lift = LIGHT_POOL.lift,
68
+ renderOrder = LIGHT_POOL.renderOrder,
69
+ fogFades = false,
70
+ } = options;
71
+ const map = options.texture ?? (defaultPoolTexture ??= createLightPoolTexture());
72
+ const material = new THREE.MeshBasicMaterial({
73
+ map,
74
+ color: new THREE.Color(hex).multiplyScalar(strength),
75
+ blending: THREE.AdditiveBlending,
76
+ depthWrite: false,
77
+ transparent: true,
78
+ });
79
+ if (fogFades) material.defines = { FOG_FADES: '' };
80
+ const pool = new THREE.Mesh(new THREE.PlaneGeometry(1, 1).rotateX(-Math.PI / 2), material);
81
+ pool.position.set(x, y + lift, z);
82
+ pool.scale.set(radius * 2, 1, radius * 2);
83
+ pool.renderOrder = renderOrder;
84
+ group.add(pool);
85
+ return pool;
86
+ }
87
+
88
+ /**
89
+ * Add a dark, glossy oval or circular pool of still water lying in a courtyard basin or hollow.
90
+ *
91
+ * @param {THREE.Object3D} group - Destination scene or group.
92
+ * @param {object} options
93
+ * @param {{ x: number, z: number }} [options.origin={ x: 0, z: 0 }] - Local frame world origin.
94
+ * @param {number} [options.x=0] - Local X position in metres.
95
+ * @param {number} [options.y=0] - Water surface elevation in metres.
96
+ * @param {number} [options.z=0] - Local Z position in metres.
97
+ * @param {number} [options.width=2] - Pool width in metres.
98
+ * @param {number} [options.depth=2] - Pool depth in metres.
99
+ * @param {number} [options.yaw=0] - Rotation around Y in radians.
100
+ * @param {number} [options.color=0x1c2a2a] - Water base sRGB colour.
101
+ * @param {number} [options.roughness=0.05] - Surface roughness.
102
+ * @param {number} [options.metalness=0.4] - Surface reflectivity factor.
103
+ * @param {number} [options.opacity=0.88] - Water opacity.
104
+ * @param {number} [options.segments=20] - Perimeter circle segments.
105
+ * @returns {THREE.Mesh}
106
+ */
107
+ export function addStillPool(group, options = {}) {
108
+ const {
109
+ origin = { x: 0, z: 0 },
110
+ x = 0,
111
+ y = 0,
112
+ z = 0,
113
+ width = 2,
114
+ depth = 2,
115
+ yaw = 0,
116
+ color = 0x1c2a2a,
117
+ roughness = 0.05,
118
+ metalness = 0.4,
119
+ opacity = 0.88,
120
+ segments = 20,
121
+ } = options;
122
+ const water = new THREE.Mesh(
123
+ new THREE.CircleGeometry(0.5, segments).rotateX(-Math.PI / 2),
124
+ new THREE.MeshStandardMaterial({ color, roughness, metalness, transparent: true, opacity }),
125
+ );
126
+ water.position.set(origin.x + x, y, origin.z + z);
127
+ water.scale.set(width, 1, depth);
128
+ water.rotation.y = yaw;
129
+ group.add(water);
130
+ return water;
131
+ }
132
+
133
+ /**
134
+ * Build a tall brass oil-lamp stand and invoke an optional flame callback at its wick.
135
+ *
136
+ * @param {{ trim: import('../geometry/builder.js').GB, cloth: import('../geometry/builder.js').GB }} kit - Destination builders.
137
+ * @param {object} [options]
138
+ * @param {number} [options.x=0] - Local X position in metres.
139
+ * @param {number} [options.y=0] - Base elevation in metres.
140
+ * @param {number} [options.z=0] - Local Z position in metres.
141
+ * @param {number} [options.height=1.25] - Stand height in metres.
142
+ * @param {object} [options.shapes] - Unit shapes (`createUnitShapes()`).
143
+ * @param {Function} [options.transform] - Transform matrix helper (`TRS`).
144
+ * @param {((x: number, y: number, z: number, size: number) => void) | null} [options.onFlame=null] - Callback receiving the wick position and flame size.
145
+ * @returns {[number, number, number]} Local wick position `[x, y, z]`.
146
+ */
147
+ export function addLampStand(kit, options = {}) {
148
+ const wick = buildLampStandGeometry(kit, options);
149
+ options.onFlame?.(wick[0], wick[1], wick[2], 0.1);
150
+ return wick;
151
+ }
152
+
153
+ /**
154
+ * Build an iron bracketed wall lantern, place its glowing horn panes, emit an optional fire/light
155
+ * site callback, and cast a soft ground light pool below it.
156
+ *
157
+ * @param {{ trim: import('../geometry/builder.js').GB }} kit - Destination builder container.
158
+ * @param {object} options
159
+ * @param {THREE.Object3D} options.group - Group receiving the glowing lantern panes and ground light pool.
160
+ * @param {{ x: number, z: number }} [options.origin={ x: 0, z: 0 }] - Local frame world origin.
161
+ * @param {number} [options.x=0] - Wall anchor local X in metres.
162
+ * @param {number} [options.y=2.5] - Bracket height in metres.
163
+ * @param {number} [options.z=0] - Wall anchor local Z in metres.
164
+ * @param {number} [options.out=0] - Outward bearing in radians.
165
+ * @param {number} [options.ground=0] - Ground elevation below the lantern for its light pool.
166
+ * @param {number} [options.poolRadius=5] - Ground light pool radius in metres.
167
+ * @param {boolean} [options.fogFades=false] - Forwarded to {@link addLightPool}.
168
+ * @param {object} [options.shapes] - Unit shapes (`createUnitShapes()`).
169
+ * @param {Function} [options.transform] - Transform matrix helper (`TRS`).
170
+ * @param {Function} [options.stickFn] - Tapered rod helper (`stick`).
171
+ * @param {((geo: THREE.BufferGeometry, hex: number, boost: number, group: THREE.Object3D) => THREE.Mesh) | null} [options.makeGlowMesh=null] - Custom emissive mesh factory.
172
+ * @param {((x: number, y: number, z: number) => void) | null} [options.onSite=null] - Optional callback receiving world lantern flame coordinates.
173
+ * @returns {{ horn: THREE.Mesh, pool: THREE.Mesh, lantern: { x: number, y: number, z: number } }}
174
+ */
175
+ export function addWallLantern(kit, options) {
176
+ const {
177
+ group,
178
+ origin = { x: 0, z: 0 },
179
+ ground = 0,
180
+ poolRadius = 5,
181
+ fogFades = false,
182
+ shapes = defaultShapes(),
183
+ makeGlowMesh = null,
184
+ onSite = null,
185
+ } = options;
186
+ const lantern = buildWallLanternGeometry(kit, { ...options, shapes });
187
+ const horn = makeGlowMesh
188
+ ? makeGlowMesh(shapes.cyl6, 0xffb860, 1.15, group)
189
+ : (() => {
190
+ const m = new THREE.Mesh(shapes.cyl6, new THREE.MeshBasicMaterial({ color: new THREE.Color(0xffb860).multiplyScalar(1.15) }));
191
+ group.add(m);
192
+ return m;
193
+ })();
194
+ horn.position.set(origin.x + lantern.x, lantern.y - 0.135, origin.z + lantern.z);
195
+ horn.scale.set(0.14, 0.27, 0.14);
196
+ onSite?.(origin.x + lantern.x, lantern.y - 0.05, origin.z + lantern.z);
197
+ const pool = addLightPool(group, origin.x + lantern.x, ground, origin.z + lantern.z, poolRadius, { fogFades });
198
+ return { horn, pool, lantern };
199
+ }