roamwright 0.61.12 → 0.61.14

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,270 @@
1
+ /**
2
+ * Instanced weathered boulders and bedded rock outcrops: wind-worn stones shaped from superquadric
3
+ * noise lumps and dipping strata outcrops with jointed ledges, weathered caps and foot scree.
4
+ * Pure geometry builders, worker-safe.
5
+ * @module
6
+ */
7
+
8
+ import * as THREE from 'three';
9
+ import { createNoise } from '../math/noise.js';
10
+ import { TAU, lerp, sstep } from '../math/scalar.js';
11
+ import { GB } from './builder.js';
12
+ import { lump } from './primitives.js';
13
+
14
+ /** Default depth in metres a loose weathered stone extends below its origin so it sits cleanly on slopes. */
15
+ export const WORN_STONE_FOOT = -0.3;
16
+
17
+ /**
18
+ * Default shape descriptors for four loose weathered stone varieties (worn block, cobble, flat slab,
19
+ * uneven lump). Dimensions (`long`, `high`, `deep`) are in metres.
20
+ */
21
+ export const WORN_STONE_FORMS = Object.freeze([
22
+ Object.freeze({ square: 2.7, long: 1.1, high: 0.7, deep: 0.8, wander: 0.14 }),
23
+ Object.freeze({ square: 2.1, long: 1.0, high: 0.76, deep: 0.9, wander: 0.1 }),
24
+ Object.freeze({ square: 2.9, long: 1.18, high: 0.5, deep: 0.76, wander: 0.12 }),
25
+ Object.freeze({ square: 2.3, long: 0.96, high: 0.66, deep: 0.86, wander: 0.2 }),
26
+ ]);
27
+
28
+ /**
29
+ * Default shape descriptors for smaller scree stones lying around an outcrop's foot.
30
+ */
31
+ export const SCREE_STONE_FORMS = Object.freeze([
32
+ Object.freeze({ square: 2.5, long: 1.1, high: 0.72, deep: 0.86, wander: 0.16 }),
33
+ Object.freeze({ square: 2.2, long: 1.0, high: 0.7, deep: 0.9, wander: 0.12 }),
34
+ Object.freeze({ square: 2.8, long: 1.16, high: 0.56, deep: 0.78, wander: 0.14 }),
35
+ ]);
36
+
37
+ /** Default seeds for the three distinct outcrop outline variations. */
38
+ export const OUTCROP_SEEDS = Object.freeze([11, 23, 37]);
39
+
40
+ /**
41
+ * Default bedding, column density, dip and scree settings for {@link beddedOutcrop}.
42
+ * Heights and offsets are in metres.
43
+ */
44
+ export const OUTCROP_SHAPE = Object.freeze({
45
+ /** Column count around a near-detail outcrop. */
46
+ round: 16,
47
+ /** Column count around a far-detail outcrop (must divide `round`). */
48
+ farRound: 8,
49
+ /** Fractional height where each rock bed ends, bottom to top. */
50
+ bedTops: Object.freeze([0.2, 0.46, 0.64, 0.86]),
51
+ /** Brightness shade factor for each bed, bottom to top. */
52
+ bedShades: Object.freeze([0.78, 0.92, 0.84, 0.96]),
53
+ /** Radial setback per successive bed in local metres. */
54
+ setBack: 0.09,
55
+ /** Base depth below ground in local metres. */
56
+ foot: -0.18,
57
+ /** Crest height of the top bed in local metres. */
58
+ high: 0.34,
59
+ /** Bed dip slope along the outcrop's length. */
60
+ dip: 0.16,
61
+ /** Number of fallen scree stones placed around the outcrop foot. */
62
+ scree: 6,
63
+ });
64
+
65
+ const _u = [0, 0, 0];
66
+ const _v = [0, 0, 0];
67
+ const _m4 = new THREE.Matrix4();
68
+ const _pos = new THREE.Vector3();
69
+ const _quat = new THREE.Quaternion();
70
+ const _euler = new THREE.Euler();
71
+ const _scale = new THREE.Vector3();
72
+
73
+ let fallbackNoise = null;
74
+ const defaultNoise = () => (fallbackNoise ??= createNoise().vnoise);
75
+
76
+ /**
77
+ * Append a flat-shaded quad `(a, b, c, d)` (anticlockwise from front) into a geometry builder,
78
+ * with `low` linear RGB on `(a, b)` and `high` on `(c, d)`.
79
+ *
80
+ * @param {Pick<import('./builder.js').GB, 'raw'>} builder - Destination geometry builder.
81
+ * @param {number[]} a - First lower corner `[x, y, z]`.
82
+ * @param {number[]} b - Second lower corner `[x, y, z]`.
83
+ * @param {number[]} c - Second upper corner `[x, y, z]`.
84
+ * @param {number[]} d - First upper corner `[x, y, z]`.
85
+ * @param {number[]} low - Linear RGB colour `[r, g, b]` for the lower edge.
86
+ * @param {number[]} high - Linear RGB colour `[r, g, b]` for the upper edge.
87
+ */
88
+ export function flatQuad(builder, a, b, c, d, low, high) {
89
+ for (let k = 0; k < 3; k++) {
90
+ _u[k] = b[k] - a[k];
91
+ _v[k] = d[k] - a[k];
92
+ }
93
+ const nx = _u[1] * _v[2] - _u[2] * _v[1];
94
+ const ny = _u[2] * _v[0] - _u[0] * _v[2];
95
+ const nz = _u[0] * _v[1] - _u[1] * _v[0];
96
+ const len = Math.hypot(nx, ny, nz) || 1;
97
+ const rx = nx / len;
98
+ const ry = ny / len;
99
+ const rz = nz / len;
100
+ builder.raw(a[0], a[1], a[2], rx, ry, rz, low[0], low[1], low[2]);
101
+ builder.raw(b[0], b[1], b[2], rx, ry, rz, low[0], low[1], low[2]);
102
+ builder.raw(c[0], c[1], c[2], rx, ry, rz, high[0], high[1], high[2]);
103
+ builder.raw(a[0], a[1], a[2], rx, ry, rz, low[0], low[1], low[2]);
104
+ builder.raw(c[0], c[1], c[2], rx, ry, rz, high[0], high[1], high[2]);
105
+ builder.raw(d[0], d[1], d[2], rx, ry, rz, high[0], high[1], high[2]);
106
+ }
107
+
108
+ /**
109
+ * Quantize a noise value `n` in `[0, 1]` into `steps` flat plateaus joined by steep ramps,
110
+ * modelling rock fractured cleanly along geological joints.
111
+ *
112
+ * @param {number} n - Input noise value in `[0, 1]`.
113
+ * @param {number} steps - Number of fracture steps.
114
+ * @returns {number} Stepped value in `[0, 1]`.
115
+ */
116
+ export function jointed(n, steps) {
117
+ const u = n * steps;
118
+ const k = Math.floor(u);
119
+ return (k + sstep(0.7, 1, u - k)) / steps;
120
+ }
121
+
122
+ /**
123
+ * Build a wind-worn boulder or cobble geometry with smooth normals and white vertex colours (ready
124
+ * for per-instance tinting). `detail` 2 emits 320 triangles, `detail` 1 emits 80, and `detail` 0 emits 20.
125
+ *
126
+ * @param {number} detail - Icosahedron subdivision level (`0`, `1` or `2`).
127
+ * @param {number} seed - Seed offset into the surface noise field.
128
+ * @param {{ square: number, long: number, high: number, deep: number, wander: number }} form - Proportions in metres and superquadric exponent.
129
+ * @param {object} [options]
130
+ * @param {(x: number, z: number, salt: number) => number} [options.noise] - Value noise in `[0, 1)`.
131
+ * @param {number} [options.foot=-0.3] - Flat underside clip height in local metres.
132
+ * @returns {import('three').BufferGeometry}
133
+ */
134
+ export function wornStone(detail, seed, { square, long, high, deep, wander }, options = {}) {
135
+ const noise = options.noise ?? defaultNoise();
136
+ const foot = options.foot ?? WORN_STONE_FOOT;
137
+ const g = lump(detail, (dir, out) => {
138
+ const boxiness = Math.abs(dir.x) ** square + Math.abs(dir.y) ** square + Math.abs(dir.z) ** square;
139
+ const broad = noise(dir.x * 2.3 + seed, dir.z * 2.3 + dir.y * 1.7, 612) - 0.5;
140
+ const grain = noise(dir.x * 5.1 + seed, dir.y * 5.1 + dir.z * 4.3, 613) - 0.5;
141
+ const r = (1 + wander * (broad + 0.5 * grain)) / boxiness ** (1 / square);
142
+ return out.set((dir.x * r * long) / 2, Math.max((dir.y * r * high) / 2, foot), (dir.z * r * deep) / 2);
143
+ });
144
+ g.setAttribute('color', new THREE.Float32BufferAttribute(new Float32Array(g.attributes.position.count * 3).fill(1), 3));
145
+ return g;
146
+ }
147
+
148
+ /**
149
+ * Build a low outcrop of dipping, jointed sedimentary beds with dust-covered ledges, a weathered
150
+ * cap and fallen scree stones around its base. Vertex colours sit around white for per-instance tinting.
151
+ *
152
+ * @param {number} seed - Outline and joint fracture seed.
153
+ * @param {boolean} [far=false] - When true, builds the coarser far-LOD outcrop sharing the same footprint.
154
+ * @param {object} [options]
155
+ * @param {(x: number, z: number, salt: number) => number} [options.noise] - Value noise in `[0, 1)`.
156
+ * @param {import('three').BufferGeometry[]} [options.screeStones] - Near scree stone geometries.
157
+ * @param {import('three').BufferGeometry[]} [options.farScreeStones] - Far scree stone geometries.
158
+ * @param {typeof GB} [options.Builder] - Geometry builder constructor (defaults to `GB`).
159
+ * @param {Partial<typeof OUTCROP_SHAPE>} [options.shape] - Overrides to {@link OUTCROP_SHAPE}.
160
+ * @returns {import('three').BufferGeometry}
161
+ */
162
+ export function beddedOutcrop(seed, far = false, options = {}) {
163
+ const noise = options.noise ?? defaultNoise();
164
+ const Builder = options.Builder ?? GB;
165
+ const cfg = options.shape ? { ...OUTCROP_SHAPE, ...options.shape } : OUTCROP_SHAPE;
166
+ const b = new Builder();
167
+ const columns = far ? cfg.farRound : cfg.round;
168
+ const step = cfg.round / columns;
169
+ const scree = far
170
+ ? (options.farScreeStones ?? SCREE_STONE_FORMS.map((form, i) => wornStone(0, 9 + 4 * i, form, { noise })))
171
+ : (options.screeStones ?? SCREE_STONE_FORMS.map((form, i) => wornStone(1, 9 + 4 * i, form, { noise })));
172
+ const long = 1.2 + 0.25 * noise(seed, 3.7, 905);
173
+ const edge = i => {
174
+ const a = (i / cfg.round) * TAU;
175
+ const r = 0.5 * (0.62 + 0.65 * noise(Math.cos(a) * 2.2 + seed, Math.sin(a) * 2.2, 901));
176
+ return [Math.cos(a) * r * long, Math.sin(a) * r];
177
+ };
178
+ const point = (i, k, top) => {
179
+ const [x, z] = edge(i % cfg.round);
180
+ const block = 1 - cfg.setBack * k - 0.24 * (jointed(noise(x * 3.1 + k * 5.3, z * 3.1 + seed, 902), 3) - 0.3) - 0.04 * top;
181
+ const up = top ? cfg.bedTops[k] : k ? cfg.bedTops[k - 1] : 0;
182
+ return [x * block, lerp(cfg.foot, cfg.high, up) + cfg.dip * x * up, z * block];
183
+ };
184
+ const dust = [1, 0.95, 0.87];
185
+ for (let k = 0; k < cfg.bedTops.length; k++) {
186
+ const shade = cfg.bedShades[k];
187
+ const last = k === cfg.bedTops.length - 1;
188
+ for (let i = 0; i < cfg.round; i += step) {
189
+ const p = point(i, k, 0);
190
+ const q = point(i + step, k, 0);
191
+ const r = point(i + step, k, 1);
192
+ const s = point(i, k, 1);
193
+ const weather = shade * (0.92 + 0.08 * noise(i * 0.7 + seed, k * 1.3, 903));
194
+ flatQuad(b, q, p, s, r, [weather * 0.8, weather * 0.79, weather * 0.78], [weather, weather, weather]);
195
+ if (last) continue;
196
+ flatQuad(b, r, s, point(i, k + 1, 0), point(i + step, k + 1, 0), dust, dust);
197
+ }
198
+ }
199
+ const top = cfg.bedTops.length - 1;
200
+ const inner = i => {
201
+ const [x, y, z] = point(i, top, 1);
202
+ return [x * 0.55, y + 0.025 + 0.02 * noise(i * 1.1, seed + 6, 909), z * 0.55];
203
+ };
204
+ const middle = [0, lerp(cfg.foot, cfg.high, cfg.bedTops[top]) + 0.045, 0];
205
+ const cap = [0.94, 0.92, 0.88];
206
+ for (let i = 0; i < cfg.round; i += step) {
207
+ flatQuad(b, point(i + step, top, 1), point(i, top, 1), inner(i), inner(i + step), cap, cap);
208
+ flatQuad(b, inner(i + step), inner(i), middle, middle, cap, cap);
209
+ }
210
+ for (let n = 0; n < cfg.scree; n++) {
211
+ const a = (n / cfg.scree) * TAU + noise(n, seed, 904) * 0.8;
212
+ const [x, z] = edge(Math.round((a / TAU) * cfg.round) % cfg.round);
213
+ const out = 1.08 + 0.3 * noise(n * 1.7, seed + 2, 906);
214
+ const size = 0.07 + 0.08 * noise(n * 2.3, seed + 4, 907);
215
+ _euler.set(n, a, n * 0.7, 'XYZ');
216
+ _quat.setFromEuler(_euler);
217
+ b.add(
218
+ scree[n % scree.length],
219
+ [0.86, 0.84, 0.81],
220
+ _m4.compose(_pos.set(x * out, size * 0.2, z * out), _quat, _scale.set(size * 1.3, size * 0.7, size)),
221
+ );
222
+ }
223
+ return b.build(true);
224
+ }
225
+
226
+ /**
227
+ * Create a world-bound rock shape library producing near and far weathered loose stones and bedded
228
+ * outcrops from a supplied noise function and optional form/seed tables.
229
+ *
230
+ * @param {object} [options]
231
+ * @param {(x: number, z: number, salt: number) => number} [options.noise] - Seeded value noise (`createNoise().vnoise`).
232
+ * @param {readonly object[]} [options.stoneForms] - Loose stone form descriptors (defaults to {@link WORN_STONE_FORMS}).
233
+ * @param {readonly object[]} [options.screeForms] - Outcrop foot scree descriptors (defaults to {@link SCREE_STONE_FORMS}).
234
+ * @param {readonly number[]} [options.outcropSeeds] - Seeds for the outcrop variants (defaults to {@link OUTCROP_SEEDS}).
235
+ * @param {number} [options.foot=-0.3] - Flat underside clip height for worn stones in metres.
236
+ * @param {typeof GB} [options.Builder] - Geometry builder class.
237
+ * @param {Partial<typeof OUTCROP_SHAPE>} [options.shape] - Overrides to {@link OUTCROP_SHAPE}.
238
+ * @returns {{
239
+ * stones: import('three').BufferGeometry[],
240
+ * farStones: import('three').BufferGeometry[],
241
+ * screeStones: import('three').BufferGeometry[],
242
+ * farScreeStones: import('three').BufferGeometry[],
243
+ * outcrop: (seed: number, far?: boolean) => import('three').BufferGeometry,
244
+ * outcropShapes: () => import('three').BufferGeometry[],
245
+ * farOutcropShapes: () => import('three').BufferGeometry[],
246
+ * }}
247
+ */
248
+ export function createRockShapes(options = {}) {
249
+ const noise = options.noise ?? defaultNoise();
250
+ const stoneForms = options.stoneForms ?? WORN_STONE_FORMS;
251
+ const screeForms = options.screeForms ?? SCREE_STONE_FORMS;
252
+ const outcropSeeds = options.outcropSeeds ?? OUTCROP_SEEDS;
253
+ const foot = options.foot ?? WORN_STONE_FOOT;
254
+ const Builder = options.Builder ?? GB;
255
+ const shape = options.shape;
256
+ const stones = stoneForms.map((form, i) => wornStone(2, 7 + 4 * i, form, { noise, foot }));
257
+ const farStones = stoneForms.map((form, i) => wornStone(1, 7 + 4 * i, form, { noise, foot }));
258
+ const screeStones = screeForms.map((form, i) => wornStone(1, 9 + 4 * i, form, { noise, foot }));
259
+ const farScreeStones = screeForms.map((form, i) => wornStone(0, 9 + 4 * i, form, { noise, foot }));
260
+ const outcrop = (seed, far = false) => beddedOutcrop(seed, far, { noise, screeStones, farScreeStones, Builder, shape });
261
+ return {
262
+ stones,
263
+ farStones,
264
+ screeStones,
265
+ farScreeStones,
266
+ outcrop,
267
+ outcropShapes: () => outcropSeeds.map(seed => outcrop(seed, false)),
268
+ farOutcropShapes: () => outcropSeeds.map(seed => outcrop(seed, true)),
269
+ };
270
+ }
package/index.js CHANGED
@@ -50,6 +50,21 @@ export { rockSheet } from './geometry/creased-sheet.js';
50
50
  export { createStrataCliffs } from './rendering/strata-cliffs.js';
51
51
  export { planTalusStones } from './geometry/strata-talus.js';
52
52
  export { meshTalusStones } from './rendering/strata-talus.js';
53
+ export {
54
+ OUTCROP_SEEDS,
55
+ OUTCROP_SHAPE,
56
+ SCREE_STONE_FORMS,
57
+ WORN_STONE_FOOT,
58
+ WORN_STONE_FORMS,
59
+ beddedOutcrop,
60
+ createRockShapes,
61
+ flatQuad,
62
+ jointed,
63
+ wornStone,
64
+ } from './geometry/strata-rocks.js';
65
+ export { HILL_RUIN, buildHillRuin } from './geometry/ruins-hill.js';
66
+ export { MOUND_RUINS, buildMoundRuins, buildMoundSherds, buildMoundWalls, createMoundRuins } from './geometry/ruins-mound.js';
67
+ export { RUBBLE_HEAP, RUBBLE_SCATTER, buildRubbleHeap, scatterRubble } from './geometry/ruins-rubble.js';
53
68
  export { planStreamBanks } from './geometry/stream-banks.js';
54
69
  export { meshStreamBanks } from './rendering/stream-banks.js';
55
70
  export { SPRING_COLOURS, SPRING_HEAD, planSpringRocks, planSprings, springFrame, springWetGround } from './geometry/stream-springs.js';
@@ -58,6 +73,20 @@ export { planShoreReeds } from './geometry/shore-reeds.js';
58
73
  export { roadRibbon } from './geometry/road-ribbon.js';
59
74
  export { planBridgeFrame, planRoadBridges } from './geometry/road-bridges.js';
60
75
  export { layRoads } from './rendering/road-ribbons.js';
76
+ export {
77
+ AVENUE_CEDAR,
78
+ PAVED_ROAD,
79
+ avenueBoleRadius,
80
+ buildAvenueCedar,
81
+ buildFarRoadPaving,
82
+ buildRoadArch,
83
+ buildRoadMilestones,
84
+ buildRoadPaving,
85
+ planRoadAvenue,
86
+ roadLine,
87
+ } from './geometry/paved-road.js';
88
+ export { createAvenueHandover, farRoadPavingMaterial, layPavedRoad, layRoadAvenue } from './rendering/paved-road.js';
89
+ export { PAVED_GROUND_LIMITS, createPavedGroundMaterial } from './rendering/paved-ground.js';
61
90
  export { createRoadTraffic, ROAD_TRAFFIC } from './motion/road-traffic.js';
62
91
  export { createFieldSurvey, FIELD_SURVEY, FIELD_USE } from './geometry/field-survey.js';
63
92
  export { LAND_TRAILS, LAND_TRAIL_MARKS, boundsOverlap, createLandTrails, rasterizeTrailMarks } from './geometry/land-trails.js';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "roamwright",
3
- "version": "0.61.12",
3
+ "version": "0.61.14",
4
4
  "description": "A procedural worldbuilding engine built on top of Three.js. Generate landscapes with rivers and changing weather, animate crowds, and explore on foot or in flight.",
5
5
  "keywords": [
6
6
  "threejs",
@@ -0,0 +1,218 @@
1
+ /**
2
+ * Procedural paved-ground shader material: stone-by-stone ringed flagstone plazas, coursed flagstone
3
+ * streets with central foot-wear bands, and cobblestone fills with optional beaten-earth patches and
4
+ * after-rain standing puddles. Sub-pixel stones, joints and crowns anti-alias smoothly via `fwidth`.
5
+ * @module
6
+ */
7
+
8
+ import * as THREE from 'three';
9
+ import { createNoise } from '../math/noise.js';
10
+ import { createHash } from '../math/random.js';
11
+ import { createSurfaceTextures, fillPixels } from '../math/surface-textures.js';
12
+
13
+ /**
14
+ * Default uniform slot limits for ringed squares, coursed street strips and rain puddles in
15
+ * {@link createPavedGroundMaterial}.
16
+ */
17
+ export const PAVED_GROUND_LIMITS = Object.freeze({
18
+ rings: 2,
19
+ strips: 4,
20
+ pools: 12,
21
+ });
22
+
23
+ function buildPavingGLSL({ rings, strips, pools }) {
24
+ return `/* glsl */
25
+ vec2 lp = vWP.xz - uPaveO; // metres in the space's frame
26
+ vec2 fw = fwidth(lp); float pxM = max(fw.x, fw.y); // how many metres a pixel spans here
27
+ vec2 q = vec2(0.0), sz = vec2(1.0); float edgeM = 1e3, wear = 0.0, kind = -1.0;
28
+ for (int i = 0; i < ${rings}; i++) { // a square's flags in rings round its centre
29
+ vec4 R = uRing[i]; vec2 d = lp - R.xy; float r = length(d);
30
+ if (kind < 0.0 && R.z > 0.0 && r < R.z) {
31
+ float ring = floor(r / R.w), n = ring < 0.5 ? 1.0 : max(6.0, floor(6.2832 * (ring + 0.5) / 1.2)); // flags about 1.2 times as long as a ring is wide
32
+ float a = atan(d.y, d.x) / 6.2832 + 0.5;
33
+ q = vec2(a * n + fract(ring * 0.618), r / R.w); sz = vec2(6.2832 * max(r, R.w) / n, R.w);
34
+ edgeM = R.z - r; kind = 0.0;
35
+ }
36
+ }
37
+ for (int i = 0; i < ${strips}; i++) { // a street's flags in courses across it, the joints broken from one course to the next
38
+ vec4 A = uStripA[i], B = uStripB[i];
39
+ if (kind < 0.0 && A.z > A.x && lp.x > A.x && lp.x < A.z && lp.y > A.y && lp.y < A.w) {
40
+ vec2 st = B.z > 0.5 ? lp : lp.yx; // across, along
41
+ vec2 lo = B.z > 0.5 ? A.xy : A.yx, hi = B.z > 0.5 ? A.zw : A.wz;
42
+ float course = floor(st.y / B.y);
43
+ q = vec2(st.x / B.x + 0.5 * mod(course, 2.0) + 0.23 * fract(course * 0.37), st.y / B.y); sz = B.xy;
44
+ edgeM = min(min(st.x - lo.x, hi.x - st.x), min(st.y - lo.y, hi.y - st.y));
45
+ wear = B.w > 0.0 ? 1.0 - smoothstep(0.0, B.w, abs(st.x - (lo.x + hi.x) * 0.5)) : 0.0;
46
+ kind = 1.0;
47
+ }
48
+ }
49
+ if (kind < 0.0) { // cobbles: rounded setts in rows, each row set its own way, each stone its own length
50
+ float rowH = uFill.x * 0.85, row = floor(lp.y / rowH), rr = fract(sin(row * 91.7) * 4375.85), k = 0.85 + 0.3 * rr;
51
+ float cx = lp.x / uFill.x * k + rr * 7.0;
52
+ cx += 0.22 * sin(cx * 1.9 + rr * 6.0); // stones of a row longer and shorter
53
+ q = vec2(cx, lp.y / rowH); sz = vec2(uFill.x / k, rowH); kind = 2.0;
54
+ }
55
+ vec2 id = floor(q), f = fract(q) - 0.5;
56
+ float rnd = fract(sin(dot(id, vec2(12.9898, 78.233))) * 43758.5453), rnd2 = fract(rnd * 17.31 + 0.13);
57
+ // metres from the stone's outline (a rounded rectangle; cobbles round, flags nearly square-cornered) to here
58
+ float corner = kind > 1.5 ? 0.32 * min(sz.x, sz.y) : 0.012;
59
+ vec2 dd = abs(f * sz) - (sz * 0.5 - corner);
60
+ float gapM = min(corner - length(max(dd, 0.0)) - min(max(dd.x, dd.y), 0.0), edgeM);
61
+ float crack = 0.0;
62
+ if (kind < 1.5 && rnd > 0.92) { // a cracked flag: a hairline across it at its own angle, kinked once
63
+ float ca = rnd2 * 6.2832; vec2 cf = f * sz; float t = dot(cf, vec2(-sin(ca), cos(ca)));
64
+ float dM = abs(dot(cf, vec2(cos(ca), sin(ca))) + 0.06 * abs(t - (rnd - 0.96) * 6.0) - 0.05);
65
+ crack = 1.0 - smoothstep(0.001, 0.001 + pxM, dM);
66
+ }
67
+ float jointW = kind > 1.5 ? 0.012 : 0.009; // half a joint's width: cobbles sit in wider joints of sand
68
+ float fade = smoothstep(0.12, 0.45, pxM / min(sz.x, sz.y)); // 1 once a stone is a few pixels across: tones and joints to their mean
69
+ float joint = max(1.0 - smoothstep(jointW - pxM * 0.5, jointW + pxM * 0.5, gapM), crack * 0.4) * (1.0 - fade);
70
+ float jointMean = clamp(2.0 * (jointW + corner * 0.3) * (sz.x + sz.y) / (sz.x * sz.y), 0.0, 0.5);
71
+ // the stone: its own tone, a few warmer or greyer, mottled with patina, grimed along its arrises, darker and smoother
72
+ // where feet have worn it, freckled close up; stains spread across many stones where people stand and water stood
73
+ vec2 sgx = dFdx(lp), sgy = dFdy(lp); // graded by the ground, not by the jump in id at a joint
74
+ float speck = textureGrad(map, lp * 0.71 + id * 0.37, sgx * 0.71, sgy * 0.71).r, mott = textureGrad(map, lp * 0.19 + id * 0.61, sgx * 0.19, sgy * 0.19).g;
75
+ vec3 tone = vec3(0.8 + 0.34 * rnd) * mix(vec3(1.0), rnd2 < 0.5 ? vec3(1.07, 1.0, 0.9) : vec3(0.93, 0.97, 1.04), abs(rnd2 - 0.5) * 1.8);
76
+ tone *= (0.84 + 0.32 * mott) * (0.85 + 0.3 * speck * (1.0 - smoothstep(0.004, 0.02, pxM))) * (1.0 - 0.18 * (1.0 - smoothstep(0.0, 0.07, gapM)));
77
+ tone = mix(tone, vec3(1.0), fade) * (1.0 - 0.13 * wear) * (1.0 - 0.22 * smoothstep(0.55, 0.85, texture2D(map, lp * 0.043 + 0.5).r));
78
+ vec3 dirt = vec3(0.5, 0.47, 0.42) * (1.0 - 0.3 * uFill.z); // as shares of the ground's vertex colour, which three.js multiplies in next
79
+ diffuseColor.rgb *= mix(tone, dirt, joint + fade * jointMean);
80
+ // where the cobbles between the blocks are broken up, beaten earth shows through
81
+ float earth = kind > 1.5 ? smoothstep(0.45, 0.75, texture2D(map, lp * 0.023).g + 0.4 * uFill.y) * uFill.y : 0.0;
82
+ diffuseColor.rgb = mix(diffuseColor.rgb, vec3(0.92, 0.86, 0.76) * (0.8 + 0.4 * speck), earth);
83
+ vec3 g1 = texture2D(map, vWP.xz / 9.0).rgb, g2 = texture2D(map, vWP.xz * 0.019 + 0.37).rgb; // the broad grain every ground has
84
+ diffuseColor.rgb *= mix(vec3(1.0), g1 * g2 * 2.3, 0.55 + 0.45 * fade);
85
+ // a stone's crown: flags flat with worn arrises, cobbles domed; the joints sit lower
86
+ float inside = clamp(gapM / (0.5 * min(sz.x, sz.y)), 0.0, 1.0);
87
+ float crown = kind > 1.5 ? 0.014 * (1.0 - (1.0 - inside) * (1.0 - inside)) : 0.004 * smoothstep(0.0, 0.05, gapM);
88
+ float dist = length(vViewPosition);
89
+ pvH = (crown - 0.006 * joint) * (1.0 - fade) * (1.0 - earth) * (1.0 - smoothstep(25.0, 60.0, dist));
90
+ pvRough = mix(0.86 - 0.18 * wear, 0.97, max(joint, earth));
91
+ // after rain: a film of water on the stone, water standing in the joints, in the low places and in the plan's puddles,
92
+ // whose edges wander and which fill the joints round them; all of it glossy, the puddles a dark mirror
93
+ if (uFill.z > 0.0) {
94
+ float pool = smoothstep(0.6, 0.72, texture2D(map, lp * 0.031 + 0.21).b * 0.7 + texture2D(map, lp * 0.11).g * 0.3) * 0.6;
95
+ float edge = (texture2D(map, lp * 0.37).r - 0.5) * 0.5;
96
+ for (int i = 0; i < ${pools}; i++) {
97
+ vec4 P = uPools[i];
98
+ if (P.z > 0.0) pool = max(pool, 1.0 - smoothstep(0.78, 1.0, length((lp - P.xy) / (P.zw * 0.5)) + edge));
99
+ }
100
+ pvWet = max(max(joint, pool), 0.55 + 0.45 * (1.0 - speck)) * uFill.z;
101
+ diffuseColor.rgb *= 1.0 - 0.45 * pvWet - 0.3 * pool;
102
+ pvRough = mix(pvRough, mix(0.22, 0.03, max(joint, pool)), uFill.z);
103
+ pvH *= 1.0 - pool;
104
+ pvPool = pool;
105
+ }
106
+ // the crowns' many slopes, once too small to draw, widen the gloss instead of leaving a mirror (less so on wet stone,
107
+ // whose film is smooth whatever lies under it: there a far light draws a path across the street, not a pale sheet)
108
+ pvRough = mix(pvRough, max(pvRough, mix(0.5, 0.3, uFill.z)), max(fade, 0.7 * smoothstep(8.0, 45.0, dist)) * (1.0 - pvPool));
109
+ `;
110
+ }
111
+
112
+ // Screen-space derivative bump tilt from the procedural stone crown height `pvH`.
113
+ const PAVING_BUMP = `/* glsl */
114
+ { vec3 sx = dFdx(-vViewPosition), sy = dFdy(-vViewPosition), r1 = cross(sy, normal), r2 = cross(normal, sx);
115
+ float det = dot(sx, r1); vec3 nb = abs(det) * normal - sign(det) * (dFdx(pvH) * r1 + dFdy(pvH) * r2);
116
+ if (dot(nb, nb) > 1e-12) normal = normalize(nb); }`;
117
+
118
+ // Grazing Fresnel sky reflection on wet stone films and standing rain puddles.
119
+ const WET_SHEEN = `/* glsl */
120
+ if (pvWet > 0.0) {
121
+ #ifdef USE_FOG
122
+ vec3 sky = fogColor;
123
+ #else
124
+ vec3 sky = vec3(0.1, 0.13, 0.2);
125
+ #endif
126
+ float fres = 0.02 + 0.98 * pow(1.0 - saturate(dot(normal, normalize(vViewPosition))), 5.0);
127
+ outgoingLight += sky * fres * mix(0.5 * pvWet, 1.0, pvPool);
128
+ }`;
129
+
130
+ let fallbackGrain = null;
131
+ function defaultGrainTexture() {
132
+ if (fallbackGrain) return fallbackGrain;
133
+ const size = 256;
134
+ const { groundGrain } = createSurfaceTextures({ noise: createNoise(41), hash2: createHash(41) });
135
+ const data = fillPixels({ size, make: groundGrain });
136
+ const tex = new THREE.DataTexture(data, size, size);
137
+ tex.colorSpace = THREE.SRGBColorSpace;
138
+ tex.wrapS = tex.wrapT = THREE.RepeatWrapping;
139
+ tex.generateMipmaps = true;
140
+ tex.minFilter = THREE.LinearMipmapLinearFilter;
141
+ tex.magFilter = THREE.LinearFilter;
142
+ tex.needsUpdate = true;
143
+ return (fallbackGrain = tex);
144
+ }
145
+
146
+ /**
147
+ * Create a procedural paved-ground `MeshStandardMaterial` drawing concentric flagstone rings,
148
+ * coursed flagstone street strips, cobblestone fills, optional beaten-earth wear and wet puddles
149
+ * in the space's local `(x, z)` frame. Vertex colours supply each area's base stone hue.
150
+ *
151
+ * @param {object} [options]
152
+ * @param {{ x: number, z: number }} [options.origin] - World-space origin `{ x, z }` of the paving plan in metres.
153
+ * @param {import('three').Texture} [options.map] - Tileable RGB noise/grain texture (generated procedurally if omitted).
154
+ * @param {Array<{ x: number, z: number, r: number, ring: number }>} [options.rings=[]] - Ringed flagstone plazas (`r` radius, `ring` radial width, metres).
155
+ * @param {Array<{ x0: number, z0: number, x1: number, z1: number, len: number, course: number, along?: 'x' | 'z', wear?: number }>} [options.strips=[]] - Coursed flagstone street rectangles.
156
+ * @param {number} [options.cobble=0.16] - Cobblestone width in metres outside rings and strips.
157
+ * @param {number} [options.earth=0] - Amount of beaten earth showing through broken cobbles (`0` to `1`).
158
+ * @param {number} [options.wet=0] - Rain wetness factor (`0` dry, `1` wet after rain).
159
+ * @param {Array<[number, number, number, number]>} [options.pools=[]] - Elliptical rain puddles `[x, z, across, along]` in metres.
160
+ * @param {Partial<typeof PAVED_GROUND_LIMITS>} [options.limits] - Override uniform array capacities (`rings`, `strips`, `pools`).
161
+ * @returns {import('three').MeshStandardMaterial}
162
+ */
163
+ export function createPavedGroundMaterial({
164
+ origin = { x: 0, z: 0 },
165
+ map,
166
+ rings = [],
167
+ strips = [],
168
+ cobble = 0.16,
169
+ earth = 0,
170
+ wet = 0,
171
+ pools = [],
172
+ limits = PAVED_GROUND_LIMITS,
173
+ } = {}) {
174
+ const cap = { ...PAVED_GROUND_LIMITS, ...limits };
175
+ const ring = Array.from({ length: cap.rings }, (_, i) => {
176
+ const r = rings[i];
177
+ return r ? new THREE.Vector4(r.x, r.z, r.r, r.r / Math.max(1, Math.round(r.r / r.ring))) : new THREE.Vector4();
178
+ });
179
+ const stripA = Array.from({ length: cap.strips }, (_, i) => {
180
+ const s = strips[i];
181
+ return s ? new THREE.Vector4(s.x0, s.z0, s.x1, s.z1) : new THREE.Vector4();
182
+ });
183
+ const stripB = Array.from({ length: cap.strips }, (_, i) => {
184
+ const s = strips[i];
185
+ return s ? new THREE.Vector4(s.len, s.course, s.along === 'z' ? 1 : 0, s.wear ?? 0) : new THREE.Vector4();
186
+ });
187
+ const pool = Array.from({ length: cap.pools }, (_, i) => new THREE.Vector4(...(pools[i] ?? [0, 0, 0, 0])));
188
+ const uniforms = {
189
+ uPaveO: { value: new THREE.Vector2(origin.x, origin.z) },
190
+ uRing: { value: ring },
191
+ uStripA: { value: stripA },
192
+ uStripB: { value: stripB },
193
+ uPools: { value: pool },
194
+ uFill: { value: new THREE.Vector4(cobble, earth, wet, 0) },
195
+ };
196
+ const pavingGLSL = buildPavingGLSL(cap);
197
+ const isDefaultCap =
198
+ cap.rings === PAVED_GROUND_LIMITS.rings && cap.strips === PAVED_GROUND_LIMITS.strips && cap.pools === PAVED_GROUND_LIMITS.pools;
199
+ const cacheKey = isDefaultCap ? 'paved-ground' : `paved-ground:${cap.rings}:${cap.strips}:${cap.pools}`;
200
+ const m = new THREE.MeshStandardMaterial({ vertexColors: true, map: map ?? defaultGrainTexture(), roughness: 0.9, metalness: 0 });
201
+ m.onBeforeCompile = shader => {
202
+ Object.assign(shader.uniforms, uniforms);
203
+ shader.vertexShader = shader.vertexShader
204
+ .replace('#include <common>', '#include <common>\nvarying vec3 vWP;')
205
+ .replace('#include <begin_vertex>', '#include <begin_vertex>\nvWP = (modelMatrix * vec4(position, 1.0)).xyz;');
206
+ shader.fragmentShader = shader.fragmentShader
207
+ .replace(
208
+ '#include <common>',
209
+ `#include <common>\nvarying vec3 vWP; uniform vec2 uPaveO; uniform vec4 uRing[${cap.rings}], uStripA[${cap.strips}], uStripB[${cap.strips}], uPools[${cap.pools}], uFill;\nfloat pvH = 0.0, pvRough = 0.9, pvWet = 0.0, pvPool = 0.0;`,
210
+ )
211
+ .replace('#include <map_fragment>', pavingGLSL)
212
+ .replace('#include <roughnessmap_fragment>', '#include <roughnessmap_fragment>\n roughnessFactor = pvRough;')
213
+ .replace('#include <normal_fragment_maps>', '#include <normal_fragment_maps>\n' + PAVING_BUMP)
214
+ .replace('#include <opaque_fragment>', WET_SHEEN + '\n#include <opaque_fragment>');
215
+ };
216
+ m.customProgramCacheKey = () => cacheKey;
217
+ return m;
218
+ }