@threenative/core 0.3.11 → 0.3.13

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 (236) hide show
  1. package/README.md +1 -1
  2. package/capabilities.json +1988 -204
  3. package/dist/{assets-YUbXa3-Y.d.ts → assets-CfMKnOsK.d.ts} +78 -1
  4. package/dist/camera-shake-CZKOfGn4.d.ts +46 -0
  5. package/dist/{canvas-layer-vCtanIeB.d.ts → canvas-layer-G7ttVy7y.d.ts} +1 -1
  6. package/dist/chunk-4SRAQFTU.js +133 -0
  7. package/dist/chunk-CFGTPFUH.js +231 -0
  8. package/dist/chunk-DIPIJICH.js +8916 -0
  9. package/dist/chunk-EEABDLUC.js +2237 -0
  10. package/dist/chunk-EFWZWLPY.js +1895 -0
  11. package/dist/chunk-GXY7B3JG.js +46 -0
  12. package/dist/chunk-GYUZJQ7U.js +280 -0
  13. package/dist/chunk-H4J6IAJE.js +504 -0
  14. package/dist/chunk-KIRUKTBQ.js +187 -0
  15. package/dist/chunk-QWJEMUUT.js +94 -0
  16. package/dist/chunk-SV4QVUTQ.js +31 -0
  17. package/dist/chunk-U4YHUKKL.js +615 -0
  18. package/dist/chunk-VP43GIWW.js +18 -0
  19. package/dist/chunk-XDTZ4QMO.js +160 -0
  20. package/dist/default-tone-mapping-GgKPTiBP.d.ts +4 -0
  21. package/dist/{game-DzMcitDO.d.ts → game-k8K3hZai.d.ts} +85 -9
  22. package/dist/hot.d.ts +5 -4
  23. package/dist/hot.js +5 -52
  24. package/dist/index.d.ts +633 -1351
  25. package/dist/index.js +12873 -23068
  26. package/dist/{model-lod-CTpZ6imz.d.ts → model-lod-DPTzeCcD.d.ts} +35 -3
  27. package/dist/playtest.d.ts +5 -4
  28. package/dist/playtest.js +25 -75
  29. package/dist/quality-BYqKGAwo.d.ts +868 -0
  30. package/dist/react-css.js +1 -215
  31. package/dist/react.d.ts +3 -2
  32. package/dist/render-environment.d.ts +170 -0
  33. package/dist/render-environment.js +352 -0
  34. package/dist/{renderer-rZm0hVqq.d.ts → renderer-BtOSseYf.d.ts} +42 -35
  35. package/dist/spells/index.d.ts +643 -0
  36. package/dist/spells/index.js +1558 -0
  37. package/dist/spells/ultra/index.d.ts +1600 -0
  38. package/dist/spells/ultra/index.js +6804 -0
  39. package/dist/terrain-jobs-worker.js +1 -123
  40. package/dist/two-sided-foliage-W523J3UM.js +1 -0
  41. package/dist/ui-layer.js +6 -384
  42. package/dist/worker.js +13 -43
  43. package/dist/world.d.ts +988 -268
  44. package/dist/world.js +17464 -18290
  45. package/mcp/animation-server.mjs +1 -1
  46. package/mcp/animation.mjs +2 -3
  47. package/mcp/engine-server.mjs +245 -52
  48. package/mcp/servers.mjs +10 -3
  49. package/mcp/terrain.mjs +8 -0
  50. package/package.json +19 -7
  51. package/patches/three@0.187.0-prd269-upgrade.patch +2102 -0
  52. package/patches/three@0.187.0.patch +2004 -407
  53. package/src/animation-batch.ts +193 -0
  54. package/src/animation-layers.ts +7 -3
  55. package/src/animation.ts +209 -29
  56. package/src/asset-cache.ts +3 -3
  57. package/src/asset-memo.ts +202 -0
  58. package/src/assets.ts +437 -125
  59. package/src/auto-batch.ts +190 -44
  60. package/src/card-lod.ts +152 -0
  61. package/src/compressed-texture-preparation.ts +1008 -0
  62. package/src/compute-driven.ts +1 -1
  63. package/src/config.ts +8 -0
  64. package/src/debug.ts +103 -22
  65. package/src/dev-global.ts +54 -0
  66. package/src/engine-hooks.ts +37 -0
  67. package/src/frame-budget.ts +50 -23
  68. package/src/game-boot-phase.ts +269 -0
  69. package/src/game-dev-tools.ts +86 -0
  70. package/src/game-frame-loop.ts +958 -0
  71. package/src/game-renderer-metrics.ts +77 -0
  72. package/src/game-startup.ts +1076 -0
  73. package/src/game-ui.ts +84 -0
  74. package/src/game-validate.ts +70 -0
  75. package/src/game.ts +198 -2264
  76. package/src/gamepad-mappings.ts +269 -0
  77. package/src/generated/console-markers.ts +13 -0
  78. package/src/geometry-capture.ts +28 -4
  79. package/src/gpu-readings.ts +98 -0
  80. package/src/gpu-scene-bvh.ts +149 -36
  81. package/src/hot.ts +4 -7
  82. package/src/index.ts +141 -9
  83. package/src/input.ts +237 -25
  84. package/src/instanced-batch-lod.ts +3 -8
  85. package/src/interpolation.ts +171 -40
  86. package/src/launch-diagnostics.ts +22 -12
  87. package/src/look/ao-admission.ts +25 -0
  88. package/src/look/auto-exposure.ts +5 -16
  89. package/src/look/default-tone-mapping.ts +41 -5
  90. package/src/look/filmic-tone-mapping.ts +15 -13
  91. package/src/look/local-exposure.ts +2 -7
  92. package/src/look/look-diagnostics.ts +3 -3
  93. package/src/look/quad-pass.ts +21 -0
  94. package/src/look/quality.ts +14 -5
  95. package/src/look/unreal-bloom.ts +4 -13
  96. package/src/look/world-environment.ts +113 -103
  97. package/src/loop.ts +29 -0
  98. package/src/merge-parts.ts +20 -24
  99. package/src/model-lod.ts +139 -17
  100. package/src/particle-kinds.ts +515 -0
  101. package/src/particle-significance.ts +12 -0
  102. package/src/particles.ts +19 -10
  103. package/src/picking.ts +17 -3
  104. package/src/platform.ts +23 -4
  105. package/src/playtest.ts +27 -1
  106. package/src/profiling/FrameStages.ts +5 -6
  107. package/src/profiling/Spans.ts +3 -17
  108. package/src/profiling/debug-telemetry.ts +2 -6
  109. package/src/profiling/render-list-validate.ts +6 -15
  110. package/src/projection-apply.ts +4 -1
  111. package/src/projection-marker.ts +2 -1
  112. package/src/projection-plan.ts +9 -6
  113. package/src/quiet-markers.ts +3 -10
  114. package/src/render/cpu-bvh.ts +100 -0
  115. package/src/render/depth-pyramid.ts +6 -14
  116. package/src/render/environment/environmentContribution.ts +202 -0
  117. package/src/render/environment/environmentRadiance.ts +44 -0
  118. package/src/render/environment/environmentSampleCache.ts +56 -0
  119. package/src/render/environment/environmentSampling.ts +201 -0
  120. package/src/render/environment/environmentSnapshot.ts +71 -0
  121. package/src/render/environment/gate.ts +57 -0
  122. package/src/render/mesh-pool.ts +4 -20
  123. package/src/render/probe-trace.ts +872 -0
  124. package/src/render/probe-volume.ts +780 -34
  125. package/src/render/radiance-cache.ts +17 -0
  126. package/src/render/resolution-subrect.ts +2 -0
  127. package/src/render/rough-diffuse.ts +46 -12
  128. package/src/render/soft-shadow.ts +27 -12
  129. package/src/render/virtual-shadow-adaptive.ts +55 -0
  130. package/src/render/virtual-shadow-casters.ts +175 -0
  131. package/src/render/virtual-shadow-layers.ts +76 -0
  132. package/src/render/virtual-shadow-level.ts +224 -0
  133. package/src/render/virtual-shadow-markers.ts +193 -0
  134. package/src/render/virtual-shadow-options.ts +370 -0
  135. package/src/render/virtual-shadow-pages.ts +5 -0
  136. package/src/render/virtual-shadow-partial.ts +13 -0
  137. package/src/render/virtual-shadow.ts +231 -1008
  138. package/src/render/world-impostor-surface.ts +402 -40
  139. package/src/render/world-impostor.ts +5 -2
  140. package/src/render-camera-cull.ts +98 -3
  141. package/src/render-environment.ts +41 -0
  142. package/src/render-pass-budget.ts +34 -7
  143. package/src/renderProjection.ts +22 -0
  144. package/src/renderer-config.ts +36 -0
  145. package/src/renderer-facts.ts +37 -0
  146. package/src/renderer.ts +144 -65
  147. package/src/resolution-scaler.ts +3 -2
  148. package/src/scene-entry-inspectors.ts +61 -0
  149. package/src/snow-field.ts +2 -1
  150. package/src/spells/cast-pool.ts +361 -0
  151. package/src/spells/index.ts +177 -0
  152. package/src/spells/mechanisms.ts +295 -0
  153. package/src/spells/reaction-field.ts +415 -0
  154. package/src/spells/spell-lights.ts +139 -0
  155. package/src/spells/spell-world.ts +187 -0
  156. package/src/spells/spell.ts +397 -0
  157. package/src/spells/spells.ts +283 -0
  158. package/src/spells/ultra/engine/camera.ts +184 -0
  159. package/src/spells/ultra/engine/quality.ts +96 -0
  160. package/src/spells/ultra/index.ts +52 -0
  161. package/src/spells/ultra/main.ts +305 -0
  162. package/src/spells/ultra/scene/arenaMaterial.ts +325 -0
  163. package/src/spells/ultra/spells/cast.ts +233 -0
  164. package/src/spells/ultra/spells/fire.ts +1267 -0
  165. package/src/spells/ultra/vfx/FluidVolume.ts +816 -0
  166. package/src/spells/ultra/vfx/FluidVolume.tsl.ts +855 -0
  167. package/src/spells/ultra/vfx/FxTarget.ts +61 -0
  168. package/src/spells/ultra/vfx/GroundField.ts +1399 -0
  169. package/src/spells/ultra/vfx/Particles.ts +1475 -0
  170. package/src/spells/ultra/vfx/Ribbons.ts +645 -0
  171. package/src/spells/ultra/vfx/Shockwaves.ts +286 -0
  172. package/src/spells/ultra/vfx/Volumes.ts +489 -0
  173. package/src/spells/ultra/vfx/common.ts +1195 -0
  174. package/src/spells/ultra/vfx/noise.ts +441 -0
  175. package/src/startup-offscreen-bytes.ts +78 -0
  176. package/src/startup-readiness.ts +128 -34
  177. package/src/static-transform.ts +25 -19
  178. package/src/streamed-textures.ts +112 -0
  179. package/src/streaming.ts +68 -4
  180. package/src/texture-streaming.ts +331 -0
  181. package/src/version.ts +1 -1
  182. package/src/warmup.ts +56 -8
  183. package/src/water-surface.ts +9 -3
  184. package/src/worker.ts +12 -2
  185. package/src/world-bundle-safety.ts +446 -0
  186. package/src/world-cell-batches.ts +1178 -0
  187. package/src/world-cell-chunks.ts +1128 -0
  188. package/src/world-cell-data.ts +995 -0
  189. package/src/world-cell-impostors.ts +1461 -0
  190. package/src/world-cell-lod-bias.ts +151 -0
  191. package/src/world-cell-models.ts +1074 -0
  192. package/src/world-cell-options.ts +177 -0
  193. package/src/world-cell-placements.ts +798 -0
  194. package/src/world-cell-prewarm.ts +592 -0
  195. package/src/world-cell-readiness.ts +357 -0
  196. package/src/world-cell-records.ts +401 -0
  197. package/src/world-cell-render-bundles.ts +459 -0
  198. package/src/world-cell-render-gpu-dress.ts +710 -0
  199. package/src/world-cell-render-main-cull.ts +540 -0
  200. package/src/world-cell-render-shadow-claims.ts +198 -0
  201. package/src/world-cell-render-util.ts +259 -0
  202. package/src/world-cell-render.ts +1501 -0
  203. package/src/world-cell-residency.ts +754 -0
  204. package/src/world-cell-stale.ts +238 -0
  205. package/src/world-cells.ts +1335 -10418
  206. package/src/world-chunk-shadow.ts +308 -0
  207. package/src/world-collar.ts +315 -0
  208. package/src/world-gpu-flags.ts +131 -0
  209. package/src/world-gpu-readback.ts +881 -0
  210. package/src/world-gpu-reference.ts +524 -0
  211. package/src/world-gpu-scene.ts +256 -2286
  212. package/src/world-gpu-shadow.ts +203 -0
  213. package/src/world-gpu-types.ts +409 -0
  214. package/src/world-gpu-validation.ts +518 -0
  215. package/src/world-heightfield.ts +802 -0
  216. package/src/world-load-limiter.ts +111 -0
  217. package/src/world-model-sections.ts +80 -0
  218. package/src/world-noise.ts +241 -0
  219. package/src/world-package.ts +42 -0
  220. package/src/world-region.ts +1 -1
  221. package/src/world-river-ribbon.ts +282 -0
  222. package/src/world-root-frame.ts +39 -0
  223. package/src/world-shore-field.ts +91 -0
  224. package/src/world-static-pose.ts +163 -0
  225. package/src/world-surface-sampler.ts +48 -0
  226. package/src/world-terrain-splat.ts +361 -153
  227. package/src/world-tile-budget.ts +249 -0
  228. package/src/world-tile-geometry.ts +469 -0
  229. package/src/world-tile-lod.ts +408 -0
  230. package/src/world-tile-observation.ts +566 -0
  231. package/src/world-tile-stitch.ts +166 -0
  232. package/src/world-tiles.ts +247 -1755
  233. package/src/world-validate.ts +6 -14
  234. package/src/world-warm.ts +51 -0
  235. package/src/world-water-bodies.ts +359 -0
  236. package/src/world.ts +48 -741
@@ -0,0 +1,111 @@
1
+ import type { Object3D } from "three";
2
+ import type { IAdmissionBudget } from "./world-tiles.js";
3
+
4
+ interface IQueuedModelLoad {
5
+ readonly run: () => Promise<Object3D>;
6
+ readonly wanted: () => boolean;
7
+ readonly resolve: (model: Object3D | undefined) => void;
8
+ readonly reject: (error: unknown) => void;
9
+ }
10
+
11
+ /**
12
+ * One bounded lane for every model load a `WorldCells` starts. Assets and chunks share it, so the
13
+ * number of `loadModel` calls in flight at once cannot grow with the number of admitted cells.
14
+ * Queued loads keep admission order, which is nearest-cell first, and one whose cell left (or
15
+ * whose asset was released) before its turn resolves `undefined` without touching the loader.
16
+ */
17
+ export class ModelLoadLimiter {
18
+ readonly #concurrency: number;
19
+ readonly #queue: IQueuedModelLoad[] = [];
20
+ #inFlight = 0;
21
+
22
+ constructor(concurrency: number) {
23
+ this.#concurrency = concurrency;
24
+ }
25
+
26
+ get inFlight(): number {
27
+ return this.#inFlight;
28
+ }
29
+
30
+ get queued(): number {
31
+ return this.#queue.length;
32
+ }
33
+
34
+ load(run: () => Promise<Object3D>, wanted: () => boolean): Promise<Object3D | undefined> {
35
+ return new Promise((resolve, reject) => {
36
+ this.#queue.push({ reject, resolve, run, wanted });
37
+ this.#pump();
38
+ });
39
+ }
40
+
41
+ #pump(): void {
42
+ while (this.#inFlight < this.#concurrency && this.#queue.length > 0) {
43
+ const job = this.#queue.shift() as IQueuedModelLoad;
44
+ if (!job.wanted()) {
45
+ job.resolve(undefined);
46
+ continue;
47
+ }
48
+ this.#inFlight += 1;
49
+ try {
50
+ job.run().then(
51
+ (model) => {
52
+ this.#inFlight -= 1;
53
+ job.resolve(model);
54
+ this.#pump();
55
+ },
56
+ (error: unknown) => {
57
+ this.#inFlight -= 1;
58
+ job.reject(error);
59
+ this.#pump();
60
+ },
61
+ );
62
+ } catch (error) {
63
+ // A loader that throws instead of rejecting must not strand its lane.
64
+ this.#inFlight -= 1;
65
+ job.reject(error);
66
+ this.#pump();
67
+ }
68
+ }
69
+ }
70
+ }
71
+
72
+ /**
73
+ * One frame's admission allowance, shared by every path that puts streamed content on screen.
74
+ *
75
+ * A streaming world has no frame-time ceiling anywhere else: a cell row arriving builds a batch per
76
+ * asset run over every placement in it, a terrain tile builds every LOD level, and the game's
77
+ * `createCollider` runs for every resident tile — all in the one frame that discovers them. That is
78
+ * the 100-330 ms hitch a 60 m/s camera feels every time the ring moves, and it is admission cost,
79
+ * not streaming: the loads never fail.
80
+ *
81
+ * The budget is opened once per `update` and drawn down by the units it admits. A unit always
82
+ * finishes, so a frame spends at most the limit plus the unit that crossed it, and the rest of the
83
+ * backlog waits for the next frame rather than being dropped.
84
+ *
85
+ * @situation streamed terrain tiles or cells hitch the frame that admits them
86
+ * @situation cap how many milliseconds a frame spends building streamed content
87
+ * @constraint open a new budget each frame; a unit always finishes, so one unit can cross the limit
88
+ * @example tiles.follow(player.position, new AdmissionBudget(2, () => performance.now()));
89
+ */
90
+ export class AdmissionBudget implements IAdmissionBudget {
91
+ readonly #limitMs: number;
92
+ readonly #now: () => number;
93
+ #spentMs = 0;
94
+
95
+ constructor(limitMs: number, now: () => number) {
96
+ this.#limitMs = limitMs;
97
+ this.#now = now;
98
+ }
99
+
100
+ get spentMs(): number {
101
+ return this.#spentMs;
102
+ }
103
+
104
+ admit(work: () => void): boolean {
105
+ if (this.#spentMs >= this.#limitMs) return false;
106
+ const startedAt = this.#now();
107
+ work();
108
+ this.#spentMs += this.#now() - startedAt;
109
+ return true;
110
+ }
111
+ }
@@ -0,0 +1,80 @@
1
+ import { type Box3, type BufferGeometry, type Material, type Mesh, Vector3 } from "three";
2
+ import { baseGeometryOf } from "./model-lod.js";
3
+
4
+ /** One material section of a mesh: the whole mesh, or one group of a multi-material mesh. */
5
+ export interface IMeshSection {
6
+ readonly material: Material;
7
+ readonly group?: { readonly start: number; readonly count: number };
8
+ }
9
+
10
+ /**
11
+ * A mesh's material sections: one per geometry group for a material array, else the whole mesh.
12
+ * Instanced props draw one batch per material, so an imported model splits here first.
13
+ *
14
+ * @situation scatter or instance an imported glTF model that has several materials
15
+ * @constraint a section's `material` can be `undefined` for a group naming a missing material slot; skip it
16
+ * @example for (const section of meshSections(mesh)) parts.push(sectionGeometry(mesh, box, section));
17
+ */
18
+ export function meshSections(mesh: Mesh): IMeshSection[] {
19
+ const materials = mesh.material;
20
+ return Array.isArray(materials)
21
+ ? mesh.geometry.groups.map((group) => ({
22
+ material: materials[group.materialIndex ?? 0] as Material,
23
+ group,
24
+ }))
25
+ : [{ material: materials }];
26
+ }
27
+
28
+ /**
29
+ * One section's geometry in model space, standing on y = 0. Every section of a model takes the same
30
+ * base from the whole model's `box`, so a crown keeps its place on its trunk: basing each section on
31
+ * its own bounds detaches them. The mesh's LOD0 geometry is cloned under its world matrix, and a
32
+ * group becomes the clone's draw range.
33
+ *
34
+ * @situation the crown of an instanced tree floats off its trunk, or the parts of a model separate
35
+ * @situation turn each part of an imported model into a geometry for an instanced prop batch
36
+ * @constraint `box` is the whole model's world bounds after any unit normalisation; call `mesh.updateWorldMatrix` first
37
+ * @example const box = new Box3().setFromObject(root); const geometry = sectionGeometry(mesh, box, section);
38
+ */
39
+ export function sectionGeometry(
40
+ mesh: Mesh,
41
+ box: Box3,
42
+ section: IMeshSection,
43
+ options: { readonly centreXZ?: boolean } = {},
44
+ ): BufferGeometry {
45
+ const geometry = baseGeometryOf(mesh).clone().applyMatrix4(mesh.matrixWorld);
46
+ const { group } = section;
47
+ if (group) {
48
+ const start = Math.max(group.start, geometry.drawRange.start);
49
+ const end = Math.min(
50
+ group.start + group.count,
51
+ geometry.drawRange.start + geometry.drawRange.count,
52
+ );
53
+ geometry.clearGroups();
54
+ geometry.setDrawRange(start, Math.max(0, end - start));
55
+ }
56
+ const centre = box.getCenter(new Vector3());
57
+ const centred = options.centreXZ === true;
58
+ geometry.translate(centred ? -centre.x : 0, -box.min.y, centred ? -centre.z : 0);
59
+ return geometry;
60
+ }
61
+
62
+ /**
63
+ * Recompute the normals of a geometry whose normals are missing, zero or not finite, and leave
64
+ * authored normals alone. Some exported art ships zero normals and draws black under any light.
65
+ * Run it after any reshape, so the recomputed normals fit the final shape.
66
+ *
67
+ * @situation an imported model draws black or unlit because it ships zero normals
68
+ * @constraint one bad normal recomputes them all; an intentionally hard-edged model loses its authored split normals only if one is bad
69
+ * @example geometry.scale(1.1, 1, 1.1); repairZeroNormals(geometry);
70
+ */
71
+ export function repairZeroNormals(geometry: BufferGeometry): boolean {
72
+ const normals = geometry.getAttribute("normal");
73
+ let valid = normals !== undefined;
74
+ for (let i = 0; valid && normals && i < normals.count; i++) {
75
+ const length = Math.hypot(normals.getX(i), normals.getY(i), normals.getZ(i));
76
+ valid = Number.isFinite(length) && length >= 0.01;
77
+ }
78
+ if (!valid) geometry.computeVertexNormals();
79
+ return !valid;
80
+ }
@@ -0,0 +1,241 @@
1
+ import {
2
+ Data3DTexture,
3
+ LinearFilter,
4
+ NoColorSpace,
5
+ RGBAFormat,
6
+ RepeatWrapping,
7
+ UnsignedByteType,
8
+ } from "three";
9
+ import { float, texture3D, vec3 } from "three/tsl";
10
+ import type { Node } from "three/webgpu";
11
+
12
+ /**
13
+ * three's MaterialX Perlin (`mx_noise_float` on a vec3) evaluated per pixel costs about 400 ALU
14
+ * operations a call. The Strata forest's ground made 44 calls a pixel: 10 ms of a 27 ms frame on an
15
+ * RTX 2080, the foliage 4 ms more. Unreal's advice for its own Noise expression is the same as this
16
+ * file: bake it into a texture and read that (UE 5.8.3: Engine/Source/Runtime/Engine/Classes/
17
+ * Materials/MaterialExpressionNoise.h:58, "can be expensive to compute").
18
+ *
19
+ * The volume holds that exact noise: the same Bob Jenkins hash, the same twelve gradients, the same
20
+ * quintic fade and 0.982 scale, with the integer lattice wrapped every {@link NOISE_PERIOD} cells so
21
+ * the volume tiles. Inside the first period the baked value at a texel centre is three's value; the
22
+ * texture filter interpolates between centres {@link NOISE_TEXELS} to a lattice cell apart. Each
23
+ * channel is an independent field (the lattice is hashed at a different z offset).
24
+ */
25
+ export const NOISE_PERIOD = 8;
26
+ /** Texels per lattice cell: a cell holds the fade's S-curve in eight linear steps. */
27
+ export const NOISE_TEXELS = 8;
28
+ const SIZE = NOISE_PERIOD * NOISE_TEXELS;
29
+
30
+ const rotl = (x: number, k: number): number => ((x << k) | (x >>> (32 - k))) >>> 0;
31
+
32
+ /** `mx_hash_int(x, y, z)`: Bob Jenkins' lookup3 final mix over three ints, as uint32. */
33
+ export function mxHashInt3(x: number, y: number, z: number): number {
34
+ const seed = (0xdeadbeef + (3 << 2) + 13) >>> 0;
35
+ let a = (seed + x) >>> 0;
36
+ let b = (seed + y) >>> 0;
37
+ let c = (seed + z) >>> 0;
38
+ c = ((c ^ b) - rotl(b, 14)) >>> 0;
39
+ a = ((a ^ c) - rotl(c, 11)) >>> 0;
40
+ b = ((b ^ a) - rotl(a, 25)) >>> 0;
41
+ c = ((c ^ b) - rotl(b, 16)) >>> 0;
42
+ a = ((a ^ c) - rotl(c, 4)) >>> 0;
43
+ b = ((b ^ a) - rotl(a, 14)) >>> 0;
44
+ c = ((c ^ b) - rotl(b, 24)) >>> 0;
45
+ return c;
46
+ }
47
+
48
+ /** `mx_gradient_float(hash, x, y, z)`, linear in (x, y, z): returned as its gradient vector. */
49
+ function gradient(hash: number): [number, number, number] {
50
+ const h = hash & 15;
51
+ const at = (x: number, y: number, z: number): number => {
52
+ const u = h < 8 ? x : y;
53
+ const v = h < 4 ? y : h === 12 || h === 14 ? x : z;
54
+ return ((h & 1) !== 0 ? -u : u) + ((h & 2) !== 0 ? -v : v);
55
+ };
56
+ return [at(1, 0, 0), at(0, 1, 0), at(0, 0, 1)];
57
+ }
58
+
59
+ const fade = (t: number): number => t * t * t * (t * (t * 6 - 15) + 10);
60
+
61
+ /**
62
+ * `mx_perlin_noise_float(p)` with the lattice wrapped every `period` cells and hashed at `zOffset`.
63
+ * With an unwrapped lattice (`period` = 2^31) and `zOffset` 0 it is three's function.
64
+ */
65
+ export function mxPerlin3(x: number, y: number, z: number, period = 2 ** 31, zOffset = 0): number {
66
+ const X = Math.floor(x);
67
+ const Y = Math.floor(y);
68
+ const Z = Math.floor(z);
69
+ const fx = x - X;
70
+ const fy = y - Y;
71
+ const fz = z - Z;
72
+ const wrap = (i: number): number => ((i % period) + period) % period;
73
+ const corner = (dx: number, dy: number, dz: number): number => {
74
+ const [gx, gy, gz] = gradient(
75
+ mxHashInt3(wrap(X + dx) | 0, wrap(Y + dy) | 0, (wrap(Z + dz) + zOffset) | 0),
76
+ );
77
+ return gx * (fx - dx) + gy * (fy - dy) + gz * (fz - dz);
78
+ };
79
+ const u = fade(fx);
80
+ const v = fade(fy);
81
+ const w = fade(fz);
82
+ const lerp = (a: number, b: number, t: number): number => a * (1 - t) + b * t;
83
+ const result = lerp(
84
+ lerp(lerp(corner(0, 0, 0), corner(1, 0, 0), u), lerp(corner(0, 1, 0), corner(1, 1, 0), u), v),
85
+ lerp(lerp(corner(0, 0, 1), corner(1, 0, 1), u), lerp(corner(0, 1, 1), corner(1, 1, 1), u), v),
86
+ w,
87
+ );
88
+ return 0.982 * result;
89
+ }
90
+
91
+ /**
92
+ * The baked RGBA volume, SIZE³ texels, x fastest. Texel i of an axis sits at lattice coordinate
93
+ * (i + 0.5) / NOISE_TEXELS, the centre the linear filter returns unblended. Gradients are hashed once
94
+ * per lattice corner, so the bake is eight dot products and a trilinear blend per texel and channel.
95
+ */
96
+ export function bakeNoiseVolume(): Uint8Array {
97
+ const corners = NOISE_PERIOD ** 3;
98
+ const grads = new Float32Array(4 * corners * 3);
99
+ for (let channel = 0; channel < 4; channel += 1)
100
+ for (let z = 0; z < NOISE_PERIOD; z += 1)
101
+ for (let y = 0; y < NOISE_PERIOD; y += 1)
102
+ for (let x = 0; x < NOISE_PERIOD; x += 1) {
103
+ const g = gradient(mxHashInt3(x, y, z + channel * 1031));
104
+ grads.set(
105
+ g,
106
+ ((channel * NOISE_PERIOD + z) * NOISE_PERIOD + y) * NOISE_PERIOD * 3 + x * 3,
107
+ );
108
+ }
109
+ const frac = new Float32Array(NOISE_TEXELS);
110
+ const weight = new Float32Array(NOISE_TEXELS);
111
+ for (let i = 0; i < NOISE_TEXELS; i += 1) {
112
+ frac[i] = (i + 0.5) / NOISE_TEXELS;
113
+ weight[i] = fade(frac[i] as number);
114
+ }
115
+ const data = new Uint8Array(SIZE ** 3 * 4);
116
+ const P = NOISE_PERIOD;
117
+ for (let tz = 0; tz < SIZE; tz += 1) {
118
+ const Z = Math.floor(tz / NOISE_TEXELS);
119
+ const fz = frac[tz % NOISE_TEXELS] as number;
120
+ const w = weight[tz % NOISE_TEXELS] as number;
121
+ for (let ty = 0; ty < SIZE; ty += 1) {
122
+ const Y = Math.floor(ty / NOISE_TEXELS);
123
+ const fy = frac[ty % NOISE_TEXELS] as number;
124
+ const v = weight[ty % NOISE_TEXELS] as number;
125
+ for (let tx = 0; tx < SIZE; tx += 1) {
126
+ const X = Math.floor(tx / NOISE_TEXELS);
127
+ const fx = frac[tx % NOISE_TEXELS] as number;
128
+ const u = weight[tx % NOISE_TEXELS] as number;
129
+ for (let channel = 0; channel < 4; channel += 1) {
130
+ const base = channel * P;
131
+ const z0 = (base + Z) * P;
132
+ const z1 = (base + ((Z + 1) % P)) * P;
133
+ const y0 = Y;
134
+ const y1 = (Y + 1) % P;
135
+ const x0 = X * 3;
136
+ const x1 = ((X + 1) % P) * 3;
137
+ const dot = (zy: number, xi: number, dx: number, dy: number, dz: number): number => {
138
+ const at = zy * P * 3 + xi;
139
+ return (
140
+ (grads[at] as number) * (fx - dx) +
141
+ (grads[at + 1] as number) * (fy - dy) +
142
+ (grads[at + 2] as number) * (fz - dz)
143
+ );
144
+ };
145
+ const c000 = dot(z0 + y0, x0, 0, 0, 0);
146
+ const c100 = dot(z0 + y0, x1, 1, 0, 0);
147
+ const c010 = dot(z0 + y1, x0, 0, 1, 0);
148
+ const c110 = dot(z0 + y1, x1, 1, 1, 0);
149
+ const c001 = dot(z1 + y0, x0, 0, 0, 1);
150
+ const c101 = dot(z1 + y0, x1, 1, 0, 1);
151
+ const c011 = dot(z1 + y1, x0, 0, 1, 1);
152
+ const c111 = dot(z1 + y1, x1, 1, 1, 1);
153
+ const x00 = c000 + (c100 - c000) * u;
154
+ const x10 = c010 + (c110 - c010) * u;
155
+ const x01 = c001 + (c101 - c001) * u;
156
+ const x11 = c011 + (c111 - c011) * u;
157
+ const n = 0.982 * ((x00 + (x10 - x00) * v) * (1 - w) + (x01 + (x11 - x01) * v) * w);
158
+ data[((tz * SIZE + ty) * SIZE + tx) * 4 + channel] = Math.max(
159
+ 0,
160
+ Math.min(255, Math.round((n * 0.5 + 0.5) * 255)),
161
+ );
162
+ }
163
+ }
164
+ }
165
+ }
166
+ return data;
167
+ }
168
+
169
+ let shared: Data3DTexture | undefined;
170
+
171
+ /**
172
+ * The one volume every material shares: baked on first use, 1 MiB of RGBA8 (it stays in L2).
173
+ *
174
+ * @situation a material needs the raw baked noise texture to sample in its own TSL
175
+ * @constraint baked once per page on the main thread (about 0.15 s); every channel is an independent field
176
+ * @example const volume = noiseVolume();
177
+ */
178
+ export function noiseVolume(): Data3DTexture {
179
+ if (shared) return shared;
180
+ const volume = new Data3DTexture(bakeNoiseVolume(), SIZE, SIZE, SIZE);
181
+ volume.format = RGBAFormat;
182
+ volume.type = UnsignedByteType;
183
+ volume.minFilter = LinearFilter;
184
+ volume.magFilter = LinearFilter;
185
+ volume.wrapS = volume.wrapT = volume.wrapR = RepeatWrapping;
186
+ volume.unpackAlignment = 1;
187
+ volume.colorSpace = NoColorSpace;
188
+ volume.needsUpdate = true;
189
+ shared = volume;
190
+ return volume;
191
+ }
192
+
193
+ type Scalar = Node<"float"> | number;
194
+
195
+ /**
196
+ * Drop-in for `mx_noise_float(p, amplitude, pivot)` on a vec3 `p`: one filtered read of the baked
197
+ * volume instead of the per-pixel Perlin. Only the 3D form: three's 2D Perlin is another function
198
+ * (0.66 scale), so a vec2 caller keeps `mx_noise_float`. `channel` 1 to 3 are independent fields.
199
+ *
200
+ * @situation a terrain, foliage or water shader calls mx_noise_float per pixel and the frame is GPU bound
201
+ * @situation open world ground material with procedural variation that must hold 60 FPS
202
+ * @constraint the field tiles every NOISE_PERIOD units of p; at p = world metres x 2.6 that is a 3 m repeat
203
+ * @constraint vec3 input only: three's 2D Perlin is another function
204
+ * @override keep mx_noise_float where exact analytic noise matters more than the frame
205
+ * @example const patch = smoothstep(-0.35, 0.35, bakedNoise(positionWorld.mul(0.025)));
206
+ */
207
+ export function bakedNoise(
208
+ p: Node<"vec3">,
209
+ amplitude: Scalar = 1,
210
+ pivot: Scalar = 0,
211
+ channel: 0 | 1 | 2 | 3 = 0,
212
+ ): Node<"float"> {
213
+ const sampled = texture3D(noiseVolume(), vec3(p).div(NOISE_PERIOD));
214
+ const lane = (["r", "g", "b", "a"] as const)[channel];
215
+ return sampled[lane].mul(2).sub(1).mul(amplitude).add(pivot) as Node<"float">;
216
+ }
217
+
218
+ /**
219
+ * Drop-in for `mx_fractal_noise_float(p, octaves, lacunarity, diminish, amplitude)`: one read an octave.
220
+ *
221
+ * @situation fractal or fbm noise in a material costs too much GPU time per pixel
222
+ * @constraint octaves is a build-time number; each octave is one filtered volume read
223
+ * @example const macro = bakedFractalNoise(vec3(positionWorld.x, 0, positionWorld.z).mul(0.014), 3);
224
+ */
225
+ export function bakedFractalNoise(
226
+ p: Node<"vec3">,
227
+ octaves = 3,
228
+ lacunarity = 2,
229
+ diminish = 0.5,
230
+ amplitude: Scalar = 1,
231
+ ): Node<"float"> {
232
+ let sum: Node<"float"> = float(0);
233
+ let scale = 1;
234
+ let weight = 1;
235
+ for (let octave = 0; octave < octaves; octave += 1) {
236
+ sum = sum.add(bakedNoise(scale === 1 ? p : p.mul(scale)).mul(weight));
237
+ scale *= lacunarity;
238
+ weight *= diminish;
239
+ }
240
+ return sum.mul(amplitude);
241
+ }
@@ -45,6 +45,11 @@ export interface IWorldTerrain {
45
45
  export interface IWorldAssetLod {
46
46
  readonly glb: string;
47
47
  readonly distance: number;
48
+ /**
49
+ * Scene to draw from `glb`. A cooked species stores every level of one model in one file with
50
+ * its textures, so its levels name the same `glb` and select a scene instead of a file.
51
+ */
52
+ readonly scene?: string;
48
53
  }
49
54
 
50
55
  export interface IWorldAssetBounds {
@@ -53,6 +58,8 @@ export interface IWorldAssetBounds {
53
58
  }
54
59
 
55
60
  export interface IWorldAsset {
61
+ /** Caller-owned terminal impostor distance in world metres; requires WorldCells impostors opt-in. */
62
+ readonly impostorDistance?: number;
56
63
  readonly glb: string;
57
64
  readonly lods?: readonly IWorldAssetLod[];
58
65
  readonly bounds: IWorldAssetBounds;
@@ -95,6 +102,8 @@ export interface IWorldPackage {
95
102
  readonly terrain: IWorldTerrain;
96
103
  readonly assets: Readonly<Record<string, IWorldAsset>>;
97
104
  readonly placements: string;
105
+ /** Optional package-relative JSON array of placement IDs in binary record order. */
106
+ readonly placementIds?: string;
98
107
  readonly cells: readonly IWorldCell[];
99
108
  }
100
109
 
@@ -112,6 +121,16 @@ function isRecord(value: unknown): value is Record<string, unknown> {
112
121
  return typeof value === "object" && value !== null && !Array.isArray(value);
113
122
  }
114
123
 
124
+ function isPackageRelativePath(value: string): boolean {
125
+ return (
126
+ !value.startsWith("/") &&
127
+ !value.startsWith("//") &&
128
+ !value.includes("\\") &&
129
+ !/^[A-Za-z][A-Za-z\d+.-]*:/u.test(value) &&
130
+ !value.split("/").includes("..")
131
+ );
132
+ }
133
+
115
134
  /**
116
135
  * Validate a `world.json` manifest against the v1 contract.
117
136
  *
@@ -295,6 +314,13 @@ export function validateWorldPackage(
295
314
  );
296
315
  }
297
316
  }
317
+ if (
318
+ value.impostorDistance !== undefined &&
319
+ (typeof value.impostorDistance !== "number" ||
320
+ !Number.isFinite(value.impostorDistance) ||
321
+ value.impostorDistance <= 0)
322
+ )
323
+ malformed(`${path}.impostorDistance`, "impostorDistance must be positive finite.");
298
324
  if (value.lods !== undefined) {
299
325
  if (!Array.isArray(value.lods)) {
300
326
  malformed(`${path}.lods`, `${path}.lods must be an array.`);
@@ -307,6 +333,17 @@ export function validateWorldPackage(
307
333
  }
308
334
  text(lod.glb, `${lodPath}.glb`);
309
335
  finite(lod.distance, `${lodPath}.distance`);
336
+ if (lod.scene !== undefined && (typeof lod.scene !== "string" || lod.scene === ""))
337
+ malformed(`${lodPath}.scene`, `${lodPath}.scene must be a nonempty string.`);
338
+ if (
339
+ typeof value.impostorDistance === "number" &&
340
+ typeof lod.distance === "number" &&
341
+ value.impostorDistance <= lod.distance
342
+ )
343
+ malformed(
344
+ `${path}.impostorDistance`,
345
+ "impostorDistance must follow every authored LOD gate.",
346
+ );
310
347
  });
311
348
  }
312
349
  }
@@ -315,6 +352,11 @@ export function validateWorldPackage(
315
352
  }
316
353
 
317
354
  text(manifest.placements, "placements");
355
+ if (manifest.placementIds !== undefined) {
356
+ const placementIds = text(manifest.placementIds, "placementIds");
357
+ if (placementIds !== undefined && !isPackageRelativePath(placementIds))
358
+ malformed("placementIds", "placementIds must be a package-relative path.");
359
+ }
318
360
 
319
361
  const maximumCellX =
320
362
  extent !== undefined && cellSize !== undefined ? Math.ceil(extent.sizeX / cellSize) : undefined;
@@ -1,4 +1,4 @@
1
- import type { IHeightfieldRegionBounds } from "./world.js";
1
+ import type { IHeightfieldRegionBounds } from "./world-heightfield.js";
2
2
 
3
3
  /** The smallest window covering both; `current` may be absent. Internal to the world modules. */
4
4
  export function unionBounds(