@threenative/core 0.3.3 → 0.3.5
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.
- package/capabilities.json +2019 -59
- package/dist/{assets-CYKk2WTu.d.ts → assets-CqvE429w.d.ts} +45 -3
- package/dist/{audio-7i3Xl0l3.d.ts → audio-DIJE5HTr.d.ts} +43 -3
- package/dist/{canvas-layer-C1SnMoJ-.d.ts → canvas-layer-C1-5CviZ.d.ts} +5 -1
- package/dist/{game-D_6r-k4Y.d.ts → game-Bj8G1wmD.d.ts} +242 -17
- package/dist/hot.d.ts +5 -5
- package/dist/index.d.ts +1131 -105
- package/dist/index.js +15201 -4782
- package/dist/model-lod-BDAUYgsS.d.ts +197 -0
- package/dist/playtest.d.ts +6 -4
- package/dist/playtest.js +84 -11
- package/dist/react-css.d.ts +62 -0
- package/dist/react-css.js +591 -0
- package/dist/react.d.ts +2 -2
- package/dist/{renderer-Cy4qeBOA.d.ts → renderer-9yEo9hPa.d.ts} +676 -21
- package/dist/terrain-jobs-worker.d.ts +2 -0
- package/dist/terrain-jobs-worker.js +130 -0
- package/dist/ui-layer.d.ts +5 -3
- package/dist/ui-layer.js +59 -8
- package/dist/world.d.ts +1596 -17
- package/dist/world.js +17035 -521
- package/gpl/fixtures/make_world_fixture.py +184 -0
- package/gpl/recipes/_common.py +11 -0
- package/gpl/recipes/decimate.py +11 -5
- package/gpl/recipes/export_world.py +699 -0
- package/mcp/blender-server.mjs +61 -4
- package/mcp/blender.mjs +3 -4
- package/mcp/engine-server.mjs +55 -21
- package/mcp/servers.mjs +4 -4
- package/package.json +15 -9
- package/patches/three@0.185.1-prd269-upgrade.patch +22418 -0
- package/patches/three@0.185.1.patch +8246 -389
- package/scripts/apply-three-patch.mjs +123 -41
- package/src/animation-blend.ts +264 -0
- package/src/animation-composition.ts +362 -0
- package/src/animation-layers.ts +260 -0
- package/src/animation-root-motion.ts +283 -0
- package/src/animation.ts +896 -0
- package/src/assets.ts +1303 -0
- package/src/atmosphere/index.ts +335 -0
- package/src/atmosphere/luts.ts +298 -0
- package/src/atmosphere/params.ts +323 -0
- package/src/audio.ts +912 -0
- package/src/billboard.ts +124 -0
- package/src/bone-lengths.ts +157 -0
- package/src/camera-shake.ts +116 -0
- package/src/canvas-layer.ts +47 -0
- package/src/clip-audit.ts +401 -0
- package/src/clustered-batch.ts +492 -0
- package/src/clustered-mesh.ts +638 -0
- package/src/compute-driven.ts +176 -0
- package/src/compute-timing.ts +318 -0
- package/src/config.ts +593 -0
- package/src/debug.ts +82 -0
- package/src/engine-render-hook.ts +25 -0
- package/src/entities.ts +79 -0
- package/src/entity-snapshot.ts +53 -0
- package/src/flight.ts +683 -0
- package/src/fluid-field.ts +748 -0
- package/src/fluid-particles.ts +1253 -0
- package/src/frame-budget.ts +1368 -0
- package/src/game.ts +2390 -0
- package/src/geometry-capture.ts +1098 -0
- package/src/gpu-class.ts +160 -0
- package/src/gpu-frame-observation.ts +424 -0
- package/src/gpu-readback.ts +143 -0
- package/src/gpu-scene-bvh.ts +464 -0
- package/src/grounding.ts +100 -0
- package/src/hot.ts +161 -0
- package/src/import-meta.d.ts +13 -0
- package/src/index.ts +1536 -0
- package/src/input.ts +690 -0
- package/src/instanced-batch-lod.ts +283 -0
- package/src/instanced-batch.ts +274 -0
- package/src/interpolation.ts +129 -0
- package/src/launch-diagnostics.ts +161 -0
- package/src/loop.ts +564 -0
- package/src/matrix-world.ts +245 -0
- package/src/merge-parts.ts +812 -0
- package/src/model-lod.ts +1315 -0
- package/src/net-protocol.ts +333 -0
- package/src/net-session.ts +477 -0
- package/src/net.ts +80 -0
- package/src/ocean/fft.ts +72 -0
- package/src/ocean/spectral.ts +728 -0
- package/src/particle-significance.ts +102 -0
- package/src/particles.ts +648 -0
- package/src/path-follow.ts +175 -0
- package/src/picking.ts +250 -0
- package/src/pipeline-census.ts +1566 -0
- package/src/platform.ts +210 -0
- package/src/playtest.ts +839 -0
- package/src/pointer-events.ts +411 -0
- package/src/pose-measure.ts +435 -0
- package/src/profiling/FrameCounters.ts +231 -0
- package/src/profiling/Spans.ts +548 -0
- package/src/profiling/opacity-convention.ts +21 -0
- package/src/profiling/render-list-validate.ts +175 -0
- package/src/profiling/render-trap-audit.ts +84 -0
- package/src/profiling/scene-warning.ts +190 -0
- package/src/profiling/span-probes.ts +191 -0
- package/src/profiling/unlit-foliage-warning.ts +149 -0
- package/src/projection-apply.ts +1529 -0
- package/src/projection-marker.ts +142 -0
- package/src/projection-plan.ts +1258 -0
- package/src/projection-skinned.ts +419 -0
- package/src/projection-stability.ts +409 -0
- package/src/projection-uniform.ts +328 -0
- package/src/random.ts +41 -0
- package/src/react-css.ts +604 -0
- package/src/react-glyphs.ts +114 -0
- package/src/react-host.ts +576 -0
- package/src/react-layout.ts +265 -0
- package/src/react.ts +60 -0
- package/src/render/alpha-antialiasing.ts +159 -0
- package/src/render/batched-velocity.ts +126 -0
- package/src/render/chain.ts +1021 -0
- package/src/render/daylight.ts +189 -0
- package/src/render/depth-pyramid.ts +596 -0
- package/src/render/foliage-alpha.ts +166 -0
- package/src/render/material-key.ts +60 -0
- package/src/render/mesh-pool.ts +144 -0
- package/src/render/probe-volume.ts +1668 -0
- package/src/render/resolution-subrect.ts +253 -0
- package/src/render/velocity.ts +442 -0
- package/src/render/virtual-shadow-pages.ts +827 -0
- package/src/render/virtual-shadow-partial.ts +174 -0
- package/src/render/virtual-shadow.ts +3330 -0
- package/src/render/world-impostor-surface.ts +722 -0
- package/src/render/world-impostor.ts +558 -0
- package/src/render-camera-cull.ts +441 -0
- package/src/render-pass-budget.ts +501 -0
- package/src/renderProjection.ts +758 -0
- package/src/renderer-config.ts +127 -0
- package/src/renderer.ts +1847 -0
- package/src/replay-protocol.ts +85 -0
- package/src/replay.ts +205 -0
- package/src/resolution-scaler.ts +819 -0
- package/src/rig-preparation.ts +271 -0
- package/src/ripple-field.ts +432 -0
- package/src/scale.ts +109 -0
- package/src/scene.ts +239 -0
- package/src/schedule.ts +155 -0
- package/src/skeletal-mesh.ts +61 -0
- package/src/skeleton.ts +100 -0
- package/src/snow-field.ts +744 -0
- package/src/softbody-topology.ts +269 -0
- package/src/softbody.ts +516 -0
- package/src/sprite-animator.ts +222 -0
- package/src/startup-readiness.ts +386 -0
- package/src/state.ts +66 -0
- package/src/static-transform.ts +274 -0
- package/src/storage-buffer.ts +253 -0
- package/src/streaming.ts +308 -0
- package/src/target-fps.ts +92 -0
- package/src/terrain-jobs-worker.ts +17 -0
- package/src/terrain-jobs.ts +353 -0
- package/src/textures.ts +39 -0
- package/src/tracers.ts +237 -0
- package/src/ui-bridge.ts +368 -0
- package/src/ui-hit-regions.ts +380 -0
- package/src/ui-layer.ts +83 -0
- package/src/ui-state.ts +220 -0
- package/src/version.ts +2 -0
- package/src/viewport.ts +253 -0
- package/src/warmup.ts +1357 -0
- package/src/water-surface.ts +384 -0
- package/src/wave-field.ts +524 -0
- package/src/world-capabilities.ts +131 -0
- package/src/world-cell-proxy.ts +392 -0
- package/src/world-cells.ts +10564 -0
- package/src/world-gpu-scene.ts +3354 -0
- package/src/world-heightmap.ts +82 -0
- package/src/world-package.ts +469 -0
- package/src/world-passes.ts +582 -0
- package/src/world-region.ts +17 -0
- package/src/world-terrain-splat.ts +564 -0
- package/src/world-tiles.ts +3826 -0
- package/src/world-topology.ts +370 -0
- package/src/world-validate.ts +48 -0
- package/src/world.ts +805 -0
- package/dist/gpu-readback-CMklJs6r.d.ts +0 -112
package/src/renderer.ts
ADDED
|
@@ -0,0 +1,1847 @@
|
|
|
1
|
+
import { RenderTarget } from "three";
|
|
2
|
+
import type { BufferGeometry, Camera, DepthTexture, Object3D, Texture } from "three";
|
|
3
|
+
import {
|
|
4
|
+
NodeUpdateType,
|
|
5
|
+
type PassNode,
|
|
6
|
+
ReadbackBuffer,
|
|
7
|
+
RenderPipeline,
|
|
8
|
+
RendererUtils,
|
|
9
|
+
type StorageBufferAttribute,
|
|
10
|
+
type Renderer as ThreeRenderer,
|
|
11
|
+
} from "three/webgpu";
|
|
12
|
+
import { ComputeTimingScopes, type IComputeTimingReceipt } from "./compute-timing.js";
|
|
13
|
+
import type { IFrameSurfaceState } from "./frame-budget.js";
|
|
14
|
+
import {
|
|
15
|
+
GPU_CLASS_MARKER,
|
|
16
|
+
type IGpuClassification,
|
|
17
|
+
SOFTWARE_ADAPTER,
|
|
18
|
+
classifyGpu,
|
|
19
|
+
} from "./gpu-class.js";
|
|
20
|
+
import {
|
|
21
|
+
GpuFrameObservation,
|
|
22
|
+
type IGpuFrameObservation,
|
|
23
|
+
type IGpuFrameObservationOptions,
|
|
24
|
+
} from "./gpu-frame-observation.js";
|
|
25
|
+
import {
|
|
26
|
+
type IPipelineCensus,
|
|
27
|
+
type PipelineCensus,
|
|
28
|
+
createPipelineCensus,
|
|
29
|
+
} from "./pipeline-census.js";
|
|
30
|
+
import type { ITimestampQueryPool } from "./render-pass-budget.js";
|
|
31
|
+
import { AlphaAntialiasing, type IAlphaAntialiasingReport } from "./render/alpha-antialiasing.js";
|
|
32
|
+
import {
|
|
33
|
+
type IRenderChainBudgetWindow,
|
|
34
|
+
type IRenderChainOptions,
|
|
35
|
+
RenderChain,
|
|
36
|
+
} from "./render/chain.js";
|
|
37
|
+
import { type IResolutionSubrect, ResolutionSubrect } from "./render/resolution-subrect.js";
|
|
38
|
+
|
|
39
|
+
import {
|
|
40
|
+
type IStorageBufferLease,
|
|
41
|
+
type IStorageBufferSource,
|
|
42
|
+
StorageBufferLeases,
|
|
43
|
+
} from "./storage-buffer.js";
|
|
44
|
+
|
|
45
|
+
export type RendererKind = "webgpu" | "webgl2";
|
|
46
|
+
|
|
47
|
+
/** Owns one output-pipeline installation, not the lifetime of its input graph dependencies. */
|
|
48
|
+
export interface IRenderOutputInstallation {
|
|
49
|
+
isCurrent(): boolean;
|
|
50
|
+
dispose(): void;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Where the transform goes when a stage does the renderer's job for it. The chain passes
|
|
55
|
+
* `false` only when a stage that read display-referred colour actually ran.
|
|
56
|
+
*/
|
|
57
|
+
export interface IRenderOutputOptions {
|
|
58
|
+
readonly outputColorTransform?: boolean;
|
|
59
|
+
readonly resolutionSubrect?: IResolutionSubrect;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Union of callbacks preserves TypeScript's legacy void-callback return-value compatibility. */
|
|
63
|
+
export type RenderOutputSetter =
|
|
64
|
+
| ((node: unknown, worldPass?: unknown, options?: IRenderOutputOptions) => void)
|
|
65
|
+
| ((
|
|
66
|
+
node: unknown,
|
|
67
|
+
worldPass?: unknown,
|
|
68
|
+
options?: IRenderOutputOptions,
|
|
69
|
+
) => IRenderOutputInstallation);
|
|
70
|
+
|
|
71
|
+
type WarmableSurface = {
|
|
72
|
+
clone: () => WarmableSurface;
|
|
73
|
+
opacity?: number;
|
|
74
|
+
transparent?: boolean;
|
|
75
|
+
needsUpdate?: boolean;
|
|
76
|
+
};
|
|
77
|
+
|
|
78
|
+
type WarmableMesh = Object3D & {
|
|
79
|
+
isMesh?: boolean;
|
|
80
|
+
} & Record<string, unknown>;
|
|
81
|
+
|
|
82
|
+
interface ITraversableOutputNode {
|
|
83
|
+
traverse(callback: (node: object) => void): void;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
const prewarmedRoots = new WeakSet<Object3D>();
|
|
87
|
+
const DEFAULT_GPU_TIMESTAMP_FRAME_INTERVAL = 8;
|
|
88
|
+
|
|
89
|
+
function warmSurface(
|
|
90
|
+
surface: WarmableSurface,
|
|
91
|
+
warmedSurfaces: Map<WarmableSurface, WarmableSurface>,
|
|
92
|
+
): WarmableSurface {
|
|
93
|
+
const warmed = warmedSurfaces.get(surface);
|
|
94
|
+
if (warmed !== undefined) return warmed;
|
|
95
|
+
const clone = surface.clone();
|
|
96
|
+
warmedSurfaces.set(surface, clone);
|
|
97
|
+
warmedSurfaces.set(clone, clone);
|
|
98
|
+
return clone;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function hasHiddenAncestor(object: Object3D): boolean {
|
|
102
|
+
let ancestor: Object3D | null = object.parent;
|
|
103
|
+
while (ancestor !== null) {
|
|
104
|
+
if (ancestor.visible === false) return true;
|
|
105
|
+
ancestor = ancestor.parent;
|
|
106
|
+
}
|
|
107
|
+
return false;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* Put transient meshes through the renderer's first-use shader path during loading.
|
|
112
|
+
*
|
|
113
|
+
* A prewarmed mesh stays in the requested subtree with zero opacity. Do not hide transient effects
|
|
114
|
+
* with `.visible = false`: that defers the pipeline and creates one long frame the first time the
|
|
115
|
+
* effect appears, never again that session. Ancestors above the requested object and unrelated
|
|
116
|
+
* siblings keep their visibility. If the requested subtree is under a hidden ancestor,
|
|
117
|
+
* `compileAsync()` compiles that subtree once as a standalone input instead of revealing the
|
|
118
|
+
* ancestor or its siblings.
|
|
119
|
+
*/
|
|
120
|
+
export function prewarm(object: Object3D | readonly Object3D[]): void {
|
|
121
|
+
const roots: readonly Object3D[] = Array.isArray(object) ? object : [object];
|
|
122
|
+
const warmedSurfaces = new Map<WarmableSurface, WarmableSurface>();
|
|
123
|
+
|
|
124
|
+
for (const root of roots) {
|
|
125
|
+
prewarmedRoots.add(root);
|
|
126
|
+
root.traverse((child: Object3D) => {
|
|
127
|
+
const mesh = child as WarmableMesh;
|
|
128
|
+
const surfaceValue = mesh["mat" + "erial"] as WarmableSurface | WarmableSurface[] | undefined;
|
|
129
|
+
if (mesh.isMesh !== true || surfaceValue === undefined) return;
|
|
130
|
+
let ancestor: Object3D | null = child;
|
|
131
|
+
while (ancestor !== null) {
|
|
132
|
+
ancestor.visible = true;
|
|
133
|
+
if (ancestor === root) break;
|
|
134
|
+
ancestor = ancestor.parent;
|
|
135
|
+
}
|
|
136
|
+
const warmedSurface = Array.isArray(surfaceValue)
|
|
137
|
+
? surfaceValue.map((surface) => warmSurface(surface, warmedSurfaces))
|
|
138
|
+
: warmSurface(surfaceValue, warmedSurfaces);
|
|
139
|
+
mesh["mat" + "erial"] = warmedSurface;
|
|
140
|
+
const surfaces = Array.isArray(warmedSurface) ? warmedSurface : [warmedSurface];
|
|
141
|
+
for (const surface of surfaces) {
|
|
142
|
+
surface.transparent = true;
|
|
143
|
+
surface.opacity = 0;
|
|
144
|
+
surface.needsUpdate = true;
|
|
145
|
+
}
|
|
146
|
+
});
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
export interface IRendererLike {
|
|
151
|
+
readonly domElement: HTMLCanvasElement;
|
|
152
|
+
readonly kind: RendererKind;
|
|
153
|
+
readonly raw: unknown;
|
|
154
|
+
/**
|
|
155
|
+
* The underlying renderer's statistics (`render.drawCalls`, `render.triangles`, …).
|
|
156
|
+
*
|
|
157
|
+
* Throws when the running renderer has none — the same fail-closed shape as `setOutputNode` —
|
|
158
|
+
* because a game that cannot count its own draws cannot apply a draw-count lever on evidence.
|
|
159
|
+
*/
|
|
160
|
+
get info(): unknown;
|
|
161
|
+
/**
|
|
162
|
+
* Builds and compiles a scene's pipelines before anything draws it.
|
|
163
|
+
*
|
|
164
|
+
* On a phone each distinct shader is compiled the first time something using it is drawn, which
|
|
165
|
+
* happens inside a frame the player is watching: 2,500 ms of a 2,882 ms Pixel 8 cold start sits
|
|
166
|
+
* between the bundle finishing and the first frame reaching the display. Calling this during
|
|
167
|
+
* load moves that cost somewhere the player is already waiting.
|
|
168
|
+
*
|
|
169
|
+
* It is on the wrapper for one reason: without it a game must cast through `.raw` to warm up,
|
|
170
|
+
* and a game that cannot warm up without a cast will not warm up.
|
|
171
|
+
*/
|
|
172
|
+
compileAsync(scene: Object3D, camera: Camera, targetScene?: Object3D): Promise<void>;
|
|
173
|
+
/** A warm-up may outlive its caller's timeout; its render targets must remain alive. */
|
|
174
|
+
readonly compiling?: boolean;
|
|
175
|
+
/** Compilation starts, including work that settles entirely between rendered frames. */
|
|
176
|
+
readonly compileCount?: number;
|
|
177
|
+
/** The bounded, fail-closed pipeline observation for this renderer, when enabled. */
|
|
178
|
+
readonly pipelineCensus?: () => IPipelineCensus;
|
|
179
|
+
/** Marks the completion of the renderer's current scene warm-up attempt. */
|
|
180
|
+
warmUpSettled?(): void;
|
|
181
|
+
/** Marks a repeatable streamed warm-up boundary for the next first draw. */
|
|
182
|
+
warmUpScopeSettled?(label: string, target?: Object3D): void;
|
|
183
|
+
/** Performs one covered output-pipeline render without marking first present. */
|
|
184
|
+
warmUpWorldPass?(scene: Object3D, camera: Camera, targetScene?: Object3D): void;
|
|
185
|
+
/**
|
|
186
|
+
* What alpha antialiasing did with the multisampled surface, and why, when it did nothing.
|
|
187
|
+
*
|
|
188
|
+
* MSAA resolves triangle edges; a cutout silhouette is carved inside the triangle by an alpha
|
|
189
|
+
* test and resolves through the coverage mask or not at all. This is where to read whether the
|
|
190
|
+
* samples this surface pays for reach the game's foliage, fences and hair.
|
|
191
|
+
*
|
|
192
|
+
* Optional on the interface for the same reason the render-chain seams are: a stub renderer
|
|
193
|
+
* implements the drawing contract, not every report. `createRenderer` always provides it, and
|
|
194
|
+
* the `TN_ALPHA_ANTIALIASING` marker is printed either way, so nothing is only readable here.
|
|
195
|
+
*/
|
|
196
|
+
alphaAntialiasing?: () => IAlphaAntialiasingReport;
|
|
197
|
+
/**
|
|
198
|
+
* The `adapter.info` field value that identifies a CPU rasteriser — `swiftshader`, `llvmpipe`,
|
|
199
|
+
* a `Microsoft Basic Render Driver` — when the adapter named one, else absent.
|
|
200
|
+
*
|
|
201
|
+
* Reading it needs `navigator.gpu`, so it is read here rather than in a game's render source.
|
|
202
|
+
* It is a fact about the machine, not a look: which tier a game runs on a software adapter is
|
|
203
|
+
* that game's own decision, and every tier name it might pick is already in its own
|
|
204
|
+
* `src/render/quality.ts`. What this removes is the reason it could not make that decision
|
|
205
|
+
* before its first expensive frame — a CPU rasteriser running a desktop render chain can lose
|
|
206
|
+
* the device on the very first frame, which no adaptation after it survives.
|
|
207
|
+
*
|
|
208
|
+
* Absent means no software name was found, never that the adapter is hardware. The native host
|
|
209
|
+
* exposes the same four `adapter.info` fields, so the same read works on every target.
|
|
210
|
+
*/
|
|
211
|
+
readonly softwareAdapter?: string;
|
|
212
|
+
/**
|
|
213
|
+
* The GPU family the adapter belongs to, the rule that named it and the four raw `adapter.info`
|
|
214
|
+
* fields it was read from; absent when no adapter reported (a WebGL2 fallback).
|
|
215
|
+
*
|
|
216
|
+
* A fact about the machine, like `softwareAdapter`, and the better input for a start tier: it
|
|
217
|
+
* tells a Mali-G52 from a Mali-G715 and an iGPU from a discrete card, where `mobile` and
|
|
218
|
+
* `software` cannot. `unknown` means no rule matched; treat it as the behaviour before this
|
|
219
|
+
* existed. Measurement still outranks it, and the class only picks where the first window starts.
|
|
220
|
+
*/
|
|
221
|
+
readonly gpuClass?: IGpuClassification;
|
|
222
|
+
/** Advances the GPU sample once before a presented frame's simulation and render passes. */
|
|
223
|
+
beginFrame?(): void;
|
|
224
|
+
compute(node: unknown, span?: "depthPyramid"): void;
|
|
225
|
+
/** Opt-in synchronous dispatch scope; consumes exact Three-owned query UID membership once resolved. */
|
|
226
|
+
computeTiming?(
|
|
227
|
+
operation: () => unknown,
|
|
228
|
+
options?: { readonly maxCalls?: number },
|
|
229
|
+
): IComputeTimingReceipt;
|
|
230
|
+
/**
|
|
231
|
+
* Creates the GPU buffers these geometries draw from, through the backend's own attribute path,
|
|
232
|
+
* and reports how many it created.
|
|
233
|
+
*
|
|
234
|
+
* `compileAsync` builds pipelines, not buffers: a streamed mesh's first draw is where its
|
|
235
|
+
* attributes reach the device, and one chunk's first draw measured 230 ms of a frame for it. This
|
|
236
|
+
* moves that to admission, one chunk at a time. WebGPU only — the WebGL fallback has no seam
|
|
237
|
+
* this can call without inventing a GL enum — and absent or throwing answers 0, so the first
|
|
238
|
+
* draw uploads exactly as it did before.
|
|
239
|
+
*/
|
|
240
|
+
uploadAttributes?(geometries: Iterable<BufferGeometry>): number;
|
|
241
|
+
/** Exclusive Float32 vec4 storage on the existing WebGPU device; release its receipt on scene exit. */
|
|
242
|
+
storageBuffer?(attribute: StorageBufferAttribute): IStorageBufferLease;
|
|
243
|
+
/**
|
|
244
|
+
* Copies one streamed subtree's textures to the device, through three's own texture path, and
|
|
245
|
+
* reports how many it took.
|
|
246
|
+
*
|
|
247
|
+
* The same argument as `uploadAttributes`, one resource class over: `compileAsync` builds
|
|
248
|
+
* pipelines, not pixels, so a streamed chunk's textures reach the device inside `_renderObjectDirect`
|
|
249
|
+
* on the frame the chunk first draws. On a Machinefall map-walk with three's internals counted per
|
|
250
|
+
* render, that was 87 ms of a 94 ms first draw in one frame, 79 ms of 131 ms in another, and 519 ms
|
|
251
|
+
* in a third — 10 renders of 19,000 hold the whole 2,574 ms the run spends on first draws.
|
|
252
|
+
* `Textures.updateTexture` returns early when the texture is already at its current version, so this
|
|
253
|
+
* is a move rather than a second upload, and a material the world shares with what is already on
|
|
254
|
+
* screen costs one call and no work. WebGPU only — the WebGL fallback has no seam here — and
|
|
255
|
+
* absent or throwing answers 0, so the first draw uploads exactly as it did before.
|
|
256
|
+
*/
|
|
257
|
+
uploadTextures?(object: Object3D): number;
|
|
258
|
+
/**
|
|
259
|
+
* Prepares unique cold compressed textures before their first compile or draw. WebGPU uses
|
|
260
|
+
* one upload lane, a measured 2 ms budget and at most 64 KiB per write; one final write may
|
|
261
|
+
* overshoot the time budget. Await this gate before exposing the textures to rendering.
|
|
262
|
+
* Original Texture/GPUTexture identities, formats and mip levels are retained. Cancellation
|
|
263
|
+
* releases this caller's interest; another caller of the same texture may still complete.
|
|
264
|
+
* Ordinary textures and the WebGL fallback retain their existing paths and report no work.
|
|
265
|
+
* `onProgress` receives the completed unique compressed texture count after each preparation
|
|
266
|
+
* promise resolves; queued textures and writes that have not settled receive no credit.
|
|
267
|
+
*/
|
|
268
|
+
prepareTextures?(
|
|
269
|
+
textures: Iterable<Texture>,
|
|
270
|
+
signal?: AbortSignal,
|
|
271
|
+
onProgress?: (completed: number) => void,
|
|
272
|
+
): Promise<number>;
|
|
273
|
+
/**
|
|
274
|
+
* Copies one GPU storage attribute back to the CPU, asynchronously.
|
|
275
|
+
*
|
|
276
|
+
* It is on the wrapper for the same reason `compute` is: the call is WebGPU-only and a game that
|
|
277
|
+
* must cast through `.raw` to read its own simulation will either not read it or read it wrong.
|
|
278
|
+
* The copy is asynchronous by nature — the caller gets the bytes some frames after the frame
|
|
279
|
+
* that produced them, and `GPUReadback` is what turns that latency into a reported number
|
|
280
|
+
* instead of a silent one. Pass a public ReadbackBuffer to own staging cleanup on rejected maps;
|
|
281
|
+
* the returned bytes are copied before the caller disposes that target in finally.
|
|
282
|
+
*/
|
|
283
|
+
readback(attribute: unknown, target?: ReadbackBuffer): Promise<ArrayBuffer>;
|
|
284
|
+
/**
|
|
285
|
+
* The scene pass's stored depth attachment and sample count, from an authored pass or three's
|
|
286
|
+
* internal framebuffer target. `undefined` when neither has rendered a depth to read.
|
|
287
|
+
*
|
|
288
|
+
* Optional because a backend that cannot render into a target of its own has no scene-pass depth to
|
|
289
|
+
* hand over. A cull reads this every dispatch: on the frame it answers, the texture holds what the
|
|
290
|
+
* previous frame's pass wrote, because this is asked before the frame draws.
|
|
291
|
+
*/
|
|
292
|
+
scenePassDepth?():
|
|
293
|
+
| {
|
|
294
|
+
readonly texture: DepthTexture;
|
|
295
|
+
readonly width: number;
|
|
296
|
+
readonly height: number;
|
|
297
|
+
readonly samples?: number;
|
|
298
|
+
}
|
|
299
|
+
| undefined;
|
|
300
|
+
render(scene: Object3D, camera: Camera): void;
|
|
301
|
+
/** Draws after the world without clearing or passing through the world's output pipeline. */
|
|
302
|
+
renderOverlay(scene: Object3D, camera: Camera): void;
|
|
303
|
+
/** Legacy input-filtered clear; use an installation receipt for same-node replacement safety. */
|
|
304
|
+
clearOutputNode?(expectedNode?: unknown): void;
|
|
305
|
+
/** Creates the core-owned chain seam without making generated render source import the package. */
|
|
306
|
+
createRenderChain?: (options: Omit<IRenderChainOptions, "renderer">) => RenderChain;
|
|
307
|
+
/** Feeds automatic render-chain tiers the completed frame-budget window. */
|
|
308
|
+
observeRenderChainBudget?: (window: IRenderChainBudgetWindow) => void;
|
|
309
|
+
/** Samples render-chain telemetry after the renderer completes a frame. */
|
|
310
|
+
observeRenderChainFrame?: () => void;
|
|
311
|
+
/** Whether the active chain requested core-owned per-object velocity history. */
|
|
312
|
+
renderChainUsesPerObjectVelocity?: () => boolean;
|
|
313
|
+
/** Internal callback used by RenderChain; games should request velocity through the chain. */
|
|
314
|
+
setRenderChainVelocityEnabled?: (enabled: boolean) => void;
|
|
315
|
+
/** Installs a graph; pass the authored world pass when the graph contains auxiliary passes. */
|
|
316
|
+
// The owned renderer returns a unique receipt. Legacy adapters may return void, without
|
|
317
|
+
// installation-level replacement safety; callers still own graph dependency disposal.
|
|
318
|
+
setOutputNode: RenderOutputSetter;
|
|
319
|
+
createResolutionSubrect?: () => IResolutionSubrect;
|
|
320
|
+
setSize(width: number, height: number, updateStyle?: boolean): void;
|
|
321
|
+
/**
|
|
322
|
+
* The GPU time the last resolved frame actually cost, in milliseconds, or `undefined` when the
|
|
323
|
+
* adapter has no `timestamp-query` and there is nothing to report.
|
|
324
|
+
*
|
|
325
|
+
* Every GPU number in this repository's performance record before this was wall-clock algebra:
|
|
326
|
+
* ablate scene content, difference a blocking device poll in a diagnostic build that never
|
|
327
|
+
* ships. This is the measurement itself. Resolving is asynchronous and off the frame path — the
|
|
328
|
+
* caller reads whatever the last resolve produced.
|
|
329
|
+
*/
|
|
330
|
+
gpuFrameMs(): number | undefined;
|
|
331
|
+
/** Age in Three.js frame IDs of the resolved render timestamp; absent when unobservable. */
|
|
332
|
+
gpuFrameAge?(): number | undefined;
|
|
333
|
+
/**
|
|
334
|
+
* The last resolved GPU frame's duration and the Three.js frame id it belongs to, or
|
|
335
|
+
* `undefined` when no resolved reading is available.
|
|
336
|
+
*
|
|
337
|
+
* `gpuFrameMs` is that duration alone; the frame id is what tells a reading still in flight
|
|
338
|
+
* from the current frame's cost, so a caller building a per-frame series never measures one
|
|
339
|
+
* resolve twice. Optional like `gpuFrameAge`, for stubs that implement only the drawing
|
|
340
|
+
* contract. `createRenderer` always provides it.
|
|
341
|
+
*/
|
|
342
|
+
gpuFrameSample?(): { readonly frame: number; readonly ms: number } | undefined;
|
|
343
|
+
/**
|
|
344
|
+
* Observes complete allocated render-query groups without changing ordinary sampling.
|
|
345
|
+
* Frame IDs are Three query IDs, including any overlay draws; callers map world callbacks.
|
|
346
|
+
* Capacities bound undrained, pending and queued membership. maxQueries counts timestamp
|
|
347
|
+
* slots (two per pass). A failed receipt is sticky and must be disposed before replacement.
|
|
348
|
+
* Requires timestamp-capable WebGPU and its existing asynchronous resolver.
|
|
349
|
+
*/
|
|
350
|
+
observeGpuFrames?(options: IGpuFrameObservationOptions): IGpuFrameObservation;
|
|
351
|
+
/**
|
|
352
|
+
* GPU milliseconds of the last resolved compute frame, when the adapter reports one.
|
|
353
|
+
*
|
|
354
|
+
* The compute pool is a separate series from the render pool and `resolveGpuFrame` resolves it,
|
|
355
|
+
* so a GPU simulation's cost is measurable instead of being charged to whatever render frame
|
|
356
|
+
* happened to overlap. `undefined` for a WebGL2 fallback, an adapter without timestamps, or a
|
|
357
|
+
* frame that ran no compute.
|
|
358
|
+
*/
|
|
359
|
+
gpuComputeMs?(): number | undefined;
|
|
360
|
+
/** Consume one fresh timestamped pyramid build, including its depth resolve; absent until resolved. */
|
|
361
|
+
gpuPyramidMs?(): number | undefined;
|
|
362
|
+
/**
|
|
363
|
+
* The main render pass's GPU milliseconds, smoothed over fresh resolved samples, or `undefined`
|
|
364
|
+
* while no reading is fresh.
|
|
365
|
+
*
|
|
366
|
+
* `gpuFrameMs` is the whole render pool, main plus every shadow, reflection, post and HUD pass;
|
|
367
|
+
* the adaptive LOD control loop needs the main-pass share alone. `game.ts` splits the resolved
|
|
368
|
+
* frame through the pass recorder and feeds the sample here with {@link noteGpuMainMs}. A
|
|
369
|
+
* repeated frame id is a resolve still in flight and not a new reading, and with no fresh sample
|
|
370
|
+
* for too long the value reads absent, so a caller never adapts on a stale number.
|
|
371
|
+
*/
|
|
372
|
+
gpuMainMs?(): number | undefined;
|
|
373
|
+
/**
|
|
374
|
+
* Records one resolved frame's main-pass GPU milliseconds into {@link gpuMainMs}. Called once a
|
|
375
|
+
* frame by `game.ts`; `ms` is `undefined` when the frame attributed no main-pass reading.
|
|
376
|
+
*/
|
|
377
|
+
noteGpuMainMs?(ms: number | undefined, frame?: number): void;
|
|
378
|
+
/**
|
|
379
|
+
* The frame rate the game resolved as its target (`resolveTargetFps`), or `undefined` before one
|
|
380
|
+
* is known or when it is uncapped. Budgets that are a share of a frame read it, so a frame that ran
|
|
381
|
+
* faster than the target does not shrink what the next one may spend.
|
|
382
|
+
*/
|
|
383
|
+
targetFps?(): number | undefined;
|
|
384
|
+
/** Records the resolved target; called by `game.ts` when it resolves or retargets. */
|
|
385
|
+
noteTargetFps?(fps: number): void;
|
|
386
|
+
/** Starts a resolve of the GPU timestamps for the frames drawn since the last call. */
|
|
387
|
+
resolveGpuFrame(): void;
|
|
388
|
+
/**
|
|
389
|
+
* Moves the drawing-buffer scale, deferring while a compile retains its targets. The adaptive scaler is the only
|
|
390
|
+
* caller; a pinned game never reaches this, which is what makes "pinned" mean pinned.
|
|
391
|
+
*/
|
|
392
|
+
setResolutionScale(scale: number, scaleSource: "auto" | "auto-pinned"): void;
|
|
393
|
+
/**
|
|
394
|
+
* What this renderer is actually drawing at. Read once per frame-budget window so every fps
|
|
395
|
+
* number is self-describing; a record and a tree once disagreed about the scale for a whole
|
|
396
|
+
* session because nothing in the measurement could say which one produced it.
|
|
397
|
+
*/
|
|
398
|
+
surface(): IFrameSurfaceState;
|
|
399
|
+
/**
|
|
400
|
+
* The drawing buffer height on its own, for a caller that wants one number every frame and no
|
|
401
|
+
* record. Optional so a platform or test double can keep exposing only `surface()`.
|
|
402
|
+
*/
|
|
403
|
+
surfaceDrawingBufferHeight?(): number;
|
|
404
|
+
dispose(): void;
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
export interface IRendererPlatformSource {
|
|
408
|
+
createCanvas(): HTMLCanvasElement;
|
|
409
|
+
hasWebGPU(): boolean;
|
|
410
|
+
observeResize(canvas: HTMLCanvasElement, resize: () => void): () => void;
|
|
411
|
+
readSize(canvas: HTMLCanvasElement): readonly [width: number, height: number];
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
export interface IRendererOptions {
|
|
415
|
+
/**
|
|
416
|
+
* Resolves alpha-tested cutout silhouettes — foliage, fences, hair — through the multisample
|
|
417
|
+
* coverage mask instead of a binary `discard`. Defaults to true, and does nothing at all on a
|
|
418
|
+
* single-sampled surface, which it reports rather than pretends. Godot's
|
|
419
|
+
* `alpha_antialiasing_mode`, in Three.js's `alphaToCoverage`.
|
|
420
|
+
*/
|
|
421
|
+
alphaAntialiasing?: boolean;
|
|
422
|
+
/** Requests multisample antialiasing from the renderer. Defaults to true. */
|
|
423
|
+
antialias?: boolean;
|
|
424
|
+
canvas?: HTMLCanvasElement;
|
|
425
|
+
gpuTimestampFrameInterval?: number;
|
|
426
|
+
preferWebGPU?: boolean;
|
|
427
|
+
/** CSS-pixel multiplier for the drawing buffer. The default is intentional DPR 1. */
|
|
428
|
+
resolutionScale?: number;
|
|
429
|
+
/** Whether the game pinned that scale or the engine chose it. Reported, never inferred. */
|
|
430
|
+
scaleSource?: "pinned" | "auto" | "auto-pinned";
|
|
431
|
+
/**
|
|
432
|
+
* Physical pixels per logical (CSS) pixel of the canvas this draws into. Default: the device's
|
|
433
|
+
* own `devicePixelRatio` on both runtimes (unified 2026-09-01; web's old DPR-1 buffer read as
|
|
434
|
+
* pixelation on any HiDPI display). The resolution scaler composes on top, so an unaffordable
|
|
435
|
+
* density is trimmed by scaler rungs rather than by the developer. An explicit value wins on
|
|
436
|
+
* both runtimes.
|
|
437
|
+
*/
|
|
438
|
+
pixelRatio?: number;
|
|
439
|
+
/** Where convention markers go. Defaults to the console, exactly as the render chain reports. */
|
|
440
|
+
report?: (line: string) => void;
|
|
441
|
+
/**
|
|
442
|
+
* Bounded pipeline detail for a real launch capture. It is on by default so a town does not
|
|
443
|
+
* need an instrumented build; pass `false` for an identical-build overhead control.
|
|
444
|
+
*/
|
|
445
|
+
pipelineCensus?: false | { readonly limit?: number };
|
|
446
|
+
source?: IRendererPlatformSource;
|
|
447
|
+
webgpuFactory?: (
|
|
448
|
+
canvas: HTMLCanvasElement,
|
|
449
|
+
options: Readonly<{ antialias: boolean }>,
|
|
450
|
+
) => Promise<unknown> | unknown;
|
|
451
|
+
webgl2Factory?: (canvas: HTMLCanvasElement, options: Readonly<{ antialias: boolean }>) => unknown;
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
type RendererInstance = IStorageBufferSource & {
|
|
455
|
+
autoClear?: boolean;
|
|
456
|
+
/** three's resolved GPU timings; `info.render.timestamp` is milliseconds. */
|
|
457
|
+
info?: {
|
|
458
|
+
frame?: number;
|
|
459
|
+
render?: { timestamp?: number };
|
|
460
|
+
compute?: { timestamp?: number };
|
|
461
|
+
};
|
|
462
|
+
backend?: {
|
|
463
|
+
trackTimestamp?: boolean;
|
|
464
|
+
timestampQueryPool?: Record<string, ITimestampQueryPool | null>;
|
|
465
|
+
/** The backend's own attribute creation, which a compile does not do. */
|
|
466
|
+
createAttribute?: (attribute: unknown) => void;
|
|
467
|
+
createIndexAttribute?: (attribute: unknown) => void;
|
|
468
|
+
getTimestampFrames?: (type: string) => number[];
|
|
469
|
+
createRenderPipeline?: (...args: unknown[]) => unknown;
|
|
470
|
+
createComputePipeline?: (...args: unknown[]) => unknown;
|
|
471
|
+
get?: (value: unknown) => unknown;
|
|
472
|
+
gpu?: {
|
|
473
|
+
requestAdapter?: (options?: unknown) => Promise<unknown> | unknown;
|
|
474
|
+
};
|
|
475
|
+
parameters?: { powerPreference?: unknown };
|
|
476
|
+
};
|
|
477
|
+
xr?: { enabled?: unknown };
|
|
478
|
+
resolveTimestampsAsync?: (type?: string) => Promise<number | undefined>;
|
|
479
|
+
/** Three answers an `antialias` request with a sample count; 0 means one sample per pixel. */
|
|
480
|
+
samples?: number;
|
|
481
|
+
/** Whether the backend owns resizable render targets for retained sub-rectangle rendering. */
|
|
482
|
+
supportsRetainedTargetSubrect?: boolean;
|
|
483
|
+
domElement: HTMLCanvasElement;
|
|
484
|
+
init?: () => Promise<void>;
|
|
485
|
+
compileAsync?: (scene: Object3D, camera: Camera, targetScene?: Object3D) => Promise<void>;
|
|
486
|
+
prepareTextureAsync?: (
|
|
487
|
+
texture: Texture,
|
|
488
|
+
options: { budgetMs: number; maxBytesPerWrite: number; signal: AbortSignal },
|
|
489
|
+
) => Promise<void>;
|
|
490
|
+
compute?: (node: unknown) => void;
|
|
491
|
+
getArrayBufferAsync?: (
|
|
492
|
+
attribute: unknown,
|
|
493
|
+
target?: ReadbackBuffer,
|
|
494
|
+
) => Promise<ArrayBuffer | ReadbackBuffer>;
|
|
495
|
+
render: (scene: Object3D, camera: Camera) => void;
|
|
496
|
+
setSize: (width: number, height: number, updateStyle?: boolean) => void;
|
|
497
|
+
dispose?: () => void;
|
|
498
|
+
/** three's per-draw seam, present on the WebGPU renderer and absent on the WebGL2 fallback. */
|
|
499
|
+
getRenderObjectFunction?: () => RenderObjectFunction | null;
|
|
500
|
+
/** three's compile-time render target seam; see the `compileAsync` wrapper. */
|
|
501
|
+
needsFrameBufferTarget?: boolean;
|
|
502
|
+
getRenderTarget?: () => unknown;
|
|
503
|
+
setRenderTarget?: (target: unknown) => void;
|
|
504
|
+
getMRT?: () => unknown;
|
|
505
|
+
setMRT?: (mrt: unknown) => void;
|
|
506
|
+
_getFrameBufferTarget?: () => unknown;
|
|
507
|
+
/** What `getRenderTarget()` answers, and the only honest read while that answer is overridden. */
|
|
508
|
+
_renderTarget?: unknown;
|
|
509
|
+
renderObject?: RenderObjectFunction;
|
|
510
|
+
setRenderObjectFunction?: (renderObjectFunction: RenderObjectFunction) => void;
|
|
511
|
+
};
|
|
512
|
+
|
|
513
|
+
type RenderObjectFunction = (...args: unknown[]) => void;
|
|
514
|
+
|
|
515
|
+
/** `samples` is the answer, `antialias` was only the request; three reports 0 for one sample. */
|
|
516
|
+
function resolveSampleCount(raw: RendererInstance): number {
|
|
517
|
+
return Number.isInteger(raw.samples) && (raw.samples ?? 0) > 0 ? (raw.samples ?? 1) : 1;
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
/**
|
|
521
|
+
* Catch a material the first time the renderer draws with it.
|
|
522
|
+
*
|
|
523
|
+
* Warm-up compiles through three's own `renderObject`, never this one, so this fires only for
|
|
524
|
+
* content that arrived after the last warm-up — whose pipeline is being built for the first time
|
|
525
|
+
* regardless, which is why converting here costs no rebuild. A game that installs its own render
|
|
526
|
+
* object function replaces this one and opts out; the marker still names what was decided.
|
|
527
|
+
*/
|
|
528
|
+
function installDrawHook(raw: RendererInstance, alphaAntialiasing: AlphaAntialiasing): void {
|
|
529
|
+
if (typeof raw.setRenderObjectFunction !== "function") return;
|
|
530
|
+
const previous = raw.getRenderObjectFunction?.() ?? null;
|
|
531
|
+
const delegate = previous ?? raw.renderObject;
|
|
532
|
+
if (typeof delegate !== "function") return;
|
|
533
|
+
raw.setRenderObjectFunction((...args) => {
|
|
534
|
+
alphaAntialiasing.convertMaterial(args[4]);
|
|
535
|
+
delegate.apply(raw, args);
|
|
536
|
+
});
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
export function readCanvasSize(canvas: HTMLCanvasElement): readonly [number, number] {
|
|
540
|
+
return [
|
|
541
|
+
Math.max(1, canvas.clientWidth || globalThis.innerWidth || 1),
|
|
542
|
+
Math.max(1, canvas.clientHeight || globalThis.innerHeight || 1),
|
|
543
|
+
];
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
export function observeCanvasResize(canvas: HTMLCanvasElement, resize: () => void): () => void {
|
|
547
|
+
if (typeof ResizeObserver !== "undefined") {
|
|
548
|
+
const observer = new ResizeObserver(resize);
|
|
549
|
+
observer.observe(canvas);
|
|
550
|
+
return () => observer.disconnect();
|
|
551
|
+
}
|
|
552
|
+
if (typeof globalThis.addEventListener !== "function") return () => undefined;
|
|
553
|
+
globalThis.addEventListener("resize", resize);
|
|
554
|
+
return () => globalThis.removeEventListener("resize", resize);
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
/**
|
|
558
|
+
* Runs one covered render through Three's asynchronous pipeline path.
|
|
559
|
+
*
|
|
560
|
+
* `compileAsync` is the only stock Three entry that hands `PipelineCache.getForRender` a promise
|
|
561
|
+
* list, which is what switches a device create to `createRenderPipelineAsync`. A normal `render()`
|
|
562
|
+
* passes none and therefore creates every missing pipeline synchronously, on the calling thread.
|
|
563
|
+
* The warm-up is a real render because only an output pipeline reaches the post and reflection
|
|
564
|
+
* passes, so it cannot be replaced by `compileAsync`; this lends that render the same promise list
|
|
565
|
+
* through the cache's own seam. A draw whose pipeline is still pending is skipped by
|
|
566
|
+
* `PipelineCache.isReady` — the pending/skip path `compileAsync` already relies on — and the
|
|
567
|
+
* warm-up awaits the whole list before the first visible frame. The frame is invisible behind the
|
|
568
|
+
* startup cover, so a skipped draw costs nothing.
|
|
569
|
+
*
|
|
570
|
+
* Returns `undefined` on a renderer without that cache or without async device creation, which
|
|
571
|
+
* keeps the previous synchronous covered render as the fallback.
|
|
572
|
+
*
|
|
573
|
+
* @internal Exported for the warm-up contract; not part of the public renderer API.
|
|
574
|
+
*/
|
|
575
|
+
export function beginAsyncPipelines(
|
|
576
|
+
raw: unknown,
|
|
577
|
+
): { readonly restore: () => void; readonly settled: () => Promise<void> } | undefined {
|
|
578
|
+
if (!isObject(raw)) return undefined;
|
|
579
|
+
const pipelines = raw._pipelines;
|
|
580
|
+
if (!isObject(pipelines) || typeof pipelines.getForRender !== "function") return undefined;
|
|
581
|
+
const device = isObject(raw.backend) ? raw.backend.device : undefined;
|
|
582
|
+
if (!isObject(device) || typeof device.createRenderPipelineAsync !== "function") return undefined;
|
|
583
|
+
const original = pipelines.getForRender as (...args: unknown[]) => unknown;
|
|
584
|
+
const pending: Promise<unknown>[] = [];
|
|
585
|
+
pipelines.getForRender = function (this: unknown, ...args: unknown[]): unknown {
|
|
586
|
+
const next = [...args];
|
|
587
|
+
if (next.length < 2 || next[1] === undefined || next[1] === null) next[1] = pending;
|
|
588
|
+
return original.apply(this, next);
|
|
589
|
+
};
|
|
590
|
+
let restored = false;
|
|
591
|
+
return {
|
|
592
|
+
restore: () => {
|
|
593
|
+
if (restored) return;
|
|
594
|
+
restored = true;
|
|
595
|
+
pipelines.getForRender = original;
|
|
596
|
+
},
|
|
597
|
+
settled: async () => {
|
|
598
|
+
// A failed async creation resolves through Three's own error path and never rejects here;
|
|
599
|
+
// settle every ticket so one refusal cannot hide the compiles that did land.
|
|
600
|
+
await Promise.all(pending.map((ticket) => Promise.resolve(ticket).catch(() => undefined)));
|
|
601
|
+
},
|
|
602
|
+
};
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
function wrapRenderer(
|
|
606
|
+
raw: RendererInstance,
|
|
607
|
+
kind: RendererKind,
|
|
608
|
+
applied: { width: number; height: number },
|
|
609
|
+
state: ISurfaceState,
|
|
610
|
+
reapply: { resize: (() => void) | undefined },
|
|
611
|
+
alphaAntialiasing: AlphaAntialiasing,
|
|
612
|
+
pipelineCensus: PipelineCensus | undefined,
|
|
613
|
+
timestampCapable: boolean,
|
|
614
|
+
timestampFrameInterval: number,
|
|
615
|
+
softwareAdapter?: string,
|
|
616
|
+
gpuClass?: IGpuClassification,
|
|
617
|
+
): IRendererLike {
|
|
618
|
+
let outputPipeline: RenderPipeline | undefined;
|
|
619
|
+
// Keep caller identity separately: RenderPipeline may wrap its public output node.
|
|
620
|
+
let outputInput: unknown;
|
|
621
|
+
let outputPass: PassNode | undefined;
|
|
622
|
+
let pendingWorldPassRefresh = false;
|
|
623
|
+
// Nested bloom/temporal quads sample this pass under distinct renderIds.
|
|
624
|
+
const refreshWorldPassOnce = (pass: PassNode | undefined): (() => void) | undefined => {
|
|
625
|
+
if (pass === undefined) return undefined;
|
|
626
|
+
const updateBefore = pass.updateBefore;
|
|
627
|
+
const updateBeforeType = pass.updateBeforeType;
|
|
628
|
+
const hadOwnUpdateBefore = Object.hasOwn(pass, "updateBefore");
|
|
629
|
+
let updated = false;
|
|
630
|
+
pass.updateBeforeType = NodeUpdateType.RENDER;
|
|
631
|
+
pass.updateBefore = function (frame) {
|
|
632
|
+
if (updated) return;
|
|
633
|
+
updated = true;
|
|
634
|
+
updateBefore.call(this, frame);
|
|
635
|
+
};
|
|
636
|
+
return () => {
|
|
637
|
+
pass.updateBeforeType = updateBeforeType;
|
|
638
|
+
if (hadOwnUpdateBefore) pass.updateBefore = updateBefore;
|
|
639
|
+
else Reflect.deleteProperty(pass, "updateBefore");
|
|
640
|
+
};
|
|
641
|
+
};
|
|
642
|
+
let warmOutputTarget: RenderTarget | undefined;
|
|
643
|
+
const renderChains = new Set<RenderChain>();
|
|
644
|
+
let renderChainUsesPerObjectVelocity = false;
|
|
645
|
+
let activeCompiles = 0;
|
|
646
|
+
let compileCount = 0;
|
|
647
|
+
let disposed = false;
|
|
648
|
+
const texturePreparations = new Set<AbortController>();
|
|
649
|
+
const storageBuffers = new StorageBufferLeases(() => raw);
|
|
650
|
+
let computeTimings: ComputeTimingScopes | undefined;
|
|
651
|
+
let pendingScale: { scale: number; source: "auto" | "auto-pinned" } | undefined;
|
|
652
|
+
let pendingSize: Parameters<IRendererLike["setSize"]> | undefined;
|
|
653
|
+
let timestampFrame = -1;
|
|
654
|
+
let timestampFramesManaged = false;
|
|
655
|
+
const pyramidQueries: string[][] = [];
|
|
656
|
+
let gpuObservation: GpuFrameObservation | undefined;
|
|
657
|
+
let gpuObservationGeneration = 0;
|
|
658
|
+
const setTimestampTracking = (): void => {
|
|
659
|
+
// Three advances info.frame only in its own animation loop, which we do not run.
|
|
660
|
+
// Advance once per presented frame: compute, world and overlay share its sample and query id.
|
|
661
|
+
timestampFrame += 1;
|
|
662
|
+
const rawInfo = (raw as { info?: { frame: number } | null }).info;
|
|
663
|
+
if (rawInfo !== undefined && rawInfo !== null) rawInfo.frame = timestampFrame;
|
|
664
|
+
const backend = raw.backend;
|
|
665
|
+
if (!timestampCapable || backend === undefined) return;
|
|
666
|
+
backend.trackTimestamp = timestampFrame % timestampFrameInterval === 0;
|
|
667
|
+
};
|
|
668
|
+
|
|
669
|
+
/**
|
|
670
|
+
* The last resolved GPU timestamp and the frame id it belongs to.
|
|
671
|
+
*
|
|
672
|
+
* `info.render.timestamp` alone is the last frame of the most recent resolve batch, and a batch
|
|
673
|
+
* that cleared several frames at once loses all but its last. The id is what lets the frame
|
|
674
|
+
* budget tell a reading still in flight from the current frame's cost instead of pushing the
|
|
675
|
+
* same lagged sample every frame. `backend.getTimestampFrames("render")` is Three's tracked
|
|
676
|
+
* resolved-frame list; its last entry is the sample, matching `gpuFrameAge`.
|
|
677
|
+
*/
|
|
678
|
+
/**
|
|
679
|
+
* The engine's own frame id once it has rendered. Three's `init()` starts its own rAF loop, which
|
|
680
|
+
* writes `info.frame = nodeFrame.frameId` every animation frame, so `info.frame` read between
|
|
681
|
+
* renders can be that smaller counter while the timestamp queries carry this one.
|
|
682
|
+
*/
|
|
683
|
+
const currentFrame = (): number | undefined =>
|
|
684
|
+
timestampFrame >= 0 ? timestampFrame : raw.info?.frame;
|
|
685
|
+
const gpuFrameSample = (): { frame: number; ms: number } | undefined => {
|
|
686
|
+
const frame = currentFrame();
|
|
687
|
+
const frames = raw.backend?.getTimestampFrames?.("render");
|
|
688
|
+
const sampled = frames?.[frames.length - 1];
|
|
689
|
+
const timestamp = raw.info?.render?.timestamp;
|
|
690
|
+
if (
|
|
691
|
+
frame === undefined ||
|
|
692
|
+
sampled === undefined ||
|
|
693
|
+
!Number.isInteger(frame) ||
|
|
694
|
+
!Number.isInteger(sampled) ||
|
|
695
|
+
sampled < 0 ||
|
|
696
|
+
frame < sampled ||
|
|
697
|
+
typeof timestamp !== "number" ||
|
|
698
|
+
!Number.isFinite(timestamp) ||
|
|
699
|
+
timestamp <= 0
|
|
700
|
+
)
|
|
701
|
+
return undefined;
|
|
702
|
+
return { frame: sampled, ms: timestamp };
|
|
703
|
+
};
|
|
704
|
+
|
|
705
|
+
/**
|
|
706
|
+
* A warm-up or a pass can leave a target bound with nothing left to restore it, and
|
|
707
|
+
* `getRenderTarget()` answers null across that overlap, so read the field. Pipelines restore their
|
|
708
|
+
* own offscreen targets, so only the surface paths need this.
|
|
709
|
+
*/
|
|
710
|
+
const bindSurface = (): void => {
|
|
711
|
+
if (typeof raw.setRenderTarget !== "function") return;
|
|
712
|
+
const bound = "_renderTarget" in raw ? raw._renderTarget : raw.getRenderTarget?.();
|
|
713
|
+
if (bound === null || bound === undefined) return;
|
|
714
|
+
raw.setRenderTarget(null);
|
|
715
|
+
};
|
|
716
|
+
|
|
717
|
+
let renderingFrame = 0;
|
|
718
|
+
const renderFrame = (scene: Object3D, camera: Camera): void => {
|
|
719
|
+
pipelineCensus?.beginWorldFrame(scene);
|
|
720
|
+
const refreshPass = pendingWorldPassRefresh ? outputPass : undefined;
|
|
721
|
+
const restoreWorldPass = refreshWorldPassOnce(refreshPass);
|
|
722
|
+
let completed = false;
|
|
723
|
+
try {
|
|
724
|
+
bindSurface();
|
|
725
|
+
if (outputPipeline === undefined) raw.render(scene, camera);
|
|
726
|
+
else {
|
|
727
|
+
// RenderPipeline.render() has no scene argument and PassNode keeps the scene it captured
|
|
728
|
+
// when the graph was built. Retarget only the authored world pass at the root the wrapper
|
|
729
|
+
// is rendering so a projection mirror and its velocity history remain the same input.
|
|
730
|
+
setOutputPipelineRoot(outputPass, scene, camera);
|
|
731
|
+
outputPipeline.render();
|
|
732
|
+
}
|
|
733
|
+
if (refreshPass !== undefined) pendingWorldPassRefresh = false;
|
|
734
|
+
pipelineCensus?.firstPresent();
|
|
735
|
+
completed = true;
|
|
736
|
+
} finally {
|
|
737
|
+
restoreWorldPass?.();
|
|
738
|
+
pipelineCensus?.endWorldFrame(scene, completed);
|
|
739
|
+
}
|
|
740
|
+
};
|
|
741
|
+
const renderOverlayFrame = (scene: Object3D, camera: Camera): void => {
|
|
742
|
+
bindSurface();
|
|
743
|
+
const hadOwnAutoClear = Object.hasOwn(raw, "autoClear");
|
|
744
|
+
const autoClear = raw.autoClear;
|
|
745
|
+
raw.autoClear = false;
|
|
746
|
+
try {
|
|
747
|
+
raw.render(scene, camera);
|
|
748
|
+
} finally {
|
|
749
|
+
if (hadOwnAutoClear) raw.autoClear = autoClear;
|
|
750
|
+
else Reflect.deleteProperty(raw, "autoClear");
|
|
751
|
+
}
|
|
752
|
+
};
|
|
753
|
+
// The main pass's own GPU series, fed a frame at a time by `game.ts` because only the pass
|
|
754
|
+
// recorder can attribute the render pool to its main call. Half/half smoothing, and a short
|
|
755
|
+
// freshness window: the adaptive LOD loop reads this every half second and must not act on a
|
|
756
|
+
// resolve that stopped landing.
|
|
757
|
+
const mainSmoothing = 0.5;
|
|
758
|
+
const mainStaleLimit = 8;
|
|
759
|
+
let gpuMainEma: number | undefined;
|
|
760
|
+
let targetFps: number | undefined;
|
|
761
|
+
let gpuMainStaleFrames = 0;
|
|
762
|
+
let gpuMainLastFrame: number | undefined;
|
|
763
|
+
const noteGpuMainMs = (ms: number | undefined, frame?: number): void => {
|
|
764
|
+
const stale = (): void => {
|
|
765
|
+
gpuMainStaleFrames += 1;
|
|
766
|
+
if (gpuMainStaleFrames >= mainStaleLimit) gpuMainEma = undefined;
|
|
767
|
+
};
|
|
768
|
+
if (ms === undefined || !Number.isFinite(ms) || ms < 0) {
|
|
769
|
+
stale();
|
|
770
|
+
return;
|
|
771
|
+
}
|
|
772
|
+
// A repeated frame id is the previous resolve still in flight, not a new reading.
|
|
773
|
+
if (frame !== undefined && frame === gpuMainLastFrame) {
|
|
774
|
+
stale();
|
|
775
|
+
return;
|
|
776
|
+
}
|
|
777
|
+
if (frame !== undefined) gpuMainLastFrame = frame;
|
|
778
|
+
gpuMainStaleFrames = 0;
|
|
779
|
+
gpuMainEma = gpuMainEma === undefined ? ms : gpuMainEma + (ms - gpuMainEma) * mainSmoothing;
|
|
780
|
+
};
|
|
781
|
+
const wrapped: IRendererLike = {
|
|
782
|
+
get compileCount() {
|
|
783
|
+
return compileCount;
|
|
784
|
+
},
|
|
785
|
+
get compiling() {
|
|
786
|
+
return activeCompiles > 0;
|
|
787
|
+
},
|
|
788
|
+
...(pipelineCensus === undefined ? {} : { pipelineCensus: () => pipelineCensus.snapshot() }),
|
|
789
|
+
...(pipelineCensus === undefined
|
|
790
|
+
? {}
|
|
791
|
+
: { warmUpSettled: () => pipelineCensus.warmUpSettled() }),
|
|
792
|
+
...(pipelineCensus === undefined
|
|
793
|
+
? {}
|
|
794
|
+
: {
|
|
795
|
+
warmUpScopeSettled: (label: string, target?: Object3D) =>
|
|
796
|
+
pipelineCensus.warmUpScopeSettled(label, target),
|
|
797
|
+
}),
|
|
798
|
+
get warmUpWorldPass() {
|
|
799
|
+
if (outputPipeline === undefined) return undefined;
|
|
800
|
+
return (scene: Object3D, camera: Camera, targetScene?: Object3D): void | Promise<void> => {
|
|
801
|
+
const outputRoot = targetScene ?? scene;
|
|
802
|
+
const scoped = targetScene !== undefined && targetScene !== scene;
|
|
803
|
+
const previousPassScene = outputPass?.scene;
|
|
804
|
+
const previousPassCamera = outputPass?.camera;
|
|
805
|
+
let restoreWorldPass: (() => void) | undefined;
|
|
806
|
+
let asyncPipelines:
|
|
807
|
+
| { readonly restore: () => void; readonly settled: () => Promise<void> }
|
|
808
|
+
| undefined;
|
|
809
|
+
const warmRenderer = raw as RendererInstance &
|
|
810
|
+
ThreeRenderer & {
|
|
811
|
+
contextNode?: unknown;
|
|
812
|
+
opaque?: boolean;
|
|
813
|
+
transparent?: boolean;
|
|
814
|
+
};
|
|
815
|
+
const rendererState = RendererUtils.saveRendererState(warmRenderer);
|
|
816
|
+
// An in-flight compile exposes a virtual target through the getter; restore the bound one.
|
|
817
|
+
if ("_renderTarget" in raw)
|
|
818
|
+
rendererState.renderTarget = Reflect.get(
|
|
819
|
+
raw,
|
|
820
|
+
"_renderTarget",
|
|
821
|
+
) as typeof rendererState.renderTarget;
|
|
822
|
+
const hadOwnTransparent = Object.hasOwn(raw, "transparent");
|
|
823
|
+
const hadOwnOpaque = Object.hasOwn(raw, "opaque");
|
|
824
|
+
const hadOwnContextNode = Object.hasOwn(raw, "contextNode");
|
|
825
|
+
const previousTransparent = Reflect.get(raw, "transparent");
|
|
826
|
+
const previousOpaque = Reflect.get(raw, "opaque");
|
|
827
|
+
const previousContextNode = Reflect.get(raw, "contextNode");
|
|
828
|
+
const previousXr = warmRenderer.xr;
|
|
829
|
+
const hadOwnXrEnabled = previousXr !== undefined && Object.hasOwn(previousXr, "enabled");
|
|
830
|
+
const previousXrEnabled =
|
|
831
|
+
previousXr === undefined ? undefined : Reflect.get(previousXr, "enabled");
|
|
832
|
+
const hadOwnSceneOverrideMaterial = Object.hasOwn(scene, "overrideMaterial");
|
|
833
|
+
const hadOwnOutputRootOverrideMaterial = Object.hasOwn(outputRoot, "overrideMaterial");
|
|
834
|
+
const previousSceneName = scene.name;
|
|
835
|
+
const previousOutputRootName = outputRoot.name;
|
|
836
|
+
const previousSceneOverrideMaterial = Reflect.get(scene, "overrideMaterial");
|
|
837
|
+
const previousOutputRootOverrideMaterial = Reflect.get(outputRoot, "overrideMaterial");
|
|
838
|
+
const previousCameraMask = camera.layers.mask;
|
|
839
|
+
const restoreField = (
|
|
840
|
+
object: object,
|
|
841
|
+
key: string,
|
|
842
|
+
hadOwn: boolean,
|
|
843
|
+
value: unknown,
|
|
844
|
+
): void => {
|
|
845
|
+
if (hadOwn) Reflect.set(object, key, value);
|
|
846
|
+
else Reflect.deleteProperty(object, key);
|
|
847
|
+
};
|
|
848
|
+
const originalParent = scene.parent;
|
|
849
|
+
const originalMatrix = scene.matrix.clone();
|
|
850
|
+
const originalMatrixWorld = scene.matrixWorld.clone();
|
|
851
|
+
const attached = scoped && !isInObject3DSubtree(outputRoot, scene);
|
|
852
|
+
if (attached) outputRoot.add(scene);
|
|
853
|
+
renderingFrame += 1;
|
|
854
|
+
try {
|
|
855
|
+
if (scoped && outputPass !== undefined) {
|
|
856
|
+
restoreWorldPass = refreshWorldPassOnce(outputPass);
|
|
857
|
+
pendingWorldPassRefresh = true;
|
|
858
|
+
}
|
|
859
|
+
if (scoped) {
|
|
860
|
+
if (raw.setRenderTarget === undefined)
|
|
861
|
+
throw new Error(
|
|
862
|
+
"TN_WARMUP_OFFSCREEN_TARGET_UNAVAILABLE: scoped world warm-up needs a render target seam.",
|
|
863
|
+
);
|
|
864
|
+
warmOutputTarget ??= new RenderTarget(1, 1);
|
|
865
|
+
raw.setRenderTarget(warmOutputTarget);
|
|
866
|
+
} else bindSurface();
|
|
867
|
+
setOutputPipelineRoot(outputPass, outputRoot, camera);
|
|
868
|
+
asyncPipelines = beginAsyncPipelines(raw);
|
|
869
|
+
outputPipeline?.render();
|
|
870
|
+
} finally {
|
|
871
|
+
renderingFrame -= 1;
|
|
872
|
+
asyncPipelines?.restore();
|
|
873
|
+
if (outputPass !== undefined) {
|
|
874
|
+
outputPass.scene = previousPassScene as Object3D;
|
|
875
|
+
outputPass.camera = previousPassCamera as Camera;
|
|
876
|
+
restoreWorldPass?.();
|
|
877
|
+
}
|
|
878
|
+
RendererUtils.restoreRendererState(warmRenderer, rendererState);
|
|
879
|
+
restoreField(raw, "transparent", hadOwnTransparent, previousTransparent);
|
|
880
|
+
restoreField(raw, "opaque", hadOwnOpaque, previousOpaque);
|
|
881
|
+
restoreField(raw, "contextNode", hadOwnContextNode, previousContextNode);
|
|
882
|
+
if (previousXr !== undefined)
|
|
883
|
+
restoreField(previousXr, "enabled", hadOwnXrEnabled, previousXrEnabled);
|
|
884
|
+
restoreField(
|
|
885
|
+
scene,
|
|
886
|
+
"overrideMaterial",
|
|
887
|
+
hadOwnSceneOverrideMaterial,
|
|
888
|
+
previousSceneOverrideMaterial,
|
|
889
|
+
);
|
|
890
|
+
restoreField(
|
|
891
|
+
outputRoot,
|
|
892
|
+
"overrideMaterial",
|
|
893
|
+
hadOwnOutputRootOverrideMaterial,
|
|
894
|
+
previousOutputRootOverrideMaterial,
|
|
895
|
+
);
|
|
896
|
+
scene.name = previousSceneName;
|
|
897
|
+
outputRoot.name = previousOutputRootName;
|
|
898
|
+
camera.layers.mask = previousCameraMask;
|
|
899
|
+
if (attached) {
|
|
900
|
+
outputRoot.remove(scene);
|
|
901
|
+
if (originalParent !== null) originalParent.add(scene);
|
|
902
|
+
}
|
|
903
|
+
scene.matrix.copy(originalMatrix);
|
|
904
|
+
scene.matrixWorld.copy(originalMatrixWorld);
|
|
905
|
+
}
|
|
906
|
+
// Every pipeline this covered render requested now exists in the renderer's caches, so the
|
|
907
|
+
// first visible frame finds them instead of compiling them synchronously. A renderer with
|
|
908
|
+
// no async cache still returns synchronously, exactly as before.
|
|
909
|
+
return asyncPipelines?.settled();
|
|
910
|
+
};
|
|
911
|
+
},
|
|
912
|
+
gpuFrameMs: () => gpuFrameSample()?.ms,
|
|
913
|
+
gpuFrameAge: () => {
|
|
914
|
+
const sample = gpuFrameSample();
|
|
915
|
+
const frame = currentFrame();
|
|
916
|
+
if (sample === undefined || frame === undefined || !Number.isInteger(frame)) return undefined;
|
|
917
|
+
// A fulfilled resolve may return the pool's lastValue on failure. The successful query's
|
|
918
|
+
// frame ID, not the promise or a changed duration, is the evidence of freshness.
|
|
919
|
+
return frame - sample.frame;
|
|
920
|
+
},
|
|
921
|
+
gpuFrameSample,
|
|
922
|
+
observeGpuFrames: (options) => {
|
|
923
|
+
if (
|
|
924
|
+
disposed ||
|
|
925
|
+
kind !== "webgpu" ||
|
|
926
|
+
!timestampCapable ||
|
|
927
|
+
typeof raw.resolveTimestampsAsync !== "function"
|
|
928
|
+
)
|
|
929
|
+
throw new Error("TN_GPU_FRAME_OBSERVATION_UNSUPPORTED");
|
|
930
|
+
if (gpuObservation !== undefined && gpuObservation.status().state !== "disposed")
|
|
931
|
+
throw new Error("TN_GPU_FRAME_OBSERVATION_ALREADY_ACTIVE");
|
|
932
|
+
gpuObservation = new GpuFrameObservation(
|
|
933
|
+
++gpuObservationGeneration,
|
|
934
|
+
timestampFrame + 1,
|
|
935
|
+
() => raw.backend?.timestampQueryPool?.render,
|
|
936
|
+
() => timestampFrame,
|
|
937
|
+
options,
|
|
938
|
+
);
|
|
939
|
+
return gpuObservation;
|
|
940
|
+
},
|
|
941
|
+
gpuMainMs: () => gpuMainEma,
|
|
942
|
+
noteGpuMainMs,
|
|
943
|
+
targetFps: () => targetFps,
|
|
944
|
+
noteTargetFps: (fps: number) => {
|
|
945
|
+
targetFps = Number.isFinite(fps) && fps > 0 ? fps : undefined;
|
|
946
|
+
},
|
|
947
|
+
gpuComputeMs: () => {
|
|
948
|
+
const timestamp = raw.info?.compute?.timestamp;
|
|
949
|
+
// Three writes `0` before the first resolve and on a failed one, so a non-positive value is
|
|
950
|
+
// no reading rather than a frame that cost nothing.
|
|
951
|
+
return typeof timestamp === "number" && Number.isFinite(timestamp) && timestamp > 0
|
|
952
|
+
? timestamp
|
|
953
|
+
: undefined;
|
|
954
|
+
},
|
|
955
|
+
gpuPyramidMs: () => {
|
|
956
|
+
const timestamps = raw.backend?.timestampQueryPool?.compute?.timestamps;
|
|
957
|
+
if (timestamps === undefined) return undefined;
|
|
958
|
+
for (const [index, uids] of pyramidQueries.entries()) {
|
|
959
|
+
const values = uids.map((uid) => timestamps.get(uid));
|
|
960
|
+
if (values.some((ms) => ms === undefined || !Number.isFinite(ms) || ms < 0)) continue;
|
|
961
|
+
pyramidQueries.splice(index, 1);
|
|
962
|
+
return values.reduce<number>((sum, ms) => sum + (ms ?? 0), 0);
|
|
963
|
+
}
|
|
964
|
+
return undefined;
|
|
965
|
+
},
|
|
966
|
+
resolveGpuFrame: () => {
|
|
967
|
+
// Fire and forget: a rejected resolve means this adapter has no timestamps, which is a
|
|
968
|
+
// reported absence rather than a frame-time error.
|
|
969
|
+
const resolveTimestampsAsync = raw.resolveTimestampsAsync;
|
|
970
|
+
if (resolveTimestampsAsync === undefined) return;
|
|
971
|
+
const observationBatch =
|
|
972
|
+
gpuObservation !== undefined && raw.backend?.trackTimestamp === true
|
|
973
|
+
? gpuObservation.capture()
|
|
974
|
+
: undefined;
|
|
975
|
+
void resolveTimestampsAsync.call(raw)?.catch(() => undefined);
|
|
976
|
+
gpuObservation?.submitted(observationBatch);
|
|
977
|
+
// Three maintains independent 2,048-query pools for render and compute passes. Resolving
|
|
978
|
+
// only the default render pool lets GPU simulations exhaust the compute pool even when the
|
|
979
|
+
// render pool is healthy, after which the adapter can be lost instead of merely reporting
|
|
980
|
+
// an absent timestamp.
|
|
981
|
+
void resolveTimestampsAsync.call(raw, "compute")?.catch(() => undefined);
|
|
982
|
+
},
|
|
983
|
+
setResolutionScale: (scale, scaleSource) => {
|
|
984
|
+
if (disposed) return;
|
|
985
|
+
// Three's asynchronous compile retains a depth target across yields. Resizing here
|
|
986
|
+
// disposes it before pipeline creation reads its format. Keep the latest request only.
|
|
987
|
+
if (activeCompiles > 0) {
|
|
988
|
+
pendingScale = { scale, source: scaleSource };
|
|
989
|
+
return;
|
|
990
|
+
}
|
|
991
|
+
state.resolutionScale = scale;
|
|
992
|
+
state.scaleSource = scaleSource;
|
|
993
|
+
reapply.resize?.();
|
|
994
|
+
},
|
|
995
|
+
surface: () => ({
|
|
996
|
+
// The renderer cannot be at a floor it does not know about; the loop that owns the scaler
|
|
997
|
+
// overrides this when one exists.
|
|
998
|
+
atFloor: false,
|
|
999
|
+
...(activeCompiles > 0 ? { compiling: true } : {}),
|
|
1000
|
+
drawingBufferHeight: applied.height,
|
|
1001
|
+
drawingBufferWidth: applied.width,
|
|
1002
|
+
resolutionScale: state.resolutionScale,
|
|
1003
|
+
...(raw.supportsRetainedTargetSubrect === false
|
|
1004
|
+
? { resolutionSubrect: false }
|
|
1005
|
+
: state.resolutionSubrect?.active === true
|
|
1006
|
+
? { resolutionSubrect: true }
|
|
1007
|
+
: {}),
|
|
1008
|
+
// Three reports 0 for a single sample per pixel; a sample count of zero would describe no
|
|
1009
|
+
// image at all.
|
|
1010
|
+
sampleCount: resolveSampleCount(raw),
|
|
1011
|
+
scaleSource: state.scaleSource,
|
|
1012
|
+
}),
|
|
1013
|
+
surfaceDrawingBufferHeight: () => applied.height,
|
|
1014
|
+
alphaAntialiasing: () => alphaAntialiasing.report(),
|
|
1015
|
+
...(softwareAdapter === undefined ? {} : { softwareAdapter }),
|
|
1016
|
+
...(gpuClass === undefined ? {} : { gpuClass }),
|
|
1017
|
+
domElement: raw.domElement,
|
|
1018
|
+
kind,
|
|
1019
|
+
raw,
|
|
1020
|
+
get info() {
|
|
1021
|
+
const info = (raw as { info?: unknown }).info;
|
|
1022
|
+
if (info === undefined || info === null)
|
|
1023
|
+
throw new Error(`info is unavailable on the ${kind} renderer.`);
|
|
1024
|
+
return info;
|
|
1025
|
+
},
|
|
1026
|
+
compileAsync: async (scene, camera, targetScene) => {
|
|
1027
|
+
if (disposed) return;
|
|
1028
|
+
// Before the compile, never after: three builds a pipeline from `alphaToCoverage` and
|
|
1029
|
+
// rebuilds it when the flag moves, so converting afterwards would throw away the warm-up
|
|
1030
|
+
// this call exists to buy. Ahead of the WebGL guard below for the same reason — the
|
|
1031
|
+
// fallback renderer honours the flag too, and this is the only hook it has.
|
|
1032
|
+
alphaAntialiasing.convertTree(scene);
|
|
1033
|
+
// WebGL has no equivalent and needs none — it compiles on first draw either way. Resolving
|
|
1034
|
+
// rather than throwing keeps one warm-up call working on every renderer a game may get.
|
|
1035
|
+
if (typeof raw.compileAsync !== "function") return;
|
|
1036
|
+
const hiddenRoots: Object3D[] = [];
|
|
1037
|
+
if (typeof scene.traverse === "function") {
|
|
1038
|
+
scene.traverse((object) => {
|
|
1039
|
+
if (prewarmedRoots.has(object) && hasHiddenAncestor(object)) hiddenRoots.push(object);
|
|
1040
|
+
});
|
|
1041
|
+
}
|
|
1042
|
+
const compileTargetScene = targetScene ?? scene;
|
|
1043
|
+
// three's `compile()` picks the frame-buffer target for its render context but never binds it
|
|
1044
|
+
// (`Renderer.js:908`, unlike `_renderScene`'s `setRenderTarget`). Inside one compile that
|
|
1045
|
+
// leaves a viewport-depth copy destination sized from that target's `samples` (4) while the
|
|
1046
|
+
// bind group layout for the same binding is sized from `currentSamples` (0): Dawn refuses the
|
|
1047
|
+
// bind group, the command buffer carrying it is invalid, and the device is lost the first
|
|
1048
|
+
// time a material samples depth under warm-up.
|
|
1049
|
+
//
|
|
1050
|
+
// The two halves disagree through one accessor. `getTextureSampleData` asks
|
|
1051
|
+
// `renderer.getRenderTarget()` for a depth texture that carries no target of its own
|
|
1052
|
+
// (`WebGPUUtils.js:112`), while the copy destination is built from the target `compile()`
|
|
1053
|
+
// already chose. So this answers that question and nothing else: `_renderTarget` is left
|
|
1054
|
+
// alone, because `render()` reads the field directly and this compile deliberately yields to
|
|
1055
|
+
// the frame loop between objects (`Renderer.js:1062`, `await yieldToMain()`). Binding the
|
|
1056
|
+
// target instead would put the live loading screen's frames into the frame-buffer target for
|
|
1057
|
+
// the whole warm-up, which is a frozen screen and a worse bug than the one being fixed.
|
|
1058
|
+
const previousGetRenderTarget = raw.getRenderTarget;
|
|
1059
|
+
const overrideTarget =
|
|
1060
|
+
raw.needsFrameBufferTarget === true &&
|
|
1061
|
+
typeof previousGetRenderTarget === "function" &&
|
|
1062
|
+
typeof raw._getFrameBufferTarget === "function" &&
|
|
1063
|
+
previousGetRenderTarget.call(raw) === null
|
|
1064
|
+
? raw._getFrameBufferTarget()
|
|
1065
|
+
: undefined;
|
|
1066
|
+
const hadOwnGetRenderTarget = Object.hasOwn(raw, "getRenderTarget");
|
|
1067
|
+
const boundBeforeCompile =
|
|
1068
|
+
(previousGetRenderTarget as (() => unknown) | undefined)?.call(raw) ?? null;
|
|
1069
|
+
if (overrideTarget !== undefined) {
|
|
1070
|
+
// Only the compile may see it. A frame rendered inside this window must get the real
|
|
1071
|
+
// answer, because three's own reflector saves `getRenderTarget()` at the top of its
|
|
1072
|
+
// `updateBefore` and restores what it saved: handed the frame-buffer target, it puts the
|
|
1073
|
+
// frame-buffer target back, and from that frame on the renderer draws into it instead of
|
|
1074
|
+
// the swapchain. Measured on a game with a water reflection — the swapchain image was
|
|
1075
|
+
// never acquired again, presents froze at 137 while the loop ran at 59 fps, and the window
|
|
1076
|
+
// showed the same loading screen for the rest of the session.
|
|
1077
|
+
raw.getRenderTarget = () =>
|
|
1078
|
+
(previousGetRenderTarget as () => unknown).call(raw) ??
|
|
1079
|
+
(renderingFrame > 0 ? null : overrideTarget);
|
|
1080
|
+
}
|
|
1081
|
+
activeCompiles += 1;
|
|
1082
|
+
compileCount += 1;
|
|
1083
|
+
try {
|
|
1084
|
+
for (const root of hiddenRoots) {
|
|
1085
|
+
if (disposed) return;
|
|
1086
|
+
await raw.compileAsync(root, camera, compileTargetScene);
|
|
1087
|
+
prewarmedRoots.delete(root);
|
|
1088
|
+
}
|
|
1089
|
+
if (!disposed) {
|
|
1090
|
+
if (targetScene === undefined) await raw.compileAsync(scene, camera);
|
|
1091
|
+
else await raw.compileAsync(scene, camera, targetScene);
|
|
1092
|
+
}
|
|
1093
|
+
} finally {
|
|
1094
|
+
if (overrideTarget !== undefined) {
|
|
1095
|
+
if (hadOwnGetRenderTarget) raw.getRenderTarget = previousGetRenderTarget;
|
|
1096
|
+
else Reflect.deleteProperty(raw as object, "getRenderTarget");
|
|
1097
|
+
// Put back the target that was bound when this compile started.
|
|
1098
|
+
//
|
|
1099
|
+
// three's compile runs node `updateBefore` hooks, and a reflector's saves
|
|
1100
|
+
// `renderer.getRenderTarget()`, draws its mirror, and restores what it saved. Inside the
|
|
1101
|
+
// window above that answer is the frame-buffer target, so the reflector *binds* it and
|
|
1102
|
+
// leaves it bound: from the next frame on the renderer draws into that target instead of
|
|
1103
|
+
// the swapchain, the swapchain image is never acquired again, and the window keeps
|
|
1104
|
+
// showing whatever was on it. Measured on a game with a water reflection — presents
|
|
1105
|
+
// frozen at 137 while the loop ran at 59 fps, with `TN_FRAME_NOT_PRESENTED`
|
|
1106
|
+
// (`texture:false`) every frame for the rest of the session.
|
|
1107
|
+
const boundNow = (previousGetRenderTarget as () => unknown).call(raw);
|
|
1108
|
+
if (boundNow === overrideTarget && typeof raw.setRenderTarget === "function")
|
|
1109
|
+
raw.setRenderTarget(boundBeforeCompile);
|
|
1110
|
+
}
|
|
1111
|
+
activeCompiles -= 1;
|
|
1112
|
+
if (activeCompiles === 0) {
|
|
1113
|
+
const requestedScale = pendingScale;
|
|
1114
|
+
const requestedSize = pendingSize;
|
|
1115
|
+
pendingScale = undefined;
|
|
1116
|
+
pendingSize = undefined;
|
|
1117
|
+
if (!disposed) {
|
|
1118
|
+
// Re-read the latest viewport when scale also changed; a queued old-scale size
|
|
1119
|
+
// must not overwrite the new drawing buffer.
|
|
1120
|
+
if (requestedScale !== undefined)
|
|
1121
|
+
wrapped.setResolutionScale(requestedScale.scale, requestedScale.source);
|
|
1122
|
+
else if (requestedSize !== undefined) wrapped.setSize(...requestedSize);
|
|
1123
|
+
}
|
|
1124
|
+
}
|
|
1125
|
+
}
|
|
1126
|
+
},
|
|
1127
|
+
beginFrame: () => {
|
|
1128
|
+
timestampFramesManaged = true;
|
|
1129
|
+
setTimestampTracking();
|
|
1130
|
+
},
|
|
1131
|
+
compute: (node, span) => {
|
|
1132
|
+
if (kind !== "webgpu") throw new Error(`compute is unavailable on the ${kind} renderer.`);
|
|
1133
|
+
if (typeof raw.compute !== "function")
|
|
1134
|
+
throw new Error("webgpu renderer does not expose compute().");
|
|
1135
|
+
// As a standalone draw: a caller that does not manage frames with beginFrame() gets one
|
|
1136
|
+
// sampler frame per dispatch, which is what the compute timing scope keys its calls by.
|
|
1137
|
+
if (!timestampFramesManaged) setTimestampTracking();
|
|
1138
|
+
const backend = raw.backend;
|
|
1139
|
+
const before = backend?.timestampQueryPool?.compute?.queryOffsets?.size ?? 0;
|
|
1140
|
+
raw.compute(node);
|
|
1141
|
+
if (span === "depthPyramid") {
|
|
1142
|
+
const offsets = backend?.timestampQueryPool?.compute?.queryOffsets;
|
|
1143
|
+
const uids = offsets === undefined ? [] : [...offsets.keys()].slice(before);
|
|
1144
|
+
if (uids.length > 0) pyramidQueries.push(uids);
|
|
1145
|
+
// Match the render-pass recorder's bounded query retention on a stalled resolve.
|
|
1146
|
+
if (pyramidQueries.length > 64) pyramidQueries.shift();
|
|
1147
|
+
}
|
|
1148
|
+
},
|
|
1149
|
+
computeTiming: (operation, options) => {
|
|
1150
|
+
if (disposed) throw new Error("TN_COMPUTE_TIMING_STALE: renderer disposed.");
|
|
1151
|
+
computeTimings ??= new ComputeTimingScopes(() => raw);
|
|
1152
|
+
return computeTimings.capture(operation, options);
|
|
1153
|
+
},
|
|
1154
|
+
uploadAttributes: (geometries) => {
|
|
1155
|
+
const backend = kind === "webgpu" ? raw.backend : undefined;
|
|
1156
|
+
if (typeof backend?.createAttribute !== "function") return 0;
|
|
1157
|
+
let created = 0;
|
|
1158
|
+
try {
|
|
1159
|
+
for (const geometry of geometries) {
|
|
1160
|
+
for (const attribute of Object.values(geometry.attributes)) {
|
|
1161
|
+
backend.createAttribute(attribute);
|
|
1162
|
+
created += 1;
|
|
1163
|
+
}
|
|
1164
|
+
const index = geometry.getIndex();
|
|
1165
|
+
if (index !== null && typeof backend.createIndexAttribute === "function") {
|
|
1166
|
+
backend.createIndexAttribute(index);
|
|
1167
|
+
created += 1;
|
|
1168
|
+
}
|
|
1169
|
+
}
|
|
1170
|
+
} catch {
|
|
1171
|
+
// A backend that will not take an attribute is a device that has already lost; the frame
|
|
1172
|
+
// that needs it tries again there, where the error belongs.
|
|
1173
|
+
}
|
|
1174
|
+
return created;
|
|
1175
|
+
},
|
|
1176
|
+
prepareTextures: async (textures, signal, onProgress) => {
|
|
1177
|
+
if (disposed) throw new Error("Renderer disposed during texture preparation.");
|
|
1178
|
+
if (kind !== "webgpu") return 0;
|
|
1179
|
+
const unique = new Set(
|
|
1180
|
+
[...textures].filter(
|
|
1181
|
+
(texture) => "isCompressedTexture" in texture && texture.isCompressedTexture === true,
|
|
1182
|
+
),
|
|
1183
|
+
);
|
|
1184
|
+
if (unique.size === 0) return 0;
|
|
1185
|
+
if (typeof raw.prepareTextureAsync !== "function")
|
|
1186
|
+
throw new Error("WebGPU renderer lacks bounded compressed texture preparation.");
|
|
1187
|
+
const controller = new AbortController();
|
|
1188
|
+
const abort = () => controller.abort(signal?.reason);
|
|
1189
|
+
if (signal?.aborted) abort();
|
|
1190
|
+
else signal?.addEventListener("abort", abort, { once: true });
|
|
1191
|
+
texturePreparations.add(controller);
|
|
1192
|
+
let completed = 0;
|
|
1193
|
+
try {
|
|
1194
|
+
for (const texture of unique) {
|
|
1195
|
+
if (controller.signal.aborted) throw controller.signal.reason;
|
|
1196
|
+
await raw.prepareTextureAsync(texture, {
|
|
1197
|
+
budgetMs: 2,
|
|
1198
|
+
maxBytesPerWrite: 65_536,
|
|
1199
|
+
signal: controller.signal,
|
|
1200
|
+
});
|
|
1201
|
+
completed += 1;
|
|
1202
|
+
onProgress?.(completed);
|
|
1203
|
+
}
|
|
1204
|
+
return unique.size;
|
|
1205
|
+
} finally {
|
|
1206
|
+
texturePreparations.delete(controller);
|
|
1207
|
+
signal?.removeEventListener("abort", abort);
|
|
1208
|
+
}
|
|
1209
|
+
},
|
|
1210
|
+
scenePassDepth: () => {
|
|
1211
|
+
// Three's implicit depth is in Textures.updateRenderTarget's data, not target.depthTexture.
|
|
1212
|
+
// Never fall through to presentation depth: the output blit does not draw the world there.
|
|
1213
|
+
// Read the existing attachment without creating a target or claiming texture bookkeeping.
|
|
1214
|
+
const host = raw as {
|
|
1215
|
+
needsFrameBufferTarget?: boolean;
|
|
1216
|
+
_getFrameBufferTarget?: () => {
|
|
1217
|
+
depthTexture?: DepthTexture | null;
|
|
1218
|
+
samples?: number;
|
|
1219
|
+
} | null;
|
|
1220
|
+
_textures?: { get(t: unknown): { depthTexture?: DepthTexture | null } };
|
|
1221
|
+
};
|
|
1222
|
+
const target =
|
|
1223
|
+
outputPass?.renderTarget ??
|
|
1224
|
+
(host.needsFrameBufferTarget === true ? host._getFrameBufferTarget?.() : undefined);
|
|
1225
|
+
if (!target) return undefined;
|
|
1226
|
+
const texture = host._textures?.get(target).depthTexture ?? target.depthTexture;
|
|
1227
|
+
if (!texture) return undefined;
|
|
1228
|
+
const width = texture.image.width ?? 0;
|
|
1229
|
+
const height = texture.image.height ?? 0;
|
|
1230
|
+
if (width < 2 || height < 2) return undefined;
|
|
1231
|
+
return { height, texture, width, samples: Math.max(1, target.samples ?? 1) };
|
|
1232
|
+
},
|
|
1233
|
+
uploadTextures: (object) => {
|
|
1234
|
+
// three's own texture path, not the backend's: `Textures.updateTexture` owns the bookkeeping
|
|
1235
|
+
// (`initialized`, `generation`, the bind groups to invalidate) that is what makes the first draw
|
|
1236
|
+
// skip the upload, and a backend call without it would upload twice.
|
|
1237
|
+
const textures = (raw as { _textures?: { updateTexture?: (t: unknown, o: object) => void } })
|
|
1238
|
+
._textures;
|
|
1239
|
+
if (kind !== "webgpu" || typeof textures?.updateTexture !== "function") return 0;
|
|
1240
|
+
const pending = new Set<unknown>();
|
|
1241
|
+
object.traverse((node) => {
|
|
1242
|
+
const material = (node as { material?: unknown }).material;
|
|
1243
|
+
if (material === undefined || material === null) return;
|
|
1244
|
+
for (const entry of Array.isArray(material) ? material : [material]) {
|
|
1245
|
+
if (typeof entry !== "object" || entry === null) continue;
|
|
1246
|
+
// A material's texture slots are own enumerable values and a `ShaderMaterial`'s live ones
|
|
1247
|
+
// are in `uniforms`; both are found by reading the value and asking whether it is a texture.
|
|
1248
|
+
for (const value of Object.values(entry as Record<string, unknown>)) {
|
|
1249
|
+
if ((value as { isTexture?: boolean } | null)?.isTexture === true) pending.add(value);
|
|
1250
|
+
}
|
|
1251
|
+
for (const uniform of Object.values(
|
|
1252
|
+
(entry as { uniforms?: Record<string, { value?: unknown }> }).uniforms ?? {},
|
|
1253
|
+
)) {
|
|
1254
|
+
if ((uniform?.value as { isTexture?: boolean } | null)?.isTexture === true)
|
|
1255
|
+
pending.add(uniform.value);
|
|
1256
|
+
}
|
|
1257
|
+
}
|
|
1258
|
+
});
|
|
1259
|
+
let created = 0;
|
|
1260
|
+
try {
|
|
1261
|
+
for (const texture of pending) {
|
|
1262
|
+
// `updateTexture` fills width, height, mip levels and the image list into the options it is
|
|
1263
|
+
// handed, so each texture needs an object of its own.
|
|
1264
|
+
textures.updateTexture?.(texture, {});
|
|
1265
|
+
created += 1;
|
|
1266
|
+
}
|
|
1267
|
+
} catch {
|
|
1268
|
+
// A device that will not take the texture takes it on the frame that needs it, where the
|
|
1269
|
+
// error belongs.
|
|
1270
|
+
}
|
|
1271
|
+
return created;
|
|
1272
|
+
},
|
|
1273
|
+
storageBuffer: (attribute) => storageBuffers.allocate(attribute),
|
|
1274
|
+
readback: async (attribute, target) => {
|
|
1275
|
+
if (kind !== "webgpu") throw new Error(`readback is unavailable on the ${kind} renderer.`);
|
|
1276
|
+
if (typeof raw.getArrayBufferAsync !== "function")
|
|
1277
|
+
throw new Error("webgpu renderer does not expose getArrayBufferAsync().");
|
|
1278
|
+
if (
|
|
1279
|
+
target !== undefined &&
|
|
1280
|
+
(!(target instanceof ReadbackBuffer) ||
|
|
1281
|
+
!Number.isSafeInteger(target.maxByteLength) ||
|
|
1282
|
+
target.maxByteLength <= 0 ||
|
|
1283
|
+
target.maxByteLength % 4 !== 0 ||
|
|
1284
|
+
target.buffer !== null)
|
|
1285
|
+
)
|
|
1286
|
+
throw new Error(
|
|
1287
|
+
"TN_READBACK_TARGET_INVALID: a fresh aligned public ReadbackBuffer is required.",
|
|
1288
|
+
);
|
|
1289
|
+
const result = await raw.getArrayBufferAsync(attribute, target);
|
|
1290
|
+
if (target === undefined) {
|
|
1291
|
+
if (!(result instanceof ArrayBuffer))
|
|
1292
|
+
throw new Error("TN_READBACK_RESULT_INVALID: CPU bytes are absent.");
|
|
1293
|
+
return result;
|
|
1294
|
+
}
|
|
1295
|
+
if (
|
|
1296
|
+
result !== target ||
|
|
1297
|
+
!(target.buffer instanceof ArrayBuffer) ||
|
|
1298
|
+
target.buffer.byteLength > target.maxByteLength
|
|
1299
|
+
)
|
|
1300
|
+
throw new Error(
|
|
1301
|
+
"TN_READBACK_RESULT_INVALID: caller-owned target did not receive bounded CPU bytes.",
|
|
1302
|
+
);
|
|
1303
|
+
return target.buffer.slice(0);
|
|
1304
|
+
},
|
|
1305
|
+
dispose: () => {
|
|
1306
|
+
computeTimings?.dispose();
|
|
1307
|
+
if (disposed) {
|
|
1308
|
+
storageBuffers.dispose();
|
|
1309
|
+
return;
|
|
1310
|
+
}
|
|
1311
|
+
disposed = true;
|
|
1312
|
+
state.resolutionSubrect?.deactivate?.();
|
|
1313
|
+
state.resolutionSubrect = undefined;
|
|
1314
|
+
for (const preparation of texturePreparations)
|
|
1315
|
+
preparation.abort(new Error("Renderer disposed during texture preparation."));
|
|
1316
|
+
texturePreparations.clear();
|
|
1317
|
+
gpuObservation?.dispose();
|
|
1318
|
+
gpuObservation = undefined;
|
|
1319
|
+
pendingScale = undefined;
|
|
1320
|
+
pendingSize = undefined;
|
|
1321
|
+
for (const chain of renderChains) chain.dispose();
|
|
1322
|
+
renderChains.clear();
|
|
1323
|
+
renderChainUsesPerObjectVelocity = false;
|
|
1324
|
+
outputPipeline?.dispose();
|
|
1325
|
+
pendingWorldPassRefresh = false;
|
|
1326
|
+
outputPipeline = undefined;
|
|
1327
|
+
warmOutputTarget?.dispose();
|
|
1328
|
+
warmOutputTarget = undefined;
|
|
1329
|
+
outputInput = undefined;
|
|
1330
|
+
outputPass = undefined;
|
|
1331
|
+
pipelineCensus?.dispose();
|
|
1332
|
+
try {
|
|
1333
|
+
storageBuffers.dispose();
|
|
1334
|
+
} finally {
|
|
1335
|
+
raw.dispose?.();
|
|
1336
|
+
}
|
|
1337
|
+
},
|
|
1338
|
+
render: (scene, camera) => {
|
|
1339
|
+
// Standalone render callers retain one frame per draw unless they supply beginFrame().
|
|
1340
|
+
if (!timestampFramesManaged) setTimestampTracking();
|
|
1341
|
+
renderingFrame += 1;
|
|
1342
|
+
try {
|
|
1343
|
+
renderFrame(scene, camera);
|
|
1344
|
+
} finally {
|
|
1345
|
+
renderingFrame -= 1;
|
|
1346
|
+
}
|
|
1347
|
+
},
|
|
1348
|
+
renderOverlay: (scene, camera) => {
|
|
1349
|
+
renderingFrame += 1;
|
|
1350
|
+
try {
|
|
1351
|
+
renderOverlayFrame(scene, camera);
|
|
1352
|
+
} finally {
|
|
1353
|
+
renderingFrame -= 1;
|
|
1354
|
+
}
|
|
1355
|
+
},
|
|
1356
|
+
...(raw.supportsRetainedTargetSubrect === false
|
|
1357
|
+
? {}
|
|
1358
|
+
: { createResolutionSubrect: () => new ResolutionSubrect() }),
|
|
1359
|
+
setOutputNode: (node, worldPass, options) => {
|
|
1360
|
+
if (kind !== "webgpu")
|
|
1361
|
+
throw new Error(`setOutputNode is unavailable on the ${kind} renderer.`);
|
|
1362
|
+
const nextOutputPass = selectOutputPass(node, worldPass);
|
|
1363
|
+
const nextPipeline = new RenderPipeline(
|
|
1364
|
+
raw as unknown as ConstructorParameters<typeof RenderPipeline>[0],
|
|
1365
|
+
node as ConstructorParameters<typeof RenderPipeline>[1],
|
|
1366
|
+
);
|
|
1367
|
+
// The pipeline applies the tone curve and the output encode by default. A stage that took
|
|
1368
|
+
// the transform over applies it itself, so the pipeline must not apply a second one.
|
|
1369
|
+
if (options?.outputColorTransform !== undefined) {
|
|
1370
|
+
nextPipeline.outputColorTransform = options.outputColorTransform;
|
|
1371
|
+
}
|
|
1372
|
+
if (state.resolutionSubrect !== options?.resolutionSubrect)
|
|
1373
|
+
state.resolutionSubrect?.deactivate?.();
|
|
1374
|
+
state.resolutionSubrect = options?.resolutionSubrect;
|
|
1375
|
+
state.resolutionSubrect?.activate?.(state.resolutionScale);
|
|
1376
|
+
outputPipeline?.dispose();
|
|
1377
|
+
pendingWorldPassRefresh = false;
|
|
1378
|
+
outputPass = nextOutputPass;
|
|
1379
|
+
outputPipeline = nextPipeline;
|
|
1380
|
+
outputInput = node;
|
|
1381
|
+
reapply.resize?.();
|
|
1382
|
+
return {
|
|
1383
|
+
isCurrent: () => outputPipeline === nextPipeline,
|
|
1384
|
+
dispose: () => {
|
|
1385
|
+
if (outputPipeline !== nextPipeline) return;
|
|
1386
|
+
pendingWorldPassRefresh = false;
|
|
1387
|
+
outputPipeline = undefined;
|
|
1388
|
+
outputInput = undefined;
|
|
1389
|
+
outputPass = undefined;
|
|
1390
|
+
nextPipeline.dispose();
|
|
1391
|
+
state.resolutionSubrect?.deactivate?.();
|
|
1392
|
+
state.resolutionSubrect = undefined;
|
|
1393
|
+
reapply.resize?.();
|
|
1394
|
+
},
|
|
1395
|
+
};
|
|
1396
|
+
},
|
|
1397
|
+
clearOutputNode: (expectedNode) => {
|
|
1398
|
+
if (expectedNode !== undefined && expectedNode !== outputInput) return;
|
|
1399
|
+
outputPipeline?.dispose();
|
|
1400
|
+
pendingWorldPassRefresh = false;
|
|
1401
|
+
outputPipeline = undefined;
|
|
1402
|
+
outputInput = undefined;
|
|
1403
|
+
outputPass = undefined;
|
|
1404
|
+
state.resolutionSubrect?.deactivate?.();
|
|
1405
|
+
state.resolutionSubrect = undefined;
|
|
1406
|
+
reapply.resize?.();
|
|
1407
|
+
},
|
|
1408
|
+
renderChainUsesPerObjectVelocity: () => renderChainUsesPerObjectVelocity,
|
|
1409
|
+
setRenderChainVelocityEnabled: (enabled) => {
|
|
1410
|
+
renderChainUsesPerObjectVelocity = enabled;
|
|
1411
|
+
},
|
|
1412
|
+
createRenderChain: (options) => {
|
|
1413
|
+
// One renderer has one output pipeline. Disposing the previous chain prevents an old scene's
|
|
1414
|
+
// automatic tier from reinstalling its graph after a scene transition.
|
|
1415
|
+
for (const chain of renderChains) chain.dispose();
|
|
1416
|
+
renderChains.clear();
|
|
1417
|
+
const chain = new RenderChain(wrapped, options);
|
|
1418
|
+
renderChains.add(chain);
|
|
1419
|
+
return chain;
|
|
1420
|
+
},
|
|
1421
|
+
observeRenderChainBudget: (window) => {
|
|
1422
|
+
for (const chain of renderChains) {
|
|
1423
|
+
if (chain.disposed) {
|
|
1424
|
+
renderChains.delete(chain);
|
|
1425
|
+
continue;
|
|
1426
|
+
}
|
|
1427
|
+
chain.observeFrameBudget(window);
|
|
1428
|
+
}
|
|
1429
|
+
},
|
|
1430
|
+
observeRenderChainFrame: () => {
|
|
1431
|
+
for (const chain of renderChains) {
|
|
1432
|
+
if (chain.disposed) {
|
|
1433
|
+
renderChains.delete(chain);
|
|
1434
|
+
continue;
|
|
1435
|
+
}
|
|
1436
|
+
chain.observeFrame();
|
|
1437
|
+
}
|
|
1438
|
+
},
|
|
1439
|
+
setSize: (width, height, updateStyle = false) => {
|
|
1440
|
+
if (disposed) return;
|
|
1441
|
+
if (activeCompiles > 0) {
|
|
1442
|
+
pendingSize = [width, height, updateStyle];
|
|
1443
|
+
return;
|
|
1444
|
+
}
|
|
1445
|
+
raw.setSize(width, height, updateStyle);
|
|
1446
|
+
applied.width = width;
|
|
1447
|
+
applied.height = height;
|
|
1448
|
+
},
|
|
1449
|
+
};
|
|
1450
|
+
return wrapped;
|
|
1451
|
+
}
|
|
1452
|
+
|
|
1453
|
+
function isOutputPassNode(node: unknown): node is PassNode {
|
|
1454
|
+
return isObject(node) && node.isPassNode === true;
|
|
1455
|
+
}
|
|
1456
|
+
|
|
1457
|
+
function selectOutputPass(node: unknown, worldPass: unknown): PassNode | undefined {
|
|
1458
|
+
return outputPassOf(worldPass) ?? outputPassOf(node) ?? findSoleOutputPass(node);
|
|
1459
|
+
}
|
|
1460
|
+
|
|
1461
|
+
/**
|
|
1462
|
+
* The pass a node names, whether it is the pass itself or one of its texture nodes.
|
|
1463
|
+
*
|
|
1464
|
+
* A game that composes onto the pass output hands `setOutputNode` the composed node, not the pass:
|
|
1465
|
+
* `renderer.setOutputNode(scenePass.getTextureNode("output"))` carries the pass on `passNode`, and
|
|
1466
|
+
* without reading that the wrapper has no scene-pass depth to give an occlusion cull.
|
|
1467
|
+
*/
|
|
1468
|
+
function outputPassOf(node: unknown): PassNode | undefined {
|
|
1469
|
+
if (isOutputPassNode(node)) return node;
|
|
1470
|
+
if (isObject(node) && node.isPassTextureNode === true && isOutputPassNode(node.passNode))
|
|
1471
|
+
return node.passNode;
|
|
1472
|
+
return undefined;
|
|
1473
|
+
}
|
|
1474
|
+
|
|
1475
|
+
function findSoleOutputPass(node: unknown): PassNode | undefined {
|
|
1476
|
+
if (!isTraversableOutputNode(node)) return undefined;
|
|
1477
|
+
const passes = new Set<PassNode>();
|
|
1478
|
+
node.traverse((candidate) => {
|
|
1479
|
+
const pass = outputPassOf(candidate);
|
|
1480
|
+
if (pass !== undefined) passes.add(pass);
|
|
1481
|
+
});
|
|
1482
|
+
if (passes.size > 1)
|
|
1483
|
+
throw new Error(
|
|
1484
|
+
"TN_RENDER_OUTPUT_PASS_AMBIGUOUS: output graph contains multiple pass nodes; pass the explicit world pass to setOutputNode().",
|
|
1485
|
+
);
|
|
1486
|
+
return passes.values().next().value;
|
|
1487
|
+
}
|
|
1488
|
+
|
|
1489
|
+
function setOutputPipelineRoot(pass: PassNode | undefined, scene: Object3D, camera: Camera): void {
|
|
1490
|
+
if (pass === undefined) return;
|
|
1491
|
+
pass.scene = scene;
|
|
1492
|
+
pass.camera = camera;
|
|
1493
|
+
}
|
|
1494
|
+
|
|
1495
|
+
function isInObject3DSubtree(root: Object3D, object: Object3D): boolean {
|
|
1496
|
+
let current: Object3D | null = object;
|
|
1497
|
+
while (current !== null) {
|
|
1498
|
+
if (current === root) return true;
|
|
1499
|
+
current = current.parent;
|
|
1500
|
+
}
|
|
1501
|
+
return false;
|
|
1502
|
+
}
|
|
1503
|
+
|
|
1504
|
+
function isObject(value: unknown): value is Record<string, unknown> {
|
|
1505
|
+
return typeof value === "object" && value !== null;
|
|
1506
|
+
}
|
|
1507
|
+
|
|
1508
|
+
function isTraversableOutputNode(value: unknown): value is ITraversableOutputNode {
|
|
1509
|
+
return isObject(value) && typeof value.traverse === "function";
|
|
1510
|
+
}
|
|
1511
|
+
|
|
1512
|
+
function addResizeHandling(
|
|
1513
|
+
renderer: IRendererLike,
|
|
1514
|
+
source: IRendererPlatformSource | undefined,
|
|
1515
|
+
state: ISurfaceState,
|
|
1516
|
+
pixelRatio: number,
|
|
1517
|
+
): { resize: () => void; stop: () => void } {
|
|
1518
|
+
// The last layout size read and the drawing buffer set from it. A canvas with no CSS size lays
|
|
1519
|
+
// out at its drawing buffer, so the buffer set here comes back as the next layout size: that echo
|
|
1520
|
+
// is not a new layout, and scaling it again compounds (Midway's canvas fell to 3x3).
|
|
1521
|
+
let layout: readonly [number, number] | undefined;
|
|
1522
|
+
let applied: readonly [number, number] | undefined;
|
|
1523
|
+
const resize = () => {
|
|
1524
|
+
let [width, height] =
|
|
1525
|
+
source?.readSize(renderer.domElement) ?? readCanvasSize(renderer.domElement);
|
|
1526
|
+
if (
|
|
1527
|
+
layout !== undefined &&
|
|
1528
|
+
applied !== undefined &&
|
|
1529
|
+
width === applied[0] &&
|
|
1530
|
+
height === applied[1]
|
|
1531
|
+
) {
|
|
1532
|
+
[width, height] = layout;
|
|
1533
|
+
// The echo proves the canvas has no size of its own, so the page would show it at its buffer:
|
|
1534
|
+
// shrunk under a scale below 1 (Midway fell to 1088x612), doubled at ratio 2. Pin it.
|
|
1535
|
+
const style = (renderer.domElement as { style?: CSSStyleDeclaration }).style;
|
|
1536
|
+
if (style !== undefined) {
|
|
1537
|
+
style.width = `${width}px`;
|
|
1538
|
+
style.height = `${height}px`;
|
|
1539
|
+
}
|
|
1540
|
+
}
|
|
1541
|
+
layout = [width, height];
|
|
1542
|
+
// Recorded as it is applied rather than read back off the canvas: the canvas dimensions are
|
|
1543
|
+
// the host's to define and on native they have been the physical surface, which is exactly
|
|
1544
|
+
// the number this scale exists to stop a game from paying by hand.
|
|
1545
|
+
const subrect = state.resolutionSubrect;
|
|
1546
|
+
const scale = subrect?.active ? 1 : state.resolutionScale;
|
|
1547
|
+
const physicalWidth = Math.max(1, Math.round(width * pixelRatio * scale));
|
|
1548
|
+
const physicalHeight = Math.max(1, Math.round(height * pixelRatio * scale));
|
|
1549
|
+
applied = [physicalWidth, physicalHeight];
|
|
1550
|
+
const surface = renderer.surface();
|
|
1551
|
+
if (
|
|
1552
|
+
surface.drawingBufferWidth !== physicalWidth ||
|
|
1553
|
+
surface.drawingBufferHeight !== physicalHeight
|
|
1554
|
+
)
|
|
1555
|
+
renderer.setSize(physicalWidth, physicalHeight, false);
|
|
1556
|
+
if (subrect?.active) {
|
|
1557
|
+
subrect.setScale?.(state.resolutionScale);
|
|
1558
|
+
subrect.setSize?.(physicalWidth, physicalHeight);
|
|
1559
|
+
}
|
|
1560
|
+
};
|
|
1561
|
+
resize();
|
|
1562
|
+
const stop =
|
|
1563
|
+
source?.observeResize(renderer.domElement, resize) ??
|
|
1564
|
+
observeCanvasResize(renderer.domElement, resize);
|
|
1565
|
+
return { resize, stop };
|
|
1566
|
+
}
|
|
1567
|
+
|
|
1568
|
+
/** The live scale, mutated only by `setResolutionScale`, read by every window report. */
|
|
1569
|
+
interface ISurfaceState {
|
|
1570
|
+
resolutionSubrect?: IResolutionSubrect | undefined;
|
|
1571
|
+
resolutionScale: number;
|
|
1572
|
+
scaleSource: "pinned" | "auto" | "auto-pinned";
|
|
1573
|
+
}
|
|
1574
|
+
|
|
1575
|
+
function createRendererPipelineCensus(
|
|
1576
|
+
raw: RendererInstance,
|
|
1577
|
+
kind: RendererKind,
|
|
1578
|
+
options: IRendererOptions,
|
|
1579
|
+
adapterIdentity?: string,
|
|
1580
|
+
): PipelineCensus | undefined {
|
|
1581
|
+
if (options.pipelineCensus === false) return undefined;
|
|
1582
|
+
const backendName =
|
|
1583
|
+
typeof raw.backend === "object" && raw.backend !== null
|
|
1584
|
+
? (raw.backend.constructor as { name?: unknown } | undefined)?.name
|
|
1585
|
+
: undefined;
|
|
1586
|
+
const census = createPipelineCensus({
|
|
1587
|
+
kind,
|
|
1588
|
+
...(options.pipelineCensus === undefined || options.pipelineCensus.limit === undefined
|
|
1589
|
+
? {}
|
|
1590
|
+
: { limit: options.pipelineCensus.limit }),
|
|
1591
|
+
...(typeof backendName === "string" && backendName.length > 0
|
|
1592
|
+
? { backendIdentity: `${kind}:${backendName}` }
|
|
1593
|
+
: {}),
|
|
1594
|
+
...(kind === "webgpu" ? { adapterIdentity: adapterIdentity ?? "unavailable" } : {}),
|
|
1595
|
+
});
|
|
1596
|
+
census.installRenderer(raw);
|
|
1597
|
+
return census;
|
|
1598
|
+
}
|
|
1599
|
+
|
|
1600
|
+
async function createWebGpuPipelineCensus(
|
|
1601
|
+
raw: RendererInstance,
|
|
1602
|
+
options: IRendererOptions,
|
|
1603
|
+
adapter: IWebGpuAdapterFacts,
|
|
1604
|
+
): Promise<PipelineCensus | undefined> {
|
|
1605
|
+
return createRendererPipelineCensus(raw, "webgpu", options, adapter.identity);
|
|
1606
|
+
}
|
|
1607
|
+
|
|
1608
|
+
/**
|
|
1609
|
+
* The adapters `navigator.gpu` has handed this page, kept for the life of the module.
|
|
1610
|
+
*
|
|
1611
|
+
* A local `const adapter = await requestAdapter()` is the shape every WebGPU sample uses, and it is
|
|
1612
|
+
* the shape Chromium punishes: a collected `GPUAdapter` takes the wire instance down with it, and
|
|
1613
|
+
* Dawn reports that on every operation still in flight as `A valid external Instance reference no
|
|
1614
|
+
* longer exists.` — the `mapAsync` of the timestamp-query pool and of a GPU readback then rejects
|
|
1615
|
+
* forever, the canvas stops presenting, and a run that was healthy at 30 s is black at the end.
|
|
1616
|
+
* Collecting needs heap pressure, so it shows up only in the long runs.
|
|
1617
|
+
*
|
|
1618
|
+
* three's backend keeps the device and `navigator.gpu` but not its adapter, so this is the only
|
|
1619
|
+
* strong reference to the one core asked for. Two adapters per renderer: one for the device's
|
|
1620
|
+
* limits, one for the identity the capture and the software gate are read from.
|
|
1621
|
+
*/
|
|
1622
|
+
const retainedAdapters = new Set<unknown>();
|
|
1623
|
+
|
|
1624
|
+
/** The adapters core is holding. A test reads this; a run never does. */
|
|
1625
|
+
export function retainedWebGpuAdapters(): ReadonlySet<unknown> {
|
|
1626
|
+
return retainedAdapters;
|
|
1627
|
+
}
|
|
1628
|
+
|
|
1629
|
+
interface IWebGpuAdapterFacts {
|
|
1630
|
+
/** The URI-encoded identity the pipeline census records; absent when the adapter reported none. */
|
|
1631
|
+
readonly identity?: string;
|
|
1632
|
+
/** The field value that names a CPU rasteriser; absent when none of them does. */
|
|
1633
|
+
readonly software?: string;
|
|
1634
|
+
/** The family the four fields classify as; absent when the adapter reported no info at all. */
|
|
1635
|
+
readonly gpuClass?: IGpuClassification;
|
|
1636
|
+
}
|
|
1637
|
+
|
|
1638
|
+
async function readWebGpuAdapterFacts(raw: RendererInstance): Promise<IWebGpuAdapterFacts> {
|
|
1639
|
+
const gpu = raw.backend?.gpu;
|
|
1640
|
+
if (gpu === undefined || typeof gpu.requestAdapter !== "function") return {};
|
|
1641
|
+
try {
|
|
1642
|
+
const adapter = await gpu.requestAdapter.call(gpu, {
|
|
1643
|
+
featureLevel: "compatibility",
|
|
1644
|
+
powerPreference: raw.backend?.parameters?.powerPreference,
|
|
1645
|
+
xrCompatible: raw.xr?.enabled === true,
|
|
1646
|
+
});
|
|
1647
|
+
if (!isObject(adapter)) return {};
|
|
1648
|
+
retainedAdapters.add(adapter);
|
|
1649
|
+
const infoCandidate = isObject(adapter.info) ? adapter.info : undefined;
|
|
1650
|
+
const legacyInfo =
|
|
1651
|
+
infoCandidate === undefined && typeof adapter.requestAdapterInfo === "function"
|
|
1652
|
+
? await adapter.requestAdapterInfo()
|
|
1653
|
+
: undefined;
|
|
1654
|
+
const info = infoCandidate ?? (isObject(legacyInfo) ? legacyInfo : undefined);
|
|
1655
|
+
if (info === undefined) return {};
|
|
1656
|
+
const fields = ["architecture", "description", "device", "vendor"] as const;
|
|
1657
|
+
const entries = fields.flatMap((field) => {
|
|
1658
|
+
const value = info[field];
|
|
1659
|
+
return typeof value === "string" && value.length > 0
|
|
1660
|
+
? [[field, encodeURIComponent(value)] as const]
|
|
1661
|
+
: [];
|
|
1662
|
+
});
|
|
1663
|
+
const software = fields
|
|
1664
|
+
.map((field) => info[field])
|
|
1665
|
+
.find((value): value is string => typeof value === "string" && SOFTWARE_ADAPTER.test(value));
|
|
1666
|
+
return {
|
|
1667
|
+
...(entries.length === 0
|
|
1668
|
+
? {}
|
|
1669
|
+
: { identity: `webgpu:${entries.map(([field, value]) => `${field}=${value}`).join("|")}` }),
|
|
1670
|
+
...(software === undefined ? {} : { software }),
|
|
1671
|
+
gpuClass: classifyGpu(
|
|
1672
|
+
Object.fromEntries(
|
|
1673
|
+
fields.map((field) => [field, typeof info[field] === "string" ? info[field] : ""]),
|
|
1674
|
+
),
|
|
1675
|
+
),
|
|
1676
|
+
};
|
|
1677
|
+
} catch {
|
|
1678
|
+
return {};
|
|
1679
|
+
}
|
|
1680
|
+
}
|
|
1681
|
+
|
|
1682
|
+
/** The per-stage texture limits worth raising past WebGPU's portable defaults (16 each). */
|
|
1683
|
+
/** Each texture limit a device is granted by default, whatever the adapter supports. */
|
|
1684
|
+
const TEXTURE_LIMITS = {
|
|
1685
|
+
maxSampledTexturesPerShaderStage: 16,
|
|
1686
|
+
maxSamplersPerShaderStage: 16,
|
|
1687
|
+
// three stores every morph target of a mesh as one layer of a texture array: a MetaHuman head
|
|
1688
|
+
// carries 821, and past the default 256 the mesh never draws.
|
|
1689
|
+
maxTextureArrayLayers: 256,
|
|
1690
|
+
} as const;
|
|
1691
|
+
|
|
1692
|
+
/**
|
|
1693
|
+
* The adapter's own texture limits, as `requiredLimits` for the device three creates.
|
|
1694
|
+
*
|
|
1695
|
+
* WebGPU grants a device the portable defaults — 16 sampled textures a stage — unless it asks for
|
|
1696
|
+
* more, whatever the adapter supports. A splat terrain (masks, albedos, normals) that also
|
|
1697
|
+
* receives an open-world shadow (three levels plus mover maps) needs ~20, and past 16 the pipeline
|
|
1698
|
+
* is invalid and the surface silently never draws. Requesting what the adapter reports costs
|
|
1699
|
+
* nothing on hardware that has it (desktop: 48+) and changes nothing where it does not.
|
|
1700
|
+
*/
|
|
1701
|
+
export async function adapterTextureLimits(): Promise<{ requiredLimits?: Record<string, number> }> {
|
|
1702
|
+
const gpu = (
|
|
1703
|
+
globalThis.navigator as { gpu?: { requestAdapter?: () => Promise<unknown> } } | undefined
|
|
1704
|
+
)?.gpu;
|
|
1705
|
+
if (gpu === undefined || typeof gpu.requestAdapter !== "function") return {};
|
|
1706
|
+
try {
|
|
1707
|
+
const adapter = await gpu.requestAdapter();
|
|
1708
|
+
retainedAdapters.add(adapter);
|
|
1709
|
+
const limits = isObject(adapter) && isObject(adapter.limits) ? adapter.limits : undefined;
|
|
1710
|
+
if (limits === undefined) return {};
|
|
1711
|
+
const requiredLimits: Record<string, number> = {};
|
|
1712
|
+
for (const [key, portable] of Object.entries(TEXTURE_LIMITS)) {
|
|
1713
|
+
const value = (limits as Record<string, unknown>)[key];
|
|
1714
|
+
if (typeof value === "number" && value > portable) requiredLimits[key] = value;
|
|
1715
|
+
}
|
|
1716
|
+
return Object.keys(requiredLimits).length === 0 ? {} : { requiredLimits };
|
|
1717
|
+
} catch {
|
|
1718
|
+
return {};
|
|
1719
|
+
}
|
|
1720
|
+
}
|
|
1721
|
+
|
|
1722
|
+
export async function createRenderer(options: IRendererOptions = {}): Promise<IRendererLike> {
|
|
1723
|
+
const source = options.source;
|
|
1724
|
+
const gpuTimestampFrameInterval =
|
|
1725
|
+
options.gpuTimestampFrameInterval ?? DEFAULT_GPU_TIMESTAMP_FRAME_INTERVAL;
|
|
1726
|
+
if (!Number.isInteger(gpuTimestampFrameInterval) || gpuTimestampFrameInterval < 1)
|
|
1727
|
+
throw new Error(
|
|
1728
|
+
`renderer.gpuTimestampFrameInterval must be a positive integer, received ${String(gpuTimestampFrameInterval)}.`,
|
|
1729
|
+
);
|
|
1730
|
+
const resolutionScale = options.resolutionScale ?? 1;
|
|
1731
|
+
const pixelRatio = options.pixelRatio ?? 1;
|
|
1732
|
+
if (!Number.isFinite(pixelRatio) || pixelRatio <= 0)
|
|
1733
|
+
throw new Error(
|
|
1734
|
+
`renderer.pixelRatio must be a finite number greater than zero, received ${String(pixelRatio)}.`,
|
|
1735
|
+
);
|
|
1736
|
+
const state: ISurfaceState = { resolutionScale, scaleSource: options.scaleSource ?? "pinned" };
|
|
1737
|
+
const reapply: { resize: (() => void) | undefined } = { resize: undefined };
|
|
1738
|
+
if (!Number.isFinite(resolutionScale) || resolutionScale <= 0)
|
|
1739
|
+
throw new Error("renderer.resolutionScale must be finite and positive.");
|
|
1740
|
+
const applied = { height: 1, width: 1 };
|
|
1741
|
+
const canvas = options.canvas ?? source?.createCanvas() ?? document.createElement("canvas");
|
|
1742
|
+
// An intrinsic canvas follows its width/height attributes. Scaling that buffer then changes
|
|
1743
|
+
// clientWidth, so ResizeObserver scales it again until it is one pixel. Own the layout only
|
|
1744
|
+
// for the browser canvas we created; supplied canvases and platform surfaces own theirs.
|
|
1745
|
+
if (options.canvas === undefined && source === undefined && canvas.style !== undefined) {
|
|
1746
|
+
canvas.style.width = "100%";
|
|
1747
|
+
canvas.style.height = "100%";
|
|
1748
|
+
}
|
|
1749
|
+
const preferWebGPU = options.preferWebGPU ?? true;
|
|
1750
|
+
// `trackTimestamp` is on so GPU time is measured, not inferred from wall clock; it is inert on an
|
|
1751
|
+
// adapter without `timestamp-query`, and `gpuTimestampFrameInterval` samples it (PRD-446).
|
|
1752
|
+
const rendererParameters = {
|
|
1753
|
+
antialias: options.antialias ?? true,
|
|
1754
|
+
trackTimestamp: true,
|
|
1755
|
+
} as const;
|
|
1756
|
+
const report = options.report ?? ((line: string) => console.log(line));
|
|
1757
|
+
// Bound to the instance rather than to the request: the whole point is that `antialias: true`
|
|
1758
|
+
// and "this surface has samples to resolve into" are different facts, and only the second one
|
|
1759
|
+
// makes the convention do anything.
|
|
1760
|
+
const arm = (raw: RendererInstance) =>
|
|
1761
|
+
new AlphaAntialiasing({
|
|
1762
|
+
enabled: options.alphaAntialiasing ?? true,
|
|
1763
|
+
report,
|
|
1764
|
+
sampleCount: () => resolveSampleCount(raw),
|
|
1765
|
+
});
|
|
1766
|
+
let renderer: IRendererLike | undefined;
|
|
1767
|
+
|
|
1768
|
+
if (preferWebGPU && (source?.hasWebGPU() ?? "gpu" in (globalThis.navigator ?? {}))) {
|
|
1769
|
+
try {
|
|
1770
|
+
const raw = options.webgpuFactory
|
|
1771
|
+
? await options.webgpuFactory(canvas, rendererParameters)
|
|
1772
|
+
: new (await import("three/webgpu")).WebGPURenderer({
|
|
1773
|
+
canvas,
|
|
1774
|
+
...rendererParameters,
|
|
1775
|
+
...(await adapterTextureLimits()),
|
|
1776
|
+
});
|
|
1777
|
+
const instance = raw as RendererInstance;
|
|
1778
|
+
await instance.init?.();
|
|
1779
|
+
const alphaAntialiasing = arm(instance);
|
|
1780
|
+
const timestampCapable = instance.backend?.trackTimestamp === true;
|
|
1781
|
+
const adapter = await readWebGpuAdapterFacts(instance);
|
|
1782
|
+
const pipelineCensus = await createWebGpuPipelineCensus(instance, options, adapter);
|
|
1783
|
+
installDrawHook(instance, alphaAntialiasing);
|
|
1784
|
+
renderer = wrapRenderer(
|
|
1785
|
+
instance,
|
|
1786
|
+
"webgpu",
|
|
1787
|
+
applied,
|
|
1788
|
+
state,
|
|
1789
|
+
reapply,
|
|
1790
|
+
alphaAntialiasing,
|
|
1791
|
+
pipelineCensus,
|
|
1792
|
+
timestampCapable,
|
|
1793
|
+
gpuTimestampFrameInterval,
|
|
1794
|
+
adapter.software,
|
|
1795
|
+
adapter.gpuClass,
|
|
1796
|
+
);
|
|
1797
|
+
if (adapter.gpuClass !== undefined)
|
|
1798
|
+
report(`${GPU_CLASS_MARKER}:${JSON.stringify(adapter.gpuClass)}`);
|
|
1799
|
+
} catch {
|
|
1800
|
+
renderer = undefined;
|
|
1801
|
+
}
|
|
1802
|
+
}
|
|
1803
|
+
|
|
1804
|
+
if (renderer === undefined) {
|
|
1805
|
+
let raw: RendererInstance;
|
|
1806
|
+
try {
|
|
1807
|
+
raw = (
|
|
1808
|
+
options.webgl2Factory
|
|
1809
|
+
? options.webgl2Factory(canvas, rendererParameters)
|
|
1810
|
+
: new (await import("three")).WebGLRenderer({ canvas, ...rendererParameters })
|
|
1811
|
+
) as RendererInstance;
|
|
1812
|
+
} catch (error) {
|
|
1813
|
+
// No WebGPU adapter and no WebGL fallback is a boot failure the player must read. The native
|
|
1814
|
+
// engine binds `WebGLRenderer` to a facade that refuses on use, and reporting that refusal
|
|
1815
|
+
// verbatim would show an internal "uncatalogued" code; a browser with no context throws
|
|
1816
|
+
// three's own message. Neither belongs in front of a player, so both become one named failure.
|
|
1817
|
+
throw new Error(
|
|
1818
|
+
"TN_NO_RENDERER: WebGPU is not available on this device and the WebGL fallback could not start, so the game cannot run.",
|
|
1819
|
+
{ cause: error },
|
|
1820
|
+
);
|
|
1821
|
+
}
|
|
1822
|
+
const alphaAntialiasing = arm(raw);
|
|
1823
|
+
const pipelineCensus = createRendererPipelineCensus(raw, "webgl2", options);
|
|
1824
|
+
installDrawHook(raw, alphaAntialiasing);
|
|
1825
|
+
renderer = wrapRenderer(
|
|
1826
|
+
raw,
|
|
1827
|
+
"webgl2",
|
|
1828
|
+
applied,
|
|
1829
|
+
state,
|
|
1830
|
+
reapply,
|
|
1831
|
+
alphaAntialiasing,
|
|
1832
|
+
pipelineCensus,
|
|
1833
|
+
false,
|
|
1834
|
+
gpuTimestampFrameInterval,
|
|
1835
|
+
);
|
|
1836
|
+
}
|
|
1837
|
+
|
|
1838
|
+
const resizing = addResizeHandling(renderer, source, state, pixelRatio);
|
|
1839
|
+
reapply.resize = resizing.resize;
|
|
1840
|
+
const stopResize = resizing.stop;
|
|
1841
|
+
const dispose = renderer.dispose;
|
|
1842
|
+
renderer.dispose = () => {
|
|
1843
|
+
stopResize();
|
|
1844
|
+
dispose();
|
|
1845
|
+
};
|
|
1846
|
+
return renderer;
|
|
1847
|
+
}
|