@voluma/vlam 0.3.0 → 0.3.4
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/README.md +2 -4
- package/dist/chunk-loader-DlNwggfG.js.map +1 -1
- package/dist/{index.d.ts → core/index.d.ts} +2 -2
- package/dist/{splat-budget.d.ts → core/splat-budget.d.ts} +1 -1
- package/dist/{splat-data.d.ts → core/splat-data.d.ts} +1 -1
- package/dist/{splat-mesh-types.d.ts → core/splat-mesh-types.d.ts} +5 -2
- package/dist/{effects.d.ts → effects/index.d.ts} +3 -3
- package/dist/effects.js.map +1 -1
- package/dist/formats/ksplat/parse-ksplat.d.ts +1 -1
- package/dist/formats/ksplat.js.map +1 -1
- package/dist/formats/lcc/collision-mesh.d.ts +2 -2
- package/dist/formats/lcc/collision-partition.d.ts +1 -1
- package/dist/formats/lcc/lcc.d.ts +3 -3
- package/dist/formats/lcc/lcc2.d.ts +2 -2
- package/dist/formats/lcc/parse-lcc.d.ts +1 -1
- package/dist/formats/lcc.js +276 -277
- package/dist/formats/lcc.js.map +1 -1
- package/dist/formats/ply/parse-compressed-ply.d.ts +2 -2
- package/dist/formats/ply/parse-splat-ply.d.ts +2 -2
- package/dist/formats/ply.js.map +1 -1
- package/dist/formats/rad/frontier-worker-protocol.d.ts +8 -1
- package/dist/formats/rad/index.d.ts +2 -2
- package/dist/formats/rad/parse-rad.d.ts +2 -2
- package/dist/formats/rad/rad-foveated-source.d.ts +3 -3
- package/dist/formats/rad/rad.d.ts +5 -5
- package/dist/formats/rad.js.map +1 -1
- package/dist/formats/sog/parse-sog.d.ts +2 -2
- package/dist/formats/sog.js.map +1 -1
- package/dist/formats/splat/parse-splat.d.ts +1 -1
- package/dist/formats/splat.js.map +1 -1
- package/dist/formats/spz/parse-spz.d.ts +1 -1
- package/dist/formats/spz.js.map +1 -1
- package/dist/half-float-Cs4FDq8Q.js.map +1 -1
- package/dist/index.js +3 -3
- package/dist/index.js.map +1 -1
- package/dist/{chunk-loader.d.ts → loaders/chunk-loader.d.ts} +2 -2
- package/dist/{load-splat-data.d.ts → loaders/load-splat-data.d.ts} +1 -1
- package/dist/{load-worker-protocol.d.ts → loaders/load-worker-protocol.d.ts} +2 -2
- package/dist/loaders.js.map +1 -1
- package/dist/loading-wLo8vRbA.js.map +1 -1
- package/dist/lod-scheduler-ChoZyEeq.js +466 -0
- package/dist/lod-scheduler-ChoZyEeq.js.map +1 -0
- package/dist/logging-BfPdd7NJ.js.map +1 -1
- package/dist/ply-header-B9WllbPg.js.map +1 -1
- package/dist/{radix-sorter-R0FCSqKu.js → radix-sorter-BrbUg_CV.js} +2 -2
- package/dist/radix-sorter-BrbUg_CV.js.map +1 -0
- package/dist/{relighting-CSQF3UcL.js → relighting-Tiwep8yd.js} +302 -294
- package/dist/relighting-Tiwep8yd.js.map +1 -0
- package/dist/{selection-volume.d.ts → selection/selection-volume.d.ts} +1 -1
- package/dist/{splat-partition.d.ts → selection/splat-partition.d.ts} +1 -1
- package/dist/selection.js.map +1 -1
- package/dist/sh-pack-D5wAe5gg.js.map +1 -1
- package/dist/splat-budget-DuVZspPQ.js.map +1 -1
- package/dist/splat-data-BZM5dhhx.js.map +1 -1
- package/dist/{splat-mesh-aQdcWA6v.js → splat-mesh-CsLOQb08.js} +3 -3
- package/dist/splat-mesh-CsLOQb08.js.map +1 -0
- package/dist/splat-mesh-types-BZIko-_9.js.map +1 -1
- package/dist/{static-lod-splat-mesh.d.ts → static-lod/static-lod-splat-mesh.d.ts} +2 -2
- package/dist/{static-lod-worker-protocol.d.ts → static-lod/static-lod-worker-protocol.d.ts} +1 -1
- package/dist/{static-lod.d.ts → static-lod/static-lod.d.ts} +1 -1
- package/dist/static-lod.js +1 -1
- package/dist/static-lod.js.map +1 -1
- package/dist/{dataset-source.d.ts → streaming/dataset-source.d.ts} +1 -1
- package/dist/{streaming.d.ts → streaming/index.d.ts} +3 -3
- package/dist/{lod-scheduler.d.ts → streaming/lod-scheduler.d.ts} +32 -0
- package/dist/{lod-source.d.ts → streaming/lod-source.d.ts} +19 -13
- package/dist/{streamed-splat-mesh-utils.d.ts → streaming/streamed-splat-mesh-utils.d.ts} +2 -2
- package/dist/{streamed-splat-mesh.d.ts → streaming/streamed-splat-mesh.d.ts} +83 -27
- package/dist/streaming.js +711 -645
- package/dist/streaming.js.map +1 -1
- package/dist/{unified-splat-mesh.d.ts → unified/unified-splat-mesh.d.ts} +13 -6
- package/dist/{work-buffer-gather.d.ts → unified/work-buffer-gather.d.ts} +5 -5
- package/dist/{work-buffer-material.d.ts → unified/work-buffer-material.d.ts} +1 -1
- package/dist/unified.js +280 -272
- package/dist/unified.js.map +1 -1
- package/dist/webgpu-limits-Y3CI_6_6.js.map +1 -1
- package/package.json +9 -9
- package/dist/lod-scheduler-B0a_uBlv.js +0 -383
- package/dist/lod-scheduler-B0a_uBlv.js.map +0 -1
- package/dist/radix-sorter-R0FCSqKu.js.map +0 -1
- package/dist/relighting-CSQF3UcL.js.map +0 -1
- package/dist/splat-mesh-aQdcWA6v.js.map +0 -1
- /package/dist/{compute-sorter.d.ts → core/compute-sorter.d.ts} +0 -0
- /package/dist/{create-splat-renderer.d.ts → core/create-splat-renderer.d.ts} +0 -0
- /package/dist/{depth-of-field.d.ts → core/depth-of-field.d.ts} +0 -0
- /package/dist/{half-float.d.ts → core/half-float.d.ts} +0 -0
- /package/dist/{logging.d.ts → core/logging.d.ts} +0 -0
- /package/dist/{merged-splat-mesh.d.ts → core/merged-splat-mesh.d.ts} +0 -0
- /package/dist/{orientation.d.ts → core/orientation.d.ts} +0 -0
- /package/dist/{radix-sort.d.ts → core/radix-sort.d.ts} +0 -0
- /package/dist/{radix-sorter.d.ts → core/radix-sorter.d.ts} +0 -0
- /package/dist/{relighting-pass.d.ts → core/relighting-pass.d.ts} +0 -0
- /package/dist/{relighting.d.ts → core/relighting.d.ts} +0 -0
- /package/dist/{sh-pack.d.ts → core/sh-pack.d.ts} +0 -0
- /package/dist/{sort-scheduler.d.ts → core/sort-scheduler.d.ts} +0 -0
- /package/dist/{sort-worker-protocol.d.ts → core/sort-worker-protocol.d.ts} +0 -0
- /package/dist/{sorter.d.ts → core/sorter.d.ts} +0 -0
- /package/dist/{source-transform.d.ts → core/source-transform.d.ts} +0 -0
- /package/dist/{splat-depth-pack.d.ts → core/splat-depth-pack.d.ts} +0 -0
- /package/dist/{splat-mesh-material.d.ts → core/splat-mesh-material.d.ts} +0 -0
- /package/dist/{splat-mesh-picking.d.ts → core/splat-mesh-picking.d.ts} +0 -0
- /package/dist/{splat-mesh-pool.d.ts → core/splat-mesh-pool.d.ts} +0 -0
- /package/dist/{splat-mesh.d.ts → core/splat-mesh.d.ts} +0 -0
- /package/dist/{splat-modifier-stack.d.ts → core/splat-modifier-stack.d.ts} +0 -0
- /package/dist/{splat-modifier.d.ts → core/splat-modifier.d.ts} +0 -0
- /package/dist/{splat-query.d.ts → core/splat-query.d.ts} +0 -0
- /package/dist/{splat-sort-bounds.d.ts → core/splat-sort-bounds.d.ts} +0 -0
- /package/dist/{storage-attribute-mirror.d.ts → core/storage-attribute-mirror.d.ts} +0 -0
- /package/dist/{webgpu-limits.d.ts → core/webgpu-limits.d.ts} +0 -0
- /package/dist/{worker-sorter.d.ts → core/worker-sorter.d.ts} +0 -0
- /package/dist/{xr-view.d.ts → core/xr-view.d.ts} +0 -0
- /package/dist/{loaders.d.ts → loaders/index.d.ts} +0 -0
- /package/dist/{loading.d.ts → loaders/loading.d.ts} +0 -0
- /package/dist/{ply-header.d.ts → loaders/ply-header.d.ts} +0 -0
- /package/dist/{selection.d.ts → selection/index.d.ts} +0 -0
- /package/dist/{static-lod-entry.d.ts → static-lod/index.d.ts} +0 -0
- /package/dist/{budget-governor.d.ts → streaming/budget-governor.d.ts} +0 -0
- /package/dist/{camera-budget-governor.d.ts → streaming/camera-budget-governor.d.ts} +0 -0
- /package/dist/{chunk-cache-budget.d.ts → streaming/chunk-cache-budget.d.ts} +0 -0
- /package/dist/{chunk-fetch-scheduler.d.ts → streaming/chunk-fetch-scheduler.d.ts} +0 -0
- /package/dist/{lod-manifest.d.ts → streaming/lod-manifest.d.ts} +0 -0
- /package/dist/{unified.d.ts → unified/index.d.ts} +0 -0
- /package/dist/{unified-work-buffer.d.ts → unified/unified-work-buffer.d.ts} +0 -0
package/dist/unified.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"unified.js","sources":["../src/lib/work-buffer-gather.ts","../src/lib/work-buffer-material.ts","../src/lib/unified-work-buffer.ts","../src/lib/unified-splat-mesh.ts"],"sourcesContent":["import * as THREE from 'three/webgpu';\nimport {\n Fn,\n If,\n bool,\n float,\n int,\n instanceIndex,\n ivec2,\n mat3,\n storage,\n textureLoad,\n uniform,\n vec3,\n vec4,\n} from 'three/tsl';\nimport {\n evaluateSplatSh,\n foldSplatModifierStack,\n asNode,\n applyIsotropicCovarianceOverride,\n DEFAULT_ISOTROPIC_VARIANCE_SCALE,\n type SplatShInputs,\n type Vec3Uniform,\n} from './splat-mesh-material';\nimport { colorSpaceToWorking } from 'three/tsl';\nimport type { SplatModifier } from './splat-modifier';\nimport { StorageMirrorReleaser } from './storage-attribute-mirror';\n\n/**\n * GPU gather pass for Phase 0 of the unified renderer. It resolves a source\n * pool's active local centers into a shared world-space storage buffer. The\n * work-buffer sorter consumes this buffer directly, so source-local pools can\n * later be heterogeneous (including streamed LOD pools).\n *\n * Internal while M15.4's draw path and public source API are completed.\n */\n/** Shared GPU storage for every gathered source in one unified frame. */\nexport class WorkBuffer {\n /** World-space center xyz; w is the drawable flag (1 draw, 0 modifier-hidden). */\n readonly centers: THREE.StorageBufferAttribute;\n /** Resolved color and opacity per work slot. */\n readonly colors: THREE.StorageBufferAttribute;\n /** First packed covariance row per work slot. */\n readonly covarianceA: THREE.StorageBufferAttribute;\n /** Second packed covariance row per work slot. */\n readonly covarianceB: THREE.StorageBufferAttribute;\n /** Per-slot isotropic covariance mix (0 = keep Σ, 1 = round dot). */\n readonly isotropicMix: THREE.StorageBufferAttribute;\n /** Per-slot isotropic target sigma radius in screen px (0 = disabled). */\n readonly isotropicScreenRadius: THREE.StorageBufferAttribute;\n\n /**\n * Slots past {@link capacity}, reserved so a pipeline warm-up has somewhere\n * harmless to write. See {@link WorkBufferGather.warmUp}: compiling a compute\n * pipeline requires actually dispatching it, and dispatching zero workgroups\n * - while it does compile - makes WebGPU log an \"unusual workgroup count of 0\"\n * warning for every source. One workgroup aimed at this tail compiles just the\n * same, silently, and cannot disturb a drawn slot: admission never allocates\n * past `capacity` and the draw's `instanceCount` never covers it.\n */\n static readonly SCRATCH_SLOTS = 256;\n\n constructor(readonly capacity: number) {\n const slots = capacity + WorkBuffer.SCRATCH_SLOTS;\n this.centers = new THREE.StorageBufferAttribute(new Float32Array(slots * 4), 4);\n this.colors = new THREE.StorageBufferAttribute(new Float32Array(slots * 4), 4);\n this.covarianceA = new THREE.StorageBufferAttribute(new Float32Array(slots * 4), 4);\n this.covarianceB = new THREE.StorageBufferAttribute(new Float32Array(slots * 4), 4);\n this.isotropicMix = new THREE.StorageBufferAttribute(new Float32Array(slots), 1);\n this.isotropicScreenRadius = new THREE.StorageBufferAttribute(new Float32Array(slots), 1);\n this.mirrors = new StorageMirrorReleaser([\n this.centers,\n this.colors,\n this.covarianceA,\n this.covarianceB,\n this.isotropicMix,\n this.isotropicScreenRadius,\n ]);\n }\n\n /**\n * Drops the JS-heap copies three keeps behind these storage buffers.\n *\n * Every one of them is written only by the gather compute pass and read only\n * by the draw material - the CPU side is zeroes that no code ever reads, and\n * three's WebGPU backend never frees it on its own. At 72 B/slot that mirror\n * is ~720 MB of JS heap on a 10M-slot scene. See `storage-attribute-mirror`.\n *\n * Safe to call after any dispatch that bound this buffer; a no-op once\n * settled, and on WebGL2 or a renderer double that has no WebGPU backend.\n */\n releaseCpuMirrors(renderer: THREE.WebGPURenderer): void {\n if (this.mirrors.settled) return;\n this.mirrors.release(renderer);\n }\n\n private readonly mirrors: StorageMirrorReleaser;\n}\n\nexport class WorkBufferGather {\n /** World-space `xyzw` center buffer, one element per unified work slot. */\n readonly centers: THREE.StorageBufferAttribute;\n /** Resolved source RGBA values; production draw consumes this next. */\n readonly colors: THREE.StorageBufferAttribute;\n /** Packed symmetric world-space covariance rows. */\n readonly covarianceA: THREE.StorageBufferAttribute;\n readonly covarianceB: THREE.StorageBufferAttribute;\n readonly isotropicMix: THREE.StorageBufferAttribute;\n readonly isotropicScreenRadius: THREE.StorageBufferAttribute;\n /** Shared target for this source's gathered range. */\n readonly workBuffer: WorkBuffer;\n private readonly capacity: number;\n private readonly activeCount = uniform(0);\n private readonly targetOffset = uniform(0);\n private readonly sourceMatrix = uniform(new THREE.Matrix4());\n private readonly cameraViewMatrix = uniform(new THREE.Matrix4());\n private readonly opacity = uniform(1);\n private readonly pass: THREE.ComputeNode;\n\n constructor(options: {\n capacity: number;\n sourceCapacity: number;\n sourceIndex: THREE.StorageBufferAttribute;\n centersTexture: THREE.DataTexture;\n colorsTexture: THREE.DataTexture;\n covarianceATexture: THREE.DataTexture;\n covarianceBTexture: THREE.DataTexture;\n dataTextureWidth: number;\n sh?: SplatShInputs | null;\n modifiers?: readonly SplatModifier[];\n channels?: ReadonlyMap<string, { texture: THREE.DataTexture }>;\n localCameraPosition?: Vec3Uniform;\n srgbOutput?: boolean;\n /**\n * Source stores Spark LOD alpha (`alpha ÷ 2`, `.rad`). Recover the full\n * `alpha ∈ [0,2]` here so the shared draw material sees one convention;\n * `alpha > 1` then marks a merged node (see `createWorkBufferMaterial`).\n */\n lodAlpha?: boolean;\n /** Reuse one target across all source gather passes. */\n workBuffer?: WorkBuffer;\n }) {\n const {\n capacity,\n sourceCapacity,\n sourceIndex,\n centersTexture,\n colorsTexture,\n covarianceATexture,\n covarianceBTexture,\n dataTextureWidth,\n } = options;\n const sh = options.sh ?? null;\n const modifiers = options.modifiers ?? [];\n const channels = options.channels ?? new Map<string, { texture: THREE.DataTexture }>();\n const localCameraPosition = options.localCameraPosition ?? uniform(new THREE.Vector3());\n this.workBuffer = options.workBuffer ?? new WorkBuffer(capacity);\n this.capacity = this.workBuffer.capacity;\n this.centers = this.workBuffer.centers;\n this.colors = this.workBuffer.colors;\n this.covarianceA = this.workBuffer.covarianceA;\n this.covarianceB = this.workBuffer.covarianceB;\n this.isotropicMix = this.workBuffer.isotropicMix;\n this.isotropicScreenRadius = this.workBuffer.isotropicScreenRadius;\n const source = storage(sourceIndex, 'uint', sourceCapacity);\n const output = storage(this.centers, 'vec4', capacity);\n const outputColor = storage(this.colors, 'vec4', capacity);\n const outputCovA = storage(this.covarianceA, 'vec4', capacity);\n const outputCovB = storage(this.covarianceB, 'vec4', capacity);\n const outputIsotropicMix = storage(this.isotropicMix, 'float', capacity);\n const outputIsotropicScreenRadius = storage(this.isotropicScreenRadius, 'float', capacity);\n this.pass = Fn(() => {\n If(float(instanceIndex).lessThan(this.activeCount), () => {\n const poolIndex = int(source.element(instanceIndex));\n const texel = ivec2(\n poolIndex.mod(int(dataTextureWidth)),\n poolIndex.div(int(dataTextureWidth)),\n );\n const localCenter = textureLoad(centersTexture, texel).xyz;\n const target = instanceIndex.add(this.targetOffset.toUint());\n const inputA = textureLoad(covarianceATexture, texel);\n const inputB = textureLoad(covarianceBTexture, texel);\n const covarianceBase = mat3(\n vec3(inputA.x, inputA.y, inputA.z),\n vec3(inputA.y, inputA.w, inputB.x),\n vec3(inputA.z, inputB.x, inputB.y),\n );\n const baseColor = textureLoad(colorsTexture, texel);\n const colorAfterSh =\n sh === null\n ? baseColor\n : vec4(\n baseColor.rgb\n .add(\n evaluateSplatSh(\n sh,\n { covarianceBTexture },\n texel,\n localCenter.sub(localCameraPosition).normalize(),\n ),\n )\n .clamp(0.0, 1.0),\n baseColor.a,\n );\n const worldCenter = this.sourceMatrix.mul(vec4(localCenter, 1.0)).xyz;\n const stack = foldSplatModifierStack(modifiers, localCameraPosition, {\n index: poolIndex,\n localCenter,\n color: colorAfterSh,\n makeWorldCenter: () => worldCenter,\n makeViewCenter: () => this.cameraViewMatrix.mul(vec4(worldCenter, 1.0)).xyz,\n makeNormal: () => {\n const inverse = covarianceBase.inverse();\n const toCamera = localCameraPosition.sub(localCenter);\n const axis = inverse.mul(inverse.mul(toCamera)).normalize();\n return axis.mul(axis.dot(toCamera).sign());\n },\n makeChannel: (name) => {\n const channel = channels.get(name);\n if (!channel) {\n throw new Error(\n `UnifiedSplatMesh: source modifier reads undefined channel \"${name}\".`,\n );\n }\n return textureLoad(channel.texture, texel).r;\n },\n });\n const center = stack.offset === null ? localCenter : localCenter.add(stack.offset);\n const visible = stack.visible === null ? bool(true) : stack.visible;\n // Stable work slots: keep hidden splats in the gather/sort range, but\n // stamp drawable=0 into center.w so the draw material clips them.\n // Alpha-zero remains a secondary guard in the color channel.\n // Compacting hidden splats out instead was evaluated and rejected\n // (ROADMAP L3): the hidden set exists only on the GPU, so compaction\n // needs a count readback before the CPU-sized sort dispatch - see the\n const gatheredCenter = this.sourceMatrix.mul(vec4(center, 1.0)).xyz;\n output.element(target).assign(vec4(gatheredCenter, visible.select(float(1), float(0))));\n const resolvedColor = options.srgbOutput\n ? stack.color\n : asNode<'vec4'>(colorSpaceToWorking(stack.color, THREE.SRGBColorSpace));\n // `.rad` stores `alpha ÷ 2`; recover it here rather than in the draw\n // material, which is shared by every source and must see one alpha\n // convention. The work buffer is float storage, so `alpha > 1` (a\n // merged node) survives to the draw unclamped.\n const sourceAlpha = options.lodAlpha\n ? asNode<'float'>(resolvedColor.a.mul(2.0))\n : asNode<'float'>(resolvedColor.a);\n outputColor\n .element(target)\n .assign(vec4(resolvedColor.rgb, visible.select(sourceAlpha.mul(this.opacity), float(0))));\n const covariance =\n stack.rotation === null\n ? covarianceBase\n : stack.rotation.mul(covarianceBase).mul(stack.rotation.transpose());\n // Collapse in mesh-local space (Spark's min(scale) is local), then lift\n // to world. Applying isotropic on world Σ with a local normal inflated\n // λ and produced large soft blobs under mesh transforms.\n let localCovariance: THREE.Node<'mat3'> = asNode<'mat3'>(covariance);\n if (stack.isotropicCovarianceMix !== null) {\n const varianceScale =\n stack.isotropicVarianceScale ?? float(DEFAULT_ISOTROPIC_VARIANCE_SCALE);\n localCovariance = applyIsotropicCovarianceOverride(\n localCovariance,\n vec3(0, 0, 1),\n stack.isotropicCovarianceMix,\n varianceScale,\n );\n }\n const linear = this.sourceMatrix.toMat3();\n const worldCovarianceBase = linear.mul(localCovariance).mul(linear.transpose());\n const worldCovariance =\n stack.scaleSquared === null\n ? worldCovarianceBase\n : worldCovarianceBase.mul(stack.scaleSquared);\n const c0 = worldCovariance.mul(vec3(1, 0, 0));\n const c1 = worldCovariance.mul(vec3(0, 1, 0));\n const c2 = worldCovariance.mul(vec3(0, 0, 1));\n outputCovA.element(target).assign(vec4(c0.x, c0.y, c0.z, c1.y));\n outputCovB.element(target).assign(vec4(c1.z, c2.z, 0, 0));\n outputIsotropicMix\n .element(target)\n .assign(stack.isotropicCovarianceMix === null ? float(0) : stack.isotropicCovarianceMix);\n outputIsotropicScreenRadius\n .element(target)\n .assign(\n stack.isotropicCovarianceMix === null\n ? float(0)\n : (stack.isotropicScreenRadiusPx ?? float(0)),\n );\n });\n })().compute(sourceCapacity, [256]);\n }\n\n /** Gathers a source's active pool slots into a contiguous work-buffer range. */\n gather(\n renderer: THREE.WebGPURenderer,\n activeCount: number,\n targetOffset: number,\n sourceMatrix: THREE.Matrix4,\n cameraViewMatrixOrOpacity: THREE.Matrix4 | number = new THREE.Matrix4(),\n opacity = 1,\n ): void {\n if (activeCount < 0 || targetOffset < 0 || targetOffset + activeCount > this.capacity) {\n throw new Error('WorkBufferGather: requested range exceeds work-buffer capacity.');\n }\n this.activeCount.value = activeCount;\n this.targetOffset.value = targetOffset;\n this.sourceMatrix.value.copy(sourceMatrix);\n const cameraViewMatrix =\n typeof cameraViewMatrixOrOpacity === 'number'\n ? new THREE.Matrix4()\n : cameraViewMatrixOrOpacity;\n this.cameraViewMatrix.value.copy(cameraViewMatrix);\n this.opacity.value = Math.max(\n 0,\n typeof cameraViewMatrixOrOpacity === 'number' ? cameraViewMatrixOrOpacity : opacity,\n );\n this.pass.count = activeCount;\n renderer.compute(this.pass);\n // The dispatch just built this pass's bind group, which is what makes three\n // create the storage buffers - synchronously. Nothing reads their CPU side\n // back, so drop it. A `WorkBuffer` shared by several gathers releases on\n // whichever dispatches first; the rest find it settled.\n this.workBuffer.releaseCpuMirrors(renderer);\n }\n\n /**\n * Compiles this gather's compute pipeline without gathering anything.\n *\n * WebGPU compiles a compute pipeline lazily, at its first dispatch - not when\n * the node graph is built. Measured on a 13-mesh scene, a source's *first*\n * `gather` took up to 2.0s while every later dispatch of the same pipeline\n * took under 0.4ms, and because `gather` runs inside `update` that compile\n * landed whole in one render frame. Running it through the async path here\n * compiles off the critical frame, so the first real gather finds it ready.\n *\n * The dispatch targets {@link WorkBuffer.SCRATCH_SLOTS} past the drawable\n * capacity rather than dispatching zero workgroups: zero also compiles, but\n * WebGPU warns about it once per source, and writing into a drawn slot could\n * leave junk behind when a cached gather is reused instead of re-run.\n *\n * Best-effort: a failure here costs only the stall it was meant to avoid, so\n * callers may ignore it.\n */\n async warmUp(renderer: THREE.WebGPURenderer): Promise<void> {\n this.activeCount.value = 1;\n this.targetOffset.value = this.capacity;\n this.pass.count = 1;\n await renderer.computeAsync(this.pass);\n // Leave nothing that a later reuse check could mistake for real state.\n this.activeCount.value = 0;\n this.targetOffset.value = 0;\n // Warm-up is often the first dispatch of all, so this is usually where the\n // mirrors actually go.\n this.workBuffer.releaseCpuMirrors(renderer);\n }\n\n /** Releases the gather pipeline. The owner releases the storage attribute. */\n dispose(): void {\n this.pass.dispose();\n }\n}\n","import * as THREE from 'three/webgpu';\nimport type { FloatUniform, Vec2Uniform } from './splat-mesh-material';\nimport {\n capProjectedEigenvaluesToScreenRadius,\n equalizeProjectedEigenvalues,\n} from './splat-mesh-material';\nimport { MAX_DOF_VARIANCE } from './depth-of-field';\nimport {\n Discard,\n Fn,\n cameraProjectionMatrix,\n float,\n instanceIndex,\n mat3,\n mix,\n modelViewMatrix,\n positionGeometry,\n screenUV,\n storage,\n texture as tslTexture,\n varying,\n vec2,\n vec3,\n vec4,\n} from 'three/tsl';\n\n/**\n * Creates the unified EWA draw material for gathered world-space splats.\n *\n * Its vertex stage reads both the sorter-written order and the gather-written\n * centers, covariance, and resolved color from storage buffers. It keeps the\n * verified ±3σ / exp(-4.5·|q|²) convention used by {@link SplatMesh}.\n */\nexport function createWorkBufferMaterial(options: {\n capacity: number;\n centers: THREE.StorageBufferAttribute;\n colors: THREE.StorageBufferAttribute;\n covarianceA: THREE.StorageBufferAttribute;\n covarianceB: THREE.StorageBufferAttribute;\n isotropicMix: THREE.StorageBufferAttribute;\n isotropicScreenRadius: THREE.StorageBufferAttribute;\n order: THREE.StorageInstancedBufferAttribute;\n focal: Vec2Uniform;\n viewport: Vec2Uniform;\n maxStdDev: FloatUniform;\n /** Screen-space minimum splat radius in px; `0` disables. */\n minSplatSizePx: FloatUniform;\n antialias: FloatUniform;\n /** Format-selected projected low-pass variance, in px². */\n projectedLowPassVariance: FloatUniform;\n /** LCC always preserves the low-pass integral; standard follows antialias. */\n compensateProjectedLowPass: FloatUniform;\n /** Core projected-2D DoF focus plane. Live; `0` aperture disables. */\n dofFocusDistance: FloatUniform;\n dofAperture: FloatUniform;\n /**\n * Proxy-mesh relight map (RGB = lit, A = coverage). Display only.\n * Host swaps the texture object and rebuilds when enabling/changing map.\n */\n relightMap: THREE.Texture;\n relightBlend: FloatUniform;\n relightBrightness: FloatUniform;\n relightBackground: FloatUniform;\n /** Coverage soft edge in screen pixels; `0` = hard mask. */\n relightSoftness: FloatUniform;\n}): THREE.NodeMaterial {\n const material = new THREE.NodeMaterial();\n const centers = storage(options.centers, 'vec4', options.capacity);\n const order = storage(options.order, 'float', options.capacity);\n const colors = storage(options.colors, 'vec4', options.capacity);\n const covarianceA = storage(options.covarianceA, 'vec4', options.capacity);\n const covarianceB = storage(options.covarianceB, 'vec4', options.capacity);\n const isotropicMix = storage(options.isotropicMix, 'float', options.capacity);\n const isotropicScreenRadius = storage(options.isotropicScreenRadius, 'float', options.capacity);\n const workColor = varying(vec4(1, 1, 1, 1), 'vWorkColor');\n const quadPosition = varying(positionGeometry.xy, 'vWorkQuadPosition');\n const opacityCompensation = varying(float(1), 'vWorkOpacityCompensation');\n // Spark LOD alpha, matching `SplatMesh`'s display graph. The gather has\n // already recovered `alpha ∈ [0,2]` for `.rad` sources, so `alpha > 1`\n // identifies a merged node here without a per-source shader variant: a\n // non-`.rad` source can only reach `alpha ≤ 1`, for which the branches below\n // collapse to the plain Gaussian this material has always drawn.\n const adjustedStdDev = varying(float(0), 'vWorkAdjustedStdDev');\n material.vertexNode = Fn(() => {\n const workIndex = order.element(instanceIndex).toInt();\n const centerSample = centers.element(workIndex);\n const center = centerSample.xyz;\n // Gather stamps drawable into center.w (1 = draw, 0 = modifier-hidden).\n const drawable = centerSample.w.greaterThan(0.5);\n workColor.assign(colors.element(workIndex));\n const viewCenter = modelViewMatrix.mul(vec4(center, 1.0)).toVar();\n const clipCenter = cameraProjectionMatrix.mul(viewCenter).toVar();\n const covA = covarianceA.element(workIndex);\n const covB = covarianceB.element(workIndex);\n const covariance = mat3(\n vec3(covA.x, covA.y, covA.z),\n vec3(covA.y, covA.w, covB.x),\n vec3(covA.z, covB.x, covB.y),\n );\n const invZ = float(1).div(viewCenter.z);\n const invZ2 = invZ.mul(invZ);\n const j1 = vec3(\n options.focal.x.mul(invZ),\n 0,\n options.focal.x.negate().mul(viewCenter.x).mul(invZ2),\n );\n const j2 = vec3(\n 0,\n options.focal.y.mul(invZ),\n options.focal.y.negate().mul(viewCenter.y).mul(invZ2),\n );\n const viewRotationT = modelViewMatrix.toMat3().transpose();\n const u1 = viewRotationT.mul(j1);\n const u2 = viewRotationT.mul(j2);\n const aRaw = u1.dot(covariance.mul(u1));\n const dRaw = u2.dot(covariance.mul(u2));\n const bRaw = u1.dot(covariance.mul(u2));\n\n const depth = viewCenter.z.negate().max(1e-4);\n const focus = options.dofFocusDistance.max(1e-4);\n // Aperture maps through the live focus plane (Spark host-helper parity), so\n // a near focus plane widens the angle and softens the whole scene.\n const halfApertureAngle = options.dofAperture.max(0).mul(0.5).div(focus).atan();\n // Spark's falloff (`/depth`). Unbounded near the camera; MAX_DOF_VARIANCE\n // below is the fill-rate guard, exactly as Spark's maxPixelRadius is.\n const focusBlur = depth.sub(focus).abs().div(depth);\n const apertureRadius = options.focal.x.mul(halfApertureAngle.tan());\n const cocRadiusPx = focusBlur.mul(apertureRadius);\n const cocVar = cocRadiusPx.mul(cocRadiusPx).min(float(MAX_DOF_VARIANCE));\n\n const a = aRaw.add(options.projectedLowPassVariance).add(cocVar);\n const d = dRaw.add(options.projectedLowPassVariance).add(cocVar);\n const b = bRaw;\n const isoMix = isotropicMix.element(workIndex);\n const detBlur = a.mul(d).sub(b.mul(b)).max(1e-9);\n // Classic LCC always compensates its 0.1 px² low-pass. Standard sources\n // retain their antialias-controlled 0.3 px² compatibility behavior.\n const detRaw = aRaw.mul(dRaw).sub(bRaw.mul(bRaw)).max(0);\n const detBase = aRaw\n .add(options.projectedLowPassVariance)\n .mul(dRaw.add(options.projectedLowPassVariance))\n .sub(bRaw.mul(bRaw))\n .max(1e-9);\n const mipFade = detRaw.div(detBlur).sqrt();\n const dofOnlyFade = detBase.div(detBlur).sqrt();\n const compensate = options.antialias.max(options.compensateProjectedLowPass);\n const fade = mix(dofOnlyFade, mipFade, compensate);\n // Screen-capped isotropic points must not inherit the mip-filter opacity\n // fade - it was derived from the pre-cap footprint and washes out dots.\n opacityCompensation.assign(mix(fade, float(1), isoMix));\n const mid = a.add(d).mul(0.5);\n const radius = vec2(a.sub(d).mul(0.5), b).length();\n let lambda1 = mid.add(radius);\n let lambda2 = mid.sub(radius).max(0);\n const equalized = equalizeProjectedEigenvalues(lambda1, lambda2, isoMix);\n lambda1 = equalized.lambda1;\n lambda2 = equalized.lambda2;\n const capped = capProjectedEigenvaluesToScreenRadius(\n lambda1,\n lambda2,\n isoMix,\n isotropicScreenRadius.element(workIndex),\n options.maxStdDev,\n );\n lambda1 = capped.lambda1;\n lambda2 = capped.lambda2;\n // A merged node (`alpha > 1`) grows the σ-cutoff `maxStdDev + 0.7·(remap−1)`\n // so one coarse splat covers the subtree it stands in for; the covariance is\n // untouched. A leaf keeps the base cutoff. `SplatMesh` does the same at\n // `applySplatMaterialGraph`'s `lodAlpha` branch.\n const remap = workColor.a.mul(4).sub(3).min(5);\n const stdDev = workColor.a\n .greaterThan(1)\n .select(options.maxStdDev.add(remap.sub(1).mul(0.7)), options.maxStdDev);\n adjustedStdDev.assign(stdDev);\n const eigenvector = vec2(b, lambda1.sub(a)).add(vec2(1e-6, 0)).normalize();\n // Screen-space minimum on each axis: a splat below the floor grows to it so\n // its Gaussian tiles with neighbours instead of leaving dark gaps between\n // sparse zoomed-out splats; already-large splats are untouched. Mirrors\n // `applySplatMaterialGraph`. `.max` after `.min(1024)` keeps the order valid.\n const minSplat = options.minSplatSizePx;\n const major = eigenvector.mul(lambda1.sqrt().mul(stdDev).min(1024).max(minSplat));\n const minor = vec2(eigenvector.y, eigenvector.x.negate()).mul(\n lambda2.sqrt().mul(stdDev).min(1024).max(minSplat),\n );\n const pixelOffset = major.mul(positionGeometry.x).add(minor.mul(positionGeometry.y));\n const ndcCenter = clipCenter.xy.div(clipCenter.w);\n const clipPosition = vec4(\n ndcCenter.add(pixelOffset.mul(2).div(options.viewport)),\n clipCenter.z.div(clipCenter.w),\n 1,\n );\n // Match SplatMesh's conservative center-frustum rejection. Without this,\n // a center behind the camera can produce a mirrored, screen-filling quad.\n // Modifier-hidden entries (drawable=0) share the clipped destination so\n // they generate no fragments while keeping a stable sort slot.\n const margin = clipCenter.w.mul(1.2);\n const inFrustum = clipCenter.z\n .greaterThan(margin.negate())\n .and(clipCenter.x.abs().lessThan(margin))\n .and(clipCenter.y.abs().lessThan(margin));\n return inFrustum.and(drawable).select(clipPosition, vec4(0, 0, 2, 1));\n })();\n material.fragmentNode = Fn(() => {\n const squaredDistance = quadPosition.dot(quadPosition);\n Discard(squaredDistance.greaterThan(1));\n // Spark's LOD falloff, mirroring `SplatMesh`'s display fragment.\n // `g = exp(-½·adjustedStdDev²·|q|²)` is the Gaussian at this fragment. A leaf\n // (`alpha ≤ 1`, and every non-`.rad` source) composites `g · alpha`. A merged\n // node uses the super-Gaussian plateau `1 − (1 − g)^a`, `a = exp((remap²−1)/e)`,\n // so a coarse splat fills its subtree's footprint without inflating Σ.\n const g = squaredDistance.mul(adjustedStdDev.mul(adjustedStdDev).mul(-0.5)).exp();\n const remap = workColor.a.mul(4).sub(3).min(5);\n const aExp = remap\n .mul(remap)\n .sub(1)\n .mul(1 / Math.E)\n .exp();\n const merged = g.oneMinus().pow(aExp).oneMinus();\n const opacity = workColor.a.greaterThan(1).select(merged, g.mul(workColor.a));\n const alpha = opacity.mul(opacityCompensation);\n const litCenter = tslTexture(options.relightMap, screenUV);\n const ox = options.relightSoftness.div(options.viewport.x.max(1));\n const oy = options.relightSoftness.div(options.viewport.y.max(1));\n const s0 = litCenter;\n const s1 = tslTexture(options.relightMap, screenUV.add(vec2(ox, 0)));\n const s2 = tslTexture(options.relightMap, screenUV.add(vec2(ox.negate(), 0)));\n const s3 = tslTexture(options.relightMap, screenUV.add(vec2(0, oy)));\n const s4 = tslTexture(options.relightMap, screenUV.add(vec2(0, oy.negate())));\n const wSum = s0.a.add(s1.a).add(s2.a).add(s3.a).add(s4.a).max(1e-4);\n const rgbSoft = s0.rgb\n .mul(s0.a)\n .add(s1.rgb.mul(s1.a))\n .add(s2.rgb.mul(s2.a))\n .add(s3.rgb.mul(s3.a))\n .add(s4.rgb.mul(s4.a))\n .div(wSum);\n const aSoft = wSum.mul(0.2);\n const litSoft = vec4(rgbSoft, aSoft);\n const lit = options.relightSoftness.greaterThan(0.5).select(litSoft, litCenter);\n const factor = mix(\n vec3(options.relightBackground),\n lit.rgb.mul(options.relightBrightness),\n lit.a,\n );\n const rgb = mix(workColor.rgb, workColor.rgb.mul(factor), options.relightBlend);\n return vec4(rgb.mul(alpha), alpha);\n })();\n material.transparent = true;\n material.depthTest = true;\n material.depthWrite = false;\n material.side = THREE.DoubleSide;\n material.blending = THREE.CustomBlending;\n material.blendSrc = THREE.OneFactor;\n material.blendDst = THREE.OneMinusSrcAlphaFactor;\n material.blendSrcAlpha = THREE.OneFactor;\n material.blendDstAlpha = THREE.OneMinusSrcAlphaFactor;\n material.toneMapped = false;\n return material;\n}\n","/**\n * Byte costs of {@link UnifiedSplatMesh}'s GPU work buffer.\n *\n * Kept off the core entry so hosts that never composite sources do not pay\n * for the accounting, and so the numbers cannot drift from the renderer\n * that allocates those buffers.\n */\n\n/** Bytes per splat in the largest unified work-buffer attribute (RGBA32F centers). */\nexport const WORK_BUFFER_CENTERS_BYTES_PER_SPLAT = 16;\n\n/**\n * Bytes per work-buffer slot across *all* of its attributes: centers, colors,\n * covarianceA and covarianceB at RGBA32F (16 each), plus the isotropic mix and\n * screen-radius scalars (4 each).\n */\nexport const WORK_BUFFER_BYTES_PER_SLOT = 16 * 4 + 4 * 2;\n\nfunction assertNonNegativeCapacity(capacity: number): void {\n if (!Number.isFinite(capacity) || capacity < 0) {\n throw new RangeError('Splat capacity must be a non-negative finite number.');\n }\n}\n\n/**\n * Byte size of the largest single storage-buffer bind VLAM allocates for a\n * given splat capacity (unified work-buffer centers: `capacity × 16`).\n *\n * Use with adapter/device limits to decide whether to raise `requiredLimits`\n * or lower the budget before constructing {@link UnifiedSplatMesh}.\n */\nexport function estimateLargestStorageBufferBytes(capacity: number): number {\n assertNonNegativeCapacity(capacity);\n return Math.floor(capacity) * WORK_BUFFER_CENTERS_BYTES_PER_SPLAT;\n}\n\n/**\n * Estimates what a {@link UnifiedSplatMesh}'s work buffer costs, in bytes,\n * once the scene has rendered a frame.\n *\n * This used to be double the figure below, and the doubling was not a detail.\n * Every `THREE.StorageBufferAttribute` is constructed around a JS typed array,\n * and three's WebGPU backend never releases it: the\n * `attribute.onUploadCallback()` call that would is missing from the backend's\n * buffer upload path. So a work buffer of N slots cost\n * N × {@link WORK_BUFFER_BYTES_PER_SLOT} on the GPU *and* the same again on the\n * JS heap, permanently, even though nothing ever reads the CPU copy back - the\n * gather pass writes these buffers entirely on the GPU.\n *\n * `WorkBuffer.releaseCpuMirrors` now drops those mirrors after the first\n * dispatch that uploads them (see `storage-attribute-mirror`), so steady state\n * is the GPU side alone. The *peak* is still double - the array has to exist\n * for the upload copy - which is what\n * {@link estimateUnifiedWorkBufferPeakBytes} reports.\n *\n * Either figure is invisible to `estimateSplatPoolBytes`, which prices the\n * splat *pool* and knows nothing about the unified renderer's scratch space. A\n * host sizing a scene for a memory-constrained device wants both.\n *\n * @param capacity - Work-buffer capacity in splats.\n * @returns Estimated steady-state bytes.\n * @throws {RangeError} if `capacity` is not a non-negative finite number.\n */\nexport function estimateUnifiedWorkBufferBytes(capacity: number): number {\n assertNonNegativeCapacity(capacity);\n return Math.floor(capacity) * WORK_BUFFER_BYTES_PER_SLOT;\n}\n\n/**\n * Peak bytes a {@link UnifiedSplatMesh}'s work buffer occupies: the window\n * between construction and the first dispatch, while the GPU buffer and the JS\n * array three copied it from are both alive.\n *\n * Ask this one when the question is \"will allocating this scene succeed\" - an\n * out-of-memory failure happens against the peak. Ask\n * {@link estimateUnifiedWorkBufferBytes} when the question is \"what will this\n * scene hold once it is up\".\n *\n * @param capacity - Work-buffer capacity in splats.\n * @returns Estimated bytes, GPU plus the not-yet-released CPU mirror.\n * @throws {RangeError} if `capacity` is not a non-negative finite number.\n */\nexport function estimateUnifiedWorkBufferPeakBytes(capacity: number): number {\n return estimateUnifiedWorkBufferBytes(capacity) * 2;\n}\n","import * as THREE from 'three/webgpu';\nimport { uniform } from 'three/tsl';\nimport { ComputeSorter, releaseRendererAttributes } from './compute-sorter';\nimport { RadixSorter } from './radix-sorter';\nimport { clampDepthOfFieldSettings, type DepthOfFieldSettings } from './depth-of-field';\nimport {\n clampRelightingSettings,\n createPlaceholderRelightTexture,\n DEFAULT_RELIGHT_BACKGROUND,\n DEFAULT_RELIGHT_BRIGHTNESS,\n DEFAULT_RELIGHT_SOFTNESS,\n type RelightingSettings,\n type RelightingUniforms,\n} from './relighting';\nimport { SplatMesh } from './splat-mesh';\nimport type { SplatPickOptions, SplatPickResult, UnifiedSourceView } from './splat-mesh';\nimport { isFillConstrainedSplatDevice } from './splat-budget';\nimport { WebGpuSortScheduler } from './sort-scheduler';\nimport { WorkBuffer, WorkBufferGather } from './work-buffer-gather';\nimport { createWorkBufferMaterial } from './work-buffer-material';\nimport type { FloatUniform, Vec2Uniform } from './splat-mesh-material';\nimport { assertStorageBufferFitsDevice } from './webgpu-limits';\nimport { estimateLargestStorageBufferBytes } from './unified-work-buffer';\nimport { resolveXrView } from './xr-view';\nimport { StorageMirrorReleaser } from './storage-attribute-mirror';\nimport type { SplatSorter } from './sorter';\n\ninterface SourceRecord {\n source: SplatMesh;\n gather: WorkBufferGather;\n graphRevision: number;\n priority: number;\n opacity: number;\n visible: boolean;\n /** Whether modifier uniforms are host-invalidated instead of assumed live. */\n cacheModifiers: boolean;\n originalVisible: boolean;\n lastGather: {\n activeCount: number;\n contentRevision: number;\n offset: number;\n opacity: number;\n matrixWorld: THREE.Matrix4;\n /** Local camera position used by view-dependent SH evaluation. */\n localCameraPosition: THREE.Vector3;\n } | null;\n /** Per-prepare scratch: the source view snapshot for the current frame. */\n view: UnifiedSourceView | null;\n /** Per-prepare scratch: registration index for stable priority ordering. */\n registrationOrder: number;\n /** Per-prepare scratch: this frame's admitted work-buffer offset. */\n offset: number;\n}\n\n/** One admitted source's work-buffer ownership from a prepared frame. */\ninterface LayoutEntry {\n source: SplatMesh;\n offset: number;\n activeCount: number;\n}\n\n/** Registration settings for one source in a {@link UnifiedSplatMesh}. */\nexport interface UnifiedSplatSourceOptions {\n /** Whole-source opacity applied after its modifier stack. Defaults to `1`. */\n opacity?: number;\n /** Whether this source contributes to the unified draw. Defaults to `true`. */\n visible?: boolean;\n /** Higher values survive a fixed work-buffer overflow first. Defaults to `0`. */\n priority?: number;\n /**\n * Cache a modifier-bearing source until {@link UnifiedSplatMesh.invalidateSource}\n * is called. Defaults to `false`, which safely re-gathers live modifier\n * uniforms every frame.\n *\n * Use this for static modifiers, or when the host has a natural dirty signal\n * for every uniform/channel mutation. Forgetting to invalidate leaves the\n * unified work-buffer output stale.\n */\n cacheModifiers?: boolean;\n}\n\n/**\n * Result of a successful {@link UnifiedSplatMesh.pick}: the frontmost hit\n * across every visible registered source, tagged with the source it landed on.\n */\nexport interface UnifiedSplatPickResult extends SplatPickResult {\n /** The registered source mesh whose splat produced the winning hit. */\n readonly source: SplatMesh;\n}\n\n/**\n * Construction settings shared by every source in a unified renderer.\n *\n * @experimental May change in a minor release.\n */\nexport interface UnifiedSplatMeshOptions {\n /** Composite source colors in display (sRGB) space. Defaults to `false`. */\n srgbOutput?: boolean;\n /**\n * Global depth-sort strategy. `'exact'` preserves every Float32 depth bit\n * through a stable radix sort of gathered world-space centers. `'counting'`\n * remains the lower-cost default for existing callers.\n *\n * @experimental Exact sorting trades two additional radix passes for better\n * ordering in large scenes with dense foliage or overlapping surfaces.\n */\n sortStrategy?: 'counting' | 'exact';\n}\n\n/**\n * Returns true when `renderer` can drive {@link UnifiedSplatMesh}.\n * Heterogeneous gather/sort/draw is WebGPU-only; WebGL2 hosts keep standalone\n * `SplatMesh` draws or static {@link MergedSplatMesh}.\n */\nexport function supportsUnifiedSplatMesh(renderer: object): boolean {\n return (\n (renderer as { backend?: { isWebGPUBackend?: boolean } }).backend?.isWebGPUBackend === true\n );\n}\n\n/**\n * One gather → global-sort → draw path for static and streamed splat sources.\n * Sources retain their own residency and update lifecycle; this mesh gathers\n * their current active pool ranges into one shared work buffer per frame.\n *\n * The unified mesh stays at identity (`matrixAutoUpdate` is off). Pose each\n * registered source mesh instead - sorter bounds and the draw material both\n * consume world-space centers written by gather.\n *\n * WebGPU only. Prefer {@link supportsUnifiedSplatMesh} before construction.\n *\n * @experimental May change in a minor release.\n */\nexport class UnifiedSplatMesh extends THREE.Mesh {\n private readonly workBuffer: WorkBuffer;\n private readonly workSourceIndex: THREE.StorageBufferAttribute;\n /** The sorted draw-order buffer; lives outside the geometry, freed on dispose. */\n private readonly orderAttribute: THREE.StorageInstancedBufferAttribute;\n /**\n * Frees the JS mirrors three keeps behind `workSourceIndex` and `order`.\n *\n * `workSourceIndex` is an identity ramp written once at construction; `order`\n * is written only by the sorter, on the GPU. Neither is ever read back, so\n * both mirrors are 4 B/slot of dead JS heap once uploaded.\n */\n private readonly mirrors: StorageMirrorReleaser;\n private readonly sorter: SplatSorter;\n private readonly renderer: THREE.WebGPURenderer;\n private readonly sources: SourceRecord[] = [];\n private previousLayout: LayoutEntry[] = [];\n /** Previous layout keyed by source; kept in step with {@link previousLayout}. */\n private readonly previousLayoutBySource = new Map<SplatMesh, LayoutEntry>();\n /** Per-prepare scratch lists, reused so a steady frame allocates nothing. */\n private readonly candidateScratch: SourceRecord[] = [];\n private readonly admittedScratch: SourceRecord[] = [];\n private readonly drawingBufferSize = new THREE.Vector2();\n /** Reused target dimensions for secondary views; avoids per-view garbage. */\n private readonly secondaryViewSize = new THREE.Vector2();\n /**\n * Camera gating for the global sorter, mirroring the standalone\n * `SplatMesh.requestSortIfNeeded` path: an unchanged work buffer under a\n * stationary camera skips the whole-buffer re-sort. Content changes\n * (regather, layout change) force the next sort through the scheduler.\n */\n private readonly sortScheduler: WebGpuSortScheduler;\n /** Model-view of the last accepted sort; starts unmatchable (zero scale). */\n private readonly lastSortedModelView = new THREE.Matrix4().makeScale(0, 0, 0);\n /**\n * Total admitted splats in the last prepared frame. `removeSource` filters\n * {@link previousLayout} directly, so a tail source's removal can leave the\n * remaining entries identical - only this total betrays the shrink, and a\n * shrunk draw range must re-sort (the old permutation indexes past it).\n */\n private previousAdmittedTotal = 0;\n private readonly bounds = new THREE.Sphere();\n private readonly focal: Vec2Uniform;\n private readonly viewport: Vec2Uniform;\n private readonly maxStdDev: FloatUniform;\n private readonly minSplatSizePx: FloatUniform;\n private readonly antialias: FloatUniform;\n private readonly projectedLowPassVariance: FloatUniform;\n private readonly compensateProjectedLowPass: FloatUniform;\n private readonly dofFocusDistance: FloatUniform;\n private readonly dofAperture: FloatUniform;\n private readonly relightPlaceholder: THREE.DataTexture;\n private relightMap: THREE.Texture;\n private readonly relightBlend: FloatUniform;\n private readonly relightBrightness: FloatUniform;\n private readonly relightBackground: FloatUniform;\n private readonly relightSoftness: FloatUniform;\n private readonly srgbOutput: boolean;\n private sourceMaxStdDev: number | null = null;\n private sourceAntialias: boolean | null = null;\n private sourceProjectedFilterProfile: 'default' | 'lcc' | null = null;\n private overflowedSourceCount = 0;\n private overflowedSplatCount = 0;\n private disposed = false;\n\n constructor(\n renderer: THREE.WebGPURenderer,\n capacity: number,\n options: UnifiedSplatMeshOptions = {},\n ) {\n if (!supportsUnifiedSplatMesh(renderer)) {\n throw new Error(\n 'UnifiedSplatMesh requires a WebGPU backend (renderer.backend.isWebGPUBackend). ' +\n 'On WebGL2 use standalone SplatMesh draws or static MergedSplatMesh.',\n );\n }\n // Fail before allocating StorageBufferAttributes that would trip a cryptic\n // CreateBindGroup validation error when the host left the 128 MiB default.\n assertStorageBufferFitsDevice(renderer, estimateLargestStorageBufferBytes(capacity), capacity);\n const workBuffer = new WorkBuffer(capacity);\n const focal = uniform(new THREE.Vector2());\n const viewport = uniform(new THREE.Vector2());\n const maxStdDev = uniform(3);\n const minSplatSizePx = uniform(0);\n const antialias = uniform(0);\n const projectedLowPassVariance = uniform(0.3);\n const compensateProjectedLowPass = uniform(0);\n const dofFocusDistance = uniform(10);\n const dofAperture = uniform(0);\n const relightPlaceholder = createPlaceholderRelightTexture();\n const relightBlend = uniform(0);\n const relightBrightness = uniform(DEFAULT_RELIGHT_BRIGHTNESS);\n const relightBackground = uniform(DEFAULT_RELIGHT_BACKGROUND);\n const relightSoftness = uniform(DEFAULT_RELIGHT_SOFTNESS);\n const order = new THREE.StorageInstancedBufferAttribute(new Float32Array(capacity), 1);\n const geometry = new THREE.InstancedBufferGeometry();\n geometry.setIndex([0, 1, 2, 0, 2, 3]);\n geometry.setAttribute(\n 'position',\n new THREE.BufferAttribute(new Float32Array([-1, -1, 0, 1, -1, 0, 1, 1, 0, -1, 1, 0]), 3),\n );\n geometry.instanceCount = 0;\n super(\n geometry,\n createWorkBufferMaterial({\n capacity,\n centers: workBuffer.centers,\n colors: workBuffer.colors,\n covarianceA: workBuffer.covarianceA,\n covarianceB: workBuffer.covarianceB,\n isotropicMix: workBuffer.isotropicMix,\n isotropicScreenRadius: workBuffer.isotropicScreenRadius,\n order,\n focal,\n viewport,\n maxStdDev,\n minSplatSizePx,\n antialias,\n projectedLowPassVariance,\n compensateProjectedLowPass,\n dofFocusDistance,\n dofAperture,\n relightMap: relightPlaceholder,\n relightBlend,\n relightBrightness,\n relightBackground,\n relightSoftness,\n }),\n );\n const indices = new Uint32Array(capacity);\n for (let i = 0; i < capacity; i++) indices[i] = i;\n this.workBuffer = workBuffer;\n this.focal = focal;\n this.viewport = viewport;\n this.maxStdDev = maxStdDev;\n this.minSplatSizePx = minSplatSizePx;\n this.antialias = antialias;\n this.projectedLowPassVariance = projectedLowPassVariance;\n this.compensateProjectedLowPass = compensateProjectedLowPass;\n this.dofFocusDistance = dofFocusDistance;\n this.dofAperture = dofAperture;\n this.relightPlaceholder = relightPlaceholder;\n this.relightMap = relightPlaceholder;\n this.relightBlend = relightBlend;\n this.relightBrightness = relightBrightness;\n this.relightBackground = relightBackground;\n this.relightSoftness = relightSoftness;\n this.srgbOutput = options.srgbOutput ?? false;\n this.sortScheduler = new WebGpuSortScheduler(undefined, isFillConstrainedSplatDevice());\n this.orderAttribute = order;\n this.workSourceIndex = new THREE.StorageBufferAttribute(indices, 1);\n this.mirrors = new StorageMirrorReleaser([this.workSourceIndex, this.orderAttribute]);\n this.renderer = renderer;\n const sortInputs = {\n renderer,\n capacity,\n centersBuffer: workBuffer.centers,\n splatIndexAttribute: order,\n sourceIndexAttribute: this.workSourceIndex,\n };\n this.sorter =\n options.sortStrategy === 'exact'\n ? new RadixSorter({ ...sortInputs, exactDepth: true })\n : new ComputeSorter(sortInputs);\n this.frustumCulled = false;\n this.matrixAutoUpdate = false;\n this.matrix.identity();\n this.matrixWorld.identity();\n }\n\n /** Fixed work-buffer splat capacity chosen at construction. */\n get capacity(): number {\n return this.workBuffer.capacity;\n }\n\n /** Registers a source. The caller keeps ownership and may still query it. */\n addSource(source: SplatMesh, options: UnifiedSplatSourceOptions = {}): void {\n this.assertNotDisposed('addSource');\n if (this.sources.some((record) => record.source === source)) return;\n const view = source.getUnifiedSourceView();\n const resolvedVisible = options.visible ?? source.visible;\n if (view.hasSourcePlacement) {\n // The gather pass resolves one matrix per source (the mesh's\n // `matrixWorld`); it knows nothing about a pool's *inner* per-source\n // placement, so a nested scene would draw every one of its sources at\n // its pool-local position. Reject rather than draw it wrong.\n throw new Error(\n 'UnifiedSplatMesh: a MergedSplatMesh is already a unified pool with its own global ' +\n 'sort; add its sources individually, or draw the mesh directly.',\n );\n }\n if (view.srgbOutput !== this.srgbOutput) {\n throw new Error(\"UnifiedSplatMesh: every source must use the renderer's srgbOutput setting.\");\n }\n if (this.sourceMaxStdDev === null) {\n this.sourceMaxStdDev = view.maxStdDev;\n this.maxStdDev.value = view.maxStdDev;\n this.minSplatSizePx.value = view.minSplatSizePx;\n } else if (this.sourceMaxStdDev !== view.maxStdDev) {\n throw new Error('UnifiedSplatMesh: every source must use the same maxStdDev setting.');\n } else if (this.minSplatSizePx.value !== view.minSplatSizePx) {\n throw new Error('UnifiedSplatMesh: every source must use the same minSplatSizePx setting.');\n }\n if (this.sourceAntialias === null) {\n this.sourceAntialias = view.antialias;\n this.antialias.value = view.antialias ? 1 : 0;\n } else if (this.sourceAntialias !== view.antialias) {\n throw new Error('UnifiedSplatMesh: every source must use the same antialias setting.');\n }\n if (this.sourceProjectedFilterProfile === null) {\n this.sourceProjectedFilterProfile = view.projectedFilterProfile;\n const lccProfile = view.projectedFilterProfile === 'lcc';\n this.projectedLowPassVariance.value = lccProfile ? 0.1 : 0.3;\n this.compensateProjectedLowPass.value = lccProfile ? 1 : 0;\n } else if (this.sourceProjectedFilterProfile !== view.projectedFilterProfile) {\n throw new Error('UnifiedSplatMesh: every source must use the same projected filter profile.');\n }\n this.sources.push({\n source,\n gather: this.createGather(view),\n graphRevision: view.graphRevision,\n priority: options.priority ?? 0,\n opacity: options.opacity ?? 1,\n visible: resolvedVisible,\n cacheModifiers: options.cacheModifiers ?? false,\n originalVisible: source.visible,\n lastGather: null,\n view: null,\n registrationOrder: 0,\n offset: 0,\n });\n source.visible = false;\n source.setUnifiedPickVisibility(resolvedVisible);\n }\n\n /**\n * Invalidates one registered source's cached gather output.\n *\n * Required after changing modifier uniforms or channels when that source was\n * registered with `cacheModifiers: true`. The following {@link update}\n * re-gathers the source and re-sorts because modifiers may move splats.\n * Returns `false` when the source is not registered.\n */\n invalidateSource(source: SplatMesh): boolean {\n this.assertNotDisposed('invalidateSource');\n const record = this.sources.find((candidate) => candidate.source === source);\n if (!record) return false;\n record.lastGather = null;\n return true;\n }\n\n /** Number of whole sources omitted in the most recent update due to capacity. */\n get droppedSourceCount(): number {\n return this.overflowedSourceCount;\n }\n\n /** Number of active splats omitted in the most recent update due to capacity. */\n get droppedSplatCount(): number {\n return this.overflowedSplatCount;\n }\n\n /** Updates a source's resolved opacity without rebuilding its gather pipeline. */\n setSourceOpacity(source: SplatMesh, opacity: number): void {\n this.assertNotDisposed('setSourceOpacity');\n const record = this.sources.find((entry) => entry.source === source);\n if (!record) throw new Error('UnifiedSplatMesh: source is not registered.');\n record.opacity = opacity;\n }\n\n /** Shows or hides a source without changing its residency. */\n setSourceVisible(source: SplatMesh, visible: boolean): void {\n this.assertNotDisposed('setSourceVisible');\n const record = this.sources.find((entry) => entry.source === source);\n if (!record) throw new Error('UnifiedSplatMesh: source is not registered.');\n record.visible = visible;\n record.source.setUnifiedPickVisibility(visible);\n }\n\n /**\n * Core projected-2D depth of field on the unified draw pass (not gather).\n * Live uniforms - no gather-cache invalidation. Pass `aperture: 0` to disable.\n */\n setDepthOfField(settings: Partial<DepthOfFieldSettings>): void {\n this.assertNotDisposed('setDepthOfField');\n const next = clampDepthOfFieldSettings(settings, this.getDepthOfField());\n this.dofFocusDistance.value = next.focusDistance;\n this.dofAperture.value = next.aperture;\n }\n\n /** Current core DoF uniforms (`aperture === 0` means off). */\n getDepthOfField(): DepthOfFieldSettings {\n return {\n focusDistance: this.dofFocusDistance.value,\n aperture: this.dofAperture.value,\n };\n }\n\n /**\n * PlayCanvas-style proxy-mesh relighting on the unified draw pass (not gather).\n * Live blend/brightness/background; map identity change rebuilds the draw\n * material. Does not invalidate gather caches. Pass `null` to disable.\n */\n setRelighting(options: RelightingSettings | null): void {\n this.assertNotDisposed('setRelighting');\n if (options === null) {\n this.relightBlend.value = 0;\n if (this.relightMap !== this.relightPlaceholder) {\n this.relightMap = this.relightPlaceholder;\n this.rebuildDrawMaterial();\n }\n return;\n }\n const next = clampRelightingSettings(options, this.getRelighting());\n this.relightBlend.value = next.blend;\n this.relightBrightness.value = next.brightness;\n this.relightBackground.value = next.background;\n this.relightSoftness.value = next.softness;\n if (options.map !== this.relightMap) {\n this.relightMap = options.map;\n this.rebuildDrawMaterial();\n }\n }\n\n /** Current relight numeric uniforms (`blend === 0` means off). */\n getRelighting(): RelightingUniforms {\n return {\n blend: this.relightBlend.value,\n brightness: this.relightBrightness.value,\n background: this.relightBackground.value,\n softness: this.relightSoftness.value,\n };\n }\n\n /**\n * Asynchronously picks the frontmost visible splat under an NDC coordinate\n * across every registered source.\n *\n * Semantics: each source that is\n * currently visible in this unified renderer runs its own depth-tested GPU\n * pick pass; the hit nearest the camera wins and the result names its source\n * mesh. Hidden sources (`setSourceVisible(source, false)`) never hit. A hit\n * whose source was removed, hidden, or disposed while its readback was in\n * flight is dropped rather than misattributed. Resolves `null` for misses,\n * an empty source list, and picks pending across {@link dispose}.\n *\n * Uses the construction renderer. Concurrent calls are safe: each source\n * serializes its own picks and shared renderer state is restored\n * synchronously before any await.\n */\n async pick(\n ndc: THREE.Vector2,\n camera: THREE.Camera,\n options?: SplatPickOptions,\n ): Promise<UnifiedSplatPickResult | null> {\n if (this.disposed) return null;\n const candidates = this.sources\n .filter((record) => record.visible)\n .map((record) => record.source);\n if (candidates.length === 0) return null;\n const hits = await Promise.all(\n candidates.map(async (source) => {\n const hit = await source.pick(ndc, camera, this.renderer, options);\n return hit === null ? null : { source, point: hit.point, distance: hit.distance };\n }),\n );\n if (this.disposed) return null;\n let best: UnifiedSplatPickResult | null = null;\n for (const hit of hits) {\n if (hit === null) continue;\n // Registration may have changed while the readbacks were in flight;\n // never attribute a hit to a source no longer picked by this renderer.\n const record = this.sources.find((entry) => entry.source === hit.source);\n if (record === undefined || !record.visible) continue;\n if (best === null || hit.distance < best.distance) best = hit;\n }\n return best;\n }\n\n /** Unregisters a source and restores its standalone draw visibility. */\n removeSource(source: SplatMesh): boolean {\n this.assertNotDisposed('removeSource');\n const index = this.sources.findIndex((entry) => entry.source === source);\n if (index < 0) return false;\n const [record] = this.sources.splice(index, 1);\n if (record) {\n record.gather.dispose();\n record.source.visible = record.originalVisible;\n record.source.setUnifiedPickVisibility(null);\n record.lastGather = null;\n }\n this.previousLayout = this.previousLayout.filter((entry) => entry.source !== source);\n this.previousLayoutBySource.delete(source);\n if (this.sources.length === 0) {\n this.sourceMaxStdDev = null;\n this.sourceAntialias = null;\n this.sourceProjectedFilterProfile = null;\n this.previousLayout = [];\n this.previousLayoutBySource.clear();\n }\n return true;\n }\n\n /** Updates source LODs, gathers their active splats, then globally sorts them. */\n update(camera: THREE.PerspectiveCamera): void {\n if (this.disposed) return;\n this.prepare(camera);\n }\n\n /**\n * Re-sorts and draws this unified source list for a secondary camera.\n * Mirrors and portals use this instead of rendering the hidden source meshes\n * individually, so their reflection keeps one global transparent order.\n */\n renderView(\n camera: THREE.PerspectiveCamera,\n renderer: THREE.WebGPURenderer,\n target: THREE.RenderTarget | null = null,\n ): void {\n if (this.disposed) return;\n if (renderer !== this.renderer) {\n throw new Error('UnifiedSplatMesh: renderView must use its construction renderer.');\n }\n if (!supportsUnifiedSplatMesh(renderer)) {\n throw new Error(\n 'UnifiedSplatMesh requires a WebGPU backend (renderer.backend.isWebGPUBackend).',\n );\n }\n // A secondary view must sort for its own camera regardless of cadence, and\n // it leaves a foreign order in the shared buffer - invalidate afterwards so\n // the next primary update re-sorts even if its camera has not moved.\n const targetSize = target ? this.secondaryViewSize.set(target.width, target.height) : undefined;\n this.prepare(camera, targetSize, true);\n const previousTarget = renderer.getRenderTarget();\n try {\n renderer.setRenderTarget(target);\n renderer.render(this, camera);\n } finally {\n renderer.setRenderTarget(previousTarget);\n // `prepare` left the shared order buffer sorted for the secondary view.\n // Invalidate even when its draw throws, or a stationary primary view can\n // render through that foreign order after the host recovers.\n this.sortScheduler.invalidate();\n }\n }\n\n private prepare(\n camera: THREE.PerspectiveCamera,\n targetSize?: THREE.Vector2,\n forceSort = false,\n ): void {\n if (!supportsUnifiedSplatMesh(this.renderer)) {\n throw new Error(\n 'UnifiedSplatMesh requires a WebGPU backend (renderer.backend.isWebGPUBackend).',\n );\n }\n // Hosts must not pose this mesh; world centers already include source transforms.\n this.matrix.identity();\n this.matrixWorld.identity();\n // A secondary view (`renderView`) states its own size and camera; the\n // primary one follows the renderer, which in XR means a *per-eye* viewport\n // and a cyclopean head pose. Taking the drawing buffer there would be twice\n // the true width and halve every splat's horizontal size, and sorting from\n // the application camera would order the scene from wherever that camera\n // was left standing.\n const xrView = targetSize ? null : resolveXrView(camera, this.renderer);\n const projectionCamera: THREE.Camera = xrView?.eye ?? camera;\n // One global sort from the head serves both eyes (see `xr-view.ts`).\n const viewCamera: THREE.Camera = xrView?.head ?? camera;\n const viewport = this.drawingBufferSize;\n if (targetSize) viewport.copy(targetSize);\n else if (xrView) viewport.set(xrView.width, xrView.height);\n else this.renderer.getDrawingBufferSize(viewport);\n const projection = projectionCamera.projectionMatrix.elements;\n this.viewport.value.copy(viewport);\n const focalX = projection[0] ?? 0;\n const focalY = projection[5] ?? 0;\n this.focal.value.set((focalX * viewport.x) / 2, (focalY * viewport.y) / 2);\n const updated = this.candidateScratch;\n updated.length = 0;\n for (let i = 0; i < this.sources.length; i++) {\n const record = this.sources[i] as SourceRecord;\n // Children take the application camera: they resolve the XR view for\n // themselves, and a streamed source needs it for LOD scheduling.\n record.source.update(camera, this.renderer, { sort: false });\n record.view = record.source.getUnifiedSourceView();\n record.registrationOrder = i;\n updated.push(record);\n }\n // Overflow is deterministic and region-safe: preserve whole sources rather\n // than gathering a prefix of a streamed cut. Higher priority wins; matching\n // priorities retain registration order.\n updated.sort((a, b) => b.priority - a.priority || a.registrationOrder - b.registrationOrder);\n\n this.overflowedSourceCount = 0;\n this.overflowedSplatCount = 0;\n this.bounds.makeEmpty();\n\n const admitted = this.admittedScratch;\n admitted.length = 0;\n let offset = 0;\n for (const record of updated) {\n const view = record.view as UnifiedSourceView;\n if (record.graphRevision !== view.graphRevision) {\n // Build the replacement before disposing the old pipeline: a modifier\n // stack that throws at graph-build time must leave the record holding\n // a live gather (and an unchanged revision) so the next update can\n // retry after the caller fixes the stack.\n const rebuilt = this.createGather(view);\n record.gather.dispose();\n record.gather = rebuilt;\n record.graphRevision = view.graphRevision;\n record.lastGather = null;\n }\n if (!record.visible) {\n record.lastGather = null;\n continue;\n }\n if (view.activeCount === 0) {\n // An empty cut (e.g. a streamed source before its first chunk lands)\n // owns no work slice: skip the zero-splat gather dispatch and keep the\n // sorter bounds limited to sources that contribute splats.\n record.lastGather = null;\n continue;\n }\n if (offset + view.activeCount > this.workBuffer.capacity) {\n this.overflowedSourceCount++;\n this.overflowedSplatCount += view.activeCount;\n record.lastGather = null;\n continue;\n }\n record.offset = offset;\n admitted.push(record);\n this.bounds.union(view.worldBounds);\n offset += view.activeCount;\n }\n\n // Geometry under the draw order changed (layout, active cut, transform,\n // opacity, content revision). Camera-only SH / modifier color refreshes\n // re-gather the *same* world centers and must not force a sort.\n let geometryInvalidated = false;\n for (const record of admitted) {\n const view = record.view as UnifiedSourceView;\n const sliceOffset = record.offset;\n const previous = this.previousLayoutBySource.get(record.source);\n const ownedSameSlice =\n previous !== undefined &&\n previous.offset === sliceOffset &&\n previous.activeCount === view.activeCount;\n const last = record.lastGather;\n const geometryMatches =\n last !== null &&\n ownedSameSlice &&\n last.activeCount === view.activeCount &&\n last.contentRevision === view.contentRevision &&\n last.offset === sliceOffset &&\n last.opacity === record.opacity &&\n last.matrixWorld.equals(view.matrixWorld);\n const reusable =\n geometryMatches &&\n // SH depends on camera position, not orientation. A stationary camera\n // can reuse the resolved colors instead of re-running a full-source\n // gather every frame; camera motion invalidates only SH-bearing slices.\n (view.sh === null || last.localCameraPosition.equals(view.localCameraPosition.value)) &&\n (view.modifiers.length === 0 || record.cacheModifiers) &&\n // Belt-and-braces: a placed pool's splats move without its own\n // `matrixWorld` changing, so a cached gather would go stale silently.\n // `addSource` already rejects these.\n !view.hasSourcePlacement;\n if (!reusable) {\n record.gather.gather(\n this.renderer,\n view.activeCount,\n sliceOffset,\n view.matrixWorld,\n viewCamera.matrixWorldInverse,\n record.opacity,\n );\n if (!geometryMatches) geometryInvalidated = true;\n if (record.lastGather === null) {\n record.lastGather = {\n activeCount: view.activeCount,\n contentRevision: view.contentRevision,\n offset: sliceOffset,\n opacity: record.opacity,\n matrixWorld: view.matrixWorld.clone(),\n localCameraPosition: view.localCameraPosition.value.clone(),\n };\n } else {\n record.lastGather.activeCount = view.activeCount;\n record.lastGather.contentRevision = view.contentRevision;\n record.lastGather.offset = sliceOffset;\n record.lastGather.opacity = record.opacity;\n record.lastGather.matrixWorld.copy(view.matrixWorld);\n record.lastGather.localCameraPosition.copy(view.localCameraPosition.value);\n }\n }\n }\n\n // Commit ownership only after every gather for this preparation has run.\n let layoutChanged =\n admitted.length !== this.previousLayout.length || offset !== this.previousAdmittedTotal;\n this.previousAdmittedTotal = offset;\n if (!layoutChanged) {\n for (let i = 0; i < admitted.length; i++) {\n const record = admitted[i] as SourceRecord;\n const entry = this.previousLayout[i] as LayoutEntry;\n if (\n entry.source !== record.source ||\n entry.offset !== record.offset ||\n entry.activeCount !== (record.view as UnifiedSourceView).activeCount\n ) {\n layoutChanged = true;\n break;\n }\n }\n }\n if (layoutChanged) {\n this.previousLayout = admitted.map((record) => ({\n source: record.source,\n offset: record.offset,\n activeCount: (record.view as UnifiedSourceView).activeCount,\n }));\n this.previousLayoutBySource.clear();\n for (const entry of this.previousLayout) this.previousLayoutBySource.set(entry.source, entry);\n }\n\n // Work-buffer *geometry* moved underneath the current draw order: the next\n // sort must run whatever the camera did. Camera-driven SH/modifier color\n // refreshes re-gather without geometryInvalidated and deliberately skip\n // this. DoF is a live draw uniform and reaches neither branch.\n if (geometryInvalidated || layoutChanged) this.sortScheduler.invalidateContent();\n\n if (offset > 0) {\n const now = performance.now();\n const viewInverse = viewCamera.matrixWorldInverse;\n if (\n forceSort ||\n this.sortScheduler.shouldSubmit(viewInverse, this.lastSortedModelView, offset, now)\n ) {\n if (this.sorter.sort(viewInverse, offset, this.bounds)) {\n this.lastSortedModelView.copy(viewInverse);\n this.sortScheduler.markAccepted(now);\n }\n }\n }\n (this.geometry as THREE.InstancedBufferGeometry).instanceCount = offset;\n // Both are uploaded by the first frame's gather/sort dispatches, and neither\n // is ever read back - see the field comment. The work buffer's own mirrors\n // are released by `WorkBufferGather.gather`.\n if (!this.mirrors.settled) this.mirrors.release(this.renderer);\n }\n\n dispose(): void {\n if (this.disposed) return;\n this.disposed = true;\n for (const record of this.sources) {\n record.gather.dispose();\n record.source.visible = record.originalVisible;\n record.source.setUnifiedPickVisibility(null);\n record.lastGather = null;\n }\n this.sources.length = 0;\n this.previousLayout = [];\n this.previousLayoutBySource.clear();\n this.candidateScratch.length = 0;\n this.admittedScratch.length = 0;\n this.sourceMaxStdDev = null;\n this.sourceAntialias = null;\n this.sourceProjectedFilterProfile = null;\n this.sorter.dispose();\n this.geometry.dispose();\n (this.material as THREE.Material).dispose();\n this.relightPlaceholder.dispose();\n // The work buffer, its source-index list and the draw-order buffer are\n // storage attributes outside the geometry, so nothing above frees their\n // GPU buffers - ~72 B per work slot leaked per scene swap without this.\n releaseRendererAttributes(this.renderer, [\n this.workBuffer.centers,\n this.workBuffer.colors,\n this.workBuffer.covarianceA,\n this.workBuffer.covarianceB,\n this.workBuffer.isotropicMix,\n this.workBuffer.isotropicScreenRadius,\n this.workSourceIndex,\n this.orderAttribute,\n ]);\n }\n\n private assertNotDisposed(operation: string): void {\n if (this.disposed) {\n throw new Error(`UnifiedSplatMesh: ${operation} called after dispose.`);\n }\n }\n\n /** Rebuilds the EWA draw material when the relight map identity changes. */\n private rebuildDrawMaterial(): void {\n const previous = this.material as THREE.Material;\n this.material = createWorkBufferMaterial({\n capacity: this.workBuffer.capacity,\n centers: this.workBuffer.centers,\n colors: this.workBuffer.colors,\n covarianceA: this.workBuffer.covarianceA,\n covarianceB: this.workBuffer.covarianceB,\n isotropicMix: this.workBuffer.isotropicMix,\n isotropicScreenRadius: this.workBuffer.isotropicScreenRadius,\n order: this.orderAttribute,\n focal: this.focal,\n viewport: this.viewport,\n maxStdDev: this.maxStdDev,\n minSplatSizePx: this.minSplatSizePx,\n antialias: this.antialias,\n projectedLowPassVariance: this.projectedLowPassVariance,\n compensateProjectedLowPass: this.compensateProjectedLowPass,\n dofFocusDistance: this.dofFocusDistance,\n dofAperture: this.dofAperture,\n relightMap: this.relightMap,\n relightBlend: this.relightBlend,\n relightBrightness: this.relightBrightness,\n relightBackground: this.relightBackground,\n relightSoftness: this.relightSoftness,\n });\n previous.dispose();\n }\n\n private createGather(view: ReturnType<SplatMesh['getUnifiedSourceView']>): WorkBufferGather {\n const gather = this.buildGather(view);\n // Compile off the critical frame. WebGPU defers compute-pipeline compilation\n // to the first dispatch, and that dispatch happens inside `update` - a\n // measured 2.0s frame on a multi-mesh scene. Warming here is best-effort:\n // if it fails or has not finished by the first real gather, the only cost is\n // the stall this avoids, so nothing waits on it.\n void gather.warmUp(this.renderer).catch(() => undefined);\n return gather;\n }\n\n private buildGather(view: ReturnType<SplatMesh['getUnifiedSourceView']>): WorkBufferGather {\n return new WorkBufferGather({\n capacity: this.workBuffer.capacity,\n sourceCapacity: view.capacity,\n sourceIndex: view.sourceIndex,\n centersTexture: view.centersTexture,\n colorsTexture: view.colorsTexture,\n covarianceATexture: view.covarianceATexture,\n covarianceBTexture: view.covarianceBTexture,\n dataTextureWidth: view.dataTextureWidth,\n sh: view.sh,\n modifiers: view.modifiers,\n channels: view.channels,\n localCameraPosition: view.localCameraPosition,\n srgbOutput: this.srgbOutput,\n // Per source, not a compatibility field: the gather normalizes `.rad`\n // half-alpha here so one shared draw material serves mixed scenes.\n lodAlpha: view.lodAlpha,\n workBuffer: this.workBuffer,\n });\n }\n}\n"],"names":["_WorkBuffer","capacity","__publicField","slots","THREE","StorageMirrorReleaser","renderer","WorkBuffer","WorkBufferGather","options","uniform","sourceCapacity","sourceIndex","centersTexture","colorsTexture","covarianceATexture","covarianceBTexture","dataTextureWidth","sh","modifiers","channels","localCameraPosition","source","storage","output","outputColor","outputCovA","outputCovB","outputIsotropicMix","outputIsotropicScreenRadius","Fn","If","float","instanceIndex","poolIndex","int","texel","ivec2","localCenter","textureLoad","target","inputA","inputB","covarianceBase","mat3","vec3","baseColor","colorAfterSh","vec4","evaluateSplatSh","worldCenter","stack","foldSplatModifierStack","inverse","toCamera","axis","name","channel","center","visible","bool","gatheredCenter","resolvedColor","asNode","colorSpaceToWorking","sourceAlpha","covariance","localCovariance","varianceScale","DEFAULT_ISOTROPIC_VARIANCE_SCALE","applyIsotropicCovarianceOverride","linear","worldCovarianceBase","worldCovariance","c0","c1","c2","activeCount","targetOffset","sourceMatrix","cameraViewMatrixOrOpacity","opacity","cameraViewMatrix","createWorkBufferMaterial","material","centers","order","colors","covarianceA","covarianceB","isotropicMix","isotropicScreenRadius","workColor","varying","quadPosition","positionGeometry","opacityCompensation","adjustedStdDev","workIndex","centerSample","drawable","viewCenter","modelViewMatrix","clipCenter","cameraProjectionMatrix","covA","covB","invZ","invZ2","j1","j2","viewRotationT","u1","u2","aRaw","dRaw","bRaw","depth","focus","halfApertureAngle","focusBlur","apertureRadius","cocRadiusPx","cocVar","MAX_DOF_VARIANCE","a","d","b","isoMix","detBlur","detRaw","detBase","mipFade","dofOnlyFade","compensate","fade","mix","mid","radius","vec2","lambda1","lambda2","equalized","equalizeProjectedEigenvalues","capped","capProjectedEigenvaluesToScreenRadius","remap","stdDev","eigenvector","minSplat","major","minor","pixelOffset","ndcCenter","clipPosition","margin","squaredDistance","Discard","g","aExp","merged","alpha","litCenter","tslTexture","screenUV","ox","oy","s0","s1","s2","s3","s4","wSum","rgbSoft","aSoft","litSoft","lit","factor","rgb","WORK_BUFFER_CENTERS_BYTES_PER_SPLAT","WORK_BUFFER_BYTES_PER_SLOT","assertNonNegativeCapacity","estimateLargestStorageBufferBytes","estimateUnifiedWorkBufferBytes","estimateUnifiedWorkBufferPeakBytes","supportsUnifiedSplatMesh","_a","UnifiedSplatMesh","assertStorageBufferFitsDevice","workBuffer","focal","viewport","maxStdDev","minSplatSizePx","antialias","projectedLowPassVariance","compensateProjectedLowPass","dofFocusDistance","dofAperture","relightPlaceholder","createPlaceholderRelightTexture","relightBlend","relightBrightness","DEFAULT_RELIGHT_BRIGHTNESS","relightBackground","DEFAULT_RELIGHT_BACKGROUND","relightSoftness","DEFAULT_RELIGHT_SOFTNESS","geometry","indices","i","WebGpuSortScheduler","isFillConstrainedSplatDevice","sortInputs","RadixSorter","ComputeSorter","record","view","resolvedVisible","lccProfile","candidate","entry","settings","next","clampDepthOfFieldSettings","clampRelightingSettings","ndc","camera","candidates","hits","hit","best","index","targetSize","previousTarget","forceSort","xrView","resolveXrView","projectionCamera","viewCamera","projection","focalX","focalY","updated","admitted","offset","rebuilt","geometryInvalidated","sliceOffset","previous","ownedSameSlice","last","geometryMatches","layoutChanged","now","viewInverse","releaseRendererAttributes","operation","gather"],"mappings":";;;;;;;;;AAsCO,MAAMA,KAAN,MAAMA,GAAW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;AAAA,MACzB,kBAAkBA,EAAK;AAAA,MACvB,IAAIA,EAAK;AAAA,MACT,WAAWA,EAAK;AAAA,MAChB,UAAUA,EAAK;AAAA,MACf,qBAAqBA,EAAK;AAAA,MAC1B,YAAY,KAAK;AAAA;AAAA;AAAA,MAGjB,UAAUA,EAAK;AAAA,MACf,YAAY,KAAK;AAAA,IAAA,CAClB;AAAA,EACH;AACF;"}
|
|
1
|
+
{"version":3,"file":"unified.js","sources":["../src/lib/unified/work-buffer-gather.ts","../src/lib/unified/work-buffer-material.ts","../src/lib/unified/unified-work-buffer.ts","../src/lib/unified/unified-splat-mesh.ts"],"sourcesContent":["import * as THREE from 'three/webgpu';\nimport {\n Fn,\n If,\n bool,\n float,\n int,\n instanceIndex,\n ivec2,\n mat3,\n storage,\n textureLoad,\n uniform,\n vec3,\n vec4,\n} from 'three/tsl';\nimport {\n evaluateSplatSh,\n foldSplatModifierStack,\n asNode,\n applyIsotropicCovarianceOverride,\n DEFAULT_ISOTROPIC_VARIANCE_SCALE,\n type SplatShInputs,\n type Vec3Uniform,\n} from '../core/splat-mesh-material';\nimport { colorSpaceToWorking } from 'three/tsl';\nimport type { SplatModifier } from '../core/splat-modifier';\nimport { StorageMirrorReleaser } from '../core/storage-attribute-mirror';\n\n/**\n * GPU gather pass for Phase 0 of the unified renderer. It resolves a source\n * pool's active local centers into a shared world-space storage buffer. The\n * work-buffer sorter consumes this buffer directly, so source-local pools can\n * later be heterogeneous (including streamed LOD pools).\n *\n * Internal while M15.4's draw path and public source API are completed.\n */\n/** Shared GPU storage for every gathered source in one unified frame. */\nexport class WorkBuffer {\n /** World-space center xyz; w is display opacity (`visibility × source opacity ×` RAD modifier ratio). */\n readonly centers: THREE.StorageBufferAttribute;\n /** Resolved color and opacity per work slot. */\n readonly colors: THREE.StorageBufferAttribute;\n /** First packed covariance row per work slot. */\n readonly covarianceA: THREE.StorageBufferAttribute;\n /** Second packed covariance row per work slot. */\n readonly covarianceB: THREE.StorageBufferAttribute;\n /** Per-slot isotropic covariance mix (0 = keep Σ, 1 = round dot). */\n readonly isotropicMix: THREE.StorageBufferAttribute;\n /** Per-slot isotropic target sigma radius in screen px (0 = disabled). */\n readonly isotropicScreenRadius: THREE.StorageBufferAttribute;\n\n /**\n * Slots past {@link capacity}, reserved so a pipeline warm-up has somewhere\n * harmless to write. See {@link WorkBufferGather.warmUp}: compiling a compute\n * pipeline requires actually dispatching it, and dispatching zero workgroups\n * - while it does compile - makes WebGPU log an \"unusual workgroup count of 0\"\n * warning for every source. One workgroup aimed at this tail compiles just the\n * same, silently, and cannot disturb a drawn slot: admission never allocates\n * past `capacity` and the draw's `instanceCount` never covers it.\n */\n static readonly SCRATCH_SLOTS = 256;\n\n constructor(readonly capacity: number) {\n const slots = capacity + WorkBuffer.SCRATCH_SLOTS;\n this.centers = new THREE.StorageBufferAttribute(new Float32Array(slots * 4), 4);\n this.colors = new THREE.StorageBufferAttribute(new Float32Array(slots * 4), 4);\n this.covarianceA = new THREE.StorageBufferAttribute(new Float32Array(slots * 4), 4);\n this.covarianceB = new THREE.StorageBufferAttribute(new Float32Array(slots * 4), 4);\n this.isotropicMix = new THREE.StorageBufferAttribute(new Float32Array(slots), 1);\n this.isotropicScreenRadius = new THREE.StorageBufferAttribute(new Float32Array(slots), 1);\n this.mirrors = new StorageMirrorReleaser([\n this.centers,\n this.colors,\n this.covarianceA,\n this.covarianceB,\n this.isotropicMix,\n this.isotropicScreenRadius,\n ]);\n }\n\n /**\n * Drops the JS-heap copies three keeps behind these storage buffers.\n *\n * Every one of them is written only by the gather compute pass and read only\n * by the draw material - the CPU side is zeroes that no code ever reads, and\n * three's WebGPU backend never frees it on its own. At 72 B/slot that mirror\n * is ~720 MB of JS heap on a 10M-slot scene. See `storage-attribute-mirror`.\n *\n * Safe to call after any dispatch that bound this buffer; a no-op once\n * settled, and on WebGL2 or a renderer double that has no WebGPU backend.\n */\n releaseCpuMirrors(renderer: THREE.WebGPURenderer): void {\n if (this.mirrors.settled) return;\n this.mirrors.release(renderer);\n }\n\n private readonly mirrors: StorageMirrorReleaser;\n}\n\nexport class WorkBufferGather {\n /** World-space `xyzw` center buffer, one element per unified work slot. */\n readonly centers: THREE.StorageBufferAttribute;\n /** Resolved source RGBA values; production draw consumes this next. */\n readonly colors: THREE.StorageBufferAttribute;\n /** Packed symmetric world-space covariance rows. */\n readonly covarianceA: THREE.StorageBufferAttribute;\n readonly covarianceB: THREE.StorageBufferAttribute;\n readonly isotropicMix: THREE.StorageBufferAttribute;\n readonly isotropicScreenRadius: THREE.StorageBufferAttribute;\n /** Shared target for this source's gathered range. */\n readonly workBuffer: WorkBuffer;\n private readonly capacity: number;\n private readonly activeCount = uniform(0);\n private readonly targetOffset = uniform(0);\n private readonly sourceMatrix = uniform(new THREE.Matrix4());\n private readonly cameraViewMatrix = uniform(new THREE.Matrix4());\n private readonly opacity = uniform(1);\n private readonly pass: THREE.ComputeNode;\n\n constructor(options: {\n capacity: number;\n sourceCapacity: number;\n sourceIndex: THREE.StorageBufferAttribute;\n centersTexture: THREE.DataTexture;\n colorsTexture: THREE.DataTexture;\n covarianceATexture: THREE.DataTexture;\n covarianceBTexture: THREE.DataTexture;\n dataTextureWidth: number;\n sh?: SplatShInputs | null;\n modifiers?: readonly SplatModifier[];\n channels?: ReadonlyMap<string, { texture: THREE.DataTexture }>;\n localCameraPosition?: Vec3Uniform;\n srgbOutput?: boolean;\n /**\n * Source stores Spark LOD alpha (`alpha ÷ 2`, `.rad`). Recover the full\n * `alpha ∈ [0,2]` into `colors.a` from the *original* texture channel so the\n * shared draw material can classify merged vs leaf without seeing fades.\n */\n lodAlpha?: boolean;\n /** Reuse one target across all source gather passes. */\n workBuffer?: WorkBuffer;\n }) {\n const {\n capacity,\n sourceCapacity,\n sourceIndex,\n centersTexture,\n colorsTexture,\n covarianceATexture,\n covarianceBTexture,\n dataTextureWidth,\n } = options;\n const sh = options.sh ?? null;\n const modifiers = options.modifiers ?? [];\n const channels = options.channels ?? new Map<string, { texture: THREE.DataTexture }>();\n const localCameraPosition = options.localCameraPosition ?? uniform(new THREE.Vector3());\n this.workBuffer = options.workBuffer ?? new WorkBuffer(capacity);\n this.capacity = this.workBuffer.capacity;\n this.centers = this.workBuffer.centers;\n this.colors = this.workBuffer.colors;\n this.covarianceA = this.workBuffer.covarianceA;\n this.covarianceB = this.workBuffer.covarianceB;\n this.isotropicMix = this.workBuffer.isotropicMix;\n this.isotropicScreenRadius = this.workBuffer.isotropicScreenRadius;\n const source = storage(sourceIndex, 'uint', sourceCapacity);\n const output = storage(this.centers, 'vec4', capacity);\n const outputColor = storage(this.colors, 'vec4', capacity);\n const outputCovA = storage(this.covarianceA, 'vec4', capacity);\n const outputCovB = storage(this.covarianceB, 'vec4', capacity);\n const outputIsotropicMix = storage(this.isotropicMix, 'float', capacity);\n const outputIsotropicScreenRadius = storage(this.isotropicScreenRadius, 'float', capacity);\n this.pass = Fn(() => {\n If(float(instanceIndex).lessThan(this.activeCount), () => {\n const poolIndex = int(source.element(instanceIndex));\n const texel = ivec2(\n poolIndex.mod(int(dataTextureWidth)),\n poolIndex.div(int(dataTextureWidth)),\n );\n const localCenter = textureLoad(centersTexture, texel).xyz;\n const target = instanceIndex.add(this.targetOffset.toUint());\n const inputA = textureLoad(covarianceATexture, texel);\n const inputB = textureLoad(covarianceBTexture, texel);\n const covarianceBase = mat3(\n vec3(inputA.x, inputA.y, inputA.z),\n vec3(inputA.y, inputA.w, inputB.x),\n vec3(inputA.z, inputB.x, inputB.y),\n );\n const baseColor = textureLoad(colorsTexture, texel);\n const colorAfterSh =\n sh === null\n ? baseColor\n : vec4(\n baseColor.rgb\n .add(\n evaluateSplatSh(\n sh,\n { covarianceBTexture },\n texel,\n localCenter.sub(localCameraPosition).normalize(),\n ),\n )\n .clamp(0.0, 1.0),\n baseColor.a,\n );\n const worldCenter = this.sourceMatrix.mul(vec4(localCenter, 1.0)).xyz;\n const stack = foldSplatModifierStack(modifiers, localCameraPosition, {\n index: poolIndex,\n localCenter,\n color: colorAfterSh,\n makeWorldCenter: () => worldCenter,\n makeViewCenter: () => this.cameraViewMatrix.mul(vec4(worldCenter, 1.0)).xyz,\n makeNormal: () => {\n const inverse = covarianceBase.inverse();\n const toCamera = localCameraPosition.sub(localCenter);\n const axis = inverse.mul(inverse.mul(toCamera)).normalize();\n return axis.mul(axis.dot(toCamera).sign());\n },\n makeChannel: (name) => {\n const channel = channels.get(name);\n if (!channel) {\n throw new Error(\n `UnifiedSplatMesh: source modifier reads undefined channel \"${name}\".`,\n );\n }\n return textureLoad(channel.texture, texel).r;\n },\n });\n const center = stack.offset === null ? localCenter : localCenter.add(stack.offset);\n const visible = stack.visible === null ? bool(true) : stack.visible;\n // Stable work slots: keep hidden splats in the gather/sort range.\n // `centers.w` is display opacity: `visibility × source opacity`, and for\n // `.rad` sources the modifier-to-original alpha ratio as well. The\n // draw material treats `w <= 0` as non-drawable. Compacting hidden\n // splats was rejected (ROADMAP L3): the hidden set exists only on the\n // GPU, so compaction needs a count readback before the CPU-sized sort.\n const gatheredCenter = this.sourceMatrix.mul(vec4(center, 1.0)).xyz;\n const encodedOriginal = asNode<'float'>(colorAfterSh.a);\n const encodedResolved = asNode<'float'>(stack.color.a);\n const visibility = visible.select(float(1), float(0));\n const resolvedColor = options.srgbOutput\n ? stack.color\n : asNode<'vec4'>(colorSpaceToWorking(stack.color, THREE.SRGBColorSpace));\n if (options.lodAlpha) {\n // Store decoded RAD alpha in `colors.a` so merged vs leaf is decided\n // from the unmodified encoding. Visual fades never enter that channel.\n const modifierOpacity = encodedOriginal\n .greaterThan(0)\n .select(encodedResolved.div(encodedOriginal.max(1e-8)), float(1));\n output\n .element(target)\n .assign(vec4(gatheredCenter, visibility.mul(this.opacity).mul(modifierOpacity)));\n outputColor.element(target).assign(vec4(resolvedColor.rgb, encodedOriginal.mul(2.0)));\n } else {\n output.element(target).assign(vec4(gatheredCenter, visibility.mul(this.opacity)));\n outputColor.element(target).assign(vec4(resolvedColor.rgb, resolvedColor.a));\n }\n const covariance =\n stack.rotation === null\n ? covarianceBase\n : stack.rotation.mul(covarianceBase).mul(stack.rotation.transpose());\n // Collapse in mesh-local space (Spark's min(scale) is local), then lift\n // to world. Applying isotropic on world Σ with a local normal inflated\n // λ and produced large soft blobs under mesh transforms.\n let localCovariance: THREE.Node<'mat3'> = asNode<'mat3'>(covariance);\n if (stack.isotropicCovarianceMix !== null) {\n const varianceScale =\n stack.isotropicVarianceScale ?? float(DEFAULT_ISOTROPIC_VARIANCE_SCALE);\n localCovariance = applyIsotropicCovarianceOverride(\n localCovariance,\n vec3(0, 0, 1),\n stack.isotropicCovarianceMix,\n varianceScale,\n );\n }\n const linear = this.sourceMatrix.toMat3();\n const worldCovarianceBase = linear.mul(localCovariance).mul(linear.transpose());\n const worldCovariance =\n stack.scaleSquared === null\n ? worldCovarianceBase\n : worldCovarianceBase.mul(stack.scaleSquared);\n const c0 = worldCovariance.mul(vec3(1, 0, 0));\n const c1 = worldCovariance.mul(vec3(0, 1, 0));\n const c2 = worldCovariance.mul(vec3(0, 0, 1));\n outputCovA.element(target).assign(vec4(c0.x, c0.y, c0.z, c1.y));\n outputCovB.element(target).assign(vec4(c1.z, c2.z, 0, 0));\n outputIsotropicMix\n .element(target)\n .assign(stack.isotropicCovarianceMix === null ? float(0) : stack.isotropicCovarianceMix);\n outputIsotropicScreenRadius\n .element(target)\n .assign(\n stack.isotropicCovarianceMix === null\n ? float(0)\n : (stack.isotropicScreenRadiusPx ?? float(0)),\n );\n });\n })().compute(sourceCapacity, [256]);\n }\n\n /** Gathers a source's active pool slots into a contiguous work-buffer range. */\n gather(\n renderer: THREE.WebGPURenderer,\n activeCount: number,\n targetOffset: number,\n sourceMatrix: THREE.Matrix4,\n cameraViewMatrixOrOpacity: THREE.Matrix4 | number = new THREE.Matrix4(),\n opacity = 1,\n ): void {\n if (activeCount < 0 || targetOffset < 0 || targetOffset + activeCount > this.capacity) {\n throw new Error('WorkBufferGather: requested range exceeds work-buffer capacity.');\n }\n this.activeCount.value = activeCount;\n this.targetOffset.value = targetOffset;\n this.sourceMatrix.value.copy(sourceMatrix);\n const cameraViewMatrix =\n typeof cameraViewMatrixOrOpacity === 'number'\n ? new THREE.Matrix4()\n : cameraViewMatrixOrOpacity;\n this.cameraViewMatrix.value.copy(cameraViewMatrix);\n this.opacity.value = Math.max(\n 0,\n typeof cameraViewMatrixOrOpacity === 'number' ? cameraViewMatrixOrOpacity : opacity,\n );\n this.pass.count = activeCount;\n renderer.compute(this.pass);\n // The dispatch just built this pass's bind group, which is what makes three\n // create the storage buffers - synchronously. Nothing reads their CPU side\n // back, so drop it. A `WorkBuffer` shared by several gathers releases on\n // whichever dispatches first; the rest find it settled.\n this.workBuffer.releaseCpuMirrors(renderer);\n }\n\n /**\n * Compiles this gather's compute pipeline without gathering anything.\n *\n * WebGPU compiles a compute pipeline lazily, at its first dispatch - not when\n * the node graph is built. Measured on a 13-mesh scene, a source's *first*\n * `gather` took up to 2.0s while every later dispatch of the same pipeline\n * took under 0.4ms, and because `gather` runs inside `update` that compile\n * landed whole in one render frame. Running it through the async path here\n * compiles off the critical frame, so the first real gather finds it ready.\n *\n * The dispatch targets {@link WorkBuffer.SCRATCH_SLOTS} past the drawable\n * capacity rather than dispatching zero workgroups: zero also compiles, but\n * WebGPU warns about it once per source, and writing into a drawn slot could\n * leave junk behind when a cached gather is reused instead of re-run.\n *\n * Best-effort: a failure here costs only the stall it was meant to avoid, so\n * callers may ignore it.\n */\n async warmUp(renderer: THREE.WebGPURenderer): Promise<void> {\n this.activeCount.value = 1;\n this.targetOffset.value = this.capacity;\n this.pass.count = 1;\n await renderer.computeAsync(this.pass);\n // Leave nothing that a later reuse check could mistake for real state.\n this.activeCount.value = 0;\n this.targetOffset.value = 0;\n // Warm-up is often the first dispatch of all, so this is usually where the\n // mirrors actually go.\n this.workBuffer.releaseCpuMirrors(renderer);\n }\n\n /** Releases the gather pipeline. The owner releases the storage attribute. */\n dispose(): void {\n this.pass.dispose();\n }\n}\n","import * as THREE from 'three/webgpu';\nimport type { FloatUniform, Vec2Uniform } from '../core/splat-mesh-material';\nimport {\n capProjectedEigenvaluesToScreenRadius,\n equalizeProjectedEigenvalues,\n} from '../core/splat-mesh-material';\nimport { MAX_DOF_VARIANCE } from '../core/depth-of-field';\nimport {\n Discard,\n Fn,\n cameraProjectionMatrix,\n float,\n instanceIndex,\n mat3,\n mix,\n modelViewMatrix,\n positionGeometry,\n screenUV,\n storage,\n texture as tslTexture,\n varying,\n vec2,\n vec3,\n vec4,\n} from 'three/tsl';\n\n/**\n * Creates the unified EWA draw material for gathered world-space splats.\n *\n * Its vertex stage reads both the sorter-written order and the gather-written\n * centers, covariance, and resolved color from storage buffers. It keeps the\n * verified ±3σ / exp(-4.5·|q|²) convention used by {@link SplatMesh}.\n */\nexport function createWorkBufferMaterial(options: {\n capacity: number;\n centers: THREE.StorageBufferAttribute;\n colors: THREE.StorageBufferAttribute;\n covarianceA: THREE.StorageBufferAttribute;\n covarianceB: THREE.StorageBufferAttribute;\n isotropicMix: THREE.StorageBufferAttribute;\n isotropicScreenRadius: THREE.StorageBufferAttribute;\n order: THREE.StorageInstancedBufferAttribute;\n focal: Vec2Uniform;\n viewport: Vec2Uniform;\n maxStdDev: FloatUniform;\n /** Screen-space minimum splat radius in px; `0` disables. */\n minSplatSizePx: FloatUniform;\n antialias: FloatUniform;\n /** Format-selected projected low-pass variance, in px². */\n projectedLowPassVariance: FloatUniform;\n /** LCC always preserves the low-pass integral; standard follows antialias. */\n compensateProjectedLowPass: FloatUniform;\n /** Core projected-2D DoF focus plane. Live; `0` aperture disables. */\n dofFocusDistance: FloatUniform;\n dofAperture: FloatUniform;\n /**\n * Proxy-mesh relight map (RGB = lit, A = coverage). Display only.\n * Host swaps the texture object and rebuilds when enabling/changing map.\n */\n relightMap: THREE.Texture;\n relightBlend: FloatUniform;\n relightBrightness: FloatUniform;\n relightBackground: FloatUniform;\n /** Coverage soft edge in screen pixels; `0` = hard mask. */\n relightSoftness: FloatUniform;\n}): THREE.NodeMaterial {\n const material = new THREE.NodeMaterial();\n const centers = storage(options.centers, 'vec4', options.capacity);\n const order = storage(options.order, 'float', options.capacity);\n const colors = storage(options.colors, 'vec4', options.capacity);\n const covarianceA = storage(options.covarianceA, 'vec4', options.capacity);\n const covarianceB = storage(options.covarianceB, 'vec4', options.capacity);\n const isotropicMix = storage(options.isotropicMix, 'float', options.capacity);\n const isotropicScreenRadius = storage(options.isotropicScreenRadius, 'float', options.capacity);\n const workColor = varying(vec4(1, 1, 1, 1), 'vWorkColor');\n const quadPosition = varying(positionGeometry.xy, 'vWorkQuadPosition');\n const opacityCompensation = varying(float(1), 'vWorkOpacityCompensation');\n const displayOpacity = varying(float(1), 'vWorkDisplayOpacity');\n // Spark LOD alpha, matching `SplatMesh`'s display graph. The gather has\n // already recovered `alpha ∈ [0,2]` for `.rad` sources, so `alpha > 1`\n // identifies a merged node here without a per-source shader variant: a\n // non-`.rad` source can only reach `alpha ≤ 1`, for which the branches below\n // collapse to the plain Gaussian this material has always drawn.\n const adjustedStdDev = varying(float(0), 'vWorkAdjustedStdDev');\n material.vertexNode = Fn(() => {\n const workIndex = order.element(instanceIndex).toInt();\n const centerSample = centers.element(workIndex);\n const center = centerSample.xyz;\n // Gather stamps display opacity into center.w. `w <= 0` is non-drawable\n // (hidden, fully faded, or a zero source). Fractional fades still draw.\n const drawable = centerSample.w.greaterThan(0);\n displayOpacity.assign(centerSample.w);\n workColor.assign(colors.element(workIndex));\n const viewCenter = modelViewMatrix.mul(vec4(center, 1.0)).toVar();\n const clipCenter = cameraProjectionMatrix.mul(viewCenter).toVar();\n const covA = covarianceA.element(workIndex);\n const covB = covarianceB.element(workIndex);\n const covariance = mat3(\n vec3(covA.x, covA.y, covA.z),\n vec3(covA.y, covA.w, covB.x),\n vec3(covA.z, covB.x, covB.y),\n );\n const invZ = float(1).div(viewCenter.z);\n const invZ2 = invZ.mul(invZ);\n const j1 = vec3(\n options.focal.x.mul(invZ),\n 0,\n options.focal.x.negate().mul(viewCenter.x).mul(invZ2),\n );\n const j2 = vec3(\n 0,\n options.focal.y.mul(invZ),\n options.focal.y.negate().mul(viewCenter.y).mul(invZ2),\n );\n const viewRotationT = modelViewMatrix.toMat3().transpose();\n const u1 = viewRotationT.mul(j1);\n const u2 = viewRotationT.mul(j2);\n const aRaw = u1.dot(covariance.mul(u1));\n const dRaw = u2.dot(covariance.mul(u2));\n const bRaw = u1.dot(covariance.mul(u2));\n\n const depth = viewCenter.z.negate().max(1e-4);\n const focus = options.dofFocusDistance.max(1e-4);\n // Aperture maps through the live focus plane (Spark host-helper parity), so\n // a near focus plane widens the angle and softens the whole scene.\n const halfApertureAngle = options.dofAperture.max(0).mul(0.5).div(focus).atan();\n // Spark's falloff (`/depth`). Unbounded near the camera; MAX_DOF_VARIANCE\n // below is the fill-rate guard, exactly as Spark's maxPixelRadius is.\n const focusBlur = depth.sub(focus).abs().div(depth);\n const apertureRadius = options.focal.x.mul(halfApertureAngle.tan());\n const cocRadiusPx = focusBlur.mul(apertureRadius);\n const cocVar = cocRadiusPx.mul(cocRadiusPx).min(float(MAX_DOF_VARIANCE));\n\n const a = aRaw.add(options.projectedLowPassVariance).add(cocVar);\n const d = dRaw.add(options.projectedLowPassVariance).add(cocVar);\n const b = bRaw;\n const isoMix = isotropicMix.element(workIndex);\n const detBlur = a.mul(d).sub(b.mul(b)).max(1e-9);\n // Classic LCC always compensates its 0.1 px² low-pass. Standard sources\n // retain their antialias-controlled 0.3 px² compatibility behavior.\n const detRaw = aRaw.mul(dRaw).sub(bRaw.mul(bRaw)).max(0);\n const detBase = aRaw\n .add(options.projectedLowPassVariance)\n .mul(dRaw.add(options.projectedLowPassVariance))\n .sub(bRaw.mul(bRaw))\n .max(1e-9);\n const mipFade = detRaw.div(detBlur).sqrt();\n const dofOnlyFade = detBase.div(detBlur).sqrt();\n const compensate = options.antialias.max(options.compensateProjectedLowPass);\n const fade = mix(dofOnlyFade, mipFade, compensate);\n // Screen-capped isotropic points must not inherit the mip-filter opacity\n // fade - it was derived from the pre-cap footprint and washes out dots.\n opacityCompensation.assign(mix(fade, float(1), isoMix));\n const mid = a.add(d).mul(0.5);\n const radius = vec2(a.sub(d).mul(0.5), b).length();\n let lambda1 = mid.add(radius);\n let lambda2 = mid.sub(radius).max(0);\n const equalized = equalizeProjectedEigenvalues(lambda1, lambda2, isoMix);\n lambda1 = equalized.lambda1;\n lambda2 = equalized.lambda2;\n const capped = capProjectedEigenvaluesToScreenRadius(\n lambda1,\n lambda2,\n isoMix,\n isotropicScreenRadius.element(workIndex),\n options.maxStdDev,\n );\n lambda1 = capped.lambda1;\n lambda2 = capped.lambda2;\n // A merged node (`alpha > 1`) grows the σ-cutoff `maxStdDev + 0.7·(remap−1)`\n // so one coarse splat covers the subtree it stands in for; the covariance is\n // untouched. A leaf keeps the base cutoff. `SplatMesh` does the same at\n // `applySplatMaterialGraph`'s `lodAlpha` branch.\n const remap = workColor.a.mul(4).sub(3).min(5);\n const stdDev = workColor.a\n .greaterThan(1)\n .select(options.maxStdDev.add(remap.sub(1).mul(0.7)), options.maxStdDev);\n adjustedStdDev.assign(stdDev);\n const eigenvector = vec2(b, lambda1.sub(a)).add(vec2(1e-6, 0)).normalize();\n // Screen-space minimum on each axis: a splat below the floor grows to it so\n // its Gaussian tiles with neighbours instead of leaving dark gaps between\n // sparse zoomed-out splats; already-large splats are untouched. Mirrors\n // `applySplatMaterialGraph`. `.max` after `.min(1024)` keeps the order valid.\n const minSplat = options.minSplatSizePx;\n const major = eigenvector.mul(lambda1.sqrt().mul(stdDev).min(1024).max(minSplat));\n const minor = vec2(eigenvector.y, eigenvector.x.negate()).mul(\n lambda2.sqrt().mul(stdDev).min(1024).max(minSplat),\n );\n const pixelOffset = major.mul(positionGeometry.x).add(minor.mul(positionGeometry.y));\n const ndcCenter = clipCenter.xy.div(clipCenter.w);\n const clipPosition = vec4(\n ndcCenter.add(pixelOffset.mul(2).div(options.viewport)),\n clipCenter.z.div(clipCenter.w),\n 1,\n );\n // Match SplatMesh's conservative center-frustum rejection. Without this,\n // a center behind the camera can produce a mirrored, screen-filling quad.\n // Modifier-hidden / zero-opacity entries (displayOpacity=0) share the\n // clipped destination so they generate no fragments while keeping a stable sort slot.\n const margin = clipCenter.w.mul(1.2);\n const inFrustum = clipCenter.z\n .greaterThan(margin.negate())\n .and(clipCenter.x.abs().lessThan(margin))\n .and(clipCenter.y.abs().lessThan(margin));\n return inFrustum.and(drawable).select(clipPosition, vec4(0, 0, 2, 1));\n })();\n material.fragmentNode = Fn(() => {\n const squaredDistance = quadPosition.dot(quadPosition);\n Discard(squaredDistance.greaterThan(1));\n // Spark's LOD falloff, mirroring `SplatMesh`'s display fragment.\n // `g = exp(-½·adjustedStdDev²·|q|²)` is the Gaussian at this fragment. A leaf\n // (`alpha ≤ 1`, and every non-`.rad` source) composites `g · alpha`. A merged\n // node uses the super-Gaussian plateau `1 − (1 − g)^a`, `a = exp((remap²−1)/e)`,\n // so a coarse splat fills its subtree's footprint without inflating Σ.\n const g = squaredDistance.mul(adjustedStdDev.mul(adjustedStdDev).mul(-0.5)).exp();\n const remap = workColor.a.mul(4).sub(3).min(5);\n const aExp = remap\n .mul(remap)\n .sub(1)\n .mul(1 / Math.E)\n .exp();\n const merged = g.oneMinus().pow(aExp).oneMinus();\n const opacity = workColor.a.greaterThan(1).select(merged, g.mul(workColor.a));\n const alpha = opacity.mul(opacityCompensation).mul(displayOpacity);\n const litCenter = tslTexture(options.relightMap, screenUV);\n const ox = options.relightSoftness.div(options.viewport.x.max(1));\n const oy = options.relightSoftness.div(options.viewport.y.max(1));\n const s0 = litCenter;\n const s1 = tslTexture(options.relightMap, screenUV.add(vec2(ox, 0)));\n const s2 = tslTexture(options.relightMap, screenUV.add(vec2(ox.negate(), 0)));\n const s3 = tslTexture(options.relightMap, screenUV.add(vec2(0, oy)));\n const s4 = tslTexture(options.relightMap, screenUV.add(vec2(0, oy.negate())));\n const wSum = s0.a.add(s1.a).add(s2.a).add(s3.a).add(s4.a).max(1e-4);\n const rgbSoft = s0.rgb\n .mul(s0.a)\n .add(s1.rgb.mul(s1.a))\n .add(s2.rgb.mul(s2.a))\n .add(s3.rgb.mul(s3.a))\n .add(s4.rgb.mul(s4.a))\n .div(wSum);\n const aSoft = wSum.mul(0.2);\n const litSoft = vec4(rgbSoft, aSoft);\n const lit = options.relightSoftness.greaterThan(0.5).select(litSoft, litCenter);\n const factor = mix(\n vec3(options.relightBackground),\n lit.rgb.mul(options.relightBrightness),\n lit.a,\n );\n const rgb = mix(workColor.rgb, workColor.rgb.mul(factor), options.relightBlend);\n return vec4(rgb.mul(alpha), alpha);\n })();\n material.transparent = true;\n material.depthTest = true;\n material.depthWrite = false;\n material.side = THREE.DoubleSide;\n material.blending = THREE.CustomBlending;\n material.blendSrc = THREE.OneFactor;\n material.blendDst = THREE.OneMinusSrcAlphaFactor;\n material.blendSrcAlpha = THREE.OneFactor;\n material.blendDstAlpha = THREE.OneMinusSrcAlphaFactor;\n material.toneMapped = false;\n return material;\n}\n","/**\n * Byte costs of {@link UnifiedSplatMesh}'s GPU work buffer.\n *\n * Kept off the core entry so hosts that never composite sources do not pay\n * for the accounting, and so the numbers cannot drift from the renderer\n * that allocates those buffers.\n */\n\n/** Bytes per splat in the largest unified work-buffer attribute (RGBA32F centers). */\nexport const WORK_BUFFER_CENTERS_BYTES_PER_SPLAT = 16;\n\n/**\n * Bytes per work-buffer slot across *all* of its attributes: centers, colors,\n * covarianceA and covarianceB at RGBA32F (16 each), plus the isotropic mix and\n * screen-radius scalars (4 each).\n */\nexport const WORK_BUFFER_BYTES_PER_SLOT = 16 * 4 + 4 * 2;\n\nfunction assertNonNegativeCapacity(capacity: number): void {\n if (!Number.isFinite(capacity) || capacity < 0) {\n throw new RangeError('Splat capacity must be a non-negative finite number.');\n }\n}\n\n/**\n * Byte size of the largest single storage-buffer bind VLAM allocates for a\n * given splat capacity (unified work-buffer centers: `capacity × 16`).\n *\n * Use with adapter/device limits to decide whether to raise `requiredLimits`\n * or lower the budget before constructing {@link UnifiedSplatMesh}.\n */\nexport function estimateLargestStorageBufferBytes(capacity: number): number {\n assertNonNegativeCapacity(capacity);\n return Math.floor(capacity) * WORK_BUFFER_CENTERS_BYTES_PER_SPLAT;\n}\n\n/**\n * Estimates what a {@link UnifiedSplatMesh}'s work buffer costs, in bytes,\n * once the scene has rendered a frame.\n *\n * This used to be double the figure below, and the doubling was not a detail.\n * Every `THREE.StorageBufferAttribute` is constructed around a JS typed array,\n * and three's WebGPU backend never releases it: the\n * `attribute.onUploadCallback()` call that would is missing from the backend's\n * buffer upload path. So a work buffer of N slots cost\n * N × {@link WORK_BUFFER_BYTES_PER_SLOT} on the GPU *and* the same again on the\n * JS heap, permanently, even though nothing ever reads the CPU copy back - the\n * gather pass writes these buffers entirely on the GPU.\n *\n * `WorkBuffer.releaseCpuMirrors` now drops those mirrors after the first\n * dispatch that uploads them (see `storage-attribute-mirror`), so steady state\n * is the GPU side alone. The *peak* is still double - the array has to exist\n * for the upload copy - which is what\n * {@link estimateUnifiedWorkBufferPeakBytes} reports.\n *\n * Either figure is invisible to `estimateSplatPoolBytes`, which prices the\n * splat *pool* and knows nothing about the unified renderer's scratch space. A\n * host sizing a scene for a memory-constrained device wants both.\n *\n * @param capacity - Work-buffer capacity in splats.\n * @returns Estimated steady-state bytes.\n * @throws {RangeError} if `capacity` is not a non-negative finite number.\n */\nexport function estimateUnifiedWorkBufferBytes(capacity: number): number {\n assertNonNegativeCapacity(capacity);\n return Math.floor(capacity) * WORK_BUFFER_BYTES_PER_SLOT;\n}\n\n/**\n * Peak bytes a {@link UnifiedSplatMesh}'s work buffer occupies: the window\n * between construction and the first dispatch, while the GPU buffer and the JS\n * array three copied it from are both alive.\n *\n * Ask this one when the question is \"will allocating this scene succeed\" - an\n * out-of-memory failure happens against the peak. Ask\n * {@link estimateUnifiedWorkBufferBytes} when the question is \"what will this\n * scene hold once it is up\".\n *\n * @param capacity - Work-buffer capacity in splats.\n * @returns Estimated bytes, GPU plus the not-yet-released CPU mirror.\n * @throws {RangeError} if `capacity` is not a non-negative finite number.\n */\nexport function estimateUnifiedWorkBufferPeakBytes(capacity: number): number {\n return estimateUnifiedWorkBufferBytes(capacity) * 2;\n}\n","import * as THREE from 'three/webgpu';\nimport { uniform } from 'three/tsl';\nimport { ComputeSorter, releaseRendererAttributes } from '../core/compute-sorter';\nimport { RadixSorter } from '../core/radix-sorter';\nimport { clampDepthOfFieldSettings, type DepthOfFieldSettings } from '../core/depth-of-field';\nimport {\n clampRelightingSettings,\n createPlaceholderRelightTexture,\n DEFAULT_RELIGHT_BACKGROUND,\n DEFAULT_RELIGHT_BRIGHTNESS,\n DEFAULT_RELIGHT_SOFTNESS,\n type RelightingSettings,\n type RelightingUniforms,\n} from '../core/relighting';\nimport { SplatMesh } from '../core/splat-mesh';\nimport type { SplatPickOptions, SplatPickResult, UnifiedSourceView } from '../core/splat-mesh';\nimport { isFillConstrainedSplatDevice } from '../core/splat-budget';\nimport { WebGpuSortScheduler } from '../core/sort-scheduler';\nimport { WorkBuffer, WorkBufferGather } from './work-buffer-gather';\nimport { createWorkBufferMaterial } from './work-buffer-material';\nimport type { FloatUniform, Vec2Uniform } from '../core/splat-mesh-material';\nimport { assertStorageBufferFitsDevice } from '../core/webgpu-limits';\nimport { estimateLargestStorageBufferBytes } from './unified-work-buffer';\nimport { resolveXrView } from '../core/xr-view';\nimport { StorageMirrorReleaser } from '../core/storage-attribute-mirror';\nimport type { SplatSorter } from '../core/sorter';\n\ninterface SourceRecord {\n source: SplatMesh;\n gather: WorkBufferGather;\n graphRevision: number;\n priority: number;\n opacity: number;\n visible: boolean;\n /** Whether modifier uniforms are host-invalidated instead of assumed live. */\n cacheModifiers: boolean;\n originalVisible: boolean;\n lastGather: {\n activeCount: number;\n contentRevision: number;\n offset: number;\n opacity: number;\n matrixWorld: THREE.Matrix4;\n /** Local camera position used by view-dependent SH evaluation. */\n localCameraPosition: THREE.Vector3;\n } | null;\n /** Per-prepare scratch: the source view snapshot for the current frame. */\n view: UnifiedSourceView | null;\n /** Per-prepare scratch: registration index for stable priority ordering. */\n registrationOrder: number;\n /** Per-prepare scratch: this frame's admitted work-buffer offset. */\n offset: number;\n}\n\n/** One admitted source's work-buffer ownership from a prepared frame. */\ninterface LayoutEntry {\n source: SplatMesh;\n offset: number;\n activeCount: number;\n}\n\n/** Registration settings for one source in a {@link UnifiedSplatMesh}. */\nexport interface UnifiedSplatSourceOptions {\n /** Whole-source display opacity applied after gather falloff. Defaults to `1`.\n * Does not change RAD LOD classification or splat shape. */\n opacity?: number;\n /** Whether this source contributes to the unified draw. Defaults to `true`. */\n visible?: boolean;\n /** Higher values survive a fixed work-buffer overflow first. Defaults to `0`. */\n priority?: number;\n /**\n * Cache a modifier-bearing source until {@link UnifiedSplatMesh.invalidateSource}\n * is called. Defaults to `false`, which safely re-gathers live modifier\n * uniforms every frame.\n *\n * Use this for static modifiers, or when the host has a natural dirty signal\n * for every uniform/channel mutation. Forgetting to invalidate leaves the\n * unified work-buffer output stale.\n */\n cacheModifiers?: boolean;\n}\n\n/**\n * Result of a successful {@link UnifiedSplatMesh.pick}: the frontmost hit\n * across every visible registered source, tagged with the source it landed on.\n */\nexport interface UnifiedSplatPickResult extends SplatPickResult {\n /** The registered source mesh whose splat produced the winning hit. */\n readonly source: SplatMesh;\n}\n\n/**\n * Construction settings shared by every source in a unified renderer.\n *\n * @experimental May change in a minor release.\n */\nexport interface UnifiedSplatMeshOptions {\n /** Composite source colors in display (sRGB) space. Defaults to `false`. */\n srgbOutput?: boolean;\n /**\n * Global depth-sort strategy. `'exact'` preserves every Float32 depth bit\n * through a stable radix sort of gathered world-space centers. `'counting'`\n * remains the lower-cost default for existing callers.\n *\n * @experimental Exact sorting trades two additional radix passes for better\n * ordering in large scenes with dense foliage or overlapping surfaces.\n */\n sortStrategy?: 'counting' | 'exact';\n}\n\n/**\n * Returns true when `renderer` can drive {@link UnifiedSplatMesh}.\n * Heterogeneous gather/sort/draw is WebGPU-only; WebGL2 hosts keep standalone\n * `SplatMesh` draws or static {@link MergedSplatMesh}.\n */\nexport function supportsUnifiedSplatMesh(renderer: object): boolean {\n return (\n (renderer as { backend?: { isWebGPUBackend?: boolean } }).backend?.isWebGPUBackend === true\n );\n}\n\n/**\n * One gather → global-sort → draw path for static and streamed splat sources.\n * Sources retain their own residency and update lifecycle; this mesh gathers\n * their current active pool ranges into one shared work buffer per frame.\n *\n * The unified mesh stays at identity (`matrixAutoUpdate` is off). Pose each\n * registered source mesh instead - sorter bounds and the draw material both\n * consume world-space centers written by gather.\n *\n * WebGPU only. Prefer {@link supportsUnifiedSplatMesh} before construction.\n *\n * @experimental May change in a minor release.\n */\nexport class UnifiedSplatMesh extends THREE.Mesh {\n private readonly workBuffer: WorkBuffer;\n private readonly workSourceIndex: THREE.StorageBufferAttribute;\n /** The sorted draw-order buffer; lives outside the geometry, freed on dispose. */\n private readonly orderAttribute: THREE.StorageInstancedBufferAttribute;\n /**\n * Frees the JS mirrors three keeps behind `workSourceIndex` and `order`.\n *\n * `workSourceIndex` is an identity ramp written once at construction; `order`\n * is written only by the sorter, on the GPU. Neither is ever read back, so\n * both mirrors are 4 B/slot of dead JS heap once uploaded.\n */\n private readonly mirrors: StorageMirrorReleaser;\n private readonly sorter: SplatSorter;\n private readonly renderer: THREE.WebGPURenderer;\n private readonly sources: SourceRecord[] = [];\n private previousLayout: LayoutEntry[] = [];\n /** Previous layout keyed by source; kept in step with {@link previousLayout}. */\n private readonly previousLayoutBySource = new Map<SplatMesh, LayoutEntry>();\n /** Per-prepare scratch lists, reused so a steady frame allocates nothing. */\n private readonly candidateScratch: SourceRecord[] = [];\n private readonly admittedScratch: SourceRecord[] = [];\n private readonly drawingBufferSize = new THREE.Vector2();\n /** Reused target dimensions for secondary views; avoids per-view garbage. */\n private readonly secondaryViewSize = new THREE.Vector2();\n /**\n * Camera gating for the global sorter, mirroring the standalone\n * `SplatMesh.requestSortIfNeeded` path: an unchanged work buffer under a\n * stationary camera skips the whole-buffer re-sort. Content changes\n * (regather, layout change) force the next sort through the scheduler.\n */\n private readonly sortScheduler: WebGpuSortScheduler;\n /** Model-view of the last accepted sort; starts unmatchable (zero scale). */\n private readonly lastSortedModelView = new THREE.Matrix4().makeScale(0, 0, 0);\n /**\n * Total admitted splats in the last prepared frame. `removeSource` filters\n * {@link previousLayout} directly, so a tail source's removal can leave the\n * remaining entries identical - only this total betrays the shrink, and a\n * shrunk draw range must re-sort (the old permutation indexes past it).\n */\n private previousAdmittedTotal = 0;\n private readonly bounds = new THREE.Sphere();\n private readonly focal: Vec2Uniform;\n private readonly viewport: Vec2Uniform;\n private readonly maxStdDev: FloatUniform;\n private readonly minSplatSizePx: FloatUniform;\n private readonly antialias: FloatUniform;\n private readonly projectedLowPassVariance: FloatUniform;\n private readonly compensateProjectedLowPass: FloatUniform;\n private readonly dofFocusDistance: FloatUniform;\n private readonly dofAperture: FloatUniform;\n private readonly relightPlaceholder: THREE.DataTexture;\n private relightMap: THREE.Texture;\n private readonly relightBlend: FloatUniform;\n private readonly relightBrightness: FloatUniform;\n private readonly relightBackground: FloatUniform;\n private readonly relightSoftness: FloatUniform;\n private readonly srgbOutput: boolean;\n private sourceMaxStdDev: number | null = null;\n private sourceAntialias: boolean | null = null;\n private sourceProjectedFilterProfile: 'default' | 'lcc' | null = null;\n private overflowedSourceCount = 0;\n private overflowedSplatCount = 0;\n private disposed = false;\n\n constructor(\n renderer: THREE.WebGPURenderer,\n capacity: number,\n options: UnifiedSplatMeshOptions = {},\n ) {\n if (!supportsUnifiedSplatMesh(renderer)) {\n throw new Error(\n 'UnifiedSplatMesh requires a WebGPU backend (renderer.backend.isWebGPUBackend). ' +\n 'On WebGL2 use standalone SplatMesh draws or static MergedSplatMesh.',\n );\n }\n // Fail before allocating StorageBufferAttributes that would trip a cryptic\n // CreateBindGroup validation error when the host left the 128 MiB default.\n assertStorageBufferFitsDevice(renderer, estimateLargestStorageBufferBytes(capacity), capacity);\n const workBuffer = new WorkBuffer(capacity);\n const focal = uniform(new THREE.Vector2());\n const viewport = uniform(new THREE.Vector2());\n const maxStdDev = uniform(3);\n const minSplatSizePx = uniform(0);\n const antialias = uniform(0);\n const projectedLowPassVariance = uniform(0.3);\n const compensateProjectedLowPass = uniform(0);\n const dofFocusDistance = uniform(10);\n const dofAperture = uniform(0);\n const relightPlaceholder = createPlaceholderRelightTexture();\n const relightBlend = uniform(0);\n const relightBrightness = uniform(DEFAULT_RELIGHT_BRIGHTNESS);\n const relightBackground = uniform(DEFAULT_RELIGHT_BACKGROUND);\n const relightSoftness = uniform(DEFAULT_RELIGHT_SOFTNESS);\n const order = new THREE.StorageInstancedBufferAttribute(new Float32Array(capacity), 1);\n const geometry = new THREE.InstancedBufferGeometry();\n geometry.setIndex([0, 1, 2, 0, 2, 3]);\n geometry.setAttribute(\n 'position',\n new THREE.BufferAttribute(new Float32Array([-1, -1, 0, 1, -1, 0, 1, 1, 0, -1, 1, 0]), 3),\n );\n geometry.instanceCount = 0;\n super(\n geometry,\n createWorkBufferMaterial({\n capacity,\n centers: workBuffer.centers,\n colors: workBuffer.colors,\n covarianceA: workBuffer.covarianceA,\n covarianceB: workBuffer.covarianceB,\n isotropicMix: workBuffer.isotropicMix,\n isotropicScreenRadius: workBuffer.isotropicScreenRadius,\n order,\n focal,\n viewport,\n maxStdDev,\n minSplatSizePx,\n antialias,\n projectedLowPassVariance,\n compensateProjectedLowPass,\n dofFocusDistance,\n dofAperture,\n relightMap: relightPlaceholder,\n relightBlend,\n relightBrightness,\n relightBackground,\n relightSoftness,\n }),\n );\n const indices = new Uint32Array(capacity);\n for (let i = 0; i < capacity; i++) indices[i] = i;\n this.workBuffer = workBuffer;\n this.focal = focal;\n this.viewport = viewport;\n this.maxStdDev = maxStdDev;\n this.minSplatSizePx = minSplatSizePx;\n this.antialias = antialias;\n this.projectedLowPassVariance = projectedLowPassVariance;\n this.compensateProjectedLowPass = compensateProjectedLowPass;\n this.dofFocusDistance = dofFocusDistance;\n this.dofAperture = dofAperture;\n this.relightPlaceholder = relightPlaceholder;\n this.relightMap = relightPlaceholder;\n this.relightBlend = relightBlend;\n this.relightBrightness = relightBrightness;\n this.relightBackground = relightBackground;\n this.relightSoftness = relightSoftness;\n this.srgbOutput = options.srgbOutput ?? false;\n this.sortScheduler = new WebGpuSortScheduler(undefined, isFillConstrainedSplatDevice());\n this.orderAttribute = order;\n this.workSourceIndex = new THREE.StorageBufferAttribute(indices, 1);\n this.mirrors = new StorageMirrorReleaser([this.workSourceIndex, this.orderAttribute]);\n this.renderer = renderer;\n const sortInputs = {\n renderer,\n capacity,\n centersBuffer: workBuffer.centers,\n splatIndexAttribute: order,\n sourceIndexAttribute: this.workSourceIndex,\n };\n this.sorter =\n options.sortStrategy === 'exact'\n ? new RadixSorter({ ...sortInputs, exactDepth: true })\n : new ComputeSorter(sortInputs);\n this.frustumCulled = false;\n this.matrixAutoUpdate = false;\n this.matrix.identity();\n this.matrixWorld.identity();\n }\n\n /** Fixed work-buffer splat capacity chosen at construction. */\n get capacity(): number {\n return this.workBuffer.capacity;\n }\n\n /** Registers a source. The caller keeps ownership and may still query it. */\n addSource(source: SplatMesh, options: UnifiedSplatSourceOptions = {}): void {\n this.assertNotDisposed('addSource');\n if (this.sources.some((record) => record.source === source)) return;\n const view = source.getUnifiedSourceView();\n const resolvedVisible = options.visible ?? source.visible;\n if (view.hasSourcePlacement) {\n // The gather pass resolves one matrix per source (the mesh's\n // `matrixWorld`); it knows nothing about a pool's *inner* per-source\n // placement, so a nested scene would draw every one of its sources at\n // its pool-local position. Reject rather than draw it wrong.\n throw new Error(\n 'UnifiedSplatMesh: a MergedSplatMesh is already a unified pool with its own global ' +\n 'sort; add its sources individually, or draw the mesh directly.',\n );\n }\n if (view.srgbOutput !== this.srgbOutput) {\n throw new Error(\"UnifiedSplatMesh: every source must use the renderer's srgbOutput setting.\");\n }\n if (this.sourceMaxStdDev === null) {\n this.sourceMaxStdDev = view.maxStdDev;\n this.maxStdDev.value = view.maxStdDev;\n this.minSplatSizePx.value = view.minSplatSizePx;\n } else if (this.sourceMaxStdDev !== view.maxStdDev) {\n throw new Error('UnifiedSplatMesh: every source must use the same maxStdDev setting.');\n } else if (this.minSplatSizePx.value !== view.minSplatSizePx) {\n throw new Error('UnifiedSplatMesh: every source must use the same minSplatSizePx setting.');\n }\n if (this.sourceAntialias === null) {\n this.sourceAntialias = view.antialias;\n this.antialias.value = view.antialias ? 1 : 0;\n } else if (this.sourceAntialias !== view.antialias) {\n throw new Error('UnifiedSplatMesh: every source must use the same antialias setting.');\n }\n if (this.sourceProjectedFilterProfile === null) {\n this.sourceProjectedFilterProfile = view.projectedFilterProfile;\n const lccProfile = view.projectedFilterProfile === 'lcc';\n this.projectedLowPassVariance.value = lccProfile ? 0.1 : 0.3;\n this.compensateProjectedLowPass.value = lccProfile ? 1 : 0;\n } else if (this.sourceProjectedFilterProfile !== view.projectedFilterProfile) {\n throw new Error('UnifiedSplatMesh: every source must use the same projected filter profile.');\n }\n this.sources.push({\n source,\n gather: this.createGather(view),\n graphRevision: view.graphRevision,\n priority: options.priority ?? 0,\n opacity: options.opacity ?? 1,\n visible: resolvedVisible,\n cacheModifiers: options.cacheModifiers ?? false,\n originalVisible: source.visible,\n lastGather: null,\n view: null,\n registrationOrder: 0,\n offset: 0,\n });\n source.visible = false;\n source.setUnifiedPickVisibility(resolvedVisible);\n }\n\n /**\n * Invalidates one registered source's cached gather output.\n *\n * Required after changing modifier uniforms or channels when that source was\n * registered with `cacheModifiers: true`. The following {@link update}\n * re-gathers the source and re-sorts because modifiers may move splats.\n * Returns `false` when the source is not registered.\n */\n invalidateSource(source: SplatMesh): boolean {\n this.assertNotDisposed('invalidateSource');\n const record = this.sources.find((candidate) => candidate.source === source);\n if (!record) return false;\n record.lastGather = null;\n return true;\n }\n\n /** Number of whole sources omitted in the most recent update due to capacity. */\n get droppedSourceCount(): number {\n return this.overflowedSourceCount;\n }\n\n /** Number of active splats omitted in the most recent update due to capacity. */\n get droppedSplatCount(): number {\n return this.overflowedSplatCount;\n }\n\n /**\n * Sets whole-source display opacity without rebuilding the gather pipeline.\n *\n * This scales the completed fragment after RAD merged-vs-leaf classification\n * and falloff. It must never alter LOD selection or splat shape; hosts such as\n * marker crossfades rely on that. Values `<= 0` skip drawing the source.\n */\n setSourceOpacity(source: SplatMesh, opacity: number): void {\n this.assertNotDisposed('setSourceOpacity');\n const record = this.sources.find((entry) => entry.source === source);\n if (!record) throw new Error('UnifiedSplatMesh: source is not registered.');\n record.opacity = opacity;\n }\n\n /** Shows or hides a source without changing its residency. */\n setSourceVisible(source: SplatMesh, visible: boolean): void {\n this.assertNotDisposed('setSourceVisible');\n const record = this.sources.find((entry) => entry.source === source);\n if (!record) throw new Error('UnifiedSplatMesh: source is not registered.');\n record.visible = visible;\n record.source.setUnifiedPickVisibility(visible);\n }\n\n /**\n * Core projected-2D depth of field on the unified draw pass (not gather).\n * Live uniforms - no gather-cache invalidation. Pass `aperture: 0` to disable.\n */\n setDepthOfField(settings: Partial<DepthOfFieldSettings>): void {\n this.assertNotDisposed('setDepthOfField');\n const next = clampDepthOfFieldSettings(settings, this.getDepthOfField());\n this.dofFocusDistance.value = next.focusDistance;\n this.dofAperture.value = next.aperture;\n }\n\n /** Current core DoF uniforms (`aperture === 0` means off). */\n getDepthOfField(): DepthOfFieldSettings {\n return {\n focusDistance: this.dofFocusDistance.value,\n aperture: this.dofAperture.value,\n };\n }\n\n /**\n * PlayCanvas-style proxy-mesh relighting on the unified draw pass (not gather).\n * Live blend/brightness/background; map identity change rebuilds the draw\n * material. Does not invalidate gather caches. Pass `null` to disable.\n */\n setRelighting(options: RelightingSettings | null): void {\n this.assertNotDisposed('setRelighting');\n if (options === null) {\n this.relightBlend.value = 0;\n if (this.relightMap !== this.relightPlaceholder) {\n this.relightMap = this.relightPlaceholder;\n this.rebuildDrawMaterial();\n }\n return;\n }\n const next = clampRelightingSettings(options, this.getRelighting());\n this.relightBlend.value = next.blend;\n this.relightBrightness.value = next.brightness;\n this.relightBackground.value = next.background;\n this.relightSoftness.value = next.softness;\n if (options.map !== this.relightMap) {\n this.relightMap = options.map;\n this.rebuildDrawMaterial();\n }\n }\n\n /** Current relight numeric uniforms (`blend === 0` means off). */\n getRelighting(): RelightingUniforms {\n return {\n blend: this.relightBlend.value,\n brightness: this.relightBrightness.value,\n background: this.relightBackground.value,\n softness: this.relightSoftness.value,\n };\n }\n\n /**\n * Asynchronously picks the frontmost visible splat under an NDC coordinate\n * across every registered source.\n *\n * Semantics: each source that is\n * currently visible in this unified renderer runs its own depth-tested GPU\n * pick pass; the hit nearest the camera wins and the result names its source\n * mesh. Hidden sources (`setSourceVisible(source, false)`) never hit. A hit\n * whose source was removed, hidden, or disposed while its readback was in\n * flight is dropped rather than misattributed. Resolves `null` for misses,\n * an empty source list, and picks pending across {@link dispose}.\n *\n * Uses the construction renderer. Concurrent calls are safe: each source\n * serializes its own picks and shared renderer state is restored\n * synchronously before any await.\n */\n async pick(\n ndc: THREE.Vector2,\n camera: THREE.Camera,\n options?: SplatPickOptions,\n ): Promise<UnifiedSplatPickResult | null> {\n if (this.disposed) return null;\n const candidates = this.sources\n .filter((record) => record.visible)\n .map((record) => record.source);\n if (candidates.length === 0) return null;\n const hits = await Promise.all(\n candidates.map(async (source) => {\n const hit = await source.pick(ndc, camera, this.renderer, options);\n return hit === null ? null : { source, point: hit.point, distance: hit.distance };\n }),\n );\n if (this.disposed) return null;\n let best: UnifiedSplatPickResult | null = null;\n for (const hit of hits) {\n if (hit === null) continue;\n // Registration may have changed while the readbacks were in flight;\n // never attribute a hit to a source no longer picked by this renderer.\n const record = this.sources.find((entry) => entry.source === hit.source);\n if (record === undefined || !record.visible) continue;\n if (best === null || hit.distance < best.distance) best = hit;\n }\n return best;\n }\n\n /** Unregisters a source and restores its standalone draw visibility. */\n removeSource(source: SplatMesh): boolean {\n this.assertNotDisposed('removeSource');\n const index = this.sources.findIndex((entry) => entry.source === source);\n if (index < 0) return false;\n const [record] = this.sources.splice(index, 1);\n if (record) {\n record.gather.dispose();\n record.source.visible = record.originalVisible;\n record.source.setUnifiedPickVisibility(null);\n record.lastGather = null;\n }\n this.previousLayout = this.previousLayout.filter((entry) => entry.source !== source);\n this.previousLayoutBySource.delete(source);\n if (this.sources.length === 0) {\n this.sourceMaxStdDev = null;\n this.sourceAntialias = null;\n this.sourceProjectedFilterProfile = null;\n this.previousLayout = [];\n this.previousLayoutBySource.clear();\n }\n return true;\n }\n\n /** Updates source LODs, gathers their active splats, then globally sorts them. */\n update(camera: THREE.PerspectiveCamera): void {\n if (this.disposed) return;\n this.prepare(camera);\n }\n\n /**\n * Re-sorts and draws this unified source list for a secondary camera.\n * Mirrors and portals use this instead of rendering the hidden source meshes\n * individually, so their reflection keeps one global transparent order.\n */\n renderView(\n camera: THREE.PerspectiveCamera,\n renderer: THREE.WebGPURenderer,\n target: THREE.RenderTarget | null = null,\n ): void {\n if (this.disposed) return;\n if (renderer !== this.renderer) {\n throw new Error('UnifiedSplatMesh: renderView must use its construction renderer.');\n }\n if (!supportsUnifiedSplatMesh(renderer)) {\n throw new Error(\n 'UnifiedSplatMesh requires a WebGPU backend (renderer.backend.isWebGPUBackend).',\n );\n }\n // A secondary view must sort for its own camera regardless of cadence, and\n // it leaves a foreign order in the shared buffer - invalidate afterwards so\n // the next primary update re-sorts even if its camera has not moved.\n const targetSize = target ? this.secondaryViewSize.set(target.width, target.height) : undefined;\n this.prepare(camera, targetSize, true);\n const previousTarget = renderer.getRenderTarget();\n try {\n renderer.setRenderTarget(target);\n renderer.render(this, camera);\n } finally {\n renderer.setRenderTarget(previousTarget);\n // `prepare` left the shared order buffer sorted for the secondary view.\n // Invalidate even when its draw throws, or a stationary primary view can\n // render through that foreign order after the host recovers.\n this.sortScheduler.invalidate();\n }\n }\n\n private prepare(\n camera: THREE.PerspectiveCamera,\n targetSize?: THREE.Vector2,\n forceSort = false,\n ): void {\n if (!supportsUnifiedSplatMesh(this.renderer)) {\n throw new Error(\n 'UnifiedSplatMesh requires a WebGPU backend (renderer.backend.isWebGPUBackend).',\n );\n }\n // Hosts must not pose this mesh; world centers already include source transforms.\n this.matrix.identity();\n this.matrixWorld.identity();\n // A secondary view (`renderView`) states its own size and camera; the\n // primary one follows the renderer, which in XR means a *per-eye* viewport\n // and a cyclopean head pose. Taking the drawing buffer there would be twice\n // the true width and halve every splat's horizontal size, and sorting from\n // the application camera would order the scene from wherever that camera\n // was left standing.\n const xrView = targetSize ? null : resolveXrView(camera, this.renderer);\n const projectionCamera: THREE.Camera = xrView?.eye ?? camera;\n // One global sort from the head serves both eyes (see `xr-view.ts`).\n const viewCamera: THREE.Camera = xrView?.head ?? camera;\n const viewport = this.drawingBufferSize;\n if (targetSize) viewport.copy(targetSize);\n else if (xrView) viewport.set(xrView.width, xrView.height);\n else this.renderer.getDrawingBufferSize(viewport);\n const projection = projectionCamera.projectionMatrix.elements;\n this.viewport.value.copy(viewport);\n const focalX = projection[0] ?? 0;\n const focalY = projection[5] ?? 0;\n this.focal.value.set((focalX * viewport.x) / 2, (focalY * viewport.y) / 2);\n const updated = this.candidateScratch;\n updated.length = 0;\n for (let i = 0; i < this.sources.length; i++) {\n const record = this.sources[i] as SourceRecord;\n // Children take the application camera: they resolve the XR view for\n // themselves, and a streamed source needs it for LOD scheduling.\n record.source.update(camera, this.renderer, { sort: false });\n record.view = record.source.getUnifiedSourceView();\n record.registrationOrder = i;\n updated.push(record);\n }\n // Overflow is deterministic and region-safe: preserve whole sources rather\n // than gathering a prefix of a streamed cut. Higher priority wins; matching\n // priorities retain registration order.\n updated.sort((a, b) => b.priority - a.priority || a.registrationOrder - b.registrationOrder);\n\n this.overflowedSourceCount = 0;\n this.overflowedSplatCount = 0;\n this.bounds.makeEmpty();\n\n const admitted = this.admittedScratch;\n admitted.length = 0;\n let offset = 0;\n for (const record of updated) {\n const view = record.view as UnifiedSourceView;\n if (record.graphRevision !== view.graphRevision) {\n // Build the replacement before disposing the old pipeline: a modifier\n // stack that throws at graph-build time must leave the record holding\n // a live gather (and an unchanged revision) so the next update can\n // retry after the caller fixes the stack.\n const rebuilt = this.createGather(view);\n record.gather.dispose();\n record.gather = rebuilt;\n record.graphRevision = view.graphRevision;\n record.lastGather = null;\n }\n if (!record.visible) {\n record.lastGather = null;\n continue;\n }\n if (view.activeCount === 0) {\n // An empty cut (e.g. a streamed source before its first chunk lands)\n // owns no work slice: skip the zero-splat gather dispatch and keep the\n // sorter bounds limited to sources that contribute splats.\n record.lastGather = null;\n continue;\n }\n if (offset + view.activeCount > this.workBuffer.capacity) {\n this.overflowedSourceCount++;\n this.overflowedSplatCount += view.activeCount;\n record.lastGather = null;\n continue;\n }\n record.offset = offset;\n admitted.push(record);\n this.bounds.union(view.worldBounds);\n offset += view.activeCount;\n }\n\n // Geometry under the draw order changed (layout, active cut, transform,\n // opacity, content revision). Camera-only SH / modifier color refreshes\n // re-gather the *same* world centers and must not force a sort.\n let geometryInvalidated = false;\n for (const record of admitted) {\n const view = record.view as UnifiedSourceView;\n const sliceOffset = record.offset;\n const previous = this.previousLayoutBySource.get(record.source);\n const ownedSameSlice =\n previous !== undefined &&\n previous.offset === sliceOffset &&\n previous.activeCount === view.activeCount;\n const last = record.lastGather;\n const geometryMatches =\n last !== null &&\n ownedSameSlice &&\n last.activeCount === view.activeCount &&\n last.contentRevision === view.contentRevision &&\n last.offset === sliceOffset &&\n last.opacity === record.opacity &&\n last.matrixWorld.equals(view.matrixWorld);\n const reusable =\n geometryMatches &&\n // SH depends on camera position, not orientation. A stationary camera\n // can reuse the resolved colors instead of re-running a full-source\n // gather every frame; camera motion invalidates only SH-bearing slices.\n (view.sh === null || last.localCameraPosition.equals(view.localCameraPosition.value)) &&\n (view.modifiers.length === 0 || record.cacheModifiers) &&\n // Belt-and-braces: a placed pool's splats move without its own\n // `matrixWorld` changing, so a cached gather would go stale silently.\n // `addSource` already rejects these.\n !view.hasSourcePlacement;\n if (!reusable) {\n record.gather.gather(\n this.renderer,\n view.activeCount,\n sliceOffset,\n view.matrixWorld,\n viewCamera.matrixWorldInverse,\n record.opacity,\n );\n if (!geometryMatches) geometryInvalidated = true;\n if (record.lastGather === null) {\n record.lastGather = {\n activeCount: view.activeCount,\n contentRevision: view.contentRevision,\n offset: sliceOffset,\n opacity: record.opacity,\n matrixWorld: view.matrixWorld.clone(),\n localCameraPosition: view.localCameraPosition.value.clone(),\n };\n } else {\n record.lastGather.activeCount = view.activeCount;\n record.lastGather.contentRevision = view.contentRevision;\n record.lastGather.offset = sliceOffset;\n record.lastGather.opacity = record.opacity;\n record.lastGather.matrixWorld.copy(view.matrixWorld);\n record.lastGather.localCameraPosition.copy(view.localCameraPosition.value);\n }\n }\n }\n\n // Commit ownership only after every gather for this preparation has run.\n let layoutChanged =\n admitted.length !== this.previousLayout.length || offset !== this.previousAdmittedTotal;\n this.previousAdmittedTotal = offset;\n if (!layoutChanged) {\n for (let i = 0; i < admitted.length; i++) {\n const record = admitted[i] as SourceRecord;\n const entry = this.previousLayout[i] as LayoutEntry;\n if (\n entry.source !== record.source ||\n entry.offset !== record.offset ||\n entry.activeCount !== (record.view as UnifiedSourceView).activeCount\n ) {\n layoutChanged = true;\n break;\n }\n }\n }\n if (layoutChanged) {\n this.previousLayout = admitted.map((record) => ({\n source: record.source,\n offset: record.offset,\n activeCount: (record.view as UnifiedSourceView).activeCount,\n }));\n this.previousLayoutBySource.clear();\n for (const entry of this.previousLayout) this.previousLayoutBySource.set(entry.source, entry);\n }\n\n // Work-buffer *geometry* moved underneath the current draw order: the next\n // sort must run whatever the camera did. Camera-driven SH/modifier color\n // refreshes re-gather without geometryInvalidated and deliberately skip\n // this. DoF is a live draw uniform and reaches neither branch.\n if (geometryInvalidated || layoutChanged) this.sortScheduler.invalidateContent();\n\n if (offset > 0) {\n const now = performance.now();\n const viewInverse = viewCamera.matrixWorldInverse;\n if (\n forceSort ||\n this.sortScheduler.shouldSubmit(viewInverse, this.lastSortedModelView, offset, now)\n ) {\n if (this.sorter.sort(viewInverse, offset, this.bounds)) {\n this.lastSortedModelView.copy(viewInverse);\n this.sortScheduler.markAccepted(now);\n }\n }\n }\n (this.geometry as THREE.InstancedBufferGeometry).instanceCount = offset;\n // Both are uploaded by the first frame's gather/sort dispatches, and neither\n // is ever read back - see the field comment. The work buffer's own mirrors\n // are released by `WorkBufferGather.gather`.\n if (!this.mirrors.settled) this.mirrors.release(this.renderer);\n }\n\n dispose(): void {\n if (this.disposed) return;\n this.disposed = true;\n for (const record of this.sources) {\n record.gather.dispose();\n record.source.visible = record.originalVisible;\n record.source.setUnifiedPickVisibility(null);\n record.lastGather = null;\n }\n this.sources.length = 0;\n this.previousLayout = [];\n this.previousLayoutBySource.clear();\n this.candidateScratch.length = 0;\n this.admittedScratch.length = 0;\n this.sourceMaxStdDev = null;\n this.sourceAntialias = null;\n this.sourceProjectedFilterProfile = null;\n this.sorter.dispose();\n this.geometry.dispose();\n (this.material as THREE.Material).dispose();\n this.relightPlaceholder.dispose();\n // The work buffer, its source-index list and the draw-order buffer are\n // storage attributes outside the geometry, so nothing above frees their\n // GPU buffers - ~72 B per work slot leaked per scene swap without this.\n releaseRendererAttributes(this.renderer, [\n this.workBuffer.centers,\n this.workBuffer.colors,\n this.workBuffer.covarianceA,\n this.workBuffer.covarianceB,\n this.workBuffer.isotropicMix,\n this.workBuffer.isotropicScreenRadius,\n this.workSourceIndex,\n this.orderAttribute,\n ]);\n }\n\n private assertNotDisposed(operation: string): void {\n if (this.disposed) {\n throw new Error(`UnifiedSplatMesh: ${operation} called after dispose.`);\n }\n }\n\n /** Rebuilds the EWA draw material when the relight map identity changes. */\n private rebuildDrawMaterial(): void {\n const previous = this.material as THREE.Material;\n this.material = createWorkBufferMaterial({\n capacity: this.workBuffer.capacity,\n centers: this.workBuffer.centers,\n colors: this.workBuffer.colors,\n covarianceA: this.workBuffer.covarianceA,\n covarianceB: this.workBuffer.covarianceB,\n isotropicMix: this.workBuffer.isotropicMix,\n isotropicScreenRadius: this.workBuffer.isotropicScreenRadius,\n order: this.orderAttribute,\n focal: this.focal,\n viewport: this.viewport,\n maxStdDev: this.maxStdDev,\n minSplatSizePx: this.minSplatSizePx,\n antialias: this.antialias,\n projectedLowPassVariance: this.projectedLowPassVariance,\n compensateProjectedLowPass: this.compensateProjectedLowPass,\n dofFocusDistance: this.dofFocusDistance,\n dofAperture: this.dofAperture,\n relightMap: this.relightMap,\n relightBlend: this.relightBlend,\n relightBrightness: this.relightBrightness,\n relightBackground: this.relightBackground,\n relightSoftness: this.relightSoftness,\n });\n previous.dispose();\n }\n\n private createGather(view: ReturnType<SplatMesh['getUnifiedSourceView']>): WorkBufferGather {\n const gather = this.buildGather(view);\n // Compile off the critical frame. WebGPU defers compute-pipeline compilation\n // to the first dispatch, and that dispatch happens inside `update` - a\n // measured 2.0s frame on a multi-mesh scene. Warming here is best-effort:\n // if it fails or has not finished by the first real gather, the only cost is\n // the stall this avoids, so nothing waits on it.\n void gather.warmUp(this.renderer).catch(() => undefined);\n return gather;\n }\n\n private buildGather(view: ReturnType<SplatMesh['getUnifiedSourceView']>): WorkBufferGather {\n return new WorkBufferGather({\n capacity: this.workBuffer.capacity,\n sourceCapacity: view.capacity,\n sourceIndex: view.sourceIndex,\n centersTexture: view.centersTexture,\n colorsTexture: view.colorsTexture,\n covarianceATexture: view.covarianceATexture,\n covarianceBTexture: view.covarianceBTexture,\n dataTextureWidth: view.dataTextureWidth,\n sh: view.sh,\n modifiers: view.modifiers,\n channels: view.channels,\n localCameraPosition: view.localCameraPosition,\n srgbOutput: this.srgbOutput,\n // Per source, not a compatibility field: the gather normalizes `.rad`\n // half-alpha here so one shared draw material serves mixed scenes.\n lodAlpha: view.lodAlpha,\n workBuffer: this.workBuffer,\n });\n }\n}\n"],"names":["_WorkBuffer","capacity","__publicField","slots","THREE","StorageMirrorReleaser","renderer","WorkBuffer","WorkBufferGather","options","uniform","sourceCapacity","sourceIndex","centersTexture","colorsTexture","covarianceATexture","covarianceBTexture","dataTextureWidth","sh","modifiers","channels","localCameraPosition","source","storage","output","outputColor","outputCovA","outputCovB","outputIsotropicMix","outputIsotropicScreenRadius","Fn","If","float","instanceIndex","poolIndex","int","texel","ivec2","localCenter","textureLoad","target","inputA","inputB","covarianceBase","mat3","vec3","baseColor","colorAfterSh","vec4","evaluateSplatSh","worldCenter","stack","foldSplatModifierStack","inverse","toCamera","axis","name","channel","center","visible","bool","gatheredCenter","encodedOriginal","asNode","encodedResolved","visibility","resolvedColor","colorSpaceToWorking","modifierOpacity","covariance","localCovariance","varianceScale","DEFAULT_ISOTROPIC_VARIANCE_SCALE","applyIsotropicCovarianceOverride","linear","worldCovarianceBase","worldCovariance","c0","c1","c2","activeCount","targetOffset","sourceMatrix","cameraViewMatrixOrOpacity","opacity","cameraViewMatrix","createWorkBufferMaterial","material","centers","order","colors","covarianceA","covarianceB","isotropicMix","isotropicScreenRadius","workColor","varying","quadPosition","positionGeometry","opacityCompensation","displayOpacity","adjustedStdDev","workIndex","centerSample","drawable","viewCenter","modelViewMatrix","clipCenter","cameraProjectionMatrix","covA","covB","invZ","invZ2","j1","j2","viewRotationT","u1","u2","aRaw","dRaw","bRaw","depth","focus","halfApertureAngle","focusBlur","apertureRadius","cocRadiusPx","cocVar","MAX_DOF_VARIANCE","a","d","b","isoMix","detBlur","detRaw","detBase","mipFade","dofOnlyFade","compensate","fade","mix","mid","radius","vec2","lambda1","lambda2","equalized","equalizeProjectedEigenvalues","capped","capProjectedEigenvaluesToScreenRadius","remap","stdDev","eigenvector","minSplat","major","minor","pixelOffset","ndcCenter","clipPosition","margin","squaredDistance","Discard","g","aExp","merged","alpha","litCenter","tslTexture","screenUV","ox","oy","s0","s1","s2","s3","s4","wSum","rgbSoft","aSoft","litSoft","lit","factor","rgb","WORK_BUFFER_CENTERS_BYTES_PER_SPLAT","WORK_BUFFER_BYTES_PER_SLOT","assertNonNegativeCapacity","estimateLargestStorageBufferBytes","estimateUnifiedWorkBufferBytes","estimateUnifiedWorkBufferPeakBytes","supportsUnifiedSplatMesh","_a","UnifiedSplatMesh","assertStorageBufferFitsDevice","workBuffer","focal","viewport","maxStdDev","minSplatSizePx","antialias","projectedLowPassVariance","compensateProjectedLowPass","dofFocusDistance","dofAperture","relightPlaceholder","createPlaceholderRelightTexture","relightBlend","relightBrightness","DEFAULT_RELIGHT_BRIGHTNESS","relightBackground","DEFAULT_RELIGHT_BACKGROUND","relightSoftness","DEFAULT_RELIGHT_SOFTNESS","geometry","indices","i","WebGpuSortScheduler","isFillConstrainedSplatDevice","sortInputs","RadixSorter","ComputeSorter","record","view","resolvedVisible","lccProfile","candidate","entry","settings","next","clampDepthOfFieldSettings","clampRelightingSettings","ndc","camera","candidates","hits","hit","best","index","targetSize","previousTarget","forceSort","xrView","resolveXrView","projectionCamera","viewCamera","projection","focalX","focalY","updated","admitted","offset","rebuilt","geometryInvalidated","sliceOffset","previous","ownedSameSlice","last","geometryMatches","layoutChanged","now","viewInverse","releaseRendererAttributes","operation","gather"],"mappings":";;;;;;;;;AAsCO,MAAMA,KAAN,MAAMA,GAAW;AAAA,EAyBtB,YAAqBC,GAAkB;AAvB9B;AAAA,IAAAC,EAAA;AAEA;AAAA,IAAAA,EAAA;AAEA;AAAA,IAAAA,EAAA;AAEA;AAAA,IAAAA,EAAA;AAEA;AAAA,IAAAA,EAAA;AAEA;AAAA,IAAAA,EAAA;AA+CQ,IAAAA,EAAA;AAlCI,SAAA,WAAAD;AACnB,UAAME,IAAQF,IAAWD,GAAW;AACpC,SAAK,UAAU,IAAII,EAAM,uBAAuB,IAAI,aAAaD,IAAQ,CAAC,GAAG,CAAC,GAC9E,KAAK,SAAS,IAAIC,EAAM,uBAAuB,IAAI,aAAaD,IAAQ,CAAC,GAAG,CAAC,GAC7E,KAAK,cAAc,IAAIC,EAAM,uBAAuB,IAAI,aAAaD,IAAQ,CAAC,GAAG,CAAC,GAClF,KAAK,cAAc,IAAIC,EAAM,uBAAuB,IAAI,aAAaD,IAAQ,CAAC,GAAG,CAAC,GAClF,KAAK,eAAe,IAAIC,EAAM,uBAAuB,IAAI,aAAaD,CAAK,GAAG,CAAC,GAC/E,KAAK,wBAAwB,IAAIC,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f,YAAY,KAAK;AAAA,IAAA,CAClB;AAAA,EACH;AACF;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"webgpu-limits-Y3CI_6_6.js","sources":["../src/lib/webgpu-limits.ts"],"sourcesContent":["import type { WebGPURenderer } from 'three/webgpu';\n\n/**\n * WebGPU device limits hosts should request for VLAM beyond the spec defaults.\n *\n * The WebGPU default `maxStorageBufferBindingSize` is 128 MiB. Unified work\n * buffers and large streamed pools allocate storage attributes past that\n * (16 bytes per splat for an RGBA32F centers buffer). Desktop adapters often\n * advertise ~2 GiB, but only when those values are passed as `requiredLimits`\n * to `adapter.requestDevice()` / Three.js `WebGPURenderer`.\n *\n * `maxTextureDimension2D` is here for the same reason: the default is 8192,\n * which caps a pool at 8192 rows of {@link SPLAT_DATA_TEXTURE_WIDTH} (≈16.7 M\n * splats of *capacity*, so ≈11.2 M resident at the usual 1.5 slack). Desktop\n * adapters commonly advertise 16384 and double that ceiling for free.\n */\nexport interface WebGpuRequiredLimits {\n maxStorageBufferBindingSize: number;\n maxBufferSize: number;\n maxTextureDimension2D: number;\n // Assignable to the `Record<string, number>` Three.js WebGPURenderer takes\n // as `requiredLimits`, and open to further WebGPU limit names.\n [limit: string]: number;\n}\n\n/**\n * WebGPU's default `maxStorageBufferBindingSize` when the host does not raise\n * it via `requiredLimits` (128 MiB).\n */\nexport const WEBGPU_DEFAULT_MAX_STORAGE_BUFFER_BINDING_SIZE = 134_217_728;\n\n/**\n * Copies the adapter's advertised buffer maxima for use as\n * `WebGPURenderer({ requiredLimits })`.\n *\n * Does not call `requestDevice` - the host owns device creation.\n */\nexport function recommendedWebGpuRequiredLimits(adapter: {\n limits: {\n maxStorageBufferBindingSize: number;\n maxBufferSize: number;\n maxTextureDimension2D?: number;\n };\n}): WebGpuRequiredLimits {\n return {\n maxStorageBufferBindingSize: adapter.limits.maxStorageBufferBindingSize,\n maxBufferSize: adapter.limits.maxBufferSize,\n // Spec minimum, so an adapter that somehow reports nothing still requests a\n // legal value rather than `undefined` (which requestDevice rejects).\n maxTextureDimension2D: adapter.limits.maxTextureDimension2D ?? 8192,\n };\n}\n\n/** Mirrors WebGPU `GPUPowerPreference` without requiring `@webgpu/types`. */\nexport type WebGpuPowerPreference = 'high-performance' | 'low-power';\n\ntype NavigatorPlatformProbe = Pick<Navigator, 'platform' | 'userAgent'> & {\n userAgentData?: { platform?: string };\n};\n\n/**\n * Whether the host should pass `powerPreference` to `navigator.gpu.requestAdapter`\n * / Three.js `WebGPURenderer`.\n *\n * Chrome on Windows ignores the option and logs a console warning when it is\n * present ([crbug.com/369219127](https://crbug.com/369219127)). Prefer\n * {@link webGpuPowerPreferenceOptions} so Windows hosts omit it automatically.\n */\nexport function supportsWebGpuPowerPreference(\n nav: NavigatorPlatformProbe | undefined = typeof navigator !== 'undefined'\n ? navigator\n : undefined,\n): boolean {\n if (!nav) return true;\n\n const uaDataPlatform = nav.userAgentData?.platform;\n if (typeof uaDataPlatform === 'string' && uaDataPlatform.length > 0) {\n return uaDataPlatform !== 'Windows';\n }\n\n // `navigator.platform` is \"Win32\" on both 32- and 64-bit Windows browsers.\n if (/^Win/i.test(nav.platform ?? '')) return false;\n return !/Windows/i.test(nav.userAgent ?? '');\n}\n\n/**\n * Options to spread into `requestAdapter(...)` and `WebGPURenderer({...})`.\n * Empty on Windows so Chrome does not warn about an ignored `powerPreference`.\n */\nexport function webGpuPowerPreferenceOptions(\n powerPreference: WebGpuPowerPreference = 'high-performance',\n nav?: NavigatorPlatformProbe,\n): { powerPreference: WebGpuPowerPreference } | Record<string, never> {\n return supportsWebGpuPowerPreference(nav) ? { powerPreference } : {};\n}\n\n/**\n * The renderer's WebGPU `maxStorageBufferBindingSize`, or 0 when it cannot be\n * read (WebGL2 fallback, or device not yet available). Callers skip the check\n * when 0 rather than falsely reject.\n */\nexport function deviceMaxStorageBufferBindingSize(renderer: WebGPURenderer): number {\n const backend = renderer.backend as\n | {\n isWebGPUBackend?: boolean;\n device?: { limits?: { maxStorageBufferBindingSize?: number } };\n }\n | undefined;\n if (backend?.isWebGPUBackend !== true) return 0;\n const limit = backend.device?.limits?.maxStorageBufferBindingSize;\n return typeof limit === 'number' && limit > 0 ? limit : 0;\n}\n\n/**\n * Throws when a planned storage buffer would exceed the device bind limit.\n * No-ops when the limit cannot be read (WebGL2 / uninitialized backend).\n */\nexport function assertStorageBufferFitsDevice(\n renderer: WebGPURenderer,\n byteSize: number,\n capacity: number,\n): void {\n const limit = deviceMaxStorageBufferBindingSize(renderer);\n if (limit <= 0 || byteSize <= limit) return;\n\n const needMiB = (byteSize / (1024 * 1024)).toFixed(1);\n const limitMiB = (limit / (1024 * 1024)).toFixed(1);\n const defaultMiB = (WEBGPU_DEFAULT_MAX_STORAGE_BUFFER_BINDING_SIZE / (1024 * 1024)).toFixed(0);\n throw new Error(\n `vlam: storage buffer needs ${needMiB} MiB for ${capacity.toLocaleString('en-US')} splats, ` +\n `but device maxStorageBufferBindingSize is ${limitMiB} MiB ` +\n `(WebGPU default is ${defaultMiB}). Pass recommendedWebGpuRequiredLimits(adapter) to ` +\n `WebGPURenderer, or lower the splat budget.`,\n );\n}\n"],"names":["WEBGPU_DEFAULT_MAX_STORAGE_BUFFER_BINDING_SIZE","recommendedWebGpuRequiredLimits","adapter","supportsWebGpuPowerPreference","nav","_a","uaDataPlatform","webGpuPowerPreferenceOptions","powerPreference","deviceMaxStorageBufferBindingSize","renderer","_b","backend","limit","assertStorageBufferFitsDevice","byteSize","capacity","needMiB","limitMiB","defaultMiB"],"mappings":"AA6BO,MAAMA,IAAiD;AAQvD,SAASC,EAAgCC,GAMvB;AACvB,SAAO;AAAA,IACL,6BAA6BA,EAAQ,OAAO;AAAA,IAC5C,eAAeA,EAAQ,OAAO;AAAA;AAAA;AAAA,IAG9B,uBAAuBA,EAAQ,OAAO,yBAAyB;AAAA,EAAA;AAEnE;AAiBO,SAASC,EACdC,IAA0C,OAAO,YAAc,MAC3D,YACA,QACK;AA3CJ,MAAAC;AA4CL,MAAI,CAACD,EAAK,QAAO;AAEjB,QAAME,KAAiBD,IAAAD,EAAI,kBAAJ,gBAAAC,EAAmB;AAC1C,SAAI,OAAOC,KAAmB,YAAYA,EAAe,SAAS,IACzDA,MAAmB,YAIxB,QAAQ,KAAKF,EAAI,YAAY,EAAE,IAAU,KACtC,CAAC,WAAW,KAAKA,EAAI,aAAa,EAAE;AAC7C;AAMO,SAASG,EACdC,IAAyC,oBACzCJ,GACoE;AACpE,SAAOD,EAA8BC,CAAG,IAAI,EAAE,iBAAAI,EAAA,IAAoB,CAAA;AACpE;AAOO,SAASC,EAAkCC,GAAkC;AAxE7E,MAAAL,GAAAM;AAyEL,QAAMC,IAAUF,EAAS;AAMzB,OAAIE,KAAA,gBAAAA,EAAS,qBAAoB,GAAM,QAAO;AAC9C,QAAMC,KAAQF,KAAAN,IAAAO,EAAQ,WAAR,gBAAAP,EAAgB,WAAhB,gBAAAM,EAAwB;AACtC,SAAO,OAAOE,KAAU,YAAYA,IAAQ,IAAIA,IAAQ;AAC1D;AAMO,SAASC,EACdJ,GACAK,GACAC,GACM;AACN,QAAMH,IAAQJ,EAAkCC,CAAQ;AACxD,MAAIG,KAAS,KAAKE,KAAYF,EAAO;AAErC,QAAMI,KAAWF,KAAY,OAAO,OAAO,QAAQ,CAAC,GAC9CG,KAAYL,KAAS,OAAO,OAAO,QAAQ,CAAC,GAC5CM,KAAc,aAAkD,OAAO,OAAO,QAAQ,CAAC;AAC7F,QAAM,IAAI;AAAA,IACR,8BAA8BF,CAAO,YAAYD,EAAS,eAAe,OAAO,CAAC,sDAClCE,CAAQ,2BAC/BC,CAAU;AAAA,EAAA;AAGtC;"}
|
|
1
|
+
{"version":3,"file":"webgpu-limits-Y3CI_6_6.js","sources":["../src/lib/core/webgpu-limits.ts"],"sourcesContent":["import type { WebGPURenderer } from 'three/webgpu';\n\n/**\n * WebGPU device limits hosts should request for VLAM beyond the spec defaults.\n *\n * The WebGPU default `maxStorageBufferBindingSize` is 128 MiB. Unified work\n * buffers and large streamed pools allocate storage attributes past that\n * (16 bytes per splat for an RGBA32F centers buffer). Desktop adapters often\n * advertise ~2 GiB, but only when those values are passed as `requiredLimits`\n * to `adapter.requestDevice()` / Three.js `WebGPURenderer`.\n *\n * `maxTextureDimension2D` is here for the same reason: the default is 8192,\n * which caps a pool at 8192 rows of {@link SPLAT_DATA_TEXTURE_WIDTH} (≈16.7 M\n * splats of *capacity*, so ≈11.2 M resident at the usual 1.5 slack). Desktop\n * adapters commonly advertise 16384 and double that ceiling for free.\n */\nexport interface WebGpuRequiredLimits {\n maxStorageBufferBindingSize: number;\n maxBufferSize: number;\n maxTextureDimension2D: number;\n // Assignable to the `Record<string, number>` Three.js WebGPURenderer takes\n // as `requiredLimits`, and open to further WebGPU limit names.\n [limit: string]: number;\n}\n\n/**\n * WebGPU's default `maxStorageBufferBindingSize` when the host does not raise\n * it via `requiredLimits` (128 MiB).\n */\nexport const WEBGPU_DEFAULT_MAX_STORAGE_BUFFER_BINDING_SIZE = 134_217_728;\n\n/**\n * Copies the adapter's advertised buffer maxima for use as\n * `WebGPURenderer({ requiredLimits })`.\n *\n * Does not call `requestDevice` - the host owns device creation.\n */\nexport function recommendedWebGpuRequiredLimits(adapter: {\n limits: {\n maxStorageBufferBindingSize: number;\n maxBufferSize: number;\n maxTextureDimension2D?: number;\n };\n}): WebGpuRequiredLimits {\n return {\n maxStorageBufferBindingSize: adapter.limits.maxStorageBufferBindingSize,\n maxBufferSize: adapter.limits.maxBufferSize,\n // Spec minimum, so an adapter that somehow reports nothing still requests a\n // legal value rather than `undefined` (which requestDevice rejects).\n maxTextureDimension2D: adapter.limits.maxTextureDimension2D ?? 8192,\n };\n}\n\n/** Mirrors WebGPU `GPUPowerPreference` without requiring `@webgpu/types`. */\nexport type WebGpuPowerPreference = 'high-performance' | 'low-power';\n\ntype NavigatorPlatformProbe = Pick<Navigator, 'platform' | 'userAgent'> & {\n userAgentData?: { platform?: string };\n};\n\n/**\n * Whether the host should pass `powerPreference` to `navigator.gpu.requestAdapter`\n * / Three.js `WebGPURenderer`.\n *\n * Chrome on Windows ignores the option and logs a console warning when it is\n * present ([crbug.com/369219127](https://crbug.com/369219127)). Prefer\n * {@link webGpuPowerPreferenceOptions} so Windows hosts omit it automatically.\n */\nexport function supportsWebGpuPowerPreference(\n nav: NavigatorPlatformProbe | undefined = typeof navigator !== 'undefined'\n ? navigator\n : undefined,\n): boolean {\n if (!nav) return true;\n\n const uaDataPlatform = nav.userAgentData?.platform;\n if (typeof uaDataPlatform === 'string' && uaDataPlatform.length > 0) {\n return uaDataPlatform !== 'Windows';\n }\n\n // `navigator.platform` is \"Win32\" on both 32- and 64-bit Windows browsers.\n if (/^Win/i.test(nav.platform ?? '')) return false;\n return !/Windows/i.test(nav.userAgent ?? '');\n}\n\n/**\n * Options to spread into `requestAdapter(...)` and `WebGPURenderer({...})`.\n * Empty on Windows so Chrome does not warn about an ignored `powerPreference`.\n */\nexport function webGpuPowerPreferenceOptions(\n powerPreference: WebGpuPowerPreference = 'high-performance',\n nav?: NavigatorPlatformProbe,\n): { powerPreference: WebGpuPowerPreference } | Record<string, never> {\n return supportsWebGpuPowerPreference(nav) ? { powerPreference } : {};\n}\n\n/**\n * The renderer's WebGPU `maxStorageBufferBindingSize`, or 0 when it cannot be\n * read (WebGL2 fallback, or device not yet available). Callers skip the check\n * when 0 rather than falsely reject.\n */\nexport function deviceMaxStorageBufferBindingSize(renderer: WebGPURenderer): number {\n const backend = renderer.backend as\n | {\n isWebGPUBackend?: boolean;\n device?: { limits?: { maxStorageBufferBindingSize?: number } };\n }\n | undefined;\n if (backend?.isWebGPUBackend !== true) return 0;\n const limit = backend.device?.limits?.maxStorageBufferBindingSize;\n return typeof limit === 'number' && limit > 0 ? limit : 0;\n}\n\n/**\n * Throws when a planned storage buffer would exceed the device bind limit.\n * No-ops when the limit cannot be read (WebGL2 / uninitialized backend).\n */\nexport function assertStorageBufferFitsDevice(\n renderer: WebGPURenderer,\n byteSize: number,\n capacity: number,\n): void {\n const limit = deviceMaxStorageBufferBindingSize(renderer);\n if (limit <= 0 || byteSize <= limit) return;\n\n const needMiB = (byteSize / (1024 * 1024)).toFixed(1);\n const limitMiB = (limit / (1024 * 1024)).toFixed(1);\n const defaultMiB = (WEBGPU_DEFAULT_MAX_STORAGE_BUFFER_BINDING_SIZE / (1024 * 1024)).toFixed(0);\n throw new Error(\n `vlam: storage buffer needs ${needMiB} MiB for ${capacity.toLocaleString('en-US')} splats, ` +\n `but device maxStorageBufferBindingSize is ${limitMiB} MiB ` +\n `(WebGPU default is ${defaultMiB}). Pass recommendedWebGpuRequiredLimits(adapter) to ` +\n `WebGPURenderer, or lower the splat budget.`,\n );\n}\n"],"names":["WEBGPU_DEFAULT_MAX_STORAGE_BUFFER_BINDING_SIZE","recommendedWebGpuRequiredLimits","adapter","supportsWebGpuPowerPreference","nav","_a","uaDataPlatform","webGpuPowerPreferenceOptions","powerPreference","deviceMaxStorageBufferBindingSize","renderer","_b","backend","limit","assertStorageBufferFitsDevice","byteSize","capacity","needMiB","limitMiB","defaultMiB"],"mappings":"AA6BO,MAAMA,IAAiD;AAQvD,SAASC,EAAgCC,GAMvB;AACvB,SAAO;AAAA,IACL,6BAA6BA,EAAQ,OAAO;AAAA,IAC5C,eAAeA,EAAQ,OAAO;AAAA;AAAA;AAAA,IAG9B,uBAAuBA,EAAQ,OAAO,yBAAyB;AAAA,EAAA;AAEnE;AAiBO,SAASC,EACdC,IAA0C,OAAO,YAAc,MAC3D,YACA,QACK;AA3CJ,MAAAC;AA4CL,MAAI,CAACD,EAAK,QAAO;AAEjB,QAAME,KAAiBD,IAAAD,EAAI,kBAAJ,gBAAAC,EAAmB;AAC1C,SAAI,OAAOC,KAAmB,YAAYA,EAAe,SAAS,IACzDA,MAAmB,YAIxB,QAAQ,KAAKF,EAAI,YAAY,EAAE,IAAU,KACtC,CAAC,WAAW,KAAKA,EAAI,aAAa,EAAE;AAC7C;AAMO,SAASG,EACdC,IAAyC,oBACzCJ,GACoE;AACpE,SAAOD,EAA8BC,CAAG,IAAI,EAAE,iBAAAI,EAAA,IAAoB,CAAA;AACpE;AAOO,SAASC,EAAkCC,GAAkC;AAxE7E,MAAAL,GAAAM;AAyEL,QAAMC,IAAUF,EAAS;AAMzB,OAAIE,KAAA,gBAAAA,EAAS,qBAAoB,GAAM,QAAO;AAC9C,QAAMC,KAAQF,KAAAN,IAAAO,EAAQ,WAAR,gBAAAP,EAAgB,WAAhB,gBAAAM,EAAwB;AACtC,SAAO,OAAOE,KAAU,YAAYA,IAAQ,IAAIA,IAAQ;AAC1D;AAMO,SAASC,EACdJ,GACAK,GACAC,GACM;AACN,QAAMH,IAAQJ,EAAkCC,CAAQ;AACxD,MAAIG,KAAS,KAAKE,KAAYF,EAAO;AAErC,QAAMI,KAAWF,KAAY,OAAO,OAAO,QAAQ,CAAC,GAC9CG,KAAYL,KAAS,OAAO,OAAO,QAAQ,CAAC,GAC5CM,KAAc,aAAkD,OAAO,OAAO,QAAQ,CAAC;AAC7F,QAAM,IAAI;AAAA,IACR,8BAA8BF,CAAO,YAAYD,EAAS,eAAe,OAAO,CAAC,sDAClCE,CAAQ,2BAC/BC,CAAU;AAAA,EAAA;AAGtC;"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@voluma/vlam",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.4",
|
|
4
4
|
"description": "VLAM! - A lightweight WebGPU Gaussian splat viewer for three.js, built for high performance, streaming LOD, and fully customizable rendering through an open shader pipeline.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "Voluma",
|
|
@@ -37,34 +37,34 @@
|
|
|
37
37
|
},
|
|
38
38
|
"main": "./dist/index.js",
|
|
39
39
|
"module": "./dist/index.js",
|
|
40
|
-
"types": "./dist/index.d.ts",
|
|
40
|
+
"types": "./dist/core/index.d.ts",
|
|
41
41
|
"exports": {
|
|
42
42
|
".": {
|
|
43
|
-
"types": "./dist/index.d.ts",
|
|
43
|
+
"types": "./dist/core/index.d.ts",
|
|
44
44
|
"import": "./dist/index.js"
|
|
45
45
|
},
|
|
46
46
|
"./loaders": {
|
|
47
|
-
"types": "./dist/loaders.d.ts",
|
|
47
|
+
"types": "./dist/loaders/index.d.ts",
|
|
48
48
|
"import": "./dist/loaders.js"
|
|
49
49
|
},
|
|
50
50
|
"./static-lod": {
|
|
51
|
-
"types": "./dist/static-lod
|
|
51
|
+
"types": "./dist/static-lod/index.d.ts",
|
|
52
52
|
"import": "./dist/static-lod.js"
|
|
53
53
|
},
|
|
54
54
|
"./streaming": {
|
|
55
|
-
"types": "./dist/streaming.d.ts",
|
|
55
|
+
"types": "./dist/streaming/index.d.ts",
|
|
56
56
|
"import": "./dist/streaming.js"
|
|
57
57
|
},
|
|
58
58
|
"./unified": {
|
|
59
|
-
"types": "./dist/unified.d.ts",
|
|
59
|
+
"types": "./dist/unified/index.d.ts",
|
|
60
60
|
"import": "./dist/unified.js"
|
|
61
61
|
},
|
|
62
62
|
"./selection": {
|
|
63
|
-
"types": "./dist/selection.d.ts",
|
|
63
|
+
"types": "./dist/selection/index.d.ts",
|
|
64
64
|
"import": "./dist/selection.js"
|
|
65
65
|
},
|
|
66
66
|
"./effects": {
|
|
67
|
-
"types": "./dist/effects.d.ts",
|
|
67
|
+
"types": "./dist/effects/index.d.ts",
|
|
68
68
|
"import": "./dist/effects.js"
|
|
69
69
|
},
|
|
70
70
|
"./formats/ply": {
|