@threenative/core 0.3.12 → 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 (165) hide show
  1. package/README.md +1 -1
  2. package/capabilities.json +1047 -44
  3. package/dist/{assets-YUbXa3-Y.d.ts → assets-CfMKnOsK.d.ts} +78 -1
  4. package/dist/{canvas-layer-CWuFRT7G.d.ts → canvas-layer-G7ttVy7y.d.ts} +1 -1
  5. package/dist/{chunk-7UUT3TY5.js → chunk-2GPHICV6.js} +1 -1
  6. package/dist/{chunk-GMHATRPW.js → chunk-GEMQJBY4.js} +1650 -383
  7. package/dist/{chunk-VAZM36TV.js → chunk-H4J6IAJE.js} +17 -10
  8. package/dist/{chunk-5O73CDMR.js → chunk-QAMSM3Z5.js} +415 -27
  9. package/dist/{chunk-2Z44XSI2.js → chunk-QAQHYOWY.js} +3 -7
  10. package/dist/{chunk-DBELTTTM.js → chunk-U4YHUKKL.js} +1 -1
  11. package/dist/{chunk-OKXUCASC.js → chunk-VBBYWGAT.js} +3 -4
  12. package/dist/chunk-VP43GIWW.js +18 -0
  13. package/dist/{chunk-N5LRP4BR.js → chunk-VQRPEOKY.js} +66 -3
  14. package/dist/{chunk-6KLNISRJ.js → chunk-XDTZ4QMO.js} +11 -4
  15. package/dist/default-tone-mapping-GgKPTiBP.d.ts +4 -0
  16. package/dist/{game-D7pAzZUY.d.ts → game-k8K3hZai.d.ts} +72 -8
  17. package/dist/hot.d.ts +5 -4
  18. package/dist/hot.js +5 -8
  19. package/dist/index.d.ts +871 -1018
  20. package/dist/index.js +4786 -1631
  21. package/dist/{model-lod-B6BMqS1r.d.ts → model-lod-DPTzeCcD.d.ts} +4 -2
  22. package/dist/playtest.d.ts +5 -4
  23. package/dist/playtest.js +6 -5
  24. package/dist/quality-BADStsTn.d.ts +868 -0
  25. package/dist/react.d.ts +3 -2
  26. package/dist/render-environment.d.ts +170 -0
  27. package/dist/render-environment.js +352 -0
  28. package/dist/{renderer-DvFVoAgj.d.ts → renderer-BtOSseYf.d.ts} +29 -31
  29. package/dist/spells/index.js +1 -1
  30. package/dist/ui-layer.js +3 -2
  31. package/dist/worker.js +12 -5
  32. package/dist/world.d.ts +280 -16
  33. package/dist/world.js +1529 -642
  34. package/mcp/animation-server.mjs +1 -1
  35. package/mcp/engine-server.mjs +135 -11
  36. package/mcp/servers.mjs +4 -4
  37. package/package.json +10 -6
  38. package/scripts/ensure-mcp.mjs +6 -1
  39. package/src/animation-batch.ts +193 -0
  40. package/src/animation-layers.ts +7 -3
  41. package/src/animation.ts +209 -29
  42. package/src/asset-cache.ts +3 -3
  43. package/src/asset-memo.ts +202 -0
  44. package/src/assets.ts +436 -131
  45. package/src/auto-batch.ts +190 -44
  46. package/src/clustered-batch.ts +146 -3
  47. package/src/clustered-mesh.ts +548 -20
  48. package/src/compute-driven.ts +1 -1
  49. package/src/config.ts +8 -0
  50. package/src/debug.ts +119 -22
  51. package/src/dev-global.ts +54 -0
  52. package/src/displaced-surface.ts +428 -0
  53. package/src/engine-hooks.ts +37 -0
  54. package/src/frame-budget.ts +35 -3
  55. package/src/game-boot-phase.ts +269 -0
  56. package/src/game-dev-tools.ts +7 -14
  57. package/src/game-frame-loop.ts +45 -82
  58. package/src/game-startup.ts +145 -70
  59. package/src/game-ui.ts +84 -0
  60. package/src/game.ts +168 -552
  61. package/src/gamepad-mappings.ts +269 -0
  62. package/src/generated/console-markers.ts +14 -0
  63. package/src/geometry-capture.ts +28 -4
  64. package/src/gpu-readings.ts +98 -0
  65. package/src/gpu-scene-bvh.ts +149 -36
  66. package/src/grass-field.ts +628 -0
  67. package/src/hot.ts +4 -7
  68. package/src/index.ts +227 -8
  69. package/src/input.ts +237 -25
  70. package/src/instanced-batch-lod.ts +3 -8
  71. package/src/interpolation.ts +171 -40
  72. package/src/look/ao-admission.ts +4 -3
  73. package/src/look/auto-exposure.ts +5 -16
  74. package/src/look/default-tone-mapping.ts +41 -5
  75. package/src/look/local-exposure.ts +2 -7
  76. package/src/look/quad-pass.ts +21 -0
  77. package/src/look/quality.ts +4 -0
  78. package/src/look/unreal-bloom.ts +4 -13
  79. package/src/look/world-environment.ts +58 -115
  80. package/src/merge-parts.ts +20 -24
  81. package/src/model-lod.ts +97 -14
  82. package/src/particle-significance.ts +12 -0
  83. package/src/particles.ts +19 -10
  84. package/src/platform.ts +23 -4
  85. package/src/profiling/FrameStages.ts +5 -6
  86. package/src/profiling/Spans.ts +3 -17
  87. package/src/profiling/debug-telemetry.ts +2 -6
  88. package/src/profiling/render-list-validate.ts +6 -15
  89. package/src/projection-marker.ts +2 -1
  90. package/src/quiet-markers.ts +3 -10
  91. package/src/render/cpu-bvh.ts +100 -0
  92. package/src/render/depth-pyramid.ts +6 -14
  93. package/src/render/environment/environmentContribution.ts +202 -0
  94. package/src/render/environment/environmentRadiance.ts +44 -0
  95. package/src/render/environment/environmentSampleCache.ts +56 -0
  96. package/src/render/environment/environmentSampling.ts +201 -0
  97. package/src/render/environment/environmentSnapshot.ts +71 -0
  98. package/src/render/environment/gate.ts +57 -0
  99. package/src/render/material-key.ts +21 -1
  100. package/src/render/mesh-pool.ts +3 -19
  101. package/src/render/probe-trace.ts +872 -0
  102. package/src/render/probe-volume.ts +780 -34
  103. package/src/render/radiance-cache.ts +17 -0
  104. package/src/render/screen-probe-gather.ts +303 -0
  105. package/src/render/short-range-ao.ts +274 -0
  106. package/src/render/virtual-shadow-partial.ts +13 -0
  107. package/src/render/virtual-shadow.ts +18 -16
  108. package/src/render/world-impostor-surface.ts +207 -9
  109. package/src/render/world-impostor.ts +5 -2
  110. package/src/render-camera-cull.ts +105 -4
  111. package/src/render-environment.ts +41 -0
  112. package/src/renderer-config.ts +36 -0
  113. package/src/renderer-facts.ts +37 -0
  114. package/src/renderer.ts +78 -32
  115. package/src/resolution-scaler.ts +3 -2
  116. package/src/scatter-field.ts +496 -0
  117. package/src/scene-entry-inspectors.ts +61 -0
  118. package/src/snow-field.ts +1 -0
  119. package/src/startup-offscreen-bytes.ts +84 -0
  120. package/src/state.ts +16 -3
  121. package/src/static-transform.ts +100 -25
  122. package/src/streamed-textures.ts +112 -0
  123. package/src/streaming.ts +68 -4
  124. package/src/texture-streaming.ts +331 -0
  125. package/src/tile-ring.ts +294 -0
  126. package/src/version.ts +1 -1
  127. package/src/warmup.ts +15 -2
  128. package/src/worker.ts +12 -2
  129. package/src/world-bundle-safety.ts +55 -10
  130. package/src/world-cell-batches.ts +166 -200
  131. package/src/world-cell-chunks.ts +3 -7
  132. package/src/world-cell-data.ts +7 -0
  133. package/src/world-cell-impostors.ts +20 -8
  134. package/src/world-cell-models.ts +36 -8
  135. package/src/world-cell-options.ts +2 -14
  136. package/src/world-cell-placements.ts +194 -90
  137. package/src/world-cell-prewarm.ts +39 -4
  138. package/src/world-cell-records.ts +401 -0
  139. package/src/world-cell-render-bundles.ts +2 -2
  140. package/src/world-cell-render-gpu-dress.ts +17 -19
  141. package/src/world-cell-render-main-cull.ts +73 -17
  142. package/src/world-cell-render-util.ts +18 -5
  143. package/src/world-cell-render.ts +13 -5
  144. package/src/world-cell-residency.ts +15 -6
  145. package/src/world-cell-stale.ts +238 -0
  146. package/src/world-cells.ts +23 -6
  147. package/src/world-gpu-flags.ts +18 -50
  148. package/src/world-gpu-reference.ts +22 -8
  149. package/src/world-gpu-scene.ts +44 -24
  150. package/src/world-gpu-shadow.ts +21 -8
  151. package/src/world-gpu-types.ts +41 -13
  152. package/src/world-load-limiter.ts +5 -0
  153. package/src/world-model-sections.ts +80 -0
  154. package/src/world-river-ribbon.ts +273 -0
  155. package/src/world-root-frame.ts +39 -0
  156. package/src/world-shore-field.ts +91 -0
  157. package/src/world-static-pose.ts +163 -0
  158. package/src/world-surface-sampler.ts +48 -0
  159. package/src/world-terrain-splat.ts +10 -18
  160. package/src/world-tile-budget.ts +4 -11
  161. package/src/world-tiles.ts +79 -12
  162. package/src/world-validate.ts +6 -14
  163. package/src/world-warm.ts +51 -0
  164. package/src/world-water-bodies.ts +113 -3
  165. package/src/world.ts +13 -0
