roamwright 0.61.5 → 0.61.7

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,246 @@
1
+ /**
2
+ * Instanced foliage and scenery scattering: binds worker-safe placements from `planScatterInstances` into
3
+ * `THREE.InstancedMesh` pools for arbitrary geometries, plant-kit trees, and grass tussocks.
4
+ * @module
5
+ */
6
+
7
+ import * as THREE from 'three';
8
+ import { createNoise } from '../math/noise.js';
9
+ import { createHash, mulberry32 } from '../math/random.js';
10
+ import { partsGeometry } from '../geometry/foliage.js';
11
+ import { createPlantTints } from '../geometry/plant-tints.js';
12
+ import { createTrees } from '../geometry/plant-trees.js';
13
+ import { PLAIN_GRASS, tussockGeometry } from '../geometry/plant-tussock.js';
14
+ import { planScatterInstances } from '../geometry/scatter-instances.js';
15
+
16
+ const DEFAULT_ROUGHNESS = 0.88;
17
+ const DEFAULT_TREE_SPECIES = Object.freeze(['broadleaf', 'conifer', 'cedar']);
18
+
19
+ function createDefaultFoliageMaterial(roughness) {
20
+ return new THREE.MeshStandardMaterial({ vertexColors: true, roughness, side: THREE.DoubleSide });
21
+ }
22
+
23
+ /**
24
+ * Scatters one or more geometries as `THREE.InstancedMesh` pools using `planScatterInstances`.
25
+ *
26
+ * @param {object} options - Geometry, placement, material and scene-graph options.
27
+ * @param {THREE.BufferGeometry[]} options.geometries - Variant geometries, one instanced mesh per entry.
28
+ * @param {THREE.Object3D | null} [options.parent=null] - Optional scene or group to attach the created meshes to.
29
+ * @param {THREE.Material | null} [options.material=null] - Shared material (defaults to double-sided vertex-coloured `MeshStandardMaterial`).
30
+ * @param {number} [options.roughness=0.88] - Roughness for the default material when `material` is omitted.
31
+ * @param {number} [options.attempts=90] - Candidate samples passed to `planScatterInstances`.
32
+ * @param {number} [options.maxPerBucket=32] - Maximum instances per geometry variant.
33
+ * @param {(attempt: number) => [number, number] | null | undefined} [options.sample] - Candidate `[x, z]` sampler in metres.
34
+ * @param {(x: number, z: number) => number} [options.groundAt] - Terrain elevation sampler `(x, z) => y` in metres.
35
+ * @param {() => number} [options.random] - Deterministic PRNG in `[0, 1)`.
36
+ * @param {[number, number]} [options.scaleRange=[1, 0]] - Uniform scale `[minScale, scaleSpan]`.
37
+ * @param {number} [options.sink=0] - Vertical sink below `groundAt(x, z)` in metres.
38
+ * @param {boolean} [options.castShadow=true] - Whether each instanced mesh casts shadows.
39
+ * @param {boolean} [options.receiveShadow=true] - Whether each instanced mesh receives shadows.
40
+ * @param {boolean} [options.stopWhenFull=false] - Stop sampling early once every variant bucket is full.
41
+ * @returns {{ meshes: THREE.InstancedMesh[], material: THREE.Material, total: number, dispose: () => void }}
42
+ */
43
+ export function scatterInstances({
44
+ geometries,
45
+ parent = null,
46
+ material = null,
47
+ roughness = DEFAULT_ROUGHNESS,
48
+ attempts = 90,
49
+ maxPerBucket = 32,
50
+ sample,
51
+ groundAt = () => 0,
52
+ random = mulberry32(1),
53
+ scaleRange = [1, 0],
54
+ sink = 0,
55
+ castShadow = true,
56
+ receiveShadow = true,
57
+ stopWhenFull = false,
58
+ } = {}) {
59
+ if (!Array.isArray(geometries) || geometries.length === 0) {
60
+ throw new RangeError('geometries must be a non-empty array of BufferGeometry');
61
+ }
62
+
63
+ const ownsMaterial = !material;
64
+ const mat = material ?? createDefaultFoliageMaterial(roughness);
65
+ const plan = planScatterInstances({
66
+ attempts,
67
+ maxPerBucket,
68
+ buckets: geometries.length,
69
+ sample,
70
+ groundAt,
71
+ random,
72
+ scaleRange,
73
+ sink,
74
+ stopWhenFull,
75
+ });
76
+
77
+ const meshes = geometries.map((geometry, index) => {
78
+ const { count, matrices } = plan.buckets[index];
79
+ const mesh = new THREE.InstancedMesh(geometry, mat, 0);
80
+ mesh.instanceMatrix = new THREE.InstancedBufferAttribute(matrices, 16);
81
+ mesh.count = count;
82
+ mesh.castShadow = castShadow;
83
+ mesh.receiveShadow = receiveShadow;
84
+ if (count > 0) mesh.computeBoundingSphere();
85
+ if (parent) parent.add(mesh);
86
+ return mesh;
87
+ });
88
+
89
+ return {
90
+ meshes,
91
+ material: mat,
92
+ total: plan.total,
93
+ dispose() {
94
+ for (const mesh of meshes) mesh.removeFromParent();
95
+ if (ownsMaterial) mat.dispose();
96
+ },
97
+ };
98
+ }
99
+
100
+ /**
101
+ * Builds instanced trees from the engine plant kit (`createTrees`) over a caller-supplied placement sampler.
102
+ *
103
+ * @param {object} [options] - Plant kit, placement and rendering options.
104
+ * @param {THREE.Object3D | null} [options.parent=null] - Optional scene or group receiving the tree meshes.
105
+ * @param {number} [options.seed=0] - World seed for tree builders and default noise/hash/PRNG.
106
+ * @param {{ fbm: Function, vnoise: Function }} [options.noise] - Seeded noise (`createNoise(seed)` by default).
107
+ * @param {Function} [options.hash] - Seeded integer hash (`createHash(seed)` by default).
108
+ * @param {() => number} [options.random] - Deterministic PRNG in `[0, 1)` (`mulberry32(seed)` by default).
109
+ * @param {(x: number, z: number) => number} [options.groundAt] - Terrain elevation sampler `(x, z) => y` in metres.
110
+ * @param {number} [options.attempts=90] - Candidate samples to draw.
111
+ * @param {number} [options.maxPerSpecies=32] - Maximum placed instances per species.
112
+ * @param {Array<'broadleaf' | 'conifer' | 'cedar' | 'burntTree' | 'thornTree' | 'acacia'>} [options.species=['broadleaf', 'conifer', 'cedar']] - Tree species to instance.
113
+ * @param {(attempt: number) => [number, number] | null | undefined} [options.sample] - Candidate `[x, z]` sampler in metres.
114
+ * @param {[number, number]} [options.scaleRange=[0.85, 0.7]] - Uniform scale `[minScale, scaleSpan]`.
115
+ * @param {number} [options.sink=0.12] - Vertical sink below `groundAt(x, z)` in metres.
116
+ * @param {number} [options.roughness=0.88] - Roughness for the default foliage material when `material` is omitted.
117
+ * @param {THREE.Material | null} [options.material=null] - Optional shared foliage material.
118
+ * @param {boolean} [options.castShadow=true] - Whether tree meshes cast shadows.
119
+ * @param {boolean} [options.receiveShadow=true] - Whether tree meshes receive shadows.
120
+ * @returns {{ meshes: THREE.InstancedMesh[], material: THREE.Material, total: number, dispose: () => void }}
121
+ */
122
+ export function scatterTrees({
123
+ parent = null,
124
+ seed = 0,
125
+ noise = createNoise(seed),
126
+ hash = createHash(seed),
127
+ random = mulberry32(seed),
128
+ groundAt = () => 0,
129
+ attempts = 90,
130
+ maxPerSpecies = 32,
131
+ species = DEFAULT_TREE_SPECIES,
132
+ sample,
133
+ scaleRange = [0.85, 0.7],
134
+ sink = 0.12,
135
+ roughness = DEFAULT_ROUGHNESS,
136
+ material = null,
137
+ castShadow = true,
138
+ receiveShadow = true,
139
+ } = {}) {
140
+ const tints = createPlantTints({ fbm: noise.fbm, vnoise: noise.vnoise, hash });
141
+ const treeKit = createTrees({ hash, ...tints, seed });
142
+ const builders = {
143
+ broadleaf: () => treeKit.broadleaf(),
144
+ conifer: () => treeKit.conifer(),
145
+ cedar: () => treeKit.cedar(0),
146
+ burntTree: () => treeKit.burntTree(),
147
+ thornTree: () => treeKit.thornTree(),
148
+ acacia: () => treeKit.acacia(),
149
+ };
150
+
151
+ const geometries = species.map(name => {
152
+ const build = builders[name];
153
+ if (!build) throw new RangeError(`Unknown tree species "${name}". Expected one of: ${Object.keys(builders).join(', ')}`);
154
+ return partsGeometry(build().near);
155
+ });
156
+
157
+ const scattered = scatterInstances({
158
+ parent,
159
+ geometries,
160
+ material,
161
+ roughness,
162
+ attempts,
163
+ maxPerBucket: maxPerSpecies,
164
+ sample,
165
+ groundAt,
166
+ random,
167
+ scaleRange,
168
+ sink,
169
+ castShadow,
170
+ receiveShadow,
171
+ stopWhenFull: false,
172
+ });
173
+
174
+ return {
175
+ meshes: scattered.meshes,
176
+ material: scattered.material,
177
+ total: scattered.total,
178
+ dispose() {
179
+ scattered.dispose();
180
+ for (const geometry of geometries) geometry.dispose();
181
+ },
182
+ };
183
+ }
184
+
185
+ /**
186
+ * Scatters instanced grass tussocks (`tussockGeometry`) across terrain points returned by `sample(attempt)`.
187
+ *
188
+ * @param {object} [options] - Tussock, placement and rendering options.
189
+ * @param {THREE.Object3D | null} [options.parent=null] - Optional scene or group receiving the tussock mesh.
190
+ * @param {number} [options.seed=0] - Seed for the tussock geometry (`mulberry32(seed)`).
191
+ * @param {() => number} [options.random] - Deterministic PRNG in `[0, 1)` for placement yaw and scale (`mulberry32(seed)` by default).
192
+ * @param {(x: number, z: number) => number} [options.groundAt] - Terrain elevation sampler `(x, z) => y` in metres.
193
+ * @param {number} [options.count=60] - Maximum number of tussocks to place.
194
+ * @param {number} [options.attempts=110] - Candidate samples to draw before stopping.
195
+ * @param {(attempt: number) => [number, number] | null | undefined} [options.sample] - Candidate `[x, z]` sampler in metres.
196
+ * @param {[number, number]} [options.scaleRange=[0.8, 0.55]] - Uniform scale `[minScale, scaleSpan]`.
197
+ * @param {object} [options.grass=PLAIN_GRASS] - Grass form descriptor passed to `tussockGeometry`.
198
+ * @param {number} [options.roughness=0.88] - Roughness for the default material when `material` is omitted.
199
+ * @param {THREE.Material | null} [options.material=null] - Optional shared foliage material.
200
+ * @param {boolean} [options.castShadow=false] - Whether the tussock mesh casts shadows.
201
+ * @param {boolean} [options.receiveShadow=false] - Whether the tussock mesh receives shadows.
202
+ * @returns {{ mesh: THREE.InstancedMesh, material: THREE.Material, count: number, dispose: () => void }}
203
+ */
204
+ export function scatterTussocks({
205
+ parent = null,
206
+ seed = 0,
207
+ random = mulberry32(seed),
208
+ groundAt = () => 0,
209
+ count = 60,
210
+ attempts = 110,
211
+ sample,
212
+ scaleRange = [0.8, 0.55],
213
+ grass = PLAIN_GRASS,
214
+ roughness = DEFAULT_ROUGHNESS,
215
+ material = null,
216
+ castShadow = false,
217
+ receiveShadow = false,
218
+ } = {}) {
219
+ const geometry = tussockGeometry(mulberry32(seed), false, grass);
220
+ const scattered = scatterInstances({
221
+ parent,
222
+ geometries: [geometry],
223
+ material,
224
+ roughness,
225
+ attempts,
226
+ maxPerBucket: count,
227
+ sample,
228
+ groundAt,
229
+ random,
230
+ scaleRange,
231
+ sink: 0,
232
+ castShadow,
233
+ receiveShadow,
234
+ stopWhenFull: true,
235
+ });
236
+
237
+ return {
238
+ mesh: scattered.meshes[0],
239
+ material: scattered.material,
240
+ count: scattered.total,
241
+ dispose() {
242
+ scattered.dispose();
243
+ geometry.dispose();
244
+ },
245
+ };
246
+ }
@@ -0,0 +1,66 @@
1
+ import * as THREE from 'three';
2
+ import { GB } from '../geometry/builder.js';
3
+ import { TRS, createUnitShapes } from '../geometry/primitives.js';
4
+
5
+ /**
6
+ * Put planned springheads and their soaked ground sheets (`planSprings`) into a scene group: for each spring, adds the
7
+ * transparent wet-ground mesh (`renderOrder` 3 by default so it lies over ground and roads and under water) and one merged
8
+ * mesh of its cleft slabs, ring boulders and strewn stones.
9
+ *
10
+ * @param {object} options
11
+ * @param {{ wetGround: { position: Float32Array, normal: Float32Array, color: Float32Array, index: number[] }, rocks: number[] }[]} options.plans - Planned springs from `planSprings`.
12
+ * @param {THREE.Object3D} options.parent - Scene or group that receives the meshes.
13
+ * @param {(fineness: number) => THREE.BufferGeometry} [options.crag] - Returns rock geometry for fineness level `1 | 2 | 3`; defaults to a unit broken stone.
14
+ * @param {THREE.Material} [options.rockMaterial] - Vertex-coloured material for springhead rocks.
15
+ * @param {THREE.Material} [options.groundMaterial] - Transparent RGBA vertex-coloured material for the soaked-ground sheet.
16
+ * @param {number} [options.renderOrder=3] - Render order applied to each wet-ground mesh.
17
+ * @returns {{ wetMeshes: THREE.Mesh[], rockMeshes: THREE.Mesh[] }} Added meshes, in spring order.
18
+ */
19
+ export function meshSprings({ plans, parent, crag, rockMaterial, groundMaterial, renderOrder = 3 }) {
20
+ let defaultRock = null;
21
+ const rockFor =
22
+ crag ??
23
+ (() => {
24
+ defaultRock ??= createUnitShapes().rock;
25
+ return defaultRock;
26
+ });
27
+ const rockMat = rockMaterial ?? new THREE.MeshStandardMaterial({ vertexColors: true, roughness: 0.88 });
28
+ const groundMat =
29
+ groundMaterial ??
30
+ new THREE.MeshStandardMaterial({
31
+ vertexColors: true,
32
+ roughness: 0.5,
33
+ transparent: true,
34
+ depthWrite: false,
35
+ polygonOffset: true,
36
+ polygonOffsetFactor: -2,
37
+ polygonOffsetUnits: -2,
38
+ });
39
+ const wetMeshes = [],
40
+ rockMeshes = [];
41
+ for (const { wetGround, rocks } of plans) {
42
+ const geometry = new THREE.BufferGeometry();
43
+ geometry.setAttribute('position', new THREE.BufferAttribute(wetGround.position, 3));
44
+ geometry.setAttribute('normal', new THREE.BufferAttribute(wetGround.normal, 3));
45
+ geometry.setAttribute('color', new THREE.BufferAttribute(wetGround.color, 4));
46
+ geometry.setIndex(wetGround.index);
47
+ const wetMesh = new THREE.Mesh(geometry, groundMat);
48
+ wetMesh.receiveShadow = true;
49
+ wetMesh.renderOrder = renderOrder;
50
+ wetMesh.matrixAutoUpdate = false;
51
+ parent.add(wetMesh);
52
+ wetMeshes.push(wetMesh);
53
+
54
+ const builder = new GB();
55
+ for (let i = 0; i < rocks.length; i += 13) {
56
+ builder.add(
57
+ rockFor(rocks[i + 9]),
58
+ [rocks[i + 10], rocks[i + 11], rocks[i + 12]],
59
+ TRS(rocks[i], rocks[i + 1], rocks[i + 2], rocks[i + 3], rocks[i + 4], rocks[i + 5], rocks[i + 6], rocks[i + 7], rocks[i + 8]),
60
+ );
61
+ }
62
+ const rockMesh = builder.mesh(rockMat, parent);
63
+ if (rockMesh) rockMeshes.push(rockMesh);
64
+ }
65
+ return { wetMeshes, rockMeshes };
66
+ }
@@ -1,172 +0,0 @@
1
- import * as THREE from 'three';
2
- import { createCityFortification, createGreatWalls, GeometryBuilder, mulberry32 } from 'roamwright';
3
- import { particleNoise } from '../math/particle-noise.js';
4
- import { C } from '../geometry/primitives.js';
5
- import { partsGeometry } from '../geometry/foliage.js';
6
- import { createPlantTints } from '../geometry/plant-tints.js';
7
- import { createTrees } from '../geometry/plant-trees.js';
8
- import { PLAIN_GRASS, tussockGeometry } from '../geometry/plant-tussock.js';
9
-
10
- // Shared fortification, foliage scatter, paddock fence, and particle-noise helpers for showcase examples.
11
-
12
- /**
13
- * Binds createGreatWalls and createCityFortification to a houseKit and terrain sampler.
14
- */
15
- export function createShowcaseFortification({ ground, addBox, shapes, houseKit }) {
16
- const great = createGreatWalls();
17
- return createCityFortification({
18
- ground,
19
- addBox,
20
- shapes,
21
- archOpening: houseKit.archOpening,
22
- archRing: houseKit.archRing,
23
- facePut: houseKit.facePut,
24
- kitNew: houseKit.kitNew,
25
- greatWalls: great.greatWalls,
26
- greatGateMouth: great.greatGateMouth,
27
- });
28
- }
29
-
30
- /**
31
- * Builds instanced trees from the engine plant kit using a caller-supplied placement sampler.
32
- */
33
- export function scatterTrees({
34
- worldGroup,
35
- noise,
36
- hash,
37
- seed,
38
- random,
39
- groundAt,
40
- attempts = 90,
41
- maxPerSpecies = 32,
42
- species = ['broadleaf', 'conifer', 'cedar'],
43
- sample,
44
- scaleRange = [0.85, 0.7],
45
- sink = 0.12,
46
- roughness = 0.88,
47
- }) {
48
- const tints = createPlantTints({ fbm: noise.fbm, vnoise: noise.vnoise, hash });
49
- const treeKit = createTrees({ hash, ...tints, seed });
50
- const material = new THREE.MeshStandardMaterial({ vertexColors: true, roughness, side: THREE.DoubleSide });
51
- const builders = {
52
- broadleaf: () => treeKit.broadleaf(),
53
- conifer: () => treeKit.conifer(),
54
- cedar: () => treeKit.cedar(0),
55
- };
56
- const geos = species.map(name => partsGeometry(builders[name]().near));
57
- const pools = geos.map(geo => {
58
- const mesh = new THREE.InstancedMesh(geo, material, maxPerSpecies);
59
- mesh.castShadow = mesh.receiveShadow = true;
60
- mesh.count = 0;
61
- worldGroup.add(mesh);
62
- return mesh;
63
- });
64
- const dummy = new THREE.Object3D();
65
- for (let i = 0; i < attempts; i++) {
66
- const pt = sample(i);
67
- if (!pt) continue;
68
- const pool = pools[i % pools.length];
69
- if (pool.count >= maxPerSpecies) continue;
70
- const [tx, tz] = pt;
71
- dummy.position.set(tx, groundAt(tx, tz) - sink, tz);
72
- dummy.rotation.set(0, random() * Math.PI * 2, 0);
73
- dummy.scale.setScalar(scaleRange[0] + random() * scaleRange[1]);
74
- dummy.updateMatrix();
75
- pool.setMatrixAt(pool.count++, dummy.matrix);
76
- }
77
- for (const pool of pools) pool.instanceMatrix.needsUpdate = true;
78
- return { pools, material };
79
- }
80
-
81
- /**
82
- * Scatters instanced grass tussocks across terrain points returned by sample(i).
83
- */
84
- export function scatterTussocks({
85
- worldGroup,
86
- seed,
87
- random,
88
- groundAt,
89
- count = 60,
90
- attempts = 110,
91
- sample,
92
- scaleRange = [0.8, 0.55],
93
- grass = PLAIN_GRASS,
94
- material = null,
95
- }) {
96
- const mat = material ?? new THREE.MeshStandardMaterial({ vertexColors: true, roughness: 0.88, side: THREE.DoubleSide });
97
- const geo = tussockGeometry(mulberry32(seed), false, grass);
98
- const mesh = new THREE.InstancedMesh(geo, mat, count);
99
- const dummy = new THREE.Object3D();
100
- let placed = 0;
101
- for (let i = 0; i < attempts && placed < count; i++) {
102
- const pt = sample(i);
103
- if (!pt) continue;
104
- const [tx, tz] = pt;
105
- dummy.position.set(tx, groundAt(tx, tz), tz);
106
- dummy.rotation.set(0, random() * Math.PI * 2, 0);
107
- dummy.scale.setScalar(scaleRange[0] + random() * scaleRange[1]);
108
- dummy.updateMatrix();
109
- mesh.setMatrixAt(placed++, dummy.matrix);
110
- }
111
- mesh.count = placed;
112
- mesh.instanceMatrix.needsUpdate = true;
113
- worldGroup.add(mesh);
114
- return mesh;
115
- }
116
-
117
- /**
118
- * Builds a circular timber post-and-rail paddock fence grounded on heightAt.
119
- */
120
- export function buildCircularFence({
121
- worldGroup,
122
- groundAt,
123
- cx = 0,
124
- cz = 0,
125
- radius = 16.5,
126
- posts = 28,
127
- random,
128
- postHeight = 1.28,
129
- railHeights = [0.48, 0.92],
130
- }) {
131
- const fence = new GeometryBuilder();
132
- for (let i = 0; i < posts; i++) {
133
- const a0 = (i / posts) * Math.PI * 2;
134
- const a1 = ((i + 1) / posts) * Math.PI * 2;
135
- const x0 = cx + Math.cos(a0) * radius;
136
- const z0 = cz + Math.sin(a0) * radius;
137
- const y0 = groundAt(x0, z0);
138
- const x1 = cx + Math.cos(a1) * radius;
139
- const z1 = cz + Math.sin(a1) * radius;
140
- const y1 = groundAt(x1, z1);
141
- fence.box(x0, y0 - 0.1, z0, 0.15, postHeight, 0.15, C(0x6d563f, 0.1, random));
142
- const mx = (x0 + x1) / 2;
143
- const mz = (z0 + z1) / 2;
144
- const my = (y0 + y1) / 2;
145
- const span = Math.hypot(x1 - x0, z1 - z0);
146
- const yaw = Math.atan2(x1 - x0, z1 - z0);
147
- for (const h of railHeights) fence.box(mx, my + h, mz, 0.07, 0.1, span, C(0x7e654b, 0.08, random), yaw);
148
- }
149
- return fence.mesh(new THREE.MeshStandardMaterial({ vertexColors: true, roughness: 0.92 }), worldGroup);
150
- }
151
-
152
- /**
153
- * Generates the seamless 4-channel procedural noise texture consumed by createParticleSystem.
154
- */
155
- export function makeParticleNoiseTexture(noise, size = 128) {
156
- const sheetAt = particleNoise({ size, noise });
157
- const sheet = new Uint8Array(size * size * 4);
158
- const texel = [0, 0, 0, 0];
159
- for (let y = 0; y < size; y++) {
160
- for (let x = 0; x < size; x++) {
161
- sheetAt((x + 0.5) / size, (size - 1 - y + 0.5) / size, texel);
162
- sheet.set(texel, (y * size + x) * 4);
163
- }
164
- }
165
- const texture = new THREE.DataTexture(sheet, size, size);
166
- texture.wrapS = texture.wrapT = THREE.RepeatWrapping;
167
- texture.magFilter = THREE.LinearFilter;
168
- texture.minFilter = THREE.LinearMipmapLinearFilter;
169
- texture.generateMipmaps = true;
170
- texture.needsUpdate = true;
171
- return texture;
172
- }