import * as THREE from 'three/webgpu'; import type { SplatSortCenterAdapter, SplatSorter } from './sorter'; import type { SplatSortMetric } from './splat-mesh-types'; import { type SplatSortRange } from './splat-sort-bounds'; import type { uniformArray } from 'three/tsl'; /** Counting-sort histogram slots retained for exact depth quantization. */ export declare const COMPUTE_SORTER_MAX_BUCKET_COUNT: number; /** Smallest histogram retained for a sparse projected list. */ export declare const COMPUTE_SORTER_MIN_BUCKET_COUNT: number; /** * GPU bytes retained by a counting sorter's private histogram, scans, and * per-splat bucket buffer. It excludes the caller-owned source/order buffers. */ export declare function estimateComputeSorterSteadyBytes(capacity: number): number; /** CPU mirrors coexist with the first GPU upload, so price the observable peak. */ export declare function estimateComputeSorterPeakBytes(capacity: number): number; /** * Rejects a {@link SplatSortCenterAdapter} on inputs it cannot apply to: * gathered work-buffer centers are already displaced (and in world space), * and a per-source placement would place the displacement in the wrong frame. */ export declare function assertSortCenterInputs(owner: string, sortCenter: SplatSortCenterAdapter | null, centersBuffer: THREE.StorageBufferAttribute | undefined, perSource: PerSourceSortTransform | undefined): void; /** * The position a sort key is measured at: the adapter's displaced center, or * the pool center itself when there is none (the original graph, unchanged). */ export declare function displacedSortCenter(sortCenter: SplatSortCenterAdapter | null, center: THREE.Node<'vec3'>, poolIndex: THREE.Node<'int'>, texel: THREE.Node<'ivec2'>): THREE.Node<'vec3'>; /** * Optional per-source world transform for a unified {@link MergedSplatMesh} pool. * When present, each splat's center is transformed to world space by its * source's matrix (selected by a per-splat id read from `sourceIdTexture`) * before its depth is computed, so clouds with different world transforms sort * against each other correctly. Absent for an ordinary single-transform mesh. */ export interface PerSourceSortTransform { /** RedFormat float texture holding each pool slot's source id (the channel). */ sourceIdTexture: THREE.DataTexture; /** Shared array of source-matrix columns; see `SourceMatrixArray`. */ columns: ReturnType; /** CPU mirror of the source-id channel, used by the WebGL2 worker sorter. */ sourceIds: Float32Array; /** Column-major source matrices, used by the WebGL2 worker sorter. */ matrices: Float32Array; } /** * GPU depth sorter: a single-pass counting sort over 2¹⁶…2²² depth buckets, * sized once from pool capacity and running entirely in TSL compute passes on * the WebGPU backend. * * 1. clear - zero the histogram * 2. histogram - depth per active splat → bucket id; count per bucket * 3. scanBlocks - exclusive prefix sum within each 256-bucket block * 4. scanBlockSums - parallel exclusive scans over groups of block totals * 5. scanSuperSums - exclusive scan over the remaining super-block totals * 6. addBlockOffsets - combine both block-sum scan levels * 7. addOffsets - combine block and bucket offsets * 8. scatter - order[offset[bucket]++] = pool index (atomic) * * Why ~4M buckets, not 64K: on a large scene, 16-bit buckets made a * near-camera bucket span thousands of overlapping grass/leaf splats whose * arbitrary intra-bucket order reshuffled as the camera moved - visible * popping. Each depth bucket is now a sub-splat-width slice, so splats that * share a bucket are effectively coplanar and their (still arbitrary) order * cannot be seen. (A multi-pass radix would give exact order but needs a * *stable* scatter, which the parallel `atomicAdd` scatter is not - hence a * single wide pass instead.) * * Dynamic capacity: the sorter walks the mesh's `sourceIndex` buffer (pool * indices of the active splats) and sorts only the first `activeCount` * entries, so ranges can be appended and removed without rebuilding * pipelines - the per-splat passes are dispatched with a dynamic invocation * count and guarded by an `activeCount` uniform. * * Portable by construction: cross-workgroup communication only happens * through the implicit synchronization WebGPU guarantees between dispatches * - no spin-waits or scheduling assumptions. * * The depth range for bucket quantization comes from the mesh's bounding * sphere transformed to view space, so no GPU min/max reduction is needed. */ export declare class ComputeSorter implements SplatSorter { readonly kind: "counting"; /** Clear, histogram, scan and scatter stages in one accepted sort. */ readonly passCount = 8; private static readonly BUCKET_COUNT; private static readonly BLOCK_SIZE; private readonly renderer; /** Histogram slots reserved for this pool; never changes as residency changes. */ private readonly histogramBucketCount; private readonly clearPass; private readonly histogramPass; private readonly scanBlocksPass; private readonly scanBlockSumsPass; private readonly scanSuperBlockSumsPass; private readonly addBlockSumOffsetsPass; private readonly addOffsetsPass; private readonly scatterPass; /** All stages in dependency order, submitted as one WebGPU compute pass. */ private readonly sortPasses; private readonly indirectDispatchAttribute; /** Sorter-owned working buffers, released on {@link dispose}. */ private readonly workingAttributes; /** Frees the JS mirrors three keeps behind the GPU-only working buffers. */ private readonly mirrors; /** Set by {@link dispose}; makes a second dispose a no-op. */ private disposed; /** Accepted sort submissions; benchmark diagnostics only. */ submissionCount: number; /** Rows of the model-view matrix used by the selected sort metric. */ private readonly viewRow0; private readonly viewRow1; private readonly viewRow2; private readonly depthMin; private readonly depthScale; /** Active splat count; a float compares exactly for counts < 2²⁴. */ private readonly activeCount; /** Highest bucket index this sort uses; see {@link effectiveBucketCount}. */ private readonly bucketMax; /** Bucket count used by the most recent {@link sort}. Diagnostic. */ lastBucketCount: number; private readonly viewCenter; private readonly sortMetric; constructor(options: { renderer: THREE.WebGPURenderer; /** Pool capacity in splats; all buffers are sized once from this. */ capacity: number; /** RGBA32F texture holding splat centers (xyz), pool-indexed. */ centersTexture?: THREE.DataTexture; /** Width of the centers texture, to map pool index → texel. */ dataTextureWidth?: number; /** Work-buffer centers (xyzw per splat), as written by a gather pass. */ centersBuffer?: THREE.StorageBufferAttribute; /** The float `splatIndex` buffer the render material reads. */ splatIndexAttribute: THREE.StorageInstancedBufferAttribute; /** Pool indices of the active splats (first `activeCount` entries). */ sourceIndexAttribute: THREE.StorageBufferAttribute; /** Dense GPU-written indices to sort instead of the CPU active list. */ visibleIndexAttribute?: THREE.StorageBufferAttribute; /** Projection parameters whose `.w` is the cached sort key. */ projectedParametersAttribute?: THREE.StorageBufferAttribute; /** GPU-written visible count shared with the projection pass. */ visibleCountAttribute?: THREE.StorageBufferAttribute; /** GPU-written dispatch dimensions for the per-splat stages. */ indirectDispatchAttribute?: THREE.IndirectStorageBufferAttribute; /** Per-source world transform for a unified pool; omit for a single mesh. */ perSource?: PerSourceSortTransform; /** Camera-space ordering key. Default `'depth'`. */ sortMetric?: SplatSortMetric; /** Displaces texture-read centers before measuring; see `SplatSortCenterAdapter`. */ sortCenter?: SplatSortCenterAdapter; }); /** * Keep the allocated depth resolution for every sort. A coarse cover can span * the whole scene with few splats, and compute projection's visible list is * small exactly when the camera is close; shrinking the bucket count with * either count makes overlapping near splats share buckets, and the unstable * scatter then reshuffles them on every sort. Scaling buckets to the visible * count made a 4M SOG shimmer up close on a Pixel 8a (2026-10-13); with the * full 2^22 histogram it measured 54-60 fps there, within run-to-run noise. */ private effectiveBucketCount; /** Rounds a pool or live-splat count to the supported power-of-two range. */ private static bucketCountFor; sort(modelView: THREE.Matrix4, activeCount: number, bounds: THREE.Sphere, visibleRange?: SplatSortRange | null): boolean; dispose(): void; } /** * Frees the GPU buffers of storage attributes that never sat in a geometry. * The renderer has no public API for this, so it reaches for the renderer's * attribute map directly; a harmless no-op if the internal shape changes, and * idempotent (the map's `delete` ignores unknown entries). Shared by the * sorters and by owners of mesh-level storage attributes (`sourceIndex`, the * unified work buffer) on dispose. */ export declare function releaseRendererAttributes(renderer: THREE.WebGPURenderer, attributes: readonly THREE.BufferAttribute[]): void;