@@ -0,0 +1,201 @@
1
+ // Generated for you. A bounded source-radiance estimate, never a material/BRDF measurement.
2
+ import {
3
+ FloatType,
4
+ LinearSRGBColorSpace,
5
+ NoToneMapping,
6
+ RGBAFormat,
7
+ RenderTarget,
8
+ type Scene,
9
+ type ToneMapping,
10
+ } from "three";
11
+ import { texture, uv } from "three/tsl";
12
+ import { MeshBasicNodeMaterial, QuadMesh, type WebGPURenderer } from "three/webgpu";
13
+ import { type IEnvironmentMeasurement, measureEnvironment } from "./environmentContribution.js";
14
+ import { sampledRadiance } from "./environmentRadiance.js";
15
+ import { cacheEnvironmentSample, cachedEnvironmentSample } from "./environmentSampleCache.js";
16
+ import {
17
+ type IEnvironmentSourceSnapshot,
18
+ captureEnvironmentSnapshot,
19
+ environmentSnapshotCurrent,
20
+ samplingSourceSupported,
21
+ } from "./environmentSnapshot.js";
22
+ import {
23
+ type IMaterialLightingEnvironment,
24
+ isWebGLFallbackRenderer,
25
+ materialLightingEnabled,
26
+ } from "./gate.js";
27
+ export interface IEnvironmentSample extends IEnvironmentSourceSnapshot {
28
+ readonly measurement: IEnvironmentMeasurement;
29
+ }
30
+ /** Editable bound on asynchronous readback, independent of the engine startup deadline. */
31
+ const ENVIRONMENT_READBACK_TIMEOUT_MS = 1000;
32
+ const WIDTH = 64;
33
+ const HEIGHT = 32;
34
+ /**
35
+ * Measures and samples the scene's real environment on the GPU, bounded by a readback deadline.
36
+ *
37
+ * @situation measure what a scene's environment actually contributes without stalling the frame
38
+ * @situation give a material's fill light the environment's own radiance
39
+ * @constraint off unless the renderer is the admitted high-tier WebGPU lane; every refusal is reported by name
40
+ * @constraint the readback is abandoned after the deadline and the frame keeps the previous answer
41
+ * @example const sample = await sampleEnvironment(renderer, scene, env);
42
+ */
43
+ export async function sampleEnvironment(
44
+ renderer: unknown,
45
+ scene: Scene,
46
+ environment: IMaterialLightingEnvironment,
47
+ ): Promise<IEnvironmentSample> {
48
+ const snapshot = captureEnvironmentSnapshot(scene);
49
+ const { source, intensity } = snapshot;
50
+ const result = (measurement: IEnvironmentMeasurement): IEnvironmentSample => ({
51
+ ...snapshot,
52
+ measurement,
53
+ });
54
+ const unknown = (reason: string): IEnvironmentSample =>
55
+ result({ status: "unknown", meanRadiance: null, meanRGB: null, reason });
56
+ if (!materialLightingEnabled("high", environment) || isWebGLFallbackRenderer(renderer))
57
+ return unknown("Environment GPU sampling is unqualified on this platform/renderer.");
58
+ if (source === null) return result(measureEnvironment(scene, WIDTH * HEIGHT));
59
+ if (!samplingSourceSupported(source))
60
+ return unknown("Environment mapping/color-space is not qualified for the bounded GPU sample.");
61
+ if (!Number.isFinite(intensity) || intensity < 0)
62
+ return unknown("Environment intensity must be finite and nonnegative.");
63
+ if (!samplingRendererSupported(renderer))
64
+ return unknown("Raw Three.js renderer lacks the qualified sampling/readback methods.");
65
+ const raw = renderer as WebGPURenderer;
66
+ const cached = cachedEnvironmentSample(raw, scene);
67
+ if (cached !== undefined) return cached;
68
+ let state: {
69
+ target: ReturnType<WebGPURenderer["getRenderTarget"]>;
70
+ face: number;
71
+ mip: number;
72
+ toneMapping: ToneMapping;
73
+ colorSpace: string;
74
+ autoClear: boolean;
75
+ };
76
+ try {
77
+ state = {
78
+ target: raw.getRenderTarget(),
79
+ face: raw.getActiveCubeFace(),
80
+ mip: raw.getActiveMipmapLevel(),
81
+ toneMapping: raw.toneMapping,
82
+ colorSpace: raw.outputColorSpace,
83
+ autoClear: raw.autoClear,
84
+ };
85
+ } catch {
86
+ return unknown("Raw renderer state could not be saved; GPU sample skipped.");
87
+ }
88
+ const target = new RenderTarget(WIDTH, HEIGHT, {
89
+ type: FloatType,
90
+ format: RGBAFormat,
91
+ depthBuffer: false,
92
+ stencilBuffer: false,
93
+ });
94
+ target.texture.colorSpace = LinearSRGBColorSpace;
95
+ const material = new MeshBasicNodeMaterial();
96
+ material.toneMapped = false;
97
+ material.colorNode = texture(source, uv()).rgb;
98
+ const quad = new QuadMesh(material);
99
+ let pendingReadback: Promise<unknown> | undefined;
100
+ let readbackSettled = false;
101
+ let cleaned = false;
102
+ function cleanup(): void {
103
+ if (cleaned) return;
104
+ cleaned = true;
105
+ try {
106
+ material.dispose();
107
+ } finally {
108
+ target.dispose();
109
+ }
110
+ // QuadMesh geometry is shared and borrowed.
111
+ }
112
+ try {
113
+ try {
114
+ raw.toneMapping = NoToneMapping;
115
+ raw.outputColorSpace = LinearSRGBColorSpace;
116
+ raw.autoClear = true;
117
+ raw.setRenderTarget(target, 0, 0);
118
+ quad.render(raw);
119
+ pendingReadback = Promise.resolve(
120
+ raw.readRenderTargetPixelsAsync(target, 0, 0, WIDTH, HEIGHT),
121
+ ).then(
122
+ (value) => {
123
+ readbackSettled = true;
124
+ return value;
125
+ },
126
+ (error) => {
127
+ readbackSettled = true;
128
+ throw error;
129
+ },
130
+ );
131
+ } finally {
132
+ // No async gap while the shared renderer points at our scratch target.
133
+ try {
134
+ raw.setRenderTarget(state.target, state.face, state.mip);
135
+ } finally {
136
+ raw.toneMapping = state.toneMapping;
137
+ raw.outputColorSpace = state.colorSpace;
138
+ raw.autoClear = state.autoClear;
139
+ }
140
+ }
141
+ const outcome = await waitForReadback(pendingReadback);
142
+ if (outcome.timedOut)
143
+ return unknown(
144
+ `Environment GPU readback exceeded ${ENVIRONMENT_READBACK_TIMEOUT_MS} ms budget; scratch resources retained until readback settles.`,
145
+ );
146
+ const samples = outcome.samples;
147
+ if (!environmentSnapshotCurrent(scene, snapshot))
148
+ return unknown(
149
+ "Environment source/content/interpretation changed while GPU readback was pending; sample refused.",
150
+ );
151
+ const sampled = result(sampledRadiance(samples, intensity));
152
+ cacheEnvironmentSample(raw, scene, sampled);
153
+ return sampled;
154
+ } catch (error) {
155
+ return unknown(`Environment GPU sample/readback unavailable: ${String(error)}`);
156
+ } finally {
157
+ finishSampleCleanup(pendingReadback, readbackSettled, cleanup);
158
+ }
159
+ }
160
+
161
+ async function waitForReadback(
162
+ readback: Promise<unknown>,
163
+ ): Promise<{ timedOut: true } | { timedOut: false; samples: unknown }> {
164
+ let timer: ReturnType<typeof setTimeout> | undefined;
165
+ try {
166
+ return await Promise.race([
167
+ readback.then((samples) => ({ timedOut: false as const, samples })),
168
+ new Promise<{ timedOut: true }>((resolve) => {
169
+ timer = setTimeout(() => resolve({ timedOut: true }), ENVIRONMENT_READBACK_TIMEOUT_MS);
170
+ }),
171
+ ]);
172
+ } finally {
173
+ if (timer !== undefined) clearTimeout(timer);
174
+ }
175
+ }
176
+
177
+ function samplingRendererSupported(renderer: unknown): renderer is WebGPURenderer {
178
+ return (
179
+ renderer !== null &&
180
+ typeof renderer === "object" &&
181
+ Reflect.get(renderer, "isWebGPURenderer") === true &&
182
+ [
183
+ "render",
184
+ "getRenderTarget",
185
+ "getActiveCubeFace",
186
+ "getActiveMipmapLevel",
187
+ "setRenderTarget",
188
+ "readRenderTargetPixelsAsync",
189
+ ].every((name) => typeof Reflect.get(renderer, name) === "function")
190
+ );
191
+ }
192
+
193
+ function finishSampleCleanup(
194
+ readback: Promise<unknown> | undefined,
195
+ settled: boolean,
196
+ cleanup: () => void,
197
+ ): void {
198
+ // Timeout permits startup, but GPU work may still reference the target/material.
199
+ if (readback !== undefined && !settled) void readback.then(cleanup, cleanup);
200
+ else cleanup();
201
+ }
@@ -0,0 +1,71 @@
1
+ // Generated for you. Borrowed environment provenance for stale-readback rejection.
2
+ import {
3
+ EquirectangularReflectionMapping,
4
+ LinearSRGBColorSpace,
5
+ NoColorSpace,
6
+ SRGBColorSpace,
7
+ type Scene,
8
+ type Texture,
9
+ } from "three";
10
+ /** Provenance stays outside the printable measurement; source/image references are borrowed. */
11
+ export interface IEnvironmentSourceSnapshot {
12
+ readonly source: Texture | null;
13
+ readonly intensity: number;
14
+ readonly textureVersion: number | null;
15
+ readonly sourceVersion: number | null;
16
+ readonly colorSpace: string | null;
17
+ readonly mapping: number | null;
18
+ readonly image: unknown;
19
+ }
20
+ /**
21
+ * The provenance of a scene's environment: which texture, at which intensity, in which colour space.
22
+ *
23
+ * @situation reject an environment readback that belongs to a different sky
24
+ * @example const snapshot = captureEnvironmentSnapshot(scene);
25
+ */
26
+ export function captureEnvironmentSnapshot(scene: Scene): IEnvironmentSourceSnapshot {
27
+ const source = scene.environment;
28
+ return {
29
+ source,
30
+ intensity: scene.environmentIntensity,
31
+ textureVersion: source?.version ?? null,
32
+ sourceVersion: source?.source.version ?? null,
33
+ colorSpace: source?.colorSpace ?? null,
34
+ mapping: source?.mapping ?? null,
35
+ image: source?.image ?? null,
36
+ };
37
+ }
38
+ /**
39
+ * Whether the scene's environment still matches the snapshot a sample was taken from.
40
+ *
41
+ * @situation hold a material's fill light to the sky that is on screen now
42
+ * @example if (environmentSnapshotCurrent(scene, snapshot)) draw(snapshot);
43
+ */
44
+ export function environmentSnapshotCurrent(
45
+ scene: Scene,
46
+ snapshot: IEnvironmentSourceSnapshot,
47
+ ): boolean {
48
+ const source = scene.environment;
49
+ return (
50
+ source === snapshot.source &&
51
+ scene.environmentIntensity === snapshot.intensity &&
52
+ (source?.version ?? null) === snapshot.textureVersion &&
53
+ (source?.source.version ?? null) === snapshot.sourceVersion &&
54
+ (source?.colorSpace ?? null) === snapshot.colorSpace &&
55
+ (source?.mapping ?? null) === snapshot.mapping &&
56
+ (source?.image ?? null) === snapshot.image
57
+ );
58
+ }
59
+
60
+ /**
61
+ * Whether an environment texture's mapping and colour space are qualified for the bounded GPU sample.
62
+ *
63
+ * @situation know why an environment was not sampled on the GPU
64
+ * @example if (samplingSourceSupported(source)) sample(source);
65
+ */
66
+ export function samplingSourceSupported(source: NonNullable<Scene["environment"]>): boolean {
67
+ return (
68
+ source.mapping === EquirectangularReflectionMapping &&
69
+ new Set<string>([NoColorSpace, LinearSRGBColorSpace, SRGBColorSpace]).has(source.colorSpace)
70
+ );
71
+ }
@@ -0,0 +1,57 @@
1
+ /**
2
+ * Which renderers may run the material-lighting lane, and whether a renderer is running three's
3
+ * WebGL backend behind a WebGPU wrapper.
4
+ *
5
+ * Both questions are asked by the environment sampling mechanism beside this file, and both were
6
+ * answered in each template's `quality.ts` — twelve copies of the same predicate, so a fix to one
7
+ * left eleven kits admitting a renderer the fix refused. The tier they compare is the caller's, so
8
+ * a game that wants a different admission rule passes its own tier; nothing here decides how
9
+ * anything looks.
10
+ */
11
+ import type { QualityTier } from "../../look/quality.js";
12
+
13
+ /** First admitted material lane: high desktop hardware WebGPU in the browser only. */
14
+ export interface IMaterialLightingEnvironment {
15
+ readonly web: boolean;
16
+ readonly rendererKind: string;
17
+ readonly mobile?: boolean;
18
+ readonly software?: boolean;
19
+ readonly webglFallback?: boolean;
20
+ }
21
+
22
+ /**
23
+ * Whether `tier` may run the material-lighting lane in `environment`.
24
+ *
25
+ * @situation decide whether this renderer is the admitted material lane
26
+ * @constraint high tier, browser, hardware WebGPU, not mobile, not software, not a WebGL fallback
27
+ * @example if (materialLightingEnabled("high", env)) lightMaterials();
28
+ */
29
+ export function materialLightingEnabled(
30
+ tier: QualityTier,
31
+ environment: IMaterialLightingEnvironment,
32
+ ): boolean {
33
+ return (
34
+ tier === "high" &&
35
+ environment.web &&
36
+ environment.rendererKind === "webgpu" &&
37
+ environment.mobile !== true &&
38
+ environment.software !== true &&
39
+ environment.webglFallback !== true
40
+ );
41
+ }
42
+
43
+ /**
44
+ * Whether a `WebGPURenderer` wrapper is running three's WebGL backend behind it.
45
+ *
46
+ * @situation refuse a GPU-only lane on a WebGL fallback instead of drawing something wrong
47
+ * @example if (isWebGLFallbackRenderer(renderer)) skipMaterialLane();
48
+ */
49
+ export function isWebGLFallbackRenderer(renderer: unknown): boolean {
50
+ if (renderer === null || typeof renderer !== "object") return false;
51
+ const backend = Reflect.get(renderer, "backend");
52
+ return (
53
+ backend !== null &&
54
+ typeof backend === "object" &&
55
+ Reflect.get(backend, "isWebGLBackend") === true
56
+ );
57
+ }
@@ -16,11 +16,31 @@ const TEXTURE_SLOTS = [
16
16
  "alphaMap",
17
17
  ] as const;
