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.
@@ -57,3 +57,150 @@ export function extendFieldBorders(
57
57
  }
58
58
  }
59
59
  }
60
+
61
+ /**
62
+ * Bit layout of the compact 1-byte-per-texel farmland map produced by {@link packFieldBits}.
63
+ */
64
+ export const FIELD_BITS = Object.freeze({
65
+ /** Farm track bit (wheel-rut strength above threshold). */
66
+ track: 1,
67
+ /** Standing crop bit (coverage above threshold). */
68
+ crop: 2,
69
+ /** Worked-season bit (lot work byte above threshold). */
70
+ worked: 4,
71
+ /** Bit shift of the quantized parcel use index (`0..6`). */
72
+ useShift: 3,
73
+ });
74
+
75
+ /** Default sentinel distance in metres where no trail or dry wash is nearby. */
76
+ export const NO_PATH_DISTANCE = 99;
77
+
78
+ /**
79
+ * Pack RGBA field and lot rasters into a single byte per texel holding track, crop, worked flags
80
+ * and quantized parcel use so the full RGBA arrays can be released after startup.
81
+ *
82
+ * @param {object} fields - Field raster container `{ data, lots, width, height }`.
83
+ * @param {Uint8Array | Uint8ClampedArray} fields.data - RGBA field raster.
84
+ * @param {Uint8Array | Uint8ClampedArray} fields.lots - RGBA lot-work raster.
85
+ * @param {number} fields.width - Raster width in texels.
86
+ * @param {number} fields.height - Raster height in texels.
87
+ * @param {object} [options]
88
+ * @param {number} [options.trackThreshold=45] - Blue-channel threshold for farm tracks.
89
+ * @param {number} [options.cropThreshold=100] - Alpha-channel threshold for standing crops.
90
+ * @param {number} [options.workedThreshold=127] - Lot blue-channel threshold for worked parcels.
91
+ * @param {number} [options.useStep=42] - Quantization divisor for the green parcel-use byte.
92
+ * @returns {Uint8Array}
93
+ */
94
+ export function packFieldBits(fields, options = {}) {
95
+ const { data, lots, width, height } = fields;
96
+ const trackThreshold = options.trackThreshold ?? 45;
97
+ const cropThreshold = options.cropThreshold ?? 100;
98
+ const workedThreshold = options.workedThreshold ?? 127;
99
+ const useStep = options.useStep ?? 42;
100
+ const count = width * height;
101
+ const bits = new Uint8Array(count);
102
+ for (let p = 0; p < count; p++) {
103
+ const k = p * 4;
104
+ bits[p] =
105
+ (data[k + 2] > trackThreshold ? FIELD_BITS.track : 0) |
106
+ (data[k + 3] > cropThreshold ? FIELD_BITS.crop : 0) |
107
+ (lots[k + 2] > workedThreshold ? FIELD_BITS.worked : 0) |
108
+ (Math.round(data[k + 1] / useStep) << FIELD_BITS.useShift);
109
+ }
110
+ return bits;
111
+ }
112
+
113
+ /**
114
+ * Crop full-map plain cover, trail-distance and wash-distance grids down to the tight bounding box
115
+ * of active cells so large empty areas cost no memory.
116
+ *
117
+ * @param {object} options
118
+ * @param {number} options.stride - Grid width and height in cells.
119
+ * @param {Uint8Array | Uint8ClampedArray} options.cover - Interleaved 2-channel plain cover grid (channel 0 is bunch grass).
120
+ * @param {Float32Array} options.track - Distance to nearest herd trail per cell in metres.
121
+ * @param {Float32Array} options.wash - Distance to nearest dry wash per cell in metres.
122
+ * @param {number} [options.noPath=NO_PATH_DISTANCE] - Sentinel distance for cells with no nearby path.
123
+ * @returns {{ i0: number, j0: number, w: number, h: number, bunch: Uint8Array, track: Float32Array, wash: Float32Array }}
124
+ */
125
+ export function packSparsePlain({ stride, cover, track, wash, noPath = NO_PATH_DISTANCE }) {
126
+ let i0 = stride;
127
+ let i1 = -1;
128
+ let j0 = stride;
129
+ let j1 = -1;
130
+ for (let j = 0; j < stride; j++) {
131
+ for (let i = 0; i < stride; i++) {
132
+ const k = j * stride + i;
133
+ if (!cover[k * 2] && track[k] === noPath && wash[k] === noPath) continue;
134
+ i0 = Math.min(i0, i);
135
+ i1 = Math.max(i1, i);
136
+ j0 = Math.min(j0, j);
137
+ j1 = Math.max(j1, j);
138
+ }
139
+ }
140
+ const w = Math.max(0, i1 - i0 + 1);
141
+ const h = Math.max(0, j1 - j0 + 1);
142
+ const out = { i0, j0, w, h, bunch: new Uint8Array(w * h), track: new Float32Array(w * h), wash: new Float32Array(w * h) };
143
+ for (let j = 0; j < h; j++) {
144
+ for (let i = 0; i < w; i++) {
145
+ const k = (j0 + j) * stride + i0 + i;
146
+ const c = j * w + i;
147
+ out.bunch[c] = cover[k * 2];
148
+ out.track[c] = track[k];
149
+ out.wash[c] = wash[k];
150
+ }
151
+ }
152
+ return out;
153
+ }
154
+
155
+ /**
156
+ * Create a compact runtime cache for grass placement queries over packed farmland bits and a
157
+ * cropped sparse plain/trail/wash rectangle.
158
+ *
159
+ * @param {object} options
160
+ * @param {number} options.stride - Terrain height-grid width in cells.
161
+ * @param {(x: number, z: number) => number} options.fieldPixel - Maps world `(x, z)` to RGBA byte offset in the field map, or `< 0` outside.
162
+ * @param {number} [options.noPath=NO_PATH_DISTANCE] - Sentinel distance returned outside the cropped plain rectangle.
163
+ * @returns {{
164
+ * keep: (input: { fields: { data: Uint8Array | Uint8ClampedArray, lots: Uint8Array | Uint8ClampedArray, width: number, height: number }, cover: Uint8Array | Uint8ClampedArray, track: Float32Array, wash: Float32Array }) => void,
165
+ * fieldSpot: (x: number, z: number) => number,
166
+ * plainAt: (cellIndex: number, out: number[]) => number[],
167
+ * clear: () => void,
168
+ * }}
169
+ */
170
+ export function createFieldCoverCache({ stride, fieldPixel, noPath = NO_PATH_DISTANCE }) {
171
+ let fieldBits = null;
172
+ let plain = null;
173
+ return {
174
+ keep({ fields, cover, track, wash }) {
175
+ fieldBits = packFieldBits(fields);
176
+ plain = packSparsePlain({ stride, cover, track, wash, noPath });
177
+ },
178
+ fieldSpot(x, z) {
179
+ const k = fieldPixel(x, z);
180
+ return k < 0 || !fieldBits ? 0 : fieldBits[k >> 2];
181
+ },
182
+ plainAt(k, out) {
183
+ if (!plain) {
184
+ out[0] = 0;
185
+ out[1] = out[2] = noPath;
186
+ return out;
187
+ }
188
+ const i = (k % stride) - plain.i0;
189
+ const j = ((k / stride) | 0) - plain.j0;
190
+ if (i < 0 || j < 0 || i >= plain.w || j >= plain.h) {
191
+ out[0] = 0;
192
+ out[1] = out[2] = noPath;
193
+ } else {
194
+ const c = j * plain.w + i;
195
+ out[0] = plain.bunch[c];
196
+ out[1] = plain.track[c];
197
+ out[2] = plain.wash[c];
198
+ }
199
+ return out;
200
+ },
201
+ clear() {
202
+ fieldBits = null;
203
+ plain = null;
204
+ },
205
+ };
206
+ }
@@ -75,6 +75,46 @@ class Copies {
75
75
 
76
76
  export { Copies, instanceArrays, instancedMesh, instancedTwin, putInstance };
77
77
 
78
+ /**
79
+ * Round-robin instanced batch builder over an array of variant geometries: distributes added
80
+ * `(matrix, [r, g, b])` instances evenly across `shapes`, then emits one static `THREE.InstancedMesh`
81
+ * per non-empty variant into a scene or group.
82
+ *
83
+ * @param {THREE.BufferGeometry[]} shapes - Variant geometries (each copied through `geometryView` on build).
84
+ * @param {number} maxInstances - Maximum total capacity allocated per shape bucket.
85
+ * @returns {{
86
+ * put: (matrix: THREE.Matrix4, rgb: readonly [number, number, number]) => void,
87
+ * addTo: (group: THREE.Object3D, material: THREE.Material, options?: { castShadow?: boolean, receiveShadow?: boolean }) => THREE.InstancedMesh[],
88
+ * }}
89
+ */
90
+ export function createShapeBatches(shapes, maxInstances) {
91
+ const batches = shapes.map(() => ({ copies: instanceArrays(maxInstances), count: 0 }));
92
+ let turn = 0;
93
+ return {
94
+ put(matrix, [r, g, b]) {
95
+ const batch = batches[turn++ % batches.length];
96
+ putInstance(batch.copies, batch.count++, matrix, r, g, b);
97
+ },
98
+ addTo(group, material, { castShadow = false, receiveShadow = true } = {}) {
99
+ const meshes = [];
100
+ batches.forEach(({ copies, count }, i) => {
101
+ if (!count) return;
102
+ const mesh = instancedMesh(geometryView(shapes[i]), material, {
103
+ matrices: copies.matrices.subarray(0, count * 16),
104
+ colours: copies.colours.subarray(0, count * 3),
105
+ });
106
+ mesh.castShadow = castShadow;
107
+ mesh.receiveShadow = receiveShadow;
108
+ mesh.matrixAutoUpdate = false;
109
+ mesh.computeBoundingSphere();
110
+ if (group) group.add(mesh);
111
+ meshes.push(mesh);
112
+ });
113
+ return meshes;
114
+ },
115
+ };
116
+ }
117
+
78
118
  // Partition static world-space transforms and their colors into independently cullable
79
119
  // cells. A single cell keeps its original arrays; order within every cell is stable.
80
120
  export function partitionInstances(arrays, cellSize) {
@@ -0,0 +1,138 @@
1
+ /**
2
+ * Pure geometry builder and flower/seed-head look tables for instanced grass tufts: fifteen tapered
3
+ * blades, the last three carrying collapsed petal slots opened on the GPU by `rendering/plant-tuft.js`.
4
+ * Worker-safe.
5
+ * @module
6
+ */
7
+
8
+ import * as THREE from 'three';
9
+ import { mulberry32 } from '../math/random.js';
10
+ import { TAU } from '../math/scalar.js';
11
+
12
+ /**
13
+ * Default tuft blade, stem and petal slot counts for {@link tuftGeometry}.
14
+ */
15
+ export const TUFT_SHAPE = Object.freeze({
16
+ /** Total blades in one grass tuft. */
17
+ blades: 15,
18
+ /** Trailing blades that can rise as flower or seed-head stems. */
19
+ stems: 3,
20
+ /** Petal slots attached to each stem tip (unused slots fold to zero). */
21
+ petals: 6,
22
+ /** Fractional distance along a petal where it reaches full width. */
23
+ sideT: 0.42,
24
+ /** Tallest blade height in tuft-local metres (`0.26..0.82`). */
25
+ tallest: 0.82,
26
+ });
27
+
28
+ /**
29
+ * Built-in flower and seed-head indices matching the order of {@link DEFAULT_FLOWER_LOOKS} (1-based; 0 is plain grass).
30
+ */
31
+ export const FLOWER_KINDS = Object.freeze({
32
+ poppy: 1,
33
+ cornflower: 2,
34
+ daisy: 3,
35
+ buttercup: 4,
36
+ yarrow: 5,
37
+ tansy: 6,
38
+ seeds: 7,
39
+ ear: 8,
40
+ });
41
+
42
+ const look = (stem, over, r, cup, wide, petals, spread, nod, heart, tip) =>
43
+ Object.freeze({ stem, over, r, cup, wide, petals, spread, nod, heart: Object.freeze(heart), tip: Object.freeze(tip) });
44
+
45
+ /**
46
+ * Default flower and grain-ear descriptors (metres, radians, linear RGB heart/tip colours) indexed by
47
+ * `FLOWER_KINDS[name] - 1`.
48
+ */
49
+ export const DEFAULT_FLOWER_LOOKS = Object.freeze([
50
+ // Field poppy: four broad scarlet petals cupped round a dark heart, nodding on a tall stem.
51
+ look(0.5, 1.12, 0.052, 0.7, 0.95, 4, 0, 0.35, [0.02, 0.012, 0.01], [0.6, 0.03, 0.015]),
52
+ // Cornflower: ragged blue flower head standing in grain.
53
+ look(0.55, 1.1, 0.03, 0.4, 0.42, 6, 0, 0.15, [0.07, 0.05, 0.2], [0.1, 0.2, 0.72]),
54
+ // Ox-eye daisy: flat white rays around a yellow centre.
55
+ look(0.32, 1.06, 0.032, 0.06, 0.36, 6, 0, 0.1, [0.78, 0.5, 0.03], [0.86, 0.86, 0.8]),
56
+ // Buttercup: small glossy yellow cup of damp ground.
57
+ look(0.36, 1.02, 0.021, 0.85, 0.9, 5, 0, 0.2, [0.62, 0.42, 0.01], [0.86, 0.68, 0.03]),
58
+ // Yarrow: flat-topped spray of off-white florets for dry plains.
59
+ look(0.4, 1.08, 0.046, 0.12, 0.62, 6, 0, 0.08, [0.5, 0.5, 0.42], [0.8, 0.78, 0.7]),
60
+ // Tansy: flat spray of golden buttons along damp margins and field edges.
61
+ look(0.45, 1.1, 0.04, 0.15, 0.62, 6, 0, 0.08, [0.45, 0.3, 0.02], [0.76, 0.56, 0.03]),
62
+ // Dry grass seed head: buff spikelets climbing a stalk over the tuft.
63
+ look(0, 1.24, 0.055, 1.2, 0.3, 6, 0.04, 0.5, [0.27, 0.22, 0.12], [0.48, 0.42, 0.27]),
64
+ // Ripe barley or wheat ear: close upright golden ear heavy enough to nod.
65
+ look(0, 1.12, 0.06, 1.38, 0.34, 6, 0.028, 0.42, [0.3, 0.2, 0.06], [0.5, 0.36, 0.12]),
66
+ ]);
67
+
68
+ /**
69
+ * Build a grass tuft `BufferGeometry` with `position`, `normal`, `aStem` and `aPetal` attributes.
70
+ * Each blade has a tapered base and bent tip (five vertices); trailing stem blades carry collapsed
71
+ * petal quads opened by the flowering tuft vertex shader (`rendering/plant-tuft.js`).
72
+ *
73
+ * @param {object} [options]
74
+ * @param {() => number} [options.random] - Deterministic PRNG in `[0, 1)` (defaults to `mulberry32(seed)`).
75
+ * @param {number} [options.seed=5] - Seed used when `random` is omitted.
76
+ * @param {Partial<typeof TUFT_SHAPE>} [options.shape] - Overrides to {@link TUFT_SHAPE}.
77
+ * @returns {THREE.BufferGeometry}
78
+ */
79
+ export function tuftGeometry(options = {}) {
80
+ const cfg = options.shape ? { ...TUFT_SHAPE, ...options.shape } : TUFT_SHAPE;
81
+ const rng = options.random ?? mulberry32(options.seed ?? 5);
82
+ const pos = [];
83
+ const stem = [];
84
+ const petal = [];
85
+ const index = [];
86
+ const corner = (x, y, z, s, h, cx, cz, p = 0, t = 0, side = 0, head = 0) => {
87
+ pos.push(x, y, z);
88
+ stem.push(s, h, cx, cz);
89
+ petal.push(p, t, side, head);
90
+ return pos.length / 3 - 1;
91
+ };
92
+ for (let b = 0; b < cfg.blades; b++) {
93
+ const a = rng() * TAU;
94
+ const r = Math.sqrt(rng()) * 0.63;
95
+ const x = Math.cos(a) * r;
96
+ const z = Math.sin(a) * r;
97
+ const h = 0.26 + rng() * 0.56;
98
+ const w = 0.016 + rng() * 0.021;
99
+ const la = rng() * TAU;
100
+ const lean = 0.08 + rng() * 0.26;
101
+ const dx = Math.cos(la);
102
+ const dz = Math.sin(la);
103
+ const mx = x + dx * lean * 0.32;
104
+ const mz = z + dz * lean * 0.32;
105
+ const mh = h * 0.58;
106
+ const w2 = w * 0.6;
107
+ const s = b >= cfg.blades - cfg.stems ? b - (cfg.blades - cfg.stems) + 1 : 0;
108
+ const tx = x + dx * lean;
109
+ const tz = z + dz * lean;
110
+ const i0 = corner(x - dz * w, 0, z + dx * w, s, h, x, z);
111
+ const i1 = corner(x + dz * w, 0, z - dx * w, s, h, x, z);
112
+ const i2 = corner(mx + dz * w2, mh, mz - dx * w2, s, h, mx, mz);
113
+ const i3 = corner(mx - dz * w2, mh, mz + dx * w2, s, h, mx, mz);
114
+ const i4 = corner(tx, h, tz, s, h, tx, tz);
115
+ index.push(i0, i1, i2, i0, i2, i3, i3, i2, i4);
116
+ if (!s) continue;
117
+ for (let p = 0; p < cfg.petals; p++) {
118
+ const foot = corner(tx, h, tz, s, h, x, z, p, 0, 0, 1);
119
+ const left = corner(tx, h, tz, s, h, x, z, p, cfg.sideT, -1, 1);
120
+ const right = corner(tx, h, tz, s, h, x, z, p, cfg.sideT, 1, 1);
121
+ const end = corner(tx, h, tz, s, h, x, z, p, 1, 0, 1);
122
+ index.push(foot, left, end, foot, end, right);
123
+ }
124
+ }
125
+ const g = new THREE.BufferGeometry();
126
+ g.setAttribute('position', new THREE.Float32BufferAttribute(pos, 3));
127
+ g.setAttribute(
128
+ 'normal',
129
+ new THREE.Float32BufferAttribute(
130
+ new Float32Array(pos.length).map((_, i) => (i % 3 === 1 ? 1 : 0)),
131
+ 3,
132
+ ),
133
+ );
134
+ g.setAttribute('aStem', new THREE.Float32BufferAttribute(stem, 4));
135
+ g.setAttribute('aPetal', new THREE.Float32BufferAttribute(petal, 4));
136
+ g.setIndex(index);
137
+ return g;
138
+ }
@@ -0,0 +1,329 @@
1
+ /**
2
+ * Siege and collapse rubble geometry: smouldering rubble mounds and wall-breach talus fans with
3
+ * optional cleared passageways. Pure geometry assembly into `GB` builders; worker-safe.
4
+ * @module
5
+ */
6
+
7
+ import { dim } from '../math/color.js';
8
+ import { createNoise } from '../math/noise.js';
9
+ import { TAU, lerp, sstep } from '../math/scalar.js';
10
+ import { C as defaultColor, TRS as defaultTransform, box as defaultBox, createUnitShapes, stick } from './primitives.js';
11
+ import { sampleSurface } from './sampled-surface.js';
12
+
13
+ const DEG = Math.PI / 180;
14
+ const EMBER_LIFT = 0.05;
15
+
16
+ let fallbackShapes = null;
17
+ const defaultShapes = () => (fallbackShapes ??= createUnitShapes());
18
+ let fallbackNoiseObj = null;
19
+ const defaultNoiseObj = () => (fallbackNoiseObj ??= createNoise());
20
+ const defaultVnoise = () => defaultNoiseObj().vnoise;
21
+ const defaultFbm = () => defaultNoiseObj().fbm;
22
+
23
+ /** Default sRGB hex smoke-blackened stone palette for collapse heaps and breach fans. */
24
+ export const DEFAULT_SCORCH_PALETTE = Object.freeze([0x4a443e, 0x5c544b, 0x3a3531, 0x6a5f52, 0x514a44]);
25
+
26
+ const angleDiff = (a, b) => ((((a - b) % TAU) + TAU + Math.PI) % TAU) - Math.PI;
27
+
28
+ /**
29
+ * Append a smouldering ember skin lifted slightly over a sampled mound grid (`nu + 1` points per row).
30
+ *
31
+ * @param {{ pos: number[], dat: number[] }} embers - Mutable ember position/data buffers.
32
+ * @param {number[][]} grid - Sampled mound points `[x, y, z]`.
33
+ * @param {number} nu - Column segments per row.
34
+ * @param {number} heat - Smoulder heat in `[0, 1]`.
35
+ * @param {number} phase - Flicker phase in `[0, 1)`.
36
+ */
37
+ export function addEmberSkin(embers, grid, nu, heat, phase) {
38
+ const w1 = nu + 1;
39
+ const rows = grid.length / w1 - 1;
40
+ const emit = k => {
41
+ const p = grid[k];
42
+ embers.pos.push(p[0], p[1] + EMBER_LIFT, p[2]);
43
+ embers.dat.push(phase, heat, 0);
44
+ };
45
+ for (let j = 0; j < rows; j++) {
46
+ for (let i = 0; i < nu; i++) {
47
+ const a = j * w1 + i;
48
+ emit(a);
49
+ emit(a + 1);
50
+ emit(a + w1);
51
+ emit(a + 1);
52
+ emit(a + w1 + 1);
53
+ emit(a + w1);
54
+ }
55
+ }
56
+ }
57
+
58
+ /**
59
+ * Build a low debris or earth mound at `(x, z)` with optional broken masonry blocks, angular stones,
60
+ * charred timber beams and a smouldering ember skin.
61
+ *
62
+ * @param {object} options
63
+ * @param {{ rock: import('./builder.js').GB, stone?: import('./builder.js').GB, wood?: import('./builder.js').GB, wall?: import('./builder.js').GB }} options.builders - Destination builders (`wall` used when `earth` is true).
64
+ * @param {() => number} [options.random=Math.random] - Repeatable PRNG in `[0, 1)`.
65
+ * @param {(x: number, z: number) => number} [options.ground] - Surface height sampler `(x, z) => y`.
66
+ * @param {number} [options.x=0] - Mound centre X in metres.
67
+ * @param {number} [options.z=0] - Mound centre Z in metres.
68
+ * @param {number} [options.radius=3] - Mound radius in metres.
69
+ * @param {number} [options.height=1] - Peak height above ground in metres.
70
+ * @param {boolean} [options.earth=false] - When true, emits only the smooth earth mound into `builders.wall`.
71
+ * @param {number[]} [options.col] - Optional linear RGB base colour override.
72
+ * @param {number} [options.count] - Debris piece count (defaults to `Math.round(2 + radius * 1.9)`).
73
+ * @param {number} [options.emberHeat=0] - Non-zero heat emits a smouldering skin into `embers`.
74
+ * @param {{ pos: number[], dat: number[] } | null} [options.embers=null] - Ember skin target buffers.
75
+ * @param {readonly number[]} [options.scorchPalette=DEFAULT_SCORCH_PALETTE] - sRGB hex rubble tones.
76
+ * @param {import('three').BufferGeometry} [options.stoneShape] - Angular stone geometry.
77
+ * @param {import('three').BufferGeometry} [options.boxShape] - Unit box geometry for timber sticks.
78
+ * @param {(x: number, z: number, salt: number) => number} [options.vnoise] - Value noise in `[0, 1)`.
79
+ * @param {Function} [options.color] - Linear RGB colour helper.
80
+ * @param {Function} [options.transform] - Transform matrix helper (`TRS`).
81
+ * @param {() => number[]} [options.charcoalColor] - Returns linear RGB charred timber colour.
82
+ */
83
+ export function buildRubbleMound(options) {
84
+ const {
85
+ builders,
86
+ random = Math.random,
87
+ ground = () => 0,
88
+ x = 0,
89
+ z = 0,
90
+ radius: r = 3,
91
+ height: h = 1,
92
+ earth = false,
93
+ col = null,
94
+ count = undefined,
95
+ emberHeat = 0,
96
+ embers = null,
97
+ scorchPalette = DEFAULT_SCORCH_PALETTE,
98
+ stoneShape = defaultShapes().rock,
99
+ boxShape = defaultBox,
100
+ vnoise = defaultVnoise(),
101
+ color = defaultColor,
102
+ transform = defaultTransform,
103
+ charcoalColor = () => color(0x1a1512, 0.3, random),
104
+ } = options;
105
+ const pick = a => a[(random() * a.length) | 0];
106
+ const between = (a, b) => a + random() * (b - a);
107
+ const cl = col || dim(color(pick(scorchPalette), 0.1, random), 0.82);
108
+ const sd = random() * 50;
109
+ const n = count ?? Math.round(2 + r * 1.9);
110
+ const skin = emberHeat ? [] : null;
111
+ const rubbleHeight = (dx, dz) => {
112
+ const q = Math.hypot(dx, dz) / r;
113
+ return q >= 1 ? 0 : h * (1 - q * q) * (0.55 + 0.9 * vnoise((x + dx) * 1.1 + sd, (z + dz) * 1.1, 31));
114
+ };
115
+ const nu = earth ? 7 : 8;
116
+ sampleSurface(
117
+ earth ? builders.wall : builders.rock,
118
+ nu,
119
+ 3,
120
+ (u, v) => {
121
+ const a = u * TAU;
122
+ const q = 0.07 + 0.93 * v;
123
+ const wob = 0.78 + 0.44 * vnoise(Math.cos(a) * 1.7 + sd, Math.sin(a) * 1.7, 32);
124
+ const dx = Math.cos(a) * r * q * wob;
125
+ const dz = Math.sin(a) * r * q * wob;
126
+ const p = [x + dx, ground(x + dx, z + dz) + (v > 0.99 ? -0.2 : rubbleHeight(dx, dz)), z + dz];
127
+ if (skin) skin.push(p);
128
+ return p;
129
+ },
130
+ () => dim(cl, 0.92 + 0.16 * random()),
131
+ { flip: true },
132
+ );
133
+ if (skin && embers) addEmberSkin(embers, skin, nu, emberHeat, sd / 50);
134
+ if (earth) return;
135
+ for (let i = 0; i < n; i++) {
136
+ const a = random() * TAU;
137
+ const q = Math.sqrt(random()) * 1.15;
138
+ const dx = Math.cos(a) * r * q;
139
+ const dz = Math.sin(a) * r * q;
140
+ const py = ground(x + dx, z + dz) + rubbleHeight(dx, dz);
141
+ const t = random();
142
+ const s = between(0.35, 0.95);
143
+ if (t < 0.5) {
144
+ builders.stone.box(
145
+ x + dx,
146
+ py - s * 0.25,
147
+ z + dz,
148
+ s * between(0.9, 1.7),
149
+ s * between(0.5, 0.8),
150
+ s * between(0.7, 1.1),
151
+ dim(cl, between(1.0, 1.5)),
152
+ random() * 6,
153
+ between(-0.5, 0.5),
154
+ between(-0.5, 0.5),
155
+ );
156
+ } else if (t < 0.9) {
157
+ builders.rock.add(
158
+ stoneShape,
159
+ dim(cl, between(0.8, 1.3)),
160
+ transform(x + dx, py - s * 0.3, z + dz, s * 1.4, s, s * 1.2, random() * 6, random(), random()),
161
+ );
162
+ } else {
163
+ stick(
164
+ builders.wood,
165
+ [x + dx, py - 0.1, z + dz],
166
+ [x + dx + between(-1.6, 1.6), py + between(0.2, 1.3), z + dz + between(-1.6, 1.6)],
167
+ between(0.14, 0.22),
168
+ charcoalColor(),
169
+ boxShape,
170
+ );
171
+ }
172
+ }
173
+ }
174
+
175
+ /**
176
+ * Build a fan of collapsed masonry spilling inward and outward through a breach in a circular
177
+ * curtain wall, with optional cleared passageway through the middle, colliders and ground scar.
178
+ *
179
+ * @param {object} options
180
+ * @param {{ rock: import('./builder.js').GB, stone: import('./builder.js').GB, wood: import('./builder.js').GB }} options.builders - Destination builders.
181
+ * @param {() => number} [options.random=Math.random] - Repeatable PRNG in `[0, 1)`.
182
+ * @param {(x: number, z: number) => number} [options.ground] - Surface height sampler `(x, z) => y`.
183
+ * @param {{ x: number, z: number }} options.centre - Ring curtain centre `(x, z)` in metres.
184
+ * @param {number} options.wallRadius - Ring curtain radius in metres.
185
+ * @param {number} options.deg - Breach bearing in degrees.
186
+ * @param {number} options.half - Half-width of the breach in degrees.
187
+ * @param {number} options.heightMax - Peak rubble fan height in metres.
188
+ * @param {number} [options.cutHalf=0] - Optional half-width in degrees of a cleared path through the breach.
189
+ * @param {readonly number[]} [options.scorchPalette=DEFAULT_SCORCH_PALETTE] - sRGB hex rubble tones.
190
+ * @param {number} [options.dustHex=0x4f4841] - Base dust mound sRGB hex tone.
191
+ * @param {import('three').BufferGeometry} [options.stoneShape] - Angular rubble stone shape.
192
+ * @param {import('three').BufferGeometry} [options.boxShape] - Unit box geometry for charred timbers.
193
+ * @param {(x: number, z: number, salt: number) => number} [options.vnoise] - Value noise in `[0, 1)`.
194
+ * @param {(x: number, z: number, octaves: number, salt: number) => number} [options.fbm] - Fractal noise in `[0, 1)`.
195
+ * @param {Function} [options.color] - Linear RGB colour helper.
196
+ * @param {Function} [options.transform] - Transform matrix helper (`TRS`).
197
+ * @param {() => number[]} [options.charcoalColor] - Returns linear RGB charred timber colour.
198
+ * @param {((x: number, z: number, radius: number) => void) | null} [options.onCollider=null] - Circle collider callback.
199
+ * @param {((x: number, z: number, radius: number, weight: number) => void) | null} [options.onScar=null] - Ground scar callback.
200
+ */
201
+ export function buildBreachFan(options) {
202
+ const {
203
+ builders,
204
+ random = Math.random,
205
+ ground = () => 0,
206
+ centre,
207
+ wallRadius,
208
+ deg,
209
+ half,
210
+ heightMax: hMax,
211
+ cutHalf = 0,
212
+ scorchPalette = DEFAULT_SCORCH_PALETTE,
213
+ dustHex = 0x4f4841,
214
+ stoneShape = defaultShapes().rock,
215
+ boxShape = defaultBox,
216
+ vnoise = defaultVnoise(),
217
+ fbm = defaultFbm(),
218
+ color = defaultColor,
219
+ transform = defaultTransform,
220
+ charcoalColor = () => color(0x1a1512, 0.3, random),
221
+ onCollider = null,
222
+ onScar = null,
223
+ } = options;
224
+ const pick = a => a[(random() * a.length) | 0];
225
+ const between = (a, b) => a + random() * (b - a);
226
+ const fromA = (deg - half * 1.7) * DEG;
227
+ const toA = (deg + half * 1.7) * DEG;
228
+ const r0 = wallRadius - 17;
229
+ const r1 = wallRadius + 21;
230
+ const dust = dim(color(dustHex), 0.8);
231
+ const rubbleHeight = (x, z) => {
232
+ const dx = x - centre.x;
233
+ const dz = z - centre.z;
234
+ const rad = Math.hypot(dx, dz);
235
+ const da = Math.abs(angleDiff(Math.atan2(dz, dx), deg * DEG)) / DEG;
236
+ const n = 0.6 + 0.8 * fbm(x * 0.19, z * 0.19, 2, 83);
237
+ const prof = Math.max(0, 1 - (rad > wallRadius ? (rad - wallRadius) / 19 : (wallRadius - rad) / 15) / n);
238
+ return (
239
+ hMax *
240
+ sstep(half * 1.7, half * 1.05, da) *
241
+ (cutHalf ? sstep(cutHalf, cutHalf * 2.6, da) : 1) *
242
+ prof *
243
+ (0.45 + 0.55 * prof) *
244
+ (0.75 + 0.5 * vnoise(x * 0.8, z * 0.8, 84))
245
+ );
246
+ };
247
+ sampleSurface(
248
+ builders.rock,
249
+ Math.round(half * 4.8),
250
+ 24,
251
+ (u, v) => {
252
+ const a = lerp(fromA, toA, u);
253
+ const rad = lerp(r0, r1, v);
254
+ const x = centre.x + Math.cos(a) * rad;
255
+ const z = centre.z + Math.sin(a) * rad;
256
+ const hh = rubbleHeight(x, z);
257
+ return [x, ground(x, z) + (hh > 0.03 ? hh + (vnoise(x * 1.7, z * 1.7, 85) - 0.5) * 0.5 : -0.3), z];
258
+ },
259
+ () => dim(dust, between(0.85, 1.15)),
260
+ { flip: true },
261
+ );
262
+ for (let i = 0, n = Math.round(half * 44); i < n; i++) {
263
+ const a = lerp(fromA, toA, random());
264
+ const rad = lerp(r0 - 4, r1 + 6, random());
265
+ const x = centre.x + Math.cos(a) * rad;
266
+ const z = centre.z + Math.sin(a) * rad;
267
+ const hh = rubbleHeight(x, z);
268
+ if (hh < 0.12 && (random() < 0.8 || (cutHalf && Math.abs(angleDiff(a, deg * DEG)) / DEG < cutHalf * 1.3))) continue;
269
+ const y = ground(x, z) + hh;
270
+ const t = random();
271
+ const s = between(0.35, 1.05);
272
+ const cl = dim(color(pick(scorchPalette), 0.12, random), between(0.85, 1.35));
273
+ if (t < 0.5) {
274
+ builders.stone.box(
275
+ x,
276
+ y - s * 0.3,
277
+ z,
278
+ s * between(1.0, 1.8),
279
+ s * between(0.5, 0.8),
280
+ s * between(0.7, 1.1),
281
+ cl,
282
+ random() * 6,
283
+ between(-0.6, 0.6),
284
+ between(-0.6, 0.6),
285
+ );
286
+ } else if (t < 0.83) {
287
+ builders.rock.add(stoneShape, cl, transform(x, y - s * 0.35, z, s * 1.5, s * 1.1, s * 1.3, random() * 6, random(), random()));
288
+ } else if (t < 0.86 && hh > 0.5) {
289
+ builders.stone.box(
290
+ x,
291
+ y - 0.9,
292
+ z,
293
+ between(2.0, 3.6),
294
+ between(1.2, 2.0),
295
+ between(2.0, 2.8),
296
+ cl,
297
+ random() * 6,
298
+ between(-0.5, 0.5),
299
+ between(-0.5, 0.5),
300
+ );
301
+ } else if (t > 0.94) {
302
+ stick(
303
+ builders.wood,
304
+ [x, y - 0.2, z],
305
+ [x + between(-2, 2), y + between(0.3, 1.8), z + between(-2, 2)],
306
+ between(0.14, 0.24),
307
+ charcoalColor(),
308
+ boxShape,
309
+ );
310
+ } else {
311
+ builders.rock.add(stoneShape, cl, transform(x, y - s * 0.2, z, s * 0.8, s * 0.6, s * 0.7, random() * 6, random(), random()));
312
+ }
313
+ }
314
+ if (onCollider) {
315
+ for (let a = fromA; a <= toA; a += 3.2 / wallRadius) {
316
+ for (let rad = r0; rad <= r1; rad += 3.2) {
317
+ const x = centre.x + Math.cos(a) * rad;
318
+ const z = centre.z + Math.sin(a) * rad;
319
+ if (rubbleHeight(x, z) > 1.25) onCollider(x, z, 2.0);
320
+ }
321
+ }
322
+ }
323
+ onScar?.(
324
+ centre.x + Math.cos(deg * DEG) * (wallRadius + 1),
325
+ centre.z + Math.sin(deg * DEG) * (wallRadius + 1),
326
+ half * DEG * wallRadius * 1.75,
327
+ 1,
328
+ );
329
+ }