@threenative/core 0.3.13 → 0.3.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/capabilities.json +299 -10
  2. package/dist/{chunk-4SRAQFTU.js → chunk-2GPHICV6.js} +1 -1
  3. package/dist/{chunk-DIPIJICH.js → chunk-GEMQJBY4.js} +70 -18
  4. package/dist/{chunk-EFWZWLPY.js → chunk-QAMSM3Z5.js} +354 -12
  5. package/dist/{chunk-SV4QVUTQ.js → chunk-QAQHYOWY.js} +1 -1
  6. package/dist/{chunk-EEABDLUC.js → chunk-VBBYWGAT.js} +2 -2
  7. package/dist/{chunk-GYUZJQ7U.js → chunk-VQRPEOKY.js} +4 -1
  8. package/dist/index.d.ts +605 -7
  9. package/dist/index.js +1973 -609
  10. package/dist/playtest.js +3 -3
  11. package/dist/{quality-BYqKGAwo.d.ts → quality-BADStsTn.d.ts} +2 -2
  12. package/dist/render-environment.d.ts +1 -1
  13. package/dist/ui-layer.js +2 -2
  14. package/dist/worker.js +2 -2
  15. package/dist/world.d.ts +13 -3
  16. package/dist/world.js +179 -36
  17. package/mcp/animation-server.mjs +1 -1
  18. package/mcp/engine-server.mjs +32 -6
  19. package/mcp/servers.mjs +3 -3
  20. package/package.json +5 -5
  21. package/scripts/ensure-mcp.mjs +6 -1
  22. package/src/clustered-batch.ts +146 -3
  23. package/src/clustered-mesh.ts +548 -20
  24. package/src/debug.ts +16 -0
  25. package/src/displaced-surface.ts +428 -0
  26. package/src/frame-budget.ts +16 -0
  27. package/src/generated/console-markers.ts +1 -0
  28. package/src/grass-field.ts +628 -0
  29. package/src/index.ts +112 -0
  30. package/src/render/material-key.ts +21 -1
  31. package/src/render/screen-probe-gather.ts +303 -0
  32. package/src/render/short-range-ao.ts +274 -0
  33. package/src/render/world-impostor-surface.ts +98 -3
  34. package/src/render-camera-cull.ts +9 -3
  35. package/src/renderer.ts +26 -4
  36. package/src/scatter-field.ts +496 -0
  37. package/src/startup-offscreen-bytes.ts +11 -5
  38. package/src/state.ts +16 -3
  39. package/src/static-transform.ts +75 -6
  40. package/src/tile-ring.ts +294 -0
  41. package/src/version.ts +1 -1
  42. package/src/warmup.ts +15 -2
  43. package/src/world-cell-batches.ts +4 -0
  44. package/src/world-cell-data.ts +7 -0
  45. package/src/world-cell-models.ts +36 -8
  46. package/src/world-cell-render-gpu-dress.ts +4 -2
  47. package/src/world-cell-render-util.ts +2 -2
  48. package/src/world-cells.ts +1 -1
  49. package/src/world-river-ribbon.ts +13 -22
  50. package/src/world-water-bodies.ts +113 -3
@@ -0,0 +1,628 @@
1
+ import {
2
+ Box3,
3
+ BufferAttribute,
4
+ type BufferGeometry,
5
+ type Camera,
6
+ Group,
7
+ InstancedBufferAttribute,
8
+ InstancedBufferGeometry,
9
+ type Material,
10
+ Mesh,
11
+ Sphere,
12
+ Vector3,
13
+ Vector4,
14
+ } from "three";
15
+ import { float, uniform, vec2, vec3 } from "three/tsl";
16
+ import type { Node, UniformNode } from "three/webgpu";
17
+ import {
18
+ type ITileRingField,
19
+ TileRing,
20
+ clamp01,
21
+ groundGrid,
22
+ hashInt,
23
+ mulberry32,
24
+ sample,
25
+ shuffled,
26
+ smoothstep,
27
+ } from "./tile-ring.js";
28
+
29
+ const MAX_PUSHERS = 4;
30
+ const DEG = Math.PI / 180;
31
+
32
+ /** The instance attributes every chunk carries; the game's material reads them by these names. */
33
+ export const GRASS_FIELD_ATTRIBUTES = {
34
+ /** vec3: the blade's root, chunk-local (the chunk mesh sits at its corner). */
35
+ root: "grassRoot",
36
+ /** vec4: facing 0..1, height 0..1, thinning priority 0..1, coverage scale 0..1. */
37
+ rand: "grassRand",
38
+ /** vec4: angle away from the tuft centre, tuft random 0..1, ground normal x, ground normal z. */
39
+ clump: "grassClump",
40
+ } as const;
41
+
42
+ export interface IGrassFieldBounds {
43
+ readonly minX: number;
44
+ readonly minZ: number;
45
+ readonly maxX: number;
46
+ readonly maxZ: number;
47
+ }
48
+
49
+ /** The blade shape the game built: every LOD level packed in one geometry, each a draw range. */
50
+ export interface IGrassFieldBlade {
51
+ readonly geometry: BufferGeometry;
52
+ /** Index ranges near to far; `lodDistances` picks between them. */
53
+ readonly lods: readonly { readonly start: number; readonly count: number }[];
54
+ /** The tallest a blade can stand, metres: pads each chunk's bounds so culling never clips a tip. */
55
+ readonly reach: number;
56
+ }
57
+
58
+ /** TSL uniforms the field keeps current; the game's material reads them so its thinning matches the CPU trim. */
59
+ export interface IGrassFieldNodes {
60
+ readonly thinStart: UniformNode<"float", number>;
61
+ readonly thinEnd: UniformNode<"float", number>;
62
+ readonly farDensity: UniformNode<"float", number>;
63
+ readonly fadeStart: UniformNode<"float", number>;
64
+ readonly drawDistance: UniformNode<"float", number>;
65
+ readonly pushers: readonly UniformNode<"vec4", Vector4>[];
66
+ /**
67
+ * The pushers' pull on a root, as vec3(push x, push z, press): push is the summed unit direction
68
+ * away from each pusher times its falloff, press the strongest falloff 0..1. `pressAt` mirrors it.
69
+ */
70
+ push(rootWorld: Node<"vec3">): Node<"vec3">;
71
+ }
72
+
73
+ export interface IGrassField3DOptions {
74
+ readonly blade: IGrassFieldBlade;
75
+ /** Builds the game's blade material from the field's uniforms. Called once. */
76
+ readonly material: (nodes: IGrassFieldNodes) => Material;
77
+ /** Ground height at (x, z), field-local metres. */
78
+ readonly getHeight: (x: number, z: number) => number;
79
+ /** Coverage 0..1 at (x, z, height, normal y): paths, clearings, biome masks. */
80
+ readonly getDensity?: (x: number, z: number, height: number, normalY: number) => number;
81
+ readonly bounds?: IGrassFieldBounds | null;
82
+ /** Blades per square metre at full coverage. */
83
+ readonly density?: number;
84
+ readonly chunkSize?: number;
85
+ readonly seed?: number;
86
+ readonly heightSampleSpacing?: number;
87
+ /** Degrees: no grass steeper than `maxSlope`, thinning over `slopeFade` degrees before it. */
88
+ readonly maxSlope?: number;
89
+ readonly slopeFade?: number;
90
+ readonly minAltitude?: number;
91
+ readonly maxAltitude?: number;
92
+ /** Tuft size, metres: blades in one tuft share a centre to lean from. */
93
+ readonly clumpSize?: number;
94
+ readonly drawDistance?: number;
95
+ /** Share of `drawDistance` over which blades sink away at the far edge. */
96
+ readonly fadeRange?: number;
97
+ /** Distances at which the next blade LOD takes over: `blade.lods.length - 1` of them. */
98
+ readonly lodDistances?: readonly number[];
99
+ readonly thinStart?: number;
100
+ readonly thinEnd?: number;
101
+ /** The share of blades left past `thinEnd`. */
102
+ readonly farDensity?: number;
103
+ /** Milliseconds per frame allowed for building chunks; one chunk always builds. */
104
+ readonly buildBudgetMs?: number;
105
+ readonly receiveShadow?: boolean;
106
+ /** Scales every density at once, as Unreal's `grass.densityScale`. */
107
+ readonly densityScale?: number;
108
+ /** Scales every distance at once, as Unreal's `grass.CullDistanceScale`. */
109
+ readonly cullDistanceScale?: number;
110
+ }
111
+
112
+ export interface IGrassFieldStats {
113
+ chunks: number;
114
+ visibleChunks: number;
115
+ blades: number;
116
+ triangles: number;
117
+ pending: number;
118
+ /** Chunks built since the field was made. */
119
+ built: number;
120
+ }
121
+
122
+ interface IChunk {
123
+ readonly ix: number;
124
+ readonly iz: number;
125
+ readonly count: number;
126
+ readonly mesh: Mesh | null;
127
+ readonly priority: Float32Array | null;
128
+ readonly radius: number;
129
+ }
130
+
131
+ /**
132
+ * Streamed, seeded, instanced grass around the camera; the game owns the blade and the material.
133
+ *
134
+ * Square chunks around the camera, each one instanced draw, built nearest first inside
135
+ * `buildBudgetMs` per frame. A chunk is built inside 1.3 × the draw distance and discarded past
136
+ * 1.4 ×, Unreal Landscape grass's guard band (UE 5.8.3:
137
+ * Engine/Source/Runtime/Landscape/Private/LandscapeGrass.cpp:88, :94), so the edge never thrashes.
138
+ * Each blade carries a priority; the material shrinks low-priority blades away with distance through
139
+ * `thinStart`/`thinEnd`/`farDensity`, and the CPU only trims the instances the shader already hid.
140
+ * Blade LOD is a draw-range switch on `blade.lods`. Up to four pushers flatten grass around them.
141
+ *
142
+ * The node creates no colour, shading or blade shape: `blade` and `material` come from the game's
143
+ * `src/render/grass.ts`, which reads `GRASS_FIELD_ATTRIBUTES` and the `nodes` uniforms.
144
+ *
145
+ * @situation Grass that sways and parts around the player across a large terrain.
146
+ * @situation Stream instanced ground cover in chunks around the camera under a frame budget.
147
+ * @situation Meadow, lawn or field grass with distance thinning and LOD that does not pop.
148
+ * @constraint Call `update(camera)` once per rendered frame, from `ctx.beforeRender`.
149
+ * @constraint Rotating or scaling the field is not supported; translating it is.
150
+ * @example
151
+ * import { GrassField3D } from "@threenative/core";
152
+ * // grassBlade and grassMaterial come from the game's own src/render/grass.ts.
153
+ * const grass = new GrassField3D({ blade: grassBlade(), material: grassMaterial, getHeight: height });
154
+ * ctx.add(grass);
155
+ * ctx.beforeRender(() => { grass.pushers[0]?.set(hero.x, hero.y, hero.z, 1.2); grass.update(camera); });
156
+ */
157
+ export class GrassField3D extends Group {
158
+ readonly blade: IGrassFieldBlade;
159
+ readonly material: Material;
160
+ readonly nodes: IGrassFieldNodes;
161
+ /** x, y, z world position and w radius (0 = off) of what flattens the grass. */
162
+ readonly pushers: readonly Vector4[];
163
+ /** Chunks and budget from the shared ring; blades and triangles from this frame's LOD pass. */
164
+ get stats(): IGrassFieldStats {
165
+ return {
166
+ blades: this.#shown.blades,
167
+ built: this.#ring.stats.built,
168
+ chunks: this.#ring.stats.tiles,
169
+ pending: this.#ring.stats.pending,
170
+ triangles: this.#shown.triangles,
171
+ visibleChunks: this.#shown.visibleChunks,
172
+ };
173
+ }
174
+ getHeight: (x: number, z: number) => number;
175
+ getDensity: ((x: number, z: number, height: number, normalY: number) => number) | null;
176
+ bounds: IGrassFieldBounds | null;
177
+ density: number;
178
+ chunkSize: number;
179
+ seed: number;
180
+ heightSampleSpacing: number;
181
+ maxSlope: number;
182
+ slopeFade: number;
183
+ minAltitude: number;
184
+ maxAltitude: number;
185
+ clumpSize: number;
186
+ drawDistance: number;
187
+ fadeRange: number;
188
+ lodDistances: readonly number[];
189
+ thinStart: number;
190
+ thinEnd: number;
191
+ farDensity: number;
192
+ buildBudgetMs: number;
193
+ override receiveShadow: boolean;
194
+ densityScale: number;
195
+ cullDistanceScale: number;
196
+ readonly #ring: TileRing<IChunk>;
197
+ readonly #shown = { blades: 0, triangles: 0, visibleChunks: 0 };
198
+ #version = 0;
199
+ #layout = "";
200
+
201
+ constructor(options: IGrassField3DOptions) {
202
+ super();
203
+ this.name = "GrassField3D";
204
+ if (typeof options.getHeight !== "function")
205
+ throw new Error("GrassField3D.getHeight must be a function (x, z) => height.");
206
+ if (typeof options.material !== "function")
207
+ throw new Error("GrassField3D.material must be a function (nodes) => Material.");
208
+ const lods = options.blade?.lods;
209
+ if (!Array.isArray(lods) || lods.length === 0)
210
+ throw new Error("GrassField3D.blade.lods must list at least one draw range.");
211
+ this.blade = options.blade;
212
+ this.getHeight = options.getHeight;
213
+ this.getDensity = options.getDensity ?? null;
214
+ this.bounds = options.bounds ?? null;
215
+ this.density = options.density ?? 30;
216
+ this.chunkSize = options.chunkSize ?? 12;
217
+ this.seed = options.seed ?? 1337;
218
+ this.heightSampleSpacing = options.heightSampleSpacing ?? 0.75;
219
+ this.maxSlope = options.maxSlope ?? 42;
220
+ this.slopeFade = options.slopeFade ?? 12;
221
+ this.minAltitude = options.minAltitude ?? Number.NEGATIVE_INFINITY;
222
+ this.maxAltitude = options.maxAltitude ?? Number.POSITIVE_INFINITY;
223
+ this.clumpSize = options.clumpSize ?? 1.4;
224
+ this.drawDistance = options.drawDistance ?? 75;
225
+ this.fadeRange = options.fadeRange ?? 0.3;
226
+ this.lodDistances = options.lodDistances ?? [16, 38];
227
+ this.thinStart = options.thinStart ?? 10;
228
+ this.thinEnd = options.thinEnd ?? 62;
229
+ this.farDensity = options.farDensity ?? 0.22;
230
+ this.buildBudgetMs = options.buildBudgetMs ?? 4;
231
+ this.receiveShadow = options.receiveShadow ?? true;
232
+ this.densityScale = options.densityScale ?? 1;
233
+ this.cullDistanceScale = options.cullDistanceScale ?? 1;
234
+ this.#validate();
235
+ this.#ring = new TileRing<IChunk>(this.#hooks());
236
+ this.pushers = Array.from({ length: MAX_PUSHERS }, () => new Vector4());
237
+ const pushers = this.pushers.map((v) => uniform(v));
238
+ this.nodes = {
239
+ thinStart: uniform(0),
240
+ thinEnd: uniform(0),
241
+ farDensity: uniform(0),
242
+ fadeStart: uniform(0),
243
+ drawDistance: uniform(0),
244
+ pushers,
245
+ push: (root: Node<"vec3">): Node<"vec3"> => {
246
+ let dir: Node<"vec2"> = vec2(0, 0);
247
+ let press: Node<"float"> = float(0);
248
+ for (const pu of pushers) {
249
+ const d = root.sub(pu.xyz);
250
+ const f = float(1)
251
+ .sub(d.length().div(pu.w.max(1e-3)).smoothstep(0, 1))
252
+ .mul(pu.w.step(1e-3).oneMinus());
253
+ dir = dir.add(d.xz.add(vec2(1e-4, 1e-4)).normalize().mul(f));
254
+ press = press.max(f);
255
+ }
256
+ return vec3(dir.x, dir.y, press);
257
+ },
258
+ };
259
+ this.#syncNodes();
260
+ this.material = options.material(this.nodes);
261
+ }
262
+
263
+ /** The pushers' press 0..1 at a world point: the CPU mirror of `nodes.push`'s z. */
264
+ pressAt(x: number, y: number, z: number): number {
265
+ let press = 0;
266
+ for (const pu of this.pushers) {
267
+ if (pu.w < 1e-3) continue;
268
+ const f = 1 - smoothstep(0, 1, Math.hypot(x - pu.x, y - pu.y, z - pu.z) / pu.w);
269
+ press = Math.max(press, f);
270
+ }
271
+ return press;
272
+ }
273
+
274
+ /** Builds every chunk in range on the next `update` regardless of budget: on load or after a teleport. */
275
+ prewarm(): void {
276
+ this.#ring.prewarm();
277
+ }
278
+
279
+ /** Re-scatter after the ground or the density changed: all chunks, or those touching a rectangle. */
280
+ refresh(rect?: IGrassFieldBounds): void {
281
+ if (rect === undefined) {
282
+ this.#version++;
283
+ return;
284
+ }
285
+ this.#ring.disposeInside(rect);
286
+ }
287
+
288
+ /** Streams, thins and LODs the chunks around `camera`. Call once per rendered frame. */
289
+ update(camera: Camera): void {
290
+ this.#validate();
291
+ this.#syncNodes();
292
+ const layout = this.#layoutKey();
293
+ if (layout !== this.#layout) {
294
+ this.#ring.clear();
295
+ this.#layout = layout;
296
+ }
297
+ camera.getWorldPosition(scratch);
298
+ this.worldToLocal(scratch);
299
+ this.#shown.visibleChunks = this.#shown.blades = this.#shown.triangles = 0;
300
+ this.#ring.update(scratch.x, scratch.z);
301
+ }
302
+
303
+ #inBounds(ix: number, iz: number): boolean {
304
+ const b = this.bounds;
305
+ const S = this.chunkSize;
306
+ return (
307
+ b === null ||
308
+ !(ix * S >= b.maxX || (ix + 1) * S <= b.minX || iz * S >= b.maxZ || (iz + 1) * S <= b.minZ)
309
+ );
310
+ }
311
+
312
+ /** The ring's hooks: a chunk that leaves the radius hides, one past the band is freed. */
313
+ #hooks(): ITileRingField<IChunk> {
314
+ const field = this;
315
+ return {
316
+ build: (ix, iz) => this.#build(ix, iz),
317
+ get buildBudgetMs() {
318
+ return field.buildBudgetMs;
319
+ },
320
+ get chunkSize() {
321
+ return field.chunkSize;
322
+ },
323
+ get drawDistance() {
324
+ return field.drawDistance * field.cullDistanceScale;
325
+ },
326
+ dispose: (chunk) => this.#dispose(chunk),
327
+ hide: (chunk) => {
328
+ if (chunk.mesh?.visible) chunk.mesh.visible = false;
329
+ },
330
+ inBounds: (ix, iz) => this.#inBounds(ix, iz),
331
+ show: (chunk, distance) => this.#applyLod(chunk, distance),
332
+ };
333
+ }
334
+
335
+ override dispose(): void {
336
+ this.#ring.clear();
337
+ this.material.dispose();
338
+ }
339
+
340
+ #validate(): void {
341
+ if (!(this.chunkSize > 0))
342
+ throw new Error(`GrassField3D.chunkSize must be > 0, got ${this.chunkSize}.`);
343
+ if (!(this.density >= 0))
344
+ throw new Error(`GrassField3D.density must be >= 0, got ${this.density}.`);
345
+ if (!(this.drawDistance > 0))
346
+ throw new Error(`GrassField3D.drawDistance must be > 0, got ${this.drawDistance}.`);
347
+ if (!(this.buildBudgetMs >= 0))
348
+ throw new Error(`GrassField3D.buildBudgetMs must be >= 0, got ${this.buildBudgetMs}.`);
349
+ if (!(this.densityScale >= 0) || !(this.cullDistanceScale > 0))
350
+ throw new Error("GrassField3D.densityScale must be >= 0 and cullDistanceScale > 0.");
351
+ const b = this.bounds;
352
+ if (b === null) return;
353
+ for (const key of ["minX", "minZ", "maxX", "maxZ"] as const)
354
+ if (!Number.isFinite(b[key])) throw new Error(`GrassField3D.bounds.${key} must be finite.`);
355
+ if (b.minX >= b.maxX) throw new Error("GrassField3D.bounds.minX must be below bounds.maxX.");
356
+ if (b.minZ >= b.maxZ) throw new Error("GrassField3D.bounds.minZ must be below bounds.maxZ.");
357
+ }
358
+
359
+ #syncNodes(): void {
360
+ const k = this.cullDistanceScale;
361
+ const n = this.nodes;
362
+ // Only on change: on the owned engine each uniform write crosses into the engine.
363
+ setIfChanged(n.thinStart, this.thinStart * k);
364
+ setIfChanged(n.thinEnd, Math.max(this.thinEnd, this.thinStart + 0.01) * k);
365
+ setIfChanged(n.farDensity, this.farDensity);
366
+ setIfChanged(n.drawDistance, this.drawDistance * k);
367
+ setIfChanged(
368
+ n.fadeStart,
369
+ this.drawDistance * k * (1 - Math.min(Math.max(this.fadeRange, 0.01), 1)),
370
+ );
371
+ }
372
+
373
+ #layoutKey(): string {
374
+ return [
375
+ this.#version,
376
+ this.density * this.densityScale,
377
+ this.chunkSize,
378
+ this.seed,
379
+ this.heightSampleSpacing,
380
+ this.maxSlope,
381
+ this.slopeFade,
382
+ this.minAltitude,
383
+ this.maxAltitude,
384
+ this.clumpSize,
385
+ ].join("|");
386
+ }
387
+
388
+ #applyLod(chunk: IChunk, d: number): void {
389
+ const mesh = chunk.mesh;
390
+ if (!mesh || !chunk.priority) return;
391
+ const k = this.cullDistanceScale;
392
+ const geo = mesh.geometry as InstancedBufferGeometry;
393
+ // The same cut-off the material applies, at the chunk's nearest point: only hidden blades go.
394
+ const thinEnd = Math.max(this.thinEnd, this.thinStart + 0.01) * k;
395
+ const edge = 1.1 + (this.farDensity - 1.1) * smoothstep(this.thinStart * k, thinEnd, d);
396
+ let n = chunk.count;
397
+ if (edge < 1) {
398
+ const pr = chunk.priority;
399
+ let lo = 0;
400
+ let hi = n;
401
+ while (lo < hi) {
402
+ const mid = (lo + hi) >> 1;
403
+ if ((pr[mid] as number) < edge) lo = mid + 1;
404
+ else hi = mid;
405
+ }
406
+ n = lo;
407
+ }
408
+ // Every write below is guarded: a standing camera re-plans nothing on the owned engine.
409
+ if (geo.instanceCount !== n) geo.instanceCount = n;
410
+ const visible = n > 0 && d < this.drawDistance * this.cullDistanceScale;
411
+ if (mesh.visible !== visible) mesh.visible = visible;
412
+ if (!visible) return;
413
+ const lods = this.blade.lods;
414
+ let lod = 0;
415
+ while (lod < lods.length - 1 && d >= (this.lodDistances[lod] ?? Number.POSITIVE_INFINITY) * k)
416
+ lod++;
417
+ const range = lods[lod] as { start: number; count: number };
418
+ if (geo.drawRange.start !== range.start || geo.drawRange.count !== range.count)
419
+ geo.setDrawRange(range.start, range.count);
420
+ if (mesh.receiveShadow !== this.receiveShadow) mesh.receiveShadow = this.receiveShadow;
421
+ this.#shown.visibleChunks++;
422
+ this.#shown.blades += n;
423
+ this.#shown.triangles += n * (range.count / 3);
424
+ }
425
+
426
+ #build(ix: number, iz: number): IChunk | null {
427
+ const S = this.chunkSize;
428
+ const ox = ix * S;
429
+ const oz = iz * S;
430
+ const seed = this.seed | 0;
431
+ const rng = mulberry32(hashInt(ix, iz, seed));
432
+ // The slope ring reaches one cell past the chunk: past the field's bounds it reads the edge
433
+ // height, so a ground that exists only inside the bounds (a resident heightfield) is never
434
+ // asked for a point it does not hold.
435
+ const b = this.bounds;
436
+ const getHeight = this.getHeight;
437
+ const height =
438
+ b === null
439
+ ? getHeight
440
+ : (x: number, z: number) =>
441
+ getHeight(Math.min(b.maxX, Math.max(b.minX, x)), Math.min(b.maxZ, Math.max(b.minZ, z)));
442
+ const ground = groundGrid(height, ox, oz, S, this.heightSampleSpacing);
443
+ // A jittered grid visited in a seeded random order: any prefix covers the chunk evenly, so
444
+ // thinning by distance is a plain instance count.
445
+ const n = Math.max(1, Math.ceil(Math.sqrt(this.density * this.densityScale * S * S)));
446
+ const total = this.density * this.densityScale > 0 ? n * n : 0;
447
+ const cell = S / n;
448
+ const order = shuffled(total, rng);
449
+ const pos = new Float32Array(total * 3);
450
+ const rand = new Float32Array(total * 4);
451
+ const clump = new Float32Array(total * 4);
452
+ const priority = new Float32Array(total);
453
+ const cosMax = Math.cos(this.maxSlope * DEG);
454
+ const slopeSpan = Math.max(
455
+ Math.cos(Math.max(this.maxSlope - this.slopeFade, 0) * DEG) - cosMax,
456
+ 1e-5,
457
+ );
458
+ const cs = Math.max(this.clumpSize, 0.05);
459
+ prepareTufts(ox, oz, S, cs, seed);
460
+ let k = 0;
461
+ let minY = Number.POSITIVE_INFINITY;
462
+ let maxY = Number.NEGATIVE_INFINITY;
463
+ for (let q = 0; q < total; q++) {
464
+ const c = order[q] as number;
465
+ const lx = ((c % n) + rng()) * cell;
466
+ const lz = (((c / n) | 0) + rng()) * cell;
467
+ const rFacing = rng();
468
+ const rHeight = rng();
469
+ const rKeep = rng();
470
+ const wx = ox + lx;
471
+ const wz = oz + lz;
472
+ if (!this.#pointInBounds(wx, wz)) continue;
473
+ ground.sample(lx, lz);
474
+ const y = sample[0] as number;
475
+ const dx = sample[1] as number;
476
+ const dz = sample[2] as number;
477
+ if (y < this.minAltitude || y > this.maxAltitude) continue;
478
+ const ny = 1 / Math.sqrt(dx * dx + dz * dz + 1);
479
+ const m = this.#coverage(wx, wz, y, ny, cosMax, slopeSpan);
480
+ if (m <= 0.001 || rKeep > m * 2) continue;
481
+ nearestTuft(wx, wz, cs);
482
+ pos[k * 3] = lx;
483
+ pos[k * 3 + 1] = y;
484
+ pos[k * 3 + 2] = lz;
485
+ priority[k] = q / total;
486
+ rand[k * 4] = rFacing;
487
+ rand[k * 4 + 1] = rHeight;
488
+ rand[k * 4 + 2] = q / total;
489
+ rand[k * 4 + 3] = 0.45 + 0.55 * m;
490
+ clump[k * 4] = fastAtan2(wz - (tuft[1] as number), wx - (tuft[0] as number));
491
+ clump[k * 4 + 1] = tuft[2] as number;
492
+ clump[k * 4 + 2] = -dx * ny;
493
+ clump[k * 4 + 3] = -dz * ny;
494
+ minY = Math.min(minY, y);
495
+ maxY = Math.max(maxY, y);
496
+ k++;
497
+ }
498
+ // Remembered as empty by the ring, so it is not rebuilt every frame.
499
+ if (k === 0) return null;
500
+ const blade = this.blade.geometry;
501
+ const geo = new InstancedBufferGeometry();
502
+ // The blade's arrays are shared; each chunk wraps them in its own attribute so disposing one
503
+ // chunk never frees another's buffers.
504
+ if (blade.index) geo.setIndex(new BufferAttribute(blade.index.array, 1));
505
+ for (const [name, attr] of Object.entries(blade.attributes))
506
+ geo.setAttribute(name, new BufferAttribute(attr.array, attr.itemSize, attr.normalized));
507
+ geo.setAttribute(
508
+ GRASS_FIELD_ATTRIBUTES.root,
509
+ new InstancedBufferAttribute(pos.slice(0, k * 3), 3),
510
+ );
511
+ geo.setAttribute(
512
+ GRASS_FIELD_ATTRIBUTES.rand,
513
+ new InstancedBufferAttribute(rand.slice(0, k * 4), 4),
514
+ );
515
+ geo.setAttribute(
516
+ GRASS_FIELD_ATTRIBUTES.clump,
517
+ new InstancedBufferAttribute(clump.slice(0, k * 4), 4),
518
+ );
519
+ geo.instanceCount = k;
520
+ const halfY = (maxY - minY) / 2;
521
+ const radius = Math.sqrt(S * S * 0.5 + halfY * halfY);
522
+ const pad = Math.max(this.blade.reach, 0) * 1.5 + 1;
523
+ geo.boundingSphere = new Sphere(new Vector3(S / 2, minY + halfY, S / 2), radius + pad);
524
+ geo.boundingBox = new Box3(
525
+ new Vector3(-pad, minY - 1, -pad),
526
+ new Vector3(S + pad, maxY + pad, S + pad),
527
+ );
528
+ const mesh = new Mesh(geo, this.material);
529
+ mesh.name = `grass ${ix},${iz}`;
530
+ mesh.position.set(ox, 0, oz);
531
+ mesh.matrixAutoUpdate = false;
532
+ mesh.updateMatrix();
533
+ mesh.raycast = () => {};
534
+ this.add(mesh);
535
+ return { ix, iz, count: k, mesh, priority: priority.slice(0, k), radius };
536
+ }
537
+
538
+ #pointInBounds(x: number, z: number): boolean {
539
+ const b = this.bounds;
540
+ return b === null || (x >= b.minX && x <= b.maxX && z >= b.minZ && z <= b.maxZ);
541
+ }
542
+
543
+ /** Slope limit times the game's mask, 0..1. */
544
+ #coverage(x: number, z: number, y: number, ny: number, cosMax: number, span: number): number {
545
+ const m = clamp01((ny - cosMax) / span);
546
+ return m > 0 && this.getDensity ? m * clamp01(this.getDensity(x, z, y, ny)) : m;
547
+ }
548
+
549
+ #dispose(chunk: IChunk): void {
550
+ if (!chunk.mesh) return;
551
+ this.remove(chunk.mesh);
552
+ chunk.mesh.geometry.dispose();
553
+ }
554
+ }
555
+
556
+ const scratch = new Vector3();
557
+
558
+ function setIfChanged(node: { value: number }, value: number): void {
559
+ if (node.value !== value) node.value = value;
560
+ }
561
+ /** Height, d/dx and d/dz of the last `groundGrid` sample. */
562
+ /** x, z and random of the last `nearestTuft` centre. */
563
+ const tuft = new Float64Array(3);
564
+
565
+ /** Tuft centres (x, z, random) of the cells round one chunk, hashed once per cell, not per blade. */
566
+ let tuftCells = new Float64Array(0);
567
+ let tuftX0 = 0;
568
+ let tuftZ0 = 0;
569
+ let tuftW = 0;
570
+
571
+ /** Fills `tuftCells` for every tuft cell a blade in `[ox, ox + S]²` can reach (its own and the ring round it). */
572
+ function prepareTufts(ox: number, oz: number, S: number, cs: number, seed: number): void {
573
+ tuftX0 = Math.floor(ox / cs) - 1;
574
+ tuftZ0 = Math.floor(oz / cs) - 1;
575
+ tuftW = Math.floor((ox + S) / cs) - tuftX0 + 2;
576
+ const rows = Math.floor((oz + S) / cs) - tuftZ0 + 2;
577
+ if (tuftCells.length < tuftW * rows * 3) tuftCells = new Float64Array(tuftW * rows * 3);
578
+ for (let r = 0; r < rows; r++)
579
+ for (let c = 0; c < tuftW; c++) {
580
+ const cx = tuftX0 + c;
581
+ const cz = tuftZ0 + r;
582
+ const h = hashInt(cx, cz, seed + 7919);
583
+ const o = (r * tuftW + c) * 3;
584
+ tuftCells[o] = (cx + (h & 1023) / 1023) * cs;
585
+ tuftCells[o + 1] = (cz + ((h >>> 10) & 1023) / 1023) * cs;
586
+ tuftCells[o + 2] = ((h >>> 20) & 1023) / 1023;
587
+ }
588
+ }
589
+
590
+ /** The nearest tuft centre on a jittered world grid, continuous across chunks, into `tuft`. */
591
+ function nearestTuft(wx: number, wz: number, cs: number): void {
592
+ const ccx = Math.floor(wx / cs);
593
+ const ccz = Math.floor(wz / cs);
594
+ let best = Number.POSITIVE_INFINITY;
595
+ for (let jz = -1; jz <= 1; jz++)
596
+ for (let jx = -1; jx <= 1; jx++) {
597
+ const o = ((ccz + jz - tuftZ0) * tuftW + (ccx + jx - tuftX0)) * 3;
598
+ const px = tuftCells[o] as number;
599
+ const pz = tuftCells[o + 1] as number;
600
+ const dd = (px - wx) * (px - wx) + (pz - wz) * (pz - wz);
601
+ if (dd >= best) continue;
602
+ best = dd;
603
+ tuft[0] = px;
604
+ tuft[1] = pz;
605
+ tuft[2] = tuftCells[o + 2] as number;
606
+ }
607
+ }
608
+
609
+ /**
610
+ * `Math.atan2` within 1e-5 rad at a fraction of its cost: a blade's tuft angle runs once per
611
+ * candidate blade, and the material only reads it through cos and sin.
612
+ */
613
+ export function fastAtan2(y: number, x: number): number {
614
+ const ax = Math.abs(x);
615
+ const ay = Math.abs(y);
616
+ const hi = Math.max(ax, ay);
617
+ if (hi === 0) return 0;
618
+ const a = Math.min(ax, ay) / hi;
619
+ const s = a * a;
620
+ let r =
621
+ ((((-0.01348047 * s + 0.057477314) * s - 0.121239071) * s + 0.195635925) * s - 0.332994597) *
622
+ s *
623
+ a +
624
+ 0.99999563 * a;
625
+ if (ay > ax) r = 1.57079637 - r;
626
+ if (x < 0) r = 3.14159274 - r;
627
+ return y < 0 ? -r : r;
628
+ }