18
18
 
19
+ /** Ids for unnamed textures whose source carries no `uuid` (the owned engine's), one per texture. */
20
+ const unnamedIds = new WeakMap<Texture, number>();
21
+ let nextUnnamedId = 0;
22
+
23
+ /** The texture's own source identity: three's source `uuid`, else a per-texture id from this module. */
24
+ function sourceId(texture: Texture): string {
25
+ const uuid = (texture.source as { uuid?: string } | undefined)?.uuid;
26
+ if (uuid !== undefined) return uuid;
27
+ let id = unnamedIds.get(texture);
28
+ if (id === undefined) {
29
+ id = nextUnnamedId++;
30
+ unnamedIds.set(texture, id);
31
+ }
32
+ return `#${String(id)}`;
33
+ }
34
+
19
35
  function textureKey(texture: Texture | null | undefined): string {
20
36
  if (texture === null || texture === undefined) return "-";
21
37
  const image = texture.image as { width?: number; height?: number } | undefined;
22
38
  const mips = (texture as { mipmaps?: readonly { data?: { byteLength?: number } }[] }).mipmaps;
23
- return `${texture.name}:${String(image?.width ?? 0)}x${String(image?.height ?? 0)}:${String(mips?.[0]?.data?.byteLength ?? 0)}:${texture.flipY ? 1 : 0}`;
39
+ // A name is what lets two loads of one image match. Without one, nothing here tells two images of
40
+ // one size apart (generated leaf atlases are all 1024², unnamed, with no mip bytes), so the
41
+ // texture's own source is its identity: it never shares, and never draws another's pixels.
42
+ const id = texture.name !== "" ? texture.name : `source:${sourceId(texture)}`;
43
+ return `${id}:${String(image?.width ?? 0)}x${String(image?.height ?? 0)}:${String(mips?.[0]?.data?.byteLength ?? 0)}:${texture.flipY ? 1 : 0}`;
24
44
  }
25
45
 
26
46
  /**
@@ -1,4 +1,5 @@
1
1
  import { type BufferGeometry, InstancedMesh, type Material } from "three";
2
+ import { batchRecords } from "../world-cell-records.js";
2
3
 
3
4
  /**
4
5
  * A pool of parked `InstancedMesh`es, keyed by the parts they draw.
@@ -17,23 +18,6 @@ export const MESH_POOL_MAX_PER_PAIR = 8;
17
18
  /** Parked meshes across every pair, so a walk's back-traffic cannot grow without bound. */
18
19
  export const MESH_POOL_MAX_HELD = 512;
19
20
 
20
- /**
21
- * The `update` the pending upload spans belong to; moved once per `WorldCells.update`, which is the
22
- * frame boundary a render's upload falls between. Module-level like the pool above, because there is
23
- * one world drawing at a time.
24
- */
25
- let writeEpoch = 0;
26
-
27
- /** The upload epoch a batch's pending span belongs to; see `advanceWriteEpoch`. */
28
- export function currentWriteEpoch(): number {
29
- return writeEpoch;
30
- }
31
-
32
- /** Starts the next upload epoch, so no batch's pending span outlives the render that consumed it. */
33
- export function advanceWriteEpoch(): void {
34
- writeEpoch += 1;
35
- }
36
-
37
21
  /** geometry -> material -> parked meshes, biggest last. */
38
22
  const meshPool = new Map<BufferGeometry, Map<Material, InstancedMesh[]>>();
39
23
  let meshPoolHeld = 0;
@@ -97,8 +81,8 @@ export function parkMesh(mesh: InstancedMesh): boolean {
97
81
  mesh.frustumCulled = false;
98
82
  mesh.castShadow = false;
99
83
  mesh.receiveShadow = false;
100
- mesh.instanceMatrix.array.fill(0);
101
- mesh.instanceMatrix.needsUpdate = true;
84
+ batchRecords.fill(mesh.instanceMatrix, 0, mesh.instanceMatrix.count * 16);
85
+ batchRecords.upload(mesh.instanceMatrix, 0, 0);
102
86
  let forGeometry = meshPool.get(mesh.geometry);
103
87
  if (forGeometry === undefined) {
104
88
  forGeometry = new Map();