@voluma/vlam 0.2.1 → 0.2.2

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.
@@ -1 +1 @@
1
- {"version":3,"file":"splat-mesh-types-8QDjTbZO.js","sources":["../src/lib/lod-scheduler.ts","../src/lib/splat-mesh-types.ts"],"sourcesContent":["import * as THREE from 'three/webgpu';\nimport type { LodLeaf, LodManifest } from './lod-manifest';\nimport type { LodSource } from './lod-source';\n\n/**\n * A contiguous splat range within one chunk file, at one LOD level - the\n * unit the pool activates. Adjacent manifest leaves that resolve to the same\n * `(file, level)` and whose ranges abut are coalesced into one run, so the\n * pool sees a handful of large ranges instead of thousands of tiny leaves.\n */\nexport interface LodRun {\n readonly file: number;\n readonly level: number;\n readonly offset: number;\n readonly count: number;\n /** First manifest-leaf index this run covers. */\n readonly leafStart: number;\n /** One past the last covered leaf index. */\n readonly leafEnd: number;\n /**\n * Physical-coverage identity when several manifest leaves form one region.\n * A classic LCC cell may be split into fetch-sized leaves, but its slices\n * must still swap as one visible unit. Undefined retains interval-based\n * grouping for hierarchical sources.\n */\n readonly coverageGroup?: number;\n /**\n * Camera distance (mesh-local) of the nearest leaf in this run, from the\n * last {@link LodScheduler.computeDesiredRuns} pass. Streamed meshes use it\n * to fetch near detail before far coarse coverage. Absent on sources that\n * do not track per-leaf distance.\n */\n readonly distance?: number;\n /**\n * True when any leaf in this run intersects the view frustum (with the\n * scheduler's edge margin). Used to rank classic-path fetches so in-view\n * detail beats behind-camera work; absent when the source does not track it.\n */\n readonly inView?: boolean;\n /**\n * Fetch-only angular distance from the camera's forward axis. Smaller values\n * are nearer the screen centre. It never affects LOD selection or budget.\n */\n readonly screenImportance?: number;\n}\n\n/** Stable identity of a run, for diffing desired vs. resident sets. */\nexport function runKey(run: LodRun): string {\n return `${run.file}:${run.level}:${run.offset}:${run.count}`;\n}\n\n/** Sentinel level meaning \"this leaf is currently dropped (renders nothing)\". */\nconst DROPPED = -1;\n\n/**\n * Maximum splats in one run. Large contiguous regions are split into several\n * runs so no single pool append (and thus no single frame) does an unbounded\n * amount of copy + upload work. Split runs stay contiguous, so they still\n * upload as one coalesced rectangle.\n */\nconst MAX_RUN_SPLATS = 128_000;\n\n/** Hysteresis dead-band around each LOD distance threshold. */\nconst THRESHOLD_MARGIN = 0.1;\n/** Minimum time a leaf must hold a level before changing again, ms. */\nconst DWELL_MS = 500;\n/** Frustum test margin, as a fraction of each leaf's own size. */\nconst FRUSTUM_MARGIN = 0.1;\n/**\n * Out-of-frustum leaves act this many times farther away instead of being\n * hard-coarsened. Rotating the camera then re-ranks leaves smoothly (and\n * dwell applies), rather than mass-flipping edge leaves every frame -\n * PlayCanvas uses the same behind-camera-penalty idea.\n */\nconst FRUSTUM_PENALTY = 3;\n\n/**\n * Chooses a level of detail per spatial leaf from the camera, keeps the\n * total within a splat budget, and coalesces the result into runs.\n *\n * The scheduler is pure with respect to rendering: it takes a camera\n * position and frustum (both in the mesh's local space) and returns the set\n * of runs that should be resident. It owns only the small amount of state\n * needed for temporal stability (each leaf's current level and when it last\n * changed), so it is straightforward to drive from a test harness.\n *\n * LOD distance model (PlayCanvas-compatible): level 0 is used within\n * `lodBaseDistance`; each successive level covers a band `lodMultiplier`×\n * farther out. By default out-of-frustum leaves act {@link FRUSTUM_PENALTY}×\n * farther away. Formats with broad spatial cells can disable that bias so an\n * orbit does not churn already-refined cells at the frustum edges.\n *\n * The distance model only sets the *floor* and the *priority*: when the\n * distance-chosen set leaves budget unused, {@link fillBudget} promotes\n * in-frustum leaves nearest-first until its configured headroom target is\n * spent (90% by default). Formats can cap that optional refinement and avoid\n * a full-finest cut even when an explicitly large budget could hold it. The\n * budget\n * therefore decides how far refinement reaches - a desktop budget yields\n * full detail even with the whole scene in view, a mobile budget refines\n * only near the camera.\n */\nexport class LodScheduler implements LodSource {\n /** World-unit distance inside which the finest level (0) is used. */\n lodBaseDistance: number;\n /** Distance ratio between successive LOD levels. */\n lodMultiplier: number;\n /** Maximum active splats; the desired set is demoted to fit. */\n budget: number;\n\n private readonly leaves: readonly LodLeaf[];\n private readonly coarsest: number;\n /** Per leaf: lowest/highest LOD level that has data. */\n private readonly minLevel: Int32Array;\n private readonly maxLevel: Int32Array;\n /**\n * Per leaf: the distance *ambition* - the finest level the camera distance\n * asks for, with hysteresis/dwell applied. This is the hysteresis *state*:\n * only {@link selectLevels} writes it, so budget demotion can never feed\n * back into the dead-band/dwell logic and oscillate. With `fillPastDistance`\n * false, {@link fillBudget} restores {@link resolved} only up to here.\n */\n private readonly level: Int32Array;\n /**\n * Per leaf: the resolved target - the ambition capped to fit the budget by\n * {@link enforceBudget}, then refilled from leftover headroom by\n * {@link fillBudget} (or DROPPED). This is what {@link coalesceRuns} emits.\n */\n private readonly resolved: Int32Array;\n /** Per leaf: timestamp of the last distance-level change, for dwell. */\n private readonly changedAt: Float64Array;\n\n private readonly distance: Float64Array;\n private readonly inFrustum: Uint8Array;\n /** Leaves that must move through the budget cut together. */\n private readonly budgetGroups: readonly Uint32Array[];\n /** Per-leaf physical coverage group, when the manifest defines one. */\n private readonly coverageGroups: Int32Array;\n /** Whether view-frustum membership affects distance and fill priority. */\n private readonly frustumAware: boolean;\n /** Fraction of the usable budget that optional refinement may consume. */\n private readonly budgetFillFraction: number;\n /** Absolute cap on optional refinement; distance-selected detail may exceed it. */\n private readonly budgetFillCap: number;\n /** Whether a budget that holds every finest leaf forces a full-finest cut. */\n private readonly forceFinestWhenFits: boolean;\n /**\n * Leaves at or inside this camera distance always resolve to their finest\n * available level (no hysteresis climb). Classic LCC uses a multi-band\n * radius so adjacent broad cells do not paint coarse discs at startup.\n */\n private readonly forceFinestWithin: number | undefined;\n /**\n * When false, {@link fillBudget} only restores toward each leaf's\n * distance-selected {@link level} - never finer. Classic LCC sets this so\n * a mid-range cell does not fetch L0 only to demote to L1 once the cut\n * settles.\n */\n private readonly fillPastDistance: boolean;\n\n /**\n * What the last cut actually decided, for the HUD.\n *\n * The resident splat count alone cannot distinguish \"the scheduler asked for\n * this\" from \"the scheduler asked for more and the mesh could not apply it\",\n * and those have opposite fixes. Measured rather than inferred after a\n * zoomed-out `sandwijck` sat at exactly its coarsest total (190,730) with a\n * 600k budget - 68% of the budget unspent, with no way to see which stage\n * declined to spend it.\n */\n readonly stats = {\n /** Leaves the frustum test accepted - `fillBudget`'s candidate set. */\n inFrustum: 0,\n /** Total leaves in the tree. */\n leaves: 0,\n /** Splats implied by the resolved cut, before the mesh applies anything. */\n desired: 0,\n /** Splats `fillBudget` added on top of the distance-chosen levels. */\n filled: 0,\n };\n\n private readonly scratchBox = new THREE.Box3();\n private readonly scratchSize = new THREE.Vector3();\n private readonly scratchCenter = new THREE.Vector3();\n private readonly screenImportance: Float32Array;\n /** Whether the last selection pass received a camera-forward vector. */\n private hasScreenImportance = false;\n /**\n * Persistent leaf-index ordering scratch for {@link enforceBudget} and\n * {@link fillBudget}, sorted in place per call instead of allocating a\n * fresh `[...keys]` array. Comparators break ties on the index itself so\n * the order is identical to the stable `Array#sort` this replaces\n * (`TypedArray#sort` stability is not guaranteed).\n */\n private readonly orderScratch: Uint32Array;\n\n constructor(\n manifest: LodManifest,\n options: {\n budget: number;\n lodBaseDistance: number;\n lodMultiplier: number;\n frustumAware?: boolean;\n budgetFillFraction?: number;\n budgetFillCap?: number;\n forceFinestWhenFits?: boolean;\n forceFinestWithin?: number;\n /**\n * When false, leftover-budget fill never refines past the distance-\n * selected level (see {@link fillPastDistance}). Default true.\n */\n fillPastDistance?: boolean;\n },\n ) {\n this.leaves = manifest.leaves;\n this.coarsest = manifest.lodLevels - 1;\n this.budget = options.budget;\n this.lodBaseDistance = options.lodBaseDistance;\n this.lodMultiplier = options.lodMultiplier;\n this.frustumAware = options.frustumAware !== false;\n this.budgetFillFraction = options.budgetFillFraction ?? 0.9;\n this.budgetFillCap = options.budgetFillCap ?? Number.POSITIVE_INFINITY;\n this.forceFinestWhenFits = options.forceFinestWhenFits !== false;\n this.forceFinestWithin = options.forceFinestWithin;\n this.fillPastDistance = options.fillPastDistance !== false;\n if (this.budgetFillFraction <= 0 || this.budgetFillFraction > 1) {\n throw new RangeError('LodScheduler budgetFillFraction must be in (0, 1].');\n }\n if (!(this.budgetFillCap > 0)) {\n throw new RangeError('LodScheduler budgetFillCap must be positive.');\n }\n if (this.forceFinestWithin !== undefined && !(this.forceFinestWithin >= 0)) {\n throw new RangeError('LodScheduler forceFinestWithin must be >= 0.');\n }\n\n const n = this.leaves.length;\n this.minLevel = new Int32Array(n);\n this.maxLevel = new Int32Array(n);\n this.level = new Int32Array(n).fill(this.coarsest);\n this.resolved = new Int32Array(n).fill(this.coarsest);\n this.changedAt = new Float64Array(n);\n this.distance = new Float64Array(n);\n this.inFrustum = new Uint8Array(n);\n this.screenImportance = new Float32Array(n);\n this.orderScratch = new Uint32Array(n);\n this.coverageGroups = new Int32Array(n).fill(-1);\n\n const groups: number[][] = [];\n const explicitGroups = new Map<number, number>();\n for (let i = 0; i < n; i++) {\n const key = (this.leaves[i] as LodLeaf).budgetGroup;\n if (key === undefined) {\n groups.push([i]);\n continue;\n }\n let groupIndex = explicitGroups.get(key);\n if (groupIndex === undefined) {\n groupIndex = groups.length;\n explicitGroups.set(key, groupIndex);\n groups.push([]);\n }\n (groups[groupIndex] as number[]).push(i);\n this.coverageGroups[i] = key;\n }\n this.budgetGroups = groups.map((members) => Uint32Array.from(members));\n\n for (let i = 0; i < n; i++) {\n const lods = (this.leaves[i] as LodLeaf).lods;\n let min = this.coarsest;\n let max = 0;\n for (let l = 0; l < lods.length; l++) {\n if (lods[l] === undefined) continue;\n min = Math.min(min, l);\n max = Math.max(max, l);\n }\n this.minLevel[i] = min;\n this.maxLevel[i] = max;\n this.level[i] = max; // start coarse\n }\n }\n\n /**\n * Recomputes the desired resident run set for the current camera.\n *\n * @param cameraLocal - Camera position in the mesh's local space.\n * @param frustum - View frustum in the mesh's local space.\n * @param now - Monotonic timestamp (ms) for dwell hysteresis.\n */\n computeDesiredRuns(\n cameraLocal: THREE.Vector3,\n frustum: THREE.Frustum,\n now: number,\n cameraForward?: THREE.Vector3,\n ): LodRun[] {\n this.selectLevels(cameraLocal, frustum, now, cameraForward);\n // When the budget already holds every leaf's finest level, skip distance /\n // frustum demotion entirely. Otherwise a small rotate marks leaves\n // out-of-frustum (×{@link FRUSTUM_PENALTY}), coarsens them, and the mesh\n // aborts fine fetches / swaps to coarse LCC discs - then has to climb\n // back when they re-enter the view.\n if (this.forceFinestWhenFits && this.budget >= this.finestTotal()) {\n for (let i = 0; i < this.leaves.length; i++) {\n this.resolved[i] = this.minLevel[i] as number;\n }\n this.stats.desired = this.activeTotal();\n this.stats.filled = 0;\n return this.coalesceRuns();\n }\n // Copy the ambition into the resolved target, cap it to the budget, then\n // refill leftover headroom. Budget stages touch only `resolved`, never the\n // ambition/hysteresis state - a stationary camera therefore resolves the\n // same cut every pass instead of oscillating red↔orange.\n this.resolved.set(this.level);\n this.enforceBudget();\n const beforeFill = this.activeTotal();\n this.fillBudget();\n this.stats.desired = this.activeTotal();\n this.stats.filled = this.stats.desired - beforeFill;\n return this.coalesceRuns();\n }\n\n /** Total active splats implied by the current resolved levels. */\n private activeTotal(): number {\n let total = 0;\n for (let i = 0; i < this.leaves.length; i++) {\n const level = this.resolved[i] as number;\n if (level === DROPPED) continue;\n total += (this.leaves[i] as LodLeaf).lods[level]?.count ?? 0;\n }\n return total;\n }\n\n /** Splats if every leaf sat at its finest available level (none dropped). */\n private finestTotal(): number {\n let total = 0;\n for (let i = 0; i < this.leaves.length; i++) {\n const level = this.minLevel[i] as number;\n total += (this.leaves[i] as LodLeaf).lods[level]?.count ?? 0;\n }\n return total;\n }\n\n private selectLevels(\n cameraLocal: THREE.Vector3,\n frustum: THREE.Frustum,\n now: number,\n cameraForward?: THREE.Vector3,\n ): void {\n const { lodBaseDistance: base, lodMultiplier: m } = this;\n this.hasScreenImportance = cameraForward !== undefined;\n let visibleCount = 0;\n this.stats.leaves = this.leaves.length;\n for (let i = 0; i < this.leaves.length; i++) {\n const leaf = this.leaves[i] as LodLeaf;\n const d = leaf.bounds.distanceToPoint(cameraLocal);\n this.distance[i] = d;\n\n // Widen the box by a fraction of its own size for edge stability.\n this.scratchBox.copy(leaf.bounds);\n leaf.bounds.getSize(this.scratchSize);\n this.scratchBox.expandByScalar(this.scratchSize.length() * FRUSTUM_MARGIN);\n const visible = frustum.intersectsBox(this.scratchBox);\n this.inFrustum[i] = visible ? 1 : 0;\n if (visible) visibleCount++;\n\n // Broad classic-LCC tiles frequently all intersect the frustum, so the\n // boolean above cannot tell the centre of the screen from its edges.\n // This is deliberately fetch metadata only: distance remains the source\n // of truth for the resolved LOD and the budget cut.\n if (cameraForward) {\n leaf.bounds.getCenter(this.scratchCenter).sub(cameraLocal);\n const depth = this.scratchCenter.dot(cameraForward);\n const lateralSquared = Math.max(0, this.scratchCenter.lengthSq() - depth * depth);\n this.screenImportance[i] =\n depth > 0 ? Math.sqrt(lateralSquared) / Math.max(depth, 0.25) : Number.POSITIVE_INFINITY;\n } else {\n this.screenImportance[i] = 0;\n }\n\n const current = this.level[i] as number;\n // Blanket force-finest only when fill may still climb past the distance\n // band (octree / pagetable). Classic LCC never uses this path.\n if (\n this.fillPastDistance &&\n this.forceFinestWithin !== undefined &&\n d <= this.forceFinestWithin\n ) {\n const finest = this.minLevel[i] as number;\n if (current !== finest) {\n this.level[i] = finest;\n this.changedAt[i] = now;\n }\n continue;\n }\n\n const effectiveDistance = !this.frustumAware || visible ? d : d * FRUSTUM_PENALTY;\n\n // Classic LCC: the ambition tracks the pure distance band only. Budget\n // demotions live in `resolved`, never here, so they cannot feed back\n // into hysteresis. A cold cell snaps straight to its band (no dwell\n // climb through intermediate LODs); afterward only a band *crossing*\n // moves the ambition - a stationary camera in the same band holds,\n // even if the budget just demoted its resolved level.\n if (!this.fillPastDistance) {\n const band = this.distanceBandLevel(i, effectiveDistance, base, m);\n const coldStart =\n (this.changedAt[i] as number) === 0 && current === (this.maxLevel[i] as number);\n if (coldStart) {\n if (band !== current) {\n this.level[i] = band;\n this.changedAt[i] = now;\n }\n continue;\n }\n if (band === current) continue;\n const proposed = this.hysteresisLevel(i, effectiveDistance, base, m, current);\n if (proposed === current) continue;\n // Coarsen immediately (moving away should not linger over budget);\n // only refinement waits out the dwell window.\n const coarsening = proposed > current;\n if (coarsening || now - (this.changedAt[i] as number) >= DWELL_MS) {\n this.level[i] = proposed;\n this.changedAt[i] = now;\n }\n continue;\n }\n\n const proposed = this.hysteresisLevel(i, effectiveDistance, base, m, current);\n if (proposed === current) continue;\n const coldSnap =\n (this.changedAt[i] as number) === 0 && current === (this.maxLevel[i] as number);\n if (coldSnap || now - (this.changedAt[i] as number) >= DWELL_MS) {\n this.level[i] = proposed;\n this.changedAt[i] = now;\n }\n }\n this.stats.inFrustum = visibleCount;\n }\n\n /**\n * Pure distance→level band (independent of the leaf's current level), so a\n * classic LCC cut never has to dwell through intermediate rungs.\n */\n private distanceBandLevel(index: number, d: number, base: number, m: number): number {\n const min = this.minLevel[index] as number;\n const max = this.maxLevel[index] as number;\n let level = min;\n while (level < max && d > base * m ** level * (1 + THRESHOLD_MARGIN)) level++;\n return this.resolveAvailable(index, level);\n }\n\n /**\n * Stable level from distance: coarsen only past `threshold·(1 + margin)`,\n * refine only within `threshold·(1 − margin)`. The available-level clamp\n * keeps leaves that lack a level on their nearest coarser one.\n */\n private hysteresisLevel(\n index: number,\n d: number,\n base: number,\n m: number,\n current: number,\n ): number {\n const min = this.minLevel[index] as number;\n const max = this.maxLevel[index] as number;\n let level = Math.min(max, Math.max(min, current));\n // threshold(L) = base·m^L is the boundary between level L and L+1.\n while (level < max && d > base * m ** level * (1 + THRESHOLD_MARGIN)) level++;\n while (level > min && d <= base * m ** (level - 1) * (1 - THRESHOLD_MARGIN)) level--;\n // Resolve to the nearest available level (prefer coarser) if this exact\n // one has no data (leaves need not carry every level).\n return this.resolveAvailable(index, level);\n }\n\n private resolveAvailable(index: number, target: number): number {\n const lods = (this.leaves[index] as LodLeaf).lods;\n for (let l = target; l <= (this.maxLevel[index] as number); l++) if (lods[l]) return l;\n for (let l = target - 1; l >= (this.minLevel[index] as number); l--) if (lods[l]) return l;\n return this.maxLevel[index] as number;\n }\n\n /** Demotes/drops lowest-priority leaves until the total fits the budget. */\n private enforceBudget(): void {\n let total = this.activeTotal();\n if (total <= this.budget) return;\n\n // Demote lowest priority first. When frustum-aware: out-of-frustum before\n // in-frustum, then farthest. Classic LCC sets frustumAware false - broad\n // XY cells often sit mostly behind the camera while the user stands in\n // them (d≈0); frustum demotion would coarsen that cell first and let\n // thinner cells ahead keep fine detail (backwards load). Distance only.\n const order = this.orderScratch.subarray(0, this.budgetGroups.length);\n for (let i = 0; i < order.length; i++) order[i] = i;\n order.sort((a, b) => {\n const ia = (this.budgetGroups[a] as Uint32Array)[0] as number;\n const ib = (this.budgetGroups[b] as Uint32Array)[0] as number;\n if (this.frustumAware) {\n const fa = this.inFrustum[ia] as number;\n const fb = this.inFrustum[ib] as number;\n if (fa !== fb) return fa - fb; // out-of-frustum (0) first\n }\n return (this.distance[ib] as number) - (this.distance[ia] as number) || ia - ib;\n });\n\n // Pass 1: coarsen toward the coarsest available level.\n for (const groupIndex of order) {\n const group = this.budgetGroups[groupIndex] as Uint32Array;\n while (total > this.budget) {\n let reduction = 0;\n let changed = false;\n for (const i of group) {\n const current = this.resolved[i] as number;\n if (current >= (this.maxLevel[i] as number)) continue;\n const lods = (this.leaves[i] as LodLeaf).lods;\n const nextLevel = this.resolveAvailable(i, current + 1);\n if (nextLevel === current) continue;\n reduction += (lods[current]?.count ?? 0) - (lods[nextLevel]?.count ?? 0);\n this.resolved[i] = nextLevel;\n changed = true;\n }\n if (!changed) break;\n total -= reduction;\n }\n if (total <= this.budget) return;\n }\n\n // Pass 2 (last resort): drop groups entirely, lowest priority first.\n for (const groupIndex of order) {\n if (total <= this.budget) return;\n for (const i of this.budgetGroups[groupIndex] as Uint32Array) {\n if ((this.resolved[i] as number) === DROPPED) continue;\n total -= (this.leaves[i] as LodLeaf).lods[this.resolved[i] as number]?.count ?? 0;\n this.resolved[i] = DROPPED;\n }\n }\n }\n\n /**\n * Uses leftover budget to restore detail after {@link enforceBudget}\n * demoted leaves, nearest first, while the total stays under the fill\n * target. By default this may also refine *past* the distance-chosen level\n * when headroom remains (octree / pagetable streams). With\n * {@link fillPastDistance} false (classic LCC), fill never goes finer than\n * each leaf's distance-selected level - so a cell at the L1 band does not\n * fetch L0 only to demote moments later with the camera still.\n */\n private fillBudget(): void {\n const target =\n this.forceFinestWhenFits && this.budget >= this.finestTotal()\n ? this.budget\n : Math.min(this.budget, this.budgetFillCap) * this.budgetFillFraction;\n let total = this.activeTotal();\n if (total >= target) return;\n\n // Candidate in-frustum groups, nearest first (ties keep manifest order),\n // packed into the front of the shared index scratch.\n let candidateCount = 0;\n for (let groupIndex = 0; groupIndex < this.budgetGroups.length; groupIndex++) {\n const first = (this.budgetGroups[groupIndex] as Uint32Array)[0] as number;\n if (\n (!this.frustumAware || this.inFrustum[first] === 1) &&\n (this.resolved[first] as number) !== DROPPED\n ) {\n this.orderScratch[candidateCount++] = groupIndex;\n }\n }\n const order = this.orderScratch.subarray(0, candidateCount);\n order.sort((a, b) => {\n const ia = (this.budgetGroups[a] as Uint32Array)[0] as number;\n const ib = (this.budgetGroups[b] as Uint32Array)[0] as number;\n return (this.distance[ia] as number) - (this.distance[ib] as number) || ia - ib;\n });\n\n // Nearest groups refine first (up to the distance floor when capped).\n for (const groupIndex of order) {\n const group = this.budgetGroups[groupIndex] as Uint32Array;\n while (true) {\n let growth = 0;\n let canPromote = false;\n for (const i of group) {\n const current = this.resolved[i] as number;\n const floor = this.fillPastDistance\n ? (this.minLevel[i] as number)\n : (this.level[i] as number);\n if (current <= floor) continue;\n const leaf = this.leaves[i] as LodLeaf;\n let finer = current - 1;\n while (finer > floor && !leaf.lods[finer]) finer--;\n if (finer < floor || !leaf.lods[finer]) continue;\n growth += (leaf.lods[finer]?.count ?? 0) - (leaf.lods[current]?.count ?? 0);\n canPromote = true;\n }\n if (!canPromote || total + growth > target) break;\n for (const i of group) {\n const current = this.resolved[i] as number;\n const floor = this.fillPastDistance\n ? (this.minLevel[i] as number)\n : (this.level[i] as number);\n if (current <= floor) continue;\n const leaf = this.leaves[i] as LodLeaf;\n let finer = current - 1;\n while (finer > floor && !leaf.lods[finer]) finer--;\n if (finer >= floor && leaf.lods[finer]) this.resolved[i] = finer;\n }\n total += growth;\n }\n }\n }\n\n private coalesceRuns(): LodRun[] {\n return this.buildRuns(0, this.leaves.length, (i) => this.resolved[i] as number);\n }\n\n /**\n * Runs covering [from, to) at each leaf's coarsest available level - used\n * to substitute always-cached coverage while a finer level is fetching.\n */\n coarsestRunsFor(from: number, to: number): LodRun[] {\n return this.buildRuns(from, to, (i) => this.maxLevel[i] as number);\n }\n\n /**\n * Runs covering [from, to) at `level`, clamped per leaf to an available rung\n * (prefer the requested level, else the next coarser, else the next finer).\n */\n runsAtLevelFor(from: number, to: number, level: number): LodRun[] {\n const wanted = Math.floor(level);\n return this.buildRuns(from, to, (i) => this.clampLeafLevel(i, wanted));\n }\n\n /** Prefer `wanted`, else next coarser, else next finer; {@link DROPPED} if none. */\n private clampLeafLevel(leafIndex: number, wanted: number): number {\n const leaf = this.leaves[leafIndex] as LodLeaf;\n if (leaf.lods[wanted]) return wanted;\n for (let l = wanted + 1; l < leaf.lods.length; l++) {\n if (leaf.lods[l]) return l;\n }\n for (let l = wanted - 1; l >= 0; l--) {\n if (leaf.lods[l]) return l;\n }\n return DROPPED;\n }\n\n /** Coalesces leaves [from, to) at `levelOf(leaf)` into contiguous runs. */\n private buildRuns(from: number, to: number, levelOf: (index: number) => number): LodRun[] {\n const runs: LodRun[] = [];\n let file = -1;\n let level = -1;\n let offset = 0;\n let count = 0;\n let leafStart = -1;\n let leafEnd = -1;\n let coverageGroup = -1;\n let distance = Number.POSITIVE_INFINITY;\n let inView = false;\n let screenImportance = Number.POSITIVE_INFINITY;\n const flush = (): void => {\n if (count > 0) {\n runs.push({\n file,\n level,\n offset,\n count,\n leafStart,\n leafEnd,\n distance,\n inView,\n ...(this.hasScreenImportance ? { screenImportance } : {}),\n ...(coverageGroup >= 0 ? { coverageGroup } : {}),\n });\n }\n count = 0;\n };\n\n for (let i = from; i < to; i++) {\n const l = levelOf(i);\n if (l === DROPPED) {\n flush();\n continue;\n }\n const range = (this.leaves[i] as LodLeaf).lods[l];\n if (!range) {\n flush();\n continue;\n }\n const leafCoverageGroup = this.coverageGroups[i] as number;\n const leafDistance = this.distance[i] as number;\n const leafInView = (this.inFrustum[i] as number) === 1;\n if (\n count > 0 &&\n range.file === file &&\n l === level &&\n leafCoverageGroup === coverageGroup &&\n range.offset === offset + count &&\n count + range.count <= MAX_RUN_SPLATS\n ) {\n count += range.count; // extend the current run\n leafEnd = i + 1;\n if (leafDistance < distance) distance = leafDistance;\n if (leafInView) inView = true;\n screenImportance = Math.min(screenImportance, this.screenImportance[i] as number);\n } else {\n flush();\n file = range.file;\n level = l;\n offset = range.offset;\n count = range.count;\n leafStart = i;\n leafEnd = i + 1;\n coverageGroup = leafCoverageGroup;\n distance = leafDistance;\n inView = leafInView;\n screenImportance = this.screenImportance[i] as number;\n }\n }\n flush();\n return runs;\n }\n}\n","/** Public configuration and result types for SplatMesh. */\nimport type * as THREE from 'three/webgpu';\nimport type { SplatData } from './splat-data';\nimport type { SplatOrientation } from './orientation';\nimport type { SplatModifier } from './splat-modifier';\nimport {\n detectSplatDeviceProfile,\n isFillConstrainedSplatDevice,\n type SplatDeviceProfile,\n} from './splat-budget';\nimport type { SplatPool } from './splat-mesh-pool';\nimport type { SplatShInputs, Vec3Uniform } from './splat-mesh-material';\n\n/** Construction-time projected-footprint policy selected by a streamed format. */\nexport type ProjectedFilterProfile = 'default' | 'lcc';\n\n/**\n * Opaque handle for a range of splats appended to a {@link SplatMesh},\n * used to remove the range again.\n */\nexport interface SplatRange {\n /** Number of splats in this range. */\n readonly count: number;\n}\n\n/**\n * Storage format of a per-splat channel (see {@link SplatMesh.defineChannel}).\n *\n * - `'byte'`: one `Uint8` per splat (`r8unorm`). Compact - a good fit for\n * masks and labels. `ctx.channel(name)` reads it back **normalized** to\n * `[0, 1]`, so a painted `255` reads as `1.0`.\n * - `'float'`: one `Float32` per splat (`r32float`), read back verbatim.\n */\nexport type SplatChannelType = 'byte' | 'float';\n\n/** Options for {@link SplatMesh.defineChannel}. */\nexport interface SplatChannelOptions {\n /** Storage format; default `'float'`. */\n type?: SplatChannelType;\n /**\n * Value every splat starts at before any {@link SplatMesh.writeChannel}.\n * Default `0`. For `'byte'` channels this is a raw `0..255` value.\n */\n fill?: number;\n}\n\n/** The highest SH order this renderer evaluates (3rd → 15 coefficients). */\nexport const MAX_SH_BANDS = 3;\n\n/**\n * The contribution-culling profile a mesh will use, given an optional\n * explicit override. Exported so callers that must decide something *before*\n * constructing the mesh - such as whether a streamed scene should fetch its\n * SH at all - agree with what the mesh itself will pick.\n */\nexport function resolveSplatPerformanceProfile(\n explicit?: SplatPerformanceProfile,\n profile: SplatDeviceProfile | undefined = detectSplatDeviceProfile(),\n): SplatPerformanceProfile {\n return explicit ?? (isFillConstrainedSplatDevice(profile) ? 'smooth' : 'quality');\n}\n\n/** Construction options for {@link SplatMesh}. */\nexport interface SplatMeshOptions {\n /**\n * Storage for per-splat higher-order SH in a dynamic-capacity pool, in\n * bands (1, 2 or 3 → 3, 8 or 15 coefficients per channel); 0 (default)\n * allocates nothing.\n *\n * Only formats that store SH per splat can fill this - LCC `Quality`, `.rad`, etc.\n * It costs 16 bytes per splat per band-group of four\n * coefficients (64 B/splat at 3 bands), so it is opt-in. On a static mesh\n * this is ignored: packed SH is taken from `source.shPacked` when present,\n * otherwise palette `source.sh` (SOG).\n */\n shBands?: 0 | 1 | 2 | 3;\n /**\n * Minimum interval between WebGPU sorts while the camera moves. When\n * omitted, the interval adapts to the active splat count. Use `0` to sort\n * every changed frame. WebGL worker sorting is unaffected.\n */\n sortIntervalMs?: number;\n /**\n * WebGPU sorter used for A/B validation. Defaults to the proven counting\n * sorter. `'radix'` keeps the fast 24-bit key path; `'exact'` lazy-loads a\n * stable 32-bit Float32-depth radix path that avoids scene-range\n * quantization. The first frames may skip sorting until the module resolves.\n *\n * @experimental Radix strategies may change in a minor release.\n */\n sortStrategy?: SplatSortStrategy;\n /**\n * Render-quality policy. `smooth` rejects negligible projected contributions.\n *\n * The default is device-aware: `smooth` on mobile (where rejecting splats too\n * small or too faint to see is worth far more than it costs), `quality`\n * everywhere else. Passing a value opts out of the detection.\n */\n performanceProfile?: SplatPerformanceProfile;\n /**\n * How far out, in standard deviations, each Gaussian is drawn before it is\n * cut off. Every splat is an alpha-blended quad sized to this radius, so it\n * sets how much each one costs to blend - the dominant cost in a busy view.\n * Lowering it shrinks every quad and clips the faint outer tail of each\n * Gaussian; the falloff within the remaining radius is unchanged.\n *\n * Defaults to `3`, the reference 3DGS rasterizer's radius. Below ~2 the\n * truncation shows as visible splat edges; much above ~5 the extra fill is not\n * worth it. Mobile coverage gaps are handled by `minSplatSizePx` instead of\n * growing every splat.\n */\n maxStdDev?: number;\n /**\n * Floor, in viewport pixels, on each rendered splat's projected quad radius.\n *\n * A screen-space *minimum* size, the counterpart to `maxScreenRadiusPx`'s\n * maximum. When a splat projects smaller than this - because it is distant, or\n * because the whole scene is zoomed out - its quad is grown to this radius and\n * the Gaussian is stretched to fill it (the falloff normalizes to the quad, so\n * no hard edge appears). Splats already larger are untouched, so it costs no\n * extra fill on the near-camera splats that dominate overdraw.\n *\n * This is the fix for the \"dark gaps when zoomed out\" failure mode: a capture\n * whose finest splats are spaced farther apart than their footprint leaves the\n * background showing between them, and the effect is worst at low resolution -\n * i.e. on a phone. Raising `maxStdDev` also closes the gaps but inflates\n * *every* splat's fragment count by its square, paying the coverage cost on the\n * large splats too; this floor spends it only where a gap can actually open.\n *\n * Defaults to `1.5` px on mobile and `0` (disabled) elsewhere, including\n * fill-constrained desktops. Values around 1–3 px close typical gaps; too\n * large a floor blurs distinct small features into discs, so tune it up from\n * small on the target device. An explicit `0` always disables the floor.\n */\n minSplatSizePx?: number;\n /**\n * Apply the Mip-Splatting 2D antialiasing filter - the screen-space low-pass\n * dilation plus the opacity compensation that conserves each Gaussian's\n * integral, so small/distant splats stop over-brightening. Match the\n * exporter: enable it for scenes trained/exported with antialiasing (the SOG\n * `antialias` meta flag sets this automatically). Defaults to `false` (the\n * classic 3DGS dilation without compensation).\n */\n antialias?: boolean;\n /**\n * Internal format-selected reconstruction profile. Classic LCC uses the\n * XGRIDS-compatible 0.1 px² compensated low-pass; callers should leave this\n * unset and select a format through {@link StreamedSplatMesh.load} instead.\n *\n * @internal\n */\n projectedFilterProfile?: ProjectedFilterProfile;\n /**\n * Emit splat colors in sRGB (display) space instead of decoding them to the\n * renderer's linear working space. Pair with a renderer that skips output\n * conversion (`outputColorSpace = LinearSRGBColorSpace`, `NoToneMapping`,\n * inline sRGB encode for other materials via `renderer.contextNode`): splats\n * then alpha-composite on gamma-encoded values - the math 3DGS training\n * optimizes against, and what WebGL splat viewers render. Defaults to\n * `false` (linear working-space compositing).\n */\n srgbOutput?: boolean;\n /**\n * Cull any splat whose projected on-screen radius exceeds this many pixels,\n * rendering a hole instead. A physically large splat close to the camera -\n * a coarse merged LOD node (a Spark `.rad` \"blob\"), or a giant background\n * Gaussian - projects huge while a fine surface splat stays small, so this\n * removes the near-camera blobs without touching detailed geometry. `0` or\n * unset disables it (the default). Baked into the material graph.\n */\n maxSplatScreenRadius?: number;\n /**\n * Foveation band lower bound (px): cull any splat whose projected on-screen\n * radius is *below* this. Paired with {@link maxSplatScreenRadius}, only\n * splats sized `(min, max]` on screen draw. Because a `.rad` LOD tree's node\n * sizes shrink geometrically, exactly one level per view ray lands in the\n * band - near rays on fine leaves, far rays on coarse nodes - giving a\n * camera-distance foveated cut. `0` or unset disables it (the default).\n * Baked into the material graph. See `docs/formats/rad-notes.md` M14.6.\n */\n minSplatScreenRadius?: number;\n /**\n * How a `.rad` foveated mesh picks its per-splat LOD cut:\n * - `'band'` (default): the screen-radius band above\n * ({@link minSplatScreenRadius}, {@link maxSplatScreenRadius}].\n * - `'frontier'`: Spark's exact tree cut - draw splat `i` iff its parent is\n * too big and it is small enough (`parentPixelScale > limit ≥ ownPixelScale`),\n * using per-splat `own_size`/`parent_size`. Full coverage by construction, no\n * band leapfrogging. Baked into the material graph. See `docs/formats/rad-notes.md`.\n * - `'pagetable'`: the {@link StreamedSplatMesh} default for `.rad` - a worker\n * owns the tree traversal and pages only the *selected* frontier into the\n * pool (Spark's selected-index model), so the whole splat budget buys\n * on-screen detail. Requires the streamed `.rad` machinery; on a plain\n * `SplatMesh` it has no worker to drive it.\n *\n * @experimental `.rad` foveation option; may change in a minor release.\n */\n foveationMode?: 'band' | 'frontier' | 'pagetable';\n /**\n * Target on-screen size (px) for the frontier / page-table cut: it keeps one\n * LOD level per view ray whose projected node size is about this. Larger =\n * coarser/fewer splats, smaller = finer/denser. Default\n * {@link DEFAULT_FOVEATION_TARGET_PX} (1, matching Spark's `lodRenderScale`),\n * so the draw budget rather than the cut size is what bounds detail. Raise it\n * to trade sharpness for fill rate on weak GPUs.\n * Acts as the *finest* bound: the adaptive limit coarsens above it to hold the\n * draw budget but never dips below it.\n *\n * @experimental `.rad` foveation option; may change in a minor release.\n */\n foveationTargetPx?: number;\n /**\n * Target upper bound on the number of splats the frontier cut *draws*\n * (Spark's `maxSplats`). Each reschedule the cut's `pixelScaleLimit`\n * self-adjusts - coarsening when the estimated drawn count exceeds this - so\n * frame cost stays bounded as detail streams in. Default\n * {@link DEFAULT_FOVEATION_DRAW_BUDGET}. Only used in `'frontier'` mode.\n *\n * @experimental `.rad` foveation option; may change in a minor release.\n */\n foveationDrawBudget?: number;\n /**\n * Cap on a rendered splat's major/minor axis ratio (`0`/unset = off). A very\n * anisotropic Gaussian (a flat 3DGS disk edge-on, or an expansion-enlarged\n * coarse LOD node) otherwise projects to a long needle; this bounds its drawn\n * length to `maxSplatAspect`× its width. Baked into the material graph.\n *\n * @experimental `.rad` foveation option; may change in a minor release.\n */\n maxSplatAspect?: number;\n /**\n * Spark's LOD alpha encoding (`.rad`): the stored opacity is `alpha/2` so the\n * shader recovers `alpha ∈ [0,2]`, and `alpha > 1` marks a merged node rendered\n * with a grown σ-cutoff + super-Gaussian falloff. Set for foveated `.rad`.\n *\n * @experimental `.rad` foveation option; may change in a minor release.\n */\n lodAlpha?: boolean;\n /**\n * How the scene is oriented into the three.js Y-up world. `'y-up'` (default)\n * normalizes every known format to Y-up - 3DGS Y-down formats\n * (PLY/`.splat`/`.ksplat`/SOG) are flipped 180° about X; SPZ/`.rad` are\n * already Y-up; LCC keeps its own Z-up→Y-up matrix. `'source'` applies no\n * cosmetic flip and renders in the data frame (raw Spark / mkkellogg parity);\n * LCC still self-orients (that is format semantics, not part of the switch).\n *\n * For a static mesh the flip is chosen from {@link SplatData.sourceFormat}\n * (stamped by the loaders); a dynamic-capacity mesh carries no format, so its\n * host applies {@link yUpTransformForFormat} itself. See {@link SplatOrientation}.\n */\n orientation?: SplatOrientation;\n /**\n * GPU storage type for the pool's continuous float textures (`centers` and\n * `covarianceA`). `'float16'` uploads them as `rgba16float` (~16 B/splat\n * saved vs the default). CPU backing stays float32 (sorter, query, writes).\n *\n * `covarianceB` is always float32: it packs integer IDs (SOG palette labels,\n * RAD frontier parents) that half floats cannot represent exactly above\n * 2048. Colors and packed SH are unchanged. Construction-time only.\n */\n poolFloatTextures?: 'float32' | 'float16';\n /**\n * An existing pool to draw from instead of allocating one.\n *\n * Several meshes sharing a pool share its memory envelope: rows go to\n * whichever mesh needs them, so a mesh the camera is near can hold far more\n * than an even split would give it, and one that is far away holds almost\n * nothing - without every mesh having reserved a private ceiling up front.\n * This is the multi-mesh analogue of a single streamed mesh's LOD budget.\n *\n * The pool is *not* owned by the mesh: {@link SplatMesh.dispose} releases the\n * mesh's rows and leaves the textures alone, so the pool's creator disposes\n * it once every tenant is gone. `capacity` on the source is then only used\n * for the mesh's own draw list, not to size storage.\n *\n * Sharing costs a whole-pool stall when the pool fragments - see\n * {@link SplatMesh.compact}.\n */\n pool?: SplatPool;\n /**\n * The device's `maxTextureDimension2D`, forwarded to a pool this mesh\n * allocates for itself so an over-tall pool fails at construction with a\n * readable error instead of at first draw. Pass `deviceMaxTextureSize(renderer)`.\n *\n * Ignored when {@link SplatMeshOptions.pool} supplies the pool - that pool\n * was already checked when its creator built it.\n */\n maxTextureSize?: number;\n}\n\n/** Available WebGPU depth-sort implementations. */\nexport type SplatSortStrategy = 'counting' | 'radix' | 'exact';\n\n/** Controls optional work during a per-frame source update. */\nexport interface SplatUpdateOptions {\n /** Leave sorting to {@link UnifiedSplatRenderer}; uploads and LOD state still update. */\n sort?: boolean;\n}\n\n/**\n * Read-only GPU-facing view of a mesh's current active pool. It is consumed by\n * the M15.4 unified gather path; streamed meshes expose their current LOD cut\n * through the same view because they inherit {@link SplatMesh}.\n *\n * @experimental May change in a minor release.\n */\nexport interface UnifiedSourceView {\n /** Total addressable pool slots. */\n readonly capacity: number;\n /** Pool indices of active splats, packed from zero. */\n readonly sourceIndex: THREE.StorageBufferAttribute;\n /** Active entries at the front of {@link sourceIndex}. */\n readonly activeCount: number;\n /** Local-space centers, RGBA32F and pool-indexed. */\n readonly centersTexture: THREE.DataTexture;\n /** Source display color and opacity, RGBA8 and pool-indexed. */\n readonly colorsTexture: THREE.DataTexture;\n /** Upper covariance rows, RGBA32F and pool-indexed. */\n readonly covarianceATexture: THREE.DataTexture;\n /** Final covariance row, RGBA32F and pool-indexed. */\n readonly covarianceBTexture: THREE.DataTexture;\n /** Centers texture row width. */\n readonly dataTextureWidth: number;\n /** Current source-local → world transform. */\n readonly matrixWorld: THREE.Matrix4;\n /** Conservative world-space bound for depth quantization. */\n readonly worldBounds: THREE.Sphere;\n /** Higher-order color data resolved by the gather pass when present. */\n readonly sh: SplatShInputs | null;\n /** Effect hooks and their source-local data channels. */\n readonly modifiers: readonly SplatModifier[];\n /**\n * True when this source is itself a unified pool with per-source placement\n * (`SplatScene`). The gather path cannot resolve nested placement, so\n * `UnifiedSplatRenderer` rejects these sources.\n */\n readonly hasSourcePlacement: boolean;\n readonly channels: ReadonlyMap<string, { texture: THREE.DataTexture }>;\n /** Same uniform node the source graph updates each frame. */\n readonly localCameraPosition: Vec3Uniform;\n /** Changes whenever a modifier graph must be rebuilt. */\n readonly graphRevision: number;\n /** Whether this source intentionally composites in display (sRGB) space. */\n readonly srgbOutput: boolean;\n /** Shared draw-path settings that must agree across unified sources. */\n readonly maxStdDev: number;\n /** Screen-space minimum splat radius, px (0 = off). */\n readonly minSplatSizePx: number;\n readonly antialias: boolean;\n /** Construction-time projected-footprint policy shared by one unified pass. */\n readonly projectedFilterProfile: ProjectedFilterProfile;\n /**\n * Whether this source stores Spark LOD alpha (`alpha ÷ 2`, `.rad`). The\n * gather recovers the full `alpha ∈ [0,2]`; the draw material then treats\n * `alpha > 1` as a merged node. Per source, not a compatibility field - a\n * scene may mix `.rad` and non-`.rad` sources.\n */\n readonly lodAlpha: boolean;\n /** Increments whenever pool-backed data or active residency changes. */\n readonly contentRevision: number;\n}\n\n/** Quality-compatible rendering or smoother contribution-culling rendering. */\nexport type SplatPerformanceProfile = 'quality' | 'smooth';\n\n/**\n * Options for {@link SplatMesh.pick}.\n *\n * Picking returns the selected splat's rendered center plane (depth-tested\n * Gaussian coverage), not a persistent splat identifier or a collision mesh.\n */\nexport interface SplatPickOptions {\n /**\n * Minimum Gaussian opacity (after falloff × splat alpha) for a fragment to\n * count as a hit. Default `0.1`.\n */\n alphaThreshold?: number;\n}\n\n/**\n * Result of a successful {@link SplatMesh.pick}.\n *\n * The point lies on the frontmost splat's billboard plane at the picked\n * pixel - suitable for click-to-focus and placement anchors, not physics.\n */\nexport interface SplatPickResult {\n /** Hit position in world space. */\n readonly point: THREE.Vector3;\n /** Distance from the camera position to {@link point}. */\n readonly distance: number;\n}\n\n/**\n * Result of {@link SplatMesh.queryNearest}: the resident splat center closest\n * to the query point, in world space.\n */\nexport interface SplatNearestResult {\n /** The splat's center, in world space. */\n readonly point: THREE.Vector3;\n /** World-space distance from the query point to {@link point}. */\n readonly distance: number;\n}\n\n/** Result of a successful synchronous {@link SplatMesh.queryRay}. */\nexport interface SplatRayResult {\n /** Resident splat center in world space. */\n readonly point: THREE.Vector3;\n /** Distance along the ray from its origin to the center's closest plane. */\n readonly distance: number;\n}\n\n/**\n * Result of {@link SplatMesh.queryHeight}: the supporting surface found beneath\n * the query point (the highest resident splat within the drop and horizontal\n * radius), in world space.\n */\nexport interface SplatHeightResult {\n /** The supporting splat's center, in world space. */\n readonly point: THREE.Vector3;\n /** How far below the query point the surface sits (world units, ≥ 0). */\n readonly drop: number;\n}\n"],"names":["runKey","run","DROPPED","MAX_RUN_SPLATS","THRESHOLD_MARGIN","DWELL_MS","FRUSTUM_MARGIN","FRUSTUM_PENALTY","LodScheduler","manifest","options","__publicField","THREE","n","groups","explicitGroups","i","key","groupIndex","members","lods","min","max","l","cameraLocal","frustum","now","cameraForward","beforeFill","total","level","_a","base","m","visibleCount","leaf","d","visible","depth","lateralSquared","current","finest","effectiveDistance","band","proposed","index","target","order","a","b","ia","ib","fa","fb","group","reduction","changed","nextLevel","_b","_c","candidateCount","first","growth","canPromote","floor","finer","from","to","wanted","leafIndex","levelOf","runs","file","offset","count","leafStart","leafEnd","coverageGroup","distance","inView","screenImportance","flush","range","leafCoverageGroup","leafDistance","leafInView","MAX_SH_BANDS","resolveSplatPerformanceProfile","explicit","profile","detectSplatDeviceProfile","isFillConstrainedSplatDevice"],"mappings":";;;;;AA+CO,SAASA,EAAOC,GAAqB;AAC1C,SAAO,GAAGA,EAAI,IAAI,IAAIA,EAAI,KAAK,IAAIA,EAAI,MAAM,IAAIA,EAAI,KAAK;AAC5D;AAGA,MAAMC,IAAU,IAQVC,IAAiB,OAGjBC,IAAmB,KAEnBC,IAAW,KAEXC,IAAiB,KAOjBC,IAAkB;AA4BjB,MAAMC,EAAkC;AAAA,EA8F7C,YACEC,GACAC,GAeA;AA7GF;AAAA,IAAAC,EAAA;AAEA;AAAA,IAAA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h-types.ts"],"sourcesContent":["import * as THREE from 'three/webgpu';\nimport type { LodLeaf, LodManifest } from './lod-manifest';\nimport type { LodSource } from './lod-source';\n\n/**\n * A contiguous splat range within one chunk file, at one LOD level - the\n * unit the pool activates. Adjacent manifest leaves that resolve to the same\n * `(file, level)` and whose ranges abut are coalesced into one run, so the\n * pool sees a handful of large ranges instead of thousands of tiny leaves.\n */\nexport interface LodRun {\n readonly file: number;\n readonly level: number;\n readonly offset: number;\n readonly count: number;\n /** First manifest-leaf index this run covers. */\n readonly leafStart: number;\n /** One past the last covered leaf index. */\n readonly leafEnd: number;\n /**\n * Physical-coverage identity when several manifest leaves form one region.\n * A classic LCC cell may be split into fetch-sized leaves, but its slices\n * must still swap as one visible unit. Undefined retains interval-based\n * grouping for hierarchical sources.\n */\n readonly coverageGroup?: number;\n /**\n * Camera distance (mesh-local) of the nearest leaf in this run, from the\n * last {@link LodScheduler.computeDesiredRuns} pass. Streamed meshes use it\n * to fetch near detail before far coarse coverage. Absent on sources that\n * do not track per-leaf distance.\n */\n readonly distance?: number;\n /**\n * True when any leaf in this run intersects the view frustum (with the\n * scheduler's edge margin). Used to rank classic-path fetches so in-view\n * detail beats behind-camera work; absent when the source does not track it.\n */\n readonly inView?: boolean;\n /**\n * Fetch-only angular distance from the camera's forward axis. Smaller values\n * are nearer the screen centre. It never affects LOD selection or budget.\n */\n readonly screenImportance?: number;\n}\n\n/** Stable identity of a run, for diffing desired vs. resident sets. */\nexport function runKey(run: LodRun): string {\n return `${run.file}:${run.level}:${run.offset}:${run.count}`;\n}\n\n/** Sentinel level meaning \"this leaf is currently dropped (renders nothing)\". */\nconst DROPPED = -1;\n\n/**\n * Maximum splats in one run. Large contiguous regions are split into several\n * runs so no single pool append (and thus no single frame) does an unbounded\n * amount of copy + upload work. Split runs stay contiguous, so they still\n * upload as one coalesced rectangle.\n */\nconst MAX_RUN_SPLATS = 128_000;\n\n/** Hysteresis dead-band around each LOD distance threshold. */\nconst THRESHOLD_MARGIN = 0.1;\n/** Minimum time a leaf must hold a level before changing again, ms. */\nconst DWELL_MS = 500;\n/** Frustum test margin, as a fraction of each leaf's own size. */\nconst FRUSTUM_MARGIN = 0.1;\n/**\n * Out-of-frustum leaves act this many times farther away instead of being\n * hard-coarsened. Rotating the camera then re-ranks leaves smoothly (and\n * dwell applies), rather than mass-flipping edge leaves every frame -\n * PlayCanvas uses the same behind-camera-penalty idea.\n */\nconst FRUSTUM_PENALTY = 3;\n\n/**\n * Chooses a level of detail per spatial leaf from the camera, keeps the\n * total within a splat budget, and coalesces the result into runs.\n *\n * The scheduler is pure with respect to rendering: it takes a camera\n * position and frustum (both in the mesh's local space) and returns the set\n * of runs that should be resident. It owns only the small amount of state\n * needed for temporal stability (each leaf's current level and when it last\n * changed), so it is straightforward to drive from a test harness.\n *\n * LOD distance model (PlayCanvas-compatible): level 0 is used within\n * `lodBaseDistance`; each successive level covers a band `lodMultiplier`×\n * farther out. By default out-of-frustum leaves act {@link FRUSTUM_PENALTY}×\n * farther away. Formats with broad spatial cells can disable that bias so an\n * orbit does not churn already-refined cells at the frustum edges.\n *\n * The distance model only sets the *floor* and the *priority*: when the\n * distance-chosen set leaves budget unused, {@link fillBudget} promotes\n * in-frustum leaves nearest-first until its configured headroom target is\n * spent (90% by default). Formats can cap that optional refinement and avoid\n * a full-finest cut even when an explicitly large budget could hold it. The\n * budget\n * therefore decides how far refinement reaches - a desktop budget yields\n * full detail even with the whole scene in view, a mobile budget refines\n * only near the camera.\n */\nexport class LodScheduler implements LodSource {\n /** World-unit distance inside which the finest level (0) is used. */\n lodBaseDistance: number;\n /** Distance ratio between successive LOD levels. */\n lodMultiplier: number;\n /** Maximum active splats; the desired set is demoted to fit. */\n budget: number;\n\n private readonly leaves: readonly LodLeaf[];\n private readonly coarsest: number;\n /** Per leaf: lowest/highest LOD level that has data. */\n private readonly minLevel: Int32Array;\n private readonly maxLevel: Int32Array;\n /**\n * Per leaf: the distance *ambition* - the finest level the camera distance\n * asks for, with hysteresis/dwell applied. This is the hysteresis *state*:\n * only {@link selectLevels} writes it, so budget demotion can never feed\n * back into the dead-band/dwell logic and oscillate. With `fillPastDistance`\n * false, {@link fillBudget} restores {@link resolved} only up to here.\n */\n private readonly level: Int32Array;\n /**\n * Per leaf: the resolved target - the ambition capped to fit the budget by\n * {@link enforceBudget}, then refilled from leftover headroom by\n * {@link fillBudget} (or DROPPED). This is what {@link coalesceRuns} emits.\n */\n private readonly resolved: Int32Array;\n /** Per leaf: timestamp of the last distance-level change, for dwell. */\n private readonly changedAt: Float64Array;\n\n private readonly distance: Float64Array;\n private readonly inFrustum: Uint8Array;\n /** Leaves that must move through the budget cut together. */\n private readonly budgetGroups: readonly Uint32Array[];\n /** Per-leaf physical coverage group, when the manifest defines one. */\n private readonly coverageGroups: Int32Array;\n /** Whether view-frustum membership affects distance and fill priority. */\n private readonly frustumAware: boolean;\n /** Fraction of the usable budget that optional refinement may consume. */\n private readonly budgetFillFraction: number;\n /** Absolute cap on optional refinement; distance-selected detail may exceed it. */\n private readonly budgetFillCap: number;\n /** Whether a budget that holds every finest leaf forces a full-finest cut. */\n private readonly forceFinestWhenFits: boolean;\n /**\n * Leaves at or inside this camera distance always resolve to their finest\n * available level (no hysteresis climb). Classic LCC uses a multi-band\n * radius so adjacent broad cells do not paint coarse discs at startup.\n */\n private readonly forceFinestWithin: number | undefined;\n /**\n * When false, {@link fillBudget} only restores toward each leaf's\n * distance-selected {@link level} - never finer. Classic LCC sets this so\n * a mid-range cell does not fetch L0 only to demote to L1 once the cut\n * settles.\n */\n private readonly fillPastDistance: boolean;\n\n /**\n * What the last cut actually decided, for the HUD.\n *\n * The resident splat count alone cannot distinguish \"the scheduler asked for\n * this\" from \"the scheduler asked for more and the mesh could not apply it\",\n * and those have opposite fixes. Measured rather than inferred after a\n * zoomed-out `sandwijck` sat at exactly its coarsest total (190,730) with a\n * 600k budget - 68% of the budget unspent, with no way to see which stage\n * declined to spend it.\n */\n readonly stats = {\n /** Leaves the frustum test accepted - `fillBudget`'s candidate set. */\n inFrustum: 0,\n /** Total leaves in the tree. */\n leaves: 0,\n /** Splats implied by the resolved cut, before the mesh applies anything. */\n desired: 0,\n /** Splats `fillBudget` added on top of the distance-chosen levels. */\n filled: 0,\n };\n\n private readonly scratchBox = new THREE.Box3();\n private readonly scratchSize = new THREE.Vector3();\n private readonly scratchCenter = new THREE.Vector3();\n private readonly screenImportance: Float32Array;\n /** Whether the last selection pass received a camera-forward vector. */\n private hasScreenImportance = false;\n /**\n * Persistent leaf-index ordering scratch for {@link enforceBudget} and\n * {@link fillBudget}, sorted in place per call instead of allocating a\n * fresh `[...keys]` array. Comparators break ties on the index itself so\n * the order is identical to the stable `Array#sort` this replaces\n * (`TypedArray#sort` stability is not guaranteed).\n */\n private readonly orderScratch: Uint32Array;\n\n constructor(\n manifest: LodManifest,\n options: {\n budget: number;\n lodBaseDistance: number;\n lodMultiplier: number;\n frustumAware?: boolean;\n budgetFillFraction?: number;\n budgetFillCap?: number;\n forceFinestWhenFits?: boolean;\n forceFinestWithin?: number;\n /**\n * When false, leftover-budget fill never refines past the distance-\n * selected level (see {@link fillPastDistance}). Default true.\n */\n fillPastDistance?: boolean;\n },\n ) {\n this.leaves = manifest.leaves;\n this.coarsest = manifest.lodLevels - 1;\n this.budget = options.budget;\n this.lodBaseDistance = options.lodBaseDistance;\n this.lodMultiplier = options.lodMultiplier;\n this.frustumAware = options.frustumAware !== false;\n this.budgetFillFraction = options.budgetFillFraction ?? 0.9;\n this.budgetFillCap = options.budgetFillCap ?? Number.POSITIVE_INFINITY;\n this.forceFinestWhenFits = options.forceFinestWhenFits !== false;\n this.forceFinestWithin = options.forceFinestWithin;\n this.fillPastDistance = options.fillPastDistance !== false;\n if (this.budgetFillFraction <= 0 || this.budgetFillFraction > 1) {\n throw new RangeError('LodScheduler budgetFillFraction must be in (0, 1].');\n }\n if (!(this.budgetFillCap > 0)) {\n throw new RangeError('LodScheduler budgetFillCap must be positive.');\n }\n if (this.forceFinestWithin !== undefined && !(this.forceFinestWithin >= 0)) {\n throw new RangeError('LodScheduler forceFinestWithin must be >= 0.');\n }\n\n const n = this.leaves.length;\n this.minLevel = new Int32Array(n);\n this.maxLevel = new Int32Array(n);\n this.level = new Int32Array(n).fill(this.coarsest);\n this.resolved = new Int32Array(n).fill(this.coarsest);\n this.changedAt = new Float64Array(n);\n this.distance = new Float64Array(n);\n this.inFrustum = new Uint8Array(n);\n this.screenImportance = new Float32Array(n);\n this.orderScratch = new Uint32Array(n);\n this.coverageGroups = new Int32Array(n).fill(-1);\n\n const groups: number[][] = [];\n const explicitGroups = new Map<number, number>();\n for (let i = 0; i < n; i++) {\n const key = (this.leaves[i] as LodLeaf).budgetGroup;\n if (key === undefined) {\n groups.push([i]);\n continue;\n }\n let groupIndex = explicitGroups.get(key);\n if (groupIndex === undefined) {\n groupIndex = groups.length;\n explicitGroups.set(key, groupIndex);\n groups.push([]);\n }\n (groups[groupIndex] as number[]).push(i);\n this.coverageGroups[i] = key;\n }\n this.budgetGroups = groups.map((members) => Uint32Array.from(members));\n\n for (let i = 0; i < n; i++) {\n const lods = (this.leaves[i] as LodLeaf).lods;\n let min = this.coarsest;\n let max = 0;\n for (let l = 0; l < lods.length; l++) {\n if (lods[l] === undefined) continue;\n min = Math.min(min, l);\n max = Math.max(max, l);\n }\n this.minLevel[i] = min;\n this.maxLevel[i] = max;\n this.level[i] = max; // start coarse\n }\n }\n\n /**\n * Recomputes the desired resident run set for the current camera.\n *\n * @param cameraLocal - Camera position in the mesh's local space.\n * @param frustum - View frustum in the mesh's local space.\n * @param now - Monotonic timestamp (ms) for dwell hysteresis.\n */\n computeDesiredRuns(\n cameraLocal: THREE.Vector3,\n frustum: THREE.Frustum,\n now: number,\n cameraForward?: THREE.Vector3,\n ): LodRun[] {\n this.selectLevels(cameraLocal, frustum, now, cameraForward);\n // When the budget already holds every leaf's finest level, skip distance /\n // frustum demotion entirely. Otherwise a small rotate marks leaves\n // out-of-frustum (×{@link FRUSTUM_PENALTY}), coarsens them, and the mesh\n // aborts fine fetches / swaps to coarse LCC discs - then has to climb\n // back when they re-enter the view.\n if (this.forceFinestWhenFits && this.budget >= this.finestTotal()) {\n for (let i = 0; i < this.leaves.length; i++) {\n this.resolved[i] = this.minLevel[i] as number;\n }\n this.stats.desired = this.activeTotal();\n this.stats.filled = 0;\n return this.coalesceRuns();\n }\n // Copy the ambition into the resolved target, cap it to the budget, then\n // refill leftover headroom. Budget stages touch only `resolved`, never the\n // ambition/hysteresis state - a stationary camera therefore resolves the\n // same cut every pass instead of oscillating red↔orange.\n this.resolved.set(this.level);\n this.enforceBudget();\n const beforeFill = this.activeTotal();\n this.fillBudget();\n this.stats.desired = this.activeTotal();\n this.stats.filled = this.stats.desired - beforeFill;\n return this.coalesceRuns();\n }\n\n /** Total active splats implied by the current resolved levels. */\n private activeTotal(): number {\n let total = 0;\n for (let i = 0; i < this.leaves.length; i++) {\n const level = this.resolved[i] as number;\n if (level === DROPPED) continue;\n total += (this.leaves[i] as LodLeaf).lods[level]?.count ?? 0;\n }\n return total;\n }\n\n /** Splats if every leaf sat at its finest available level (none dropped). */\n private finestTotal(): number {\n let total = 0;\n for (let i = 0; i < this.leaves.length; i++) {\n const level = this.minLevel[i] as number;\n total += (this.leaves[i] as LodLeaf).lods[level]?.count ?? 0;\n }\n return total;\n }\n\n private selectLevels(\n cameraLocal: THREE.Vector3,\n frustum: THREE.Frustum,\n now: number,\n cameraForward?: THREE.Vector3,\n ): void {\n const { lodBaseDistance: base, lodMultiplier: m } = this;\n this.hasScreenImportance = cameraForward !== undefined;\n let visibleCount = 0;\n this.stats.leaves = this.leaves.length;\n for (let i = 0; i < this.leaves.length; i++) {\n const leaf = this.leaves[i] as LodLeaf;\n const d = leaf.bounds.distanceToPoint(cameraLocal);\n this.distance[i] = d;\n\n // Widen the box by a fraction of its own size for edge stability.\n this.scratchBox.copy(leaf.bounds);\n leaf.bounds.getSize(this.scratchSize);\n this.scratchBox.expandByScalar(this.scratchSize.length() * FRUSTUM_MARGIN);\n const visible = frustum.intersectsBox(this.scratchBox);\n this.inFrustum[i] = visible ? 1 : 0;\n if (visible) visibleCount++;\n\n // Broad classic-LCC tiles frequently all intersect the frustum, so the\n // boolean above cannot tell the centre of the screen from its edges.\n // This is deliberately fetch metadata only: distance remains the source\n // of truth for the resolved LOD and the budget cut.\n if (cameraForward) {\n leaf.bounds.getCenter(this.scratchCenter).sub(cameraLocal);\n const depth = this.scratchCenter.dot(cameraForward);\n const lateralSquared = Math.max(0, this.scratchCenter.lengthSq() - depth * depth);\n this.screenImportance[i] =\n depth > 0 ? Math.sqrt(lateralSquared) / Math.max(depth, 0.25) : Number.POSITIVE_INFINITY;\n } else {\n this.screenImportance[i] = 0;\n }\n\n const current = this.level[i] as number;\n // Blanket force-finest only when fill may still climb past the distance\n // band (octree / pagetable). Classic LCC never uses this path.\n if (\n this.fillPastDistance &&\n this.forceFinestWithin !== undefined &&\n d <= this.forceFinestWithin\n ) {\n const finest = this.minLevel[i] as number;\n if (current !== finest) {\n this.level[i] = finest;\n this.changedAt[i] = now;\n }\n continue;\n }\n\n const effectiveDistance = !this.frustumAware || visible ? d : d * FRUSTUM_PENALTY;\n\n // Classic LCC: the ambition tracks the pure distance band only. Budget\n // demotions live in `resolved`, never here, so they cannot feed back\n // into hysteresis. A cold cell snaps straight to its band (no dwell\n // climb through intermediate LODs); afterward only a band *crossing*\n // moves the ambition - a stationary camera in the same band holds,\n // even if the budget just demoted its resolved level.\n if (!this.fillPastDistance) {\n const band = this.distanceBandLevel(i, effectiveDistance, base, m);\n const coldStart =\n (this.changedAt[i] as number) === 0 && current === (this.maxLevel[i] as number);\n if (coldStart) {\n if (band !== current) {\n this.level[i] = band;\n this.changedAt[i] = now;\n }\n continue;\n }\n if (band === current) continue;\n const proposed = this.hysteresisLevel(i, effectiveDistance, base, m, current);\n if (proposed === current) continue;\n // Coarsen immediately (moving away should not linger over budget);\n // only refinement waits out the dwell window.\n const coarsening = proposed > current;\n if (coarsening || now - (this.changedAt[i] as number) >= DWELL_MS) {\n this.level[i] = proposed;\n this.changedAt[i] = now;\n }\n continue;\n }\n\n const proposed = this.hysteresisLevel(i, effectiveDistance, base, m, current);\n if (proposed === current) continue;\n const coldSnap =\n (this.changedAt[i] as number) === 0 && current === (this.maxLevel[i] as number);\n if (coldSnap || now - (this.changedAt[i] as number) >= DWELL_MS) {\n this.level[i] = proposed;\n this.changedAt[i] = now;\n }\n }\n this.stats.inFrustum = visibleCount;\n }\n\n /**\n * Pure distance→level band (independent of the leaf's current level), so a\n * classic LCC cut never has to dwell through intermediate rungs.\n */\n private distanceBandLevel(index: number, d: number, base: number, m: number): number {\n const min = this.minLevel[index] as number;\n const max = this.maxLevel[index] as number;\n let level = min;\n while (level < max && d > base * m ** level * (1 + THRESHOLD_MARGIN)) level++;\n return this.resolveAvailable(index, level);\n }\n\n /**\n * Stable level from distance: coarsen only past `threshold·(1 + margin)`,\n * refine only within `threshold·(1 − margin)`. The available-level clamp\n * keeps leaves that lack a level on their nearest coarser one.\n */\n private hysteresisLevel(\n index: number,\n d: number,\n base: number,\n m: number,\n current: number,\n ): number {\n const min = this.minLevel[index] as number;\n const max = this.maxLevel[index] as number;\n let level = Math.min(max, Math.max(min, current));\n // threshold(L) = base·m^L is the boundary between level L and L+1.\n while (level < max && d > base * m ** level * (1 + THRESHOLD_MARGIN)) level++;\n while (level > min && d <= base * m ** (level - 1) * (1 - THRESHOLD_MARGIN)) level--;\n // Resolve to the nearest available level (prefer coarser) if this exact\n // one has no data (leaves need not carry every level).\n return this.resolveAvailable(index, level);\n }\n\n private resolveAvailable(index: number, target: number): number {\n const lods = (this.leaves[index] as LodLeaf).lods;\n for (let l = target; l <= (this.maxLevel[index] as number); l++) if (lods[l]) return l;\n for (let l = target - 1; l >= (this.minLevel[index] as number); l--) if (lods[l]) return l;\n return this.maxLevel[index] as number;\n }\n\n /** Demotes/drops lowest-priority leaves until the total fits the budget. */\n private enforceBudget(): void {\n let total = this.activeTotal();\n if (total <= this.budget) return;\n\n // Demote lowest priority first. When frustum-aware: out-of-frustum before\n // in-frustum, then farthest. Classic LCC sets frustumAware false - broad\n // XY cells often sit mostly behind the camera while the user stands in\n // them (d≈0); frustum demotion would coarsen that cell first and let\n // thinner cells ahead keep fine detail (backwards load). Distance only.\n const order = this.orderScratch.subarray(0, this.budgetGroups.length);\n for (let i = 0; i < order.length; i++) order[i] = i;\n order.sort((a, b) => {\n const ia = (this.budgetGroups[a] as Uint32Array)[0] as number;\n const ib = (this.budgetGroups[b] as Uint32Array)[0] as number;\n if (this.frustumAware) {\n const fa = this.inFrustum[ia] as number;\n const fb = this.inFrustum[ib] as number;\n if (fa !== fb) return fa - fb; // out-of-frustum (0) first\n }\n return (this.distance[ib] as number) - (this.distance[ia] as number) || ia - ib;\n });\n\n // Pass 1: coarsen toward the coarsest available level.\n for (const groupIndex of order) {\n const group = this.budgetGroups[groupIndex] as Uint32Array;\n while (total > this.budget) {\n let reduction = 0;\n let changed = false;\n for (const i of group) {\n const current = this.resolved[i] as number;\n if (current >= (this.maxLevel[i] as number)) continue;\n const lods = (this.leaves[i] as LodLeaf).lods;\n const nextLevel = this.resolveAvailable(i, current + 1);\n if (nextLevel === current) continue;\n reduction += (lods[current]?.count ?? 0) - (lods[nextLevel]?.count ?? 0);\n this.resolved[i] = nextLevel;\n changed = true;\n }\n if (!changed) break;\n total -= reduction;\n }\n if (total <= this.budget) return;\n }\n\n // Pass 2 (last resort): drop groups entirely, lowest priority first.\n for (const groupIndex of order) {\n if (total <= this.budget) return;\n for (const i of this.budgetGroups[groupIndex] as Uint32Array) {\n if ((this.resolved[i] as number) === DROPPED) continue;\n total -= (this.leaves[i] as LodLeaf).lods[this.resolved[i] as number]?.count ?? 0;\n this.resolved[i] = DROPPED;\n }\n }\n }\n\n /**\n * Uses leftover budget to restore detail after {@link enforceBudget}\n * demoted leaves, nearest first, while the total stays under the fill\n * target. By default this may also refine *past* the distance-chosen level\n * when headroom remains (octree / pagetable streams). With\n * {@link fillPastDistance} false (classic LCC), fill never goes finer than\n * each leaf's distance-selected level - so a cell at the L1 band does not\n * fetch L0 only to demote moments later with the camera still.\n */\n private fillBudget(): void {\n const target =\n this.forceFinestWhenFits && this.budget >= this.finestTotal()\n ? this.budget\n : Math.min(this.budget, this.budgetFillCap) * this.budgetFillFraction;\n let total = this.activeTotal();\n if (total >= target) return;\n\n // Candidate in-frustum groups, nearest first (ties keep manifest order),\n // packed into the front of the shared index scratch.\n let candidateCount = 0;\n for (let groupIndex = 0; groupIndex < this.budgetGroups.length; groupIndex++) {\n const first = (this.budgetGroups[groupIndex] as Uint32Array)[0] as number;\n if (\n (!this.frustumAware || this.inFrustum[first] === 1) &&\n (this.resolved[first] as number) !== DROPPED\n ) {\n this.orderScratch[candidateCount++] = groupIndex;\n }\n }\n const order = this.orderScratch.subarray(0, candidateCount);\n order.sort((a, b) => {\n const ia = (this.budgetGroups[a] as Uint32Array)[0] as number;\n const ib = (this.budgetGroups[b] as Uint32Array)[0] as number;\n return (this.distance[ia] as number) - (this.distance[ib] as number) || ia - ib;\n });\n\n // Nearest groups refine first (up to the distance floor when capped).\n for (const groupIndex of order) {\n const group = this.budgetGroups[groupIndex] as Uint32Array;\n while (true) {\n let growth = 0;\n let canPromote = false;\n for (const i of group) {\n const current = this.resolved[i] as number;\n const floor = this.fillPastDistance\n ? (this.minLevel[i] as number)\n : (this.level[i] as number);\n if (current <= floor) continue;\n const leaf = this.leaves[i] as LodLeaf;\n let finer = current - 1;\n while (finer > floor && !leaf.lods[finer]) finer--;\n if (finer < floor || !leaf.lods[finer]) continue;\n growth += (leaf.lods[finer]?.count ?? 0) - (leaf.lods[current]?.count ?? 0);\n canPromote = true;\n }\n if (!canPromote || total + growth > target) break;\n for (const i of group) {\n const current = this.resolved[i] as number;\n const floor = this.fillPastDistance\n ? (this.minLevel[i] as number)\n : (this.level[i] as number);\n if (current <= floor) continue;\n const leaf = this.leaves[i] as LodLeaf;\n let finer = current - 1;\n while (finer > floor && !leaf.lods[finer]) finer--;\n if (finer >= floor && leaf.lods[finer]) this.resolved[i] = finer;\n }\n total += growth;\n }\n }\n }\n\n private coalesceRuns(): LodRun[] {\n return this.buildRuns(0, this.leaves.length, (i) => this.resolved[i] as number);\n }\n\n /**\n * Runs covering [from, to) at each leaf's coarsest available level - used\n * to substitute always-cached coverage while a finer level is fetching.\n */\n coarsestRunsFor(from: number, to: number): LodRun[] {\n return this.buildRuns(from, to, (i) => this.maxLevel[i] as number);\n }\n\n /**\n * Runs covering [from, to) at `level`, clamped per leaf to an available rung\n * (prefer the requested level, else the next coarser, else the next finer).\n */\n runsAtLevelFor(from: number, to: number, level: number): LodRun[] {\n const wanted = Math.floor(level);\n return this.buildRuns(from, to, (i) => this.clampLeafLevel(i, wanted));\n }\n\n /** Prefer `wanted`, else next coarser, else next finer; {@link DROPPED} if none. */\n private clampLeafLevel(leafIndex: number, wanted: number): number {\n const leaf = this.leaves[leafIndex] as LodLeaf;\n if (leaf.lods[wanted]) return wanted;\n for (let l = wanted + 1; l < leaf.lods.length; l++) {\n if (leaf.lods[l]) return l;\n }\n for (let l = wanted - 1; l >= 0; l--) {\n if (leaf.lods[l]) return l;\n }\n return DROPPED;\n }\n\n /** Coalesces leaves [from, to) at `levelOf(leaf)` into contiguous runs. */\n private buildRuns(from: number, to: number, levelOf: (index: number) => number): LodRun[] {\n const runs: LodRun[] = [];\n let file = -1;\n let level = -1;\n let offset = 0;\n let count = 0;\n let leafStart = -1;\n let leafEnd = -1;\n let coverageGroup = -1;\n let distance = Number.POSITIVE_INFINITY;\n let inView = false;\n let screenImportance = Number.POSITIVE_INFINITY;\n const flush = (): void => {\n if (count > 0) {\n runs.push({\n file,\n level,\n offset,\n count,\n leafStart,\n leafEnd,\n distance,\n inView,\n ...(this.hasScreenImportance ? { screenImportance } : {}),\n ...(coverageGroup >= 0 ? { coverageGroup } : {}),\n });\n }\n count = 0;\n };\n\n for (let i = from; i < to; i++) {\n const l = levelOf(i);\n if (l === DROPPED) {\n flush();\n continue;\n }\n const range = (this.leaves[i] as LodLeaf).lods[l];\n if (!range) {\n flush();\n continue;\n }\n const leafCoverageGroup = this.coverageGroups[i] as number;\n const leafDistance = this.distance[i] as number;\n const leafInView = (this.inFrustum[i] as number) === 1;\n if (\n count > 0 &&\n range.file === file &&\n l === level &&\n leafCoverageGroup === coverageGroup &&\n range.offset === offset + count &&\n count + range.count <= MAX_RUN_SPLATS\n ) {\n count += range.count; // extend the current run\n leafEnd = i + 1;\n if (leafDistance < distance) distance = leafDistance;\n if (leafInView) inView = true;\n screenImportance = Math.min(screenImportance, this.screenImportance[i] as number);\n } else {\n flush();\n file = range.file;\n level = l;\n offset = range.offset;\n count = range.count;\n leafStart = i;\n leafEnd = i + 1;\n coverageGroup = leafCoverageGroup;\n distance = leafDistance;\n inView = leafInView;\n screenImportance = this.screenImportance[i] as number;\n }\n }\n flush();\n return runs;\n }\n}\n","/** Public configuration and result types for SplatMesh. */\nimport type * as THREE from 'three/webgpu';\nimport type { SplatData } from './splat-data';\nimport type { SplatOrientation } from './orientation';\nimport type { SplatModifier } from './splat-modifier';\nimport {\n detectSplatDeviceProfile,\n isFillConstrainedSplatDevice,\n type SplatDeviceProfile,\n} from './splat-budget';\nimport type { SplatPool } from './splat-mesh-pool';\nimport type { SplatShInputs, Vec3Uniform } from './splat-mesh-material';\n\n/** Construction-time projected-footprint policy selected by a streamed format. */\nexport type ProjectedFilterProfile = 'default' | 'lcc';\n\n/**\n * Opaque handle for a range of splats appended to a {@link SplatMesh},\n * used to remove the range again.\n */\nexport interface SplatRange {\n /** Number of splats in this range. */\n readonly count: number;\n}\n\n/**\n * Storage format of a per-splat channel (see {@link SplatMesh.defineChannel}).\n *\n * - `'byte'`: one `Uint8` per splat (`r8unorm`). Compact - a good fit for\n * masks and labels. `ctx.channel(name)` reads it back **normalized** to\n * `[0, 1]`, so a painted `255` reads as `1.0`.\n * - `'float'`: one `Float32` per splat (`r32float`), read back verbatim.\n */\nexport type SplatChannelType = 'byte' | 'float';\n\n/** Options for {@link SplatMesh.defineChannel}. */\nexport interface SplatChannelOptions {\n /** Storage format; default `'float'`. */\n type?: SplatChannelType;\n /**\n * Value every splat starts at before any {@link SplatMesh.writeChannel}.\n * Default `0`. For `'byte'` channels this is a raw `0..255` value.\n */\n fill?: number;\n}\n\n/** The highest SH order this renderer evaluates (3rd → 15 coefficients). */\nexport const MAX_SH_BANDS = 3;\n\n/**\n * The contribution-culling profile a mesh will use, given an optional\n * explicit override. Exported so callers that must decide something *before*\n * constructing the mesh - such as whether a streamed scene should fetch its\n * SH at all - agree with what the mesh itself will pick.\n */\nexport function resolveSplatPerformanceProfile(\n explicit?: SplatPerformanceProfile,\n profile: SplatDeviceProfile | undefined = detectSplatDeviceProfile(),\n): SplatPerformanceProfile {\n return explicit ?? (isFillConstrainedSplatDevice(profile) ? 'smooth' : 'quality');\n}\n\n/** Construction options for {@link SplatMesh}. */\nexport interface SplatMeshOptions {\n /**\n * Storage for per-splat higher-order SH in a dynamic-capacity pool, in\n * bands (1, 2 or 3 → 3, 8 or 15 coefficients per channel); 0 (default)\n * allocates nothing.\n *\n * Only formats that store SH per splat can fill this - LCC `Quality`, `.rad`, etc.\n * It costs 16 bytes per splat per band-group of four\n * coefficients (64 B/splat at 3 bands), so it is opt-in. On a static mesh\n * this is ignored: packed SH is taken from `source.shPacked` when present,\n * otherwise palette `source.sh` (SOG).\n */\n shBands?: 0 | 1 | 2 | 3;\n /**\n * Minimum interval between WebGPU sorts while the camera moves. When\n * omitted, the interval adapts to the active splat count. Use `0` to sort\n * every changed frame. WebGL worker sorting is unaffected.\n */\n sortIntervalMs?: number;\n /**\n * WebGPU sorter used for A/B validation. Defaults to the proven counting\n * sorter. `'radix'` keeps the fast 24-bit key path; `'exact'` lazy-loads a\n * stable 32-bit Float32-depth radix path that avoids scene-range\n * quantization. The first frames may skip sorting until the module resolves.\n *\n * @experimental Radix strategies may change in a minor release.\n */\n sortStrategy?: SplatSortStrategy;\n /**\n * Render-quality policy. `smooth` rejects negligible projected contributions.\n *\n * The default is device-aware: `smooth` on mobile (where rejecting splats too\n * small or too faint to see is worth far more than it costs), `quality`\n * everywhere else. Passing a value opts out of the detection.\n */\n performanceProfile?: SplatPerformanceProfile;\n /**\n * How far out, in standard deviations, each Gaussian is drawn before it is\n * cut off. Every splat is an alpha-blended quad sized to this radius, so it\n * sets how much each one costs to blend - the dominant cost in a busy view.\n * Lowering it shrinks every quad and clips the faint outer tail of each\n * Gaussian; the falloff within the remaining radius is unchanged.\n *\n * Defaults to `3`, the reference 3DGS rasterizer's radius. Below ~2 the\n * truncation shows as visible splat edges; much above ~5 the extra fill is not\n * worth it. Mobile coverage gaps are handled by `minSplatSizePx` instead of\n * growing every splat.\n */\n maxStdDev?: number;\n /**\n * Floor, in viewport pixels, on each rendered splat's projected quad radius.\n *\n * A screen-space *minimum* size, the counterpart to `maxScreenRadiusPx`'s\n * maximum. When a splat projects smaller than this - because it is distant, or\n * because the whole scene is zoomed out - its quad is grown to this radius and\n * the Gaussian is stretched to fill it (the falloff normalizes to the quad, so\n * no hard edge appears). Splats already larger are untouched, so it costs no\n * extra fill on the near-camera splats that dominate overdraw.\n *\n * This is the fix for the \"dark gaps when zoomed out\" failure mode: a capture\n * whose finest splats are spaced farther apart than their footprint leaves the\n * background showing between them, and the effect is worst at low resolution -\n * i.e. on a phone. Raising `maxStdDev` also closes the gaps but inflates\n * *every* splat's fragment count by its square, paying the coverage cost on the\n * large splats too; this floor spends it only where a gap can actually open.\n *\n * Defaults to `1.5` px on mobile and `0` (disabled) elsewhere, including\n * fill-constrained desktops. Values around 1–3 px close typical gaps; too\n * large a floor blurs distinct small features into discs, so tune it up from\n * small on the target device. An explicit `0` always disables the floor.\n */\n minSplatSizePx?: number;\n /**\n * Apply the Mip-Splatting 2D antialiasing filter - the screen-space low-pass\n * dilation plus the opacity compensation that conserves each Gaussian's\n * integral, so small/distant splats stop over-brightening. Match the\n * exporter: enable it for scenes trained/exported with antialiasing (the SOG\n * `antialias` meta flag sets this automatically). Defaults to `false` (the\n * classic 3DGS dilation without compensation).\n */\n antialias?: boolean;\n /**\n * Internal format-selected reconstruction profile. Classic LCC uses the\n * XGRIDS-compatible 0.1 px² compensated low-pass; callers should leave this\n * unset and select a format through {@link StreamedSplatMesh.load} instead.\n *\n * @internal\n */\n projectedFilterProfile?: ProjectedFilterProfile;\n /**\n * Emit splat colors in sRGB (display) space instead of decoding them to the\n * renderer's linear working space. Pair with a renderer that skips output\n * conversion (`outputColorSpace = LinearSRGBColorSpace`, `NoToneMapping`,\n * inline sRGB encode for other materials via `renderer.contextNode`): splats\n * then alpha-composite on gamma-encoded values - the math 3DGS training\n * optimizes against, and what WebGL splat viewers render. Defaults to\n * `false` (linear working-space compositing).\n */\n srgbOutput?: boolean;\n /**\n * Cull any splat whose projected on-screen radius exceeds this many pixels,\n * rendering a hole instead. A physically large splat close to the camera -\n * a coarse merged LOD node (a Spark `.rad` \"blob\"), or a giant background\n * Gaussian - projects huge while a fine surface splat stays small, so this\n * removes the near-camera blobs without touching detailed geometry. `0` or\n * unset disables it (the default). Baked into the material graph.\n */\n maxSplatScreenRadius?: number;\n /**\n * Foveation band lower bound (px): cull any splat whose projected on-screen\n * radius is *below* this. Paired with {@link maxSplatScreenRadius}, only\n * splats sized `(min, max]` on screen draw. Because a `.rad` LOD tree's node\n * sizes shrink geometrically, exactly one level per view ray lands in the\n * band - near rays on fine leaves, far rays on coarse nodes - giving a\n * camera-distance foveated cut. `0` or unset disables it (the default).\n * Baked into the material graph. See `docs/formats/rad-notes.md` M14.6.\n */\n minSplatScreenRadius?: number;\n /**\n * How a `.rad` foveated mesh picks its per-splat LOD cut:\n * - `'band'` (default): the screen-radius band above\n * ({@link minSplatScreenRadius}, {@link maxSplatScreenRadius}].\n * - `'frontier'`: Spark's exact tree cut - draw splat `i` iff its parent is\n * too big and it is small enough (`parentPixelScale > limit ≥ ownPixelScale`),\n * using per-splat `own_size`/`parent_size`. Full coverage by construction, no\n * band leapfrogging. Baked into the material graph. See `docs/formats/rad-notes.md`.\n * - `'pagetable'`: the {@link StreamedSplatMesh} default for `.rad` - a worker\n * owns the tree traversal and pages only the *selected* frontier into the\n * pool (Spark's selected-index model), so the whole splat budget buys\n * on-screen detail. Requires the streamed `.rad` machinery; on a plain\n * `SplatMesh` it has no worker to drive it.\n *\n * @experimental `.rad` foveation option; may change in a minor release.\n */\n foveationMode?: 'band' | 'frontier' | 'pagetable';\n /**\n * Target on-screen size (px) for the frontier / page-table cut: it keeps one\n * LOD level per view ray whose projected node size is about this. Larger =\n * coarser/fewer splats, smaller = finer/denser. Default\n * {@link DEFAULT_FOVEATION_TARGET_PX} (1, matching Spark's `lodRenderScale`),\n * so the draw budget rather than the cut size is what bounds detail. Raise it\n * to trade sharpness for fill rate on weak GPUs.\n * Acts as the *finest* bound: the adaptive limit coarsens above it to hold the\n * draw budget but never dips below it.\n *\n * @experimental `.rad` foveation option; may change in a minor release.\n */\n foveationTargetPx?: number;\n /**\n * Target upper bound on the number of splats the frontier cut *draws*\n * (Spark's `maxSplats`). Each reschedule the cut's `pixelScaleLimit`\n * self-adjusts - coarsening when the estimated drawn count exceeds this - so\n * frame cost stays bounded as detail streams in. Default\n * {@link DEFAULT_FOVEATION_DRAW_BUDGET}. Only used in `'frontier'` mode.\n *\n * @experimental `.rad` foveation option; may change in a minor release.\n */\n foveationDrawBudget?: number;\n /**\n * Cap on a rendered splat's major/minor axis ratio (`0`/unset = off). A very\n * anisotropic Gaussian (a flat 3DGS disk edge-on, or an expansion-enlarged\n * coarse LOD node) otherwise projects to a long needle; this bounds its drawn\n * length to `maxSplatAspect`× its width. Baked into the material graph.\n *\n * @experimental `.rad` foveation option; may change in a minor release.\n */\n maxSplatAspect?: number;\n /**\n * Spark's LOD alpha encoding (`.rad`): the stored opacity is `alpha/2` so the\n * shader recovers `alpha ∈ [0,2]`, and `alpha > 1` marks a merged node rendered\n * with a grown σ-cutoff + super-Gaussian falloff. Set for foveated `.rad`.\n *\n * @experimental `.rad` foveation option; may change in a minor release.\n */\n lodAlpha?: boolean;\n /**\n * How the scene is oriented into the three.js Y-up world. `'y-up'` (default)\n * normalizes every known format to Y-up - 3DGS Y-down formats\n * (PLY/`.splat`/`.ksplat`/SOG) are flipped 180° about X; SPZ/`.rad` are\n * already Y-up; LCC keeps its own Z-up→Y-up matrix. `'source'` applies no\n * cosmetic flip and renders in the data frame (raw Spark / mkkellogg parity);\n * LCC still self-orients (that is format semantics, not part of the switch).\n *\n * For a static mesh the flip is chosen from {@link SplatData.sourceFormat}\n * (stamped by the loaders); a dynamic-capacity mesh carries no format, so its\n * host applies {@link yUpTransformForFormat} itself. See {@link SplatOrientation}.\n */\n orientation?: SplatOrientation;\n /**\n * GPU storage type for the pool's continuous float textures (`centers` and\n * `covarianceA`). `'float16'` uploads them as `rgba16float` (~16 B/splat\n * saved vs the default). CPU backing stays float32 (sorter, query, writes).\n *\n * `covarianceB` is always float32: it packs integer IDs (SOG palette labels,\n * RAD frontier parents) that half floats cannot represent exactly above\n * 2048. Colors and packed SH are unchanged. Construction-time only.\n */\n poolFloatTextures?: 'float32' | 'float16';\n /**\n * An existing pool to draw from instead of allocating one.\n *\n * Several meshes sharing a pool share its memory envelope: rows go to\n * whichever mesh needs them, so a mesh the camera is near can hold far more\n * than an even split would give it, and one that is far away holds almost\n * nothing - without every mesh having reserved a private ceiling up front.\n * This is the multi-mesh analogue of a single streamed mesh's LOD budget.\n *\n * The pool is *not* owned by the mesh: {@link SplatMesh.dispose} releases the\n * mesh's rows and leaves the textures alone, so the pool's creator disposes\n * it once every tenant is gone. `capacity` on the source is then only used\n * for the mesh's own draw list, not to size storage.\n *\n * Sharing costs a whole-pool stall when the pool fragments - see\n * {@link SplatMesh.compact}.\n */\n pool?: SplatPool;\n /**\n * The device's `maxTextureDimension2D`, forwarded to a pool this mesh\n * allocates for itself so an over-tall pool fails at construction with a\n * readable error instead of at first draw. Pass `deviceMaxTextureSize(renderer)`.\n *\n * Ignored when {@link SplatMeshOptions.pool} supplies the pool - that pool\n * was already checked when its creator built it.\n */\n maxTextureSize?: number;\n}\n\n/** Available WebGPU depth-sort implementations. */\nexport type SplatSortStrategy = 'counting' | 'radix' | 'exact';\n\n/** Controls optional work during a per-frame source update. */\nexport interface SplatUpdateOptions {\n /** Leave sorting to {@link UnifiedSplatRenderer}; uploads and LOD state still update. */\n sort?: boolean;\n}\n\n/**\n * Read-only GPU-facing view of a mesh's current active pool. It is consumed by\n * the M15.4 unified gather path; streamed meshes expose their current LOD cut\n * through the same view because they inherit {@link SplatMesh}.\n *\n * @experimental May change in a minor release.\n */\nexport interface UnifiedSourceView {\n /** Total addressable pool slots. */\n readonly capacity: number;\n /** Pool indices of active splats, packed from zero. */\n readonly sourceIndex: THREE.StorageBufferAttribute;\n /** Active entries at the front of {@link sourceIndex}. */\n readonly activeCount: number;\n /** Local-space centers, RGBA32F and pool-indexed. */\n readonly centersTexture: THREE.DataTexture;\n /** Source display color and opacity, RGBA8 and pool-indexed. */\n readonly colorsTexture: THREE.DataTexture;\n /** Upper covariance rows, RGBA32F and pool-indexed. */\n readonly covarianceATexture: THREE.DataTexture;\n /** Final covariance row, RGBA32F and pool-indexed. */\n readonly covarianceBTexture: THREE.DataTexture;\n /** Centers texture row width. */\n readonly dataTextureWidth: number;\n /** Current source-local → world transform. */\n readonly matrixWorld: THREE.Matrix4;\n /** Conservative world-space bound for depth quantization. */\n readonly worldBounds: THREE.Sphere;\n /** Higher-order color data resolved by the gather pass when present. */\n readonly sh: SplatShInputs | null;\n /** Effect hooks and their source-local data channels. */\n readonly modifiers: readonly SplatModifier[];\n /**\n * True when this source is itself a unified pool with per-source placement\n * (`SplatScene`). The gather path cannot resolve nested placement, so\n * `UnifiedSplatRenderer` rejects these sources.\n */\n readonly hasSourcePlacement: boolean;\n readonly channels: ReadonlyMap<string, { texture: THREE.DataTexture }>;\n /** Same uniform node the source graph updates each frame. */\n readonly localCameraPosition: Vec3Uniform;\n /** Changes whenever a modifier graph must be rebuilt. */\n readonly graphRevision: number;\n /** Whether this source intentionally composites in display (sRGB) space. */\n readonly srgbOutput: boolean;\n /** Shared draw-path settings that must agree across unified sources. */\n readonly maxStdDev: number;\n /** Screen-space minimum splat radius, px (0 = off). */\n readonly minSplatSizePx: number;\n readonly antialias: boolean;\n /** Construction-time projected-footprint policy shared by one unified pass. */\n readonly projectedFilterProfile: ProjectedFilterProfile;\n /**\n * Whether this source stores Spark LOD alpha (`alpha ÷ 2`, `.rad`). The\n * gather recovers the full `alpha ∈ [0,2]`; the draw material then treats\n * `alpha > 1` as a merged node. Per source, not a compatibility field - a\n * scene may mix `.rad` and non-`.rad` sources.\n */\n readonly lodAlpha: boolean;\n /** Increments whenever pool-backed data or active residency changes. */\n readonly contentRevision: number;\n}\n\n/** Quality-compatible rendering or smoother contribution-culling rendering. */\nexport type SplatPerformanceProfile = 'quality' | 'smooth';\n\n/**\n * Options for {@link SplatMesh.pick}.\n *\n * Picking returns the selected splat's rendered center plane (depth-tested\n * Gaussian coverage), not a persistent splat identifier or a collision mesh.\n */\nexport interface SplatPickOptions {\n /**\n * Minimum Gaussian opacity (after falloff × splat alpha) for a fragment to\n * count as a hit. Default `0.1`.\n */\n alphaThreshold?: number;\n}\n\n/**\n * Result of a successful {@link SplatMesh.pick}.\n *\n * The point lies on the frontmost splat's billboard plane at the picked\n * pixel - suitable for click-to-focus and placement anchors, not physics.\n */\nexport interface SplatPickResult {\n /** Hit position in world space. */\n readonly point: THREE.Vector3;\n /** Distance from the camera position to {@link point}. */\n readonly distance: number;\n}\n\n/**\n * Result of {@link SplatMesh.queryNearest}: the resident splat center closest\n * to the query point, in world space.\n */\nexport interface SplatNearestResult {\n /** The splat's center, in world space. */\n readonly point: THREE.Vector3;\n /** World-space distance from the query point to {@link point}. */\n readonly distance: number;\n}\n\n/** Result of a successful synchronous {@link SplatMesh.queryRay}. */\nexport interface SplatRayResult {\n /** Resident splat center in world space. */\n readonly point: THREE.Vector3;\n /** Distance along the ray from its origin to the center's closest plane. */\n readonly distance: number;\n}\n\n/**\n * Result of {@link SplatMesh.queryHeight}: the supporting surface found beneath\n * the query point (the highest resident splat within the drop and horizontal\n * radius), in world space.\n */\nexport interface SplatHeightResult {\n /** The supporting splat's center, in world space. */\n readonly point: THREE.Vector3;\n /** How far below the query point the surface sits (world units, ≥ 0). */\n readonly drop: number;\n}\n"],"names":["runKey","run","DROPPED","MAX_RUN_SPLATS","THRESHOLD_MARGIN","DWELL_MS","FRUSTUM_MARGIN","FRUSTUM_PENALTY","LodScheduler","manifest","options","__publicField","THREE","n","groups","explicitGroups","i","key","groupIndex","members","lods","min","max","l","cameraLocal","frustum","now","cameraForward","beforeFill","total","level","_a","base","m","visibleCount","leaf","d","visible","depth","lateralSquared","current","finest","effectiveDistance","band","proposed","index","target","order","a","b","ia","ib","fa","fb","group","reduction","changed","nextLevel","_b","_c","candidateCount","first","growth","canPromote","floor","finer","from","to","wanted","leafIndex","levelOf","runs","file","offset","count","leafStart","leafEnd","coverageGroup","distance","inView","screenImportance","flush","range","leafCoverageGroup","leafDistance","leafInView","MAX_SH_BANDS","resolveSplatPerformanceProfile","explicit","profile","detectSplatDeviceProfile","isFillConstrainedSplatDevice"],"mappings":";;;;;AA+CO,SAASA,EAAOC,GAAqB;AAC1C,SAAO,GAAGA,EAAI,IAAI,IAAIA,EAAI,KAAK,IAAIA,EAAI,MAAM,IAAIA,EAAI,KAAK;AAC5D;AAGA,MAAMC,IAAU,IAQVC,IAAiB,OAGjBC,IAAmB,KAEnBC,IAAW,KAEXC,IAAiB,KAOjBC,IAAkB;AA4BjB,MAAMC,EAAkC;AAAA,EA8F7C,YACEC,GACAC,GAeA;AA7GF;AAAA,IAAAC,EAAA;AAEA;AAAA,IAAAA,EAAA;AAEA;AAAA,IAAAA,EAAA;AAEiB,IAAAA,EAAA;AACA,IAAAA,EAAA;AAEA;AAAA,IAAAA,EAAA;AACA,IAAAA,EAAA;AAQA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAAAA,EAAA;AAMA;AAAA;AAAA;AAAA;AA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UAAIO,MAAMrB,GAAS;AACjB,QAAA+E,EAAA;AACA;AAAA,MACF;AACA,YAAMC,IAAS,KAAK,OAAOlE,CAAC,EAAc,KAAKO,CAAC;AAChD,UAAI,CAAC2D,GAAO;AACV,QAAAD,EAAA;AACA;AAAA,MACF;AACA,YAAME,IAAoB,KAAK,eAAenE,CAAC,GACzCoE,IAAe,KAAK,SAASpE,CAAC,GAC9BqE,IAAc,KAAK,UAAUrE,CAAC,MAAiB;AACrD,MACE0D,IAAQ,KACRQ,EAAM,SAASV,KACfjD,MAAMO,KACNqD,MAAsBN,KACtBK,EAAM,WAAWT,IAASC,KAC1BA,IAAQQ,EAAM,SAAS/E,KAEvBuE,KAASQ,EAAM,OACfN,IAAU5D,IAAI,GACVoE,IAAeN,MAAUA,IAAWM,IACpCC,MAAYN,IAAS,KACzBC,IAAmB,KAAK,IAAIA,GAAkB,KAAK,iBAAiBhE,CAAC,CAAW,MAEhFiE,EAAA,GACAT,IAAOU,EAAM,MACbpD,IAAQP,GACRkD,IAASS,EAAM,QACfR,IAAQQ,EAAM,OACdP,IAAY3D,GACZ4D,IAAU5D,IAAI,GACd6D,IAAgBM,GAChBL,IAAWM,GACXL,IAASM,GACTL,IAAmB,KAAK,iBAAiBhE,CAAC;AAAA,IAE9C;AACA,WAAAiE,EAAA,GACOV;AAAA,EACT;AACF;AC/pBO,MAAMe,IAAe;AAQrB,SAASC,EACdC,GACAC,IAA0CC,KACjB;AACzB,SAAOF,MAAaG,EAA6BF,CAAO,IAAI,WAAW;AACzE;"}
@@ -22,8 +22,9 @@ import type { ChunkCacheBudget } from './chunk-cache-budget';
22
22
  */
23
23
  export declare function estimateSceneDecodedBytes(scene: StreamedScene): number;
24
24
  /**
25
- * Read-only startup-hold progress for classic `.lcc` {@link StreamedSplatMeshOptions.initialReveal}.
26
- * Exported for hosts that gate visibility on the first useful near-L0 frame.
25
+ * Read-only startup-hold progress for {@link StreamedSplatMeshOptions.initialReveal}.
26
+ * Exported for hosts that gate visibility on the first useful coverage frame
27
+ * (classic `.lcc` nearby L0, or `.lcc2` in-view coarsest cells).
27
28
  */
28
29
  export type InitialRevealState = {
29
30
  readonly status: 'disabled';
@@ -156,10 +157,11 @@ export interface StreamedSplatMeshOptions extends SplatMeshOptions {
156
157
  */
157
158
  maxSplatsPerSwap?: number;
158
159
  /**
159
- * First-frame reveal policy for classic `.lcc` streaming.
160
+ * First-frame reveal policy for streamed formats that can hide empty cells.
160
161
  *
161
- * - `'progressive'`: cells become visible as each L0 coverage group commits
162
- * - can show sparse near-detail while siblings load.
162
+ * - `'progressive'`: cells become visible as each swap group commits — can
163
+ * show sparse near-detail (classic `.lcc`) or empty octree squares
164
+ * (`.lcc2`) while siblings load.
163
165
  * - `'hold-near-l0'` (the default for classic `.lcc` when unset): hide the
164
166
  * mesh until the camera's home coverage group is resident (L0 when it fits;
165
167
  * otherwise coarsen via the leaf ladder L1→L2). Neighbours are not part of
@@ -168,16 +170,20 @@ export interface StreamedSplatMeshOptions extends SplatMeshOptions {
168
170
  * does not require frustum intersection (HiRes tiles often fail `inView`
169
171
  * when the camera stands inside looking out). Coarser rungs come from
170
172
  * `LodSource.runsAtLevelFor`. Only home files are fetched during the hold.
171
- * A one-minute watchdog also degrades if the cut cannot finish. Other
172
- * streamed formats default to `'progressive'` and treat the hold as
173
- * disabled.
174
- *
175
- * Does not make detail downloads instantaneous; it avoids lower-LOD traffic
176
- * and multi-cell buildup before the first useful frame. The hold uses the
177
- * **resolved** cut from the first schedule (after camera + format transform),
178
- * not distance ambition alone.
179
- */
180
- initialReveal?: 'progressive' | 'hold-near-l0';
173
+ * A one-minute watchdog also degrades if the cut cannot finish.
174
+ * - `'hold-coverage'` (the default for `.lcc2` when unset): hide the mesh
175
+ * until every in-view finest cell has a coarsest covering node resident
176
+ * (any LOD). Does not wait for finest tiles or the rest of the stream.
177
+ * An empty frustum falls back to the nearest cell. Requires
178
+ * `LodSource.coverageRunsFor`; other formats treat this as disabled.
179
+ *
180
+ * A one-minute watchdog degrades to progressive if the frozen set cannot
181
+ * finish. Does not make detail downloads instantaneous. Classic `.lcc` uses
182
+ * the **resolved** cut from the first schedule (after camera + format
183
+ * transform), not distance ambition alone. Other streamed formats default
184
+ * to `'progressive'`.
185
+ */
186
+ initialReveal?: 'progressive' | 'hold-near-l0' | 'hold-coverage';
181
187
  /** Receives lightweight LOD swap markers for performance attribution. */
182
188
  onPerformanceEvent?: (event: StreamedSplatPerformanceEvent) => void;
183
189
  /**
@@ -492,11 +498,13 @@ export declare class StreamedSplatMesh extends SplatMesh {
492
498
  /** Set when the env tile is larger than the whole pool - terminal, warned once. */
493
499
  private envUnfit;
494
500
  /**
495
- * Classic `.lcc` startup hold. `'capture'` waits for the first schedule after
496
- * the host applies the final camera; `'holding'` freezes that nearby-detail set.
501
+ * Startup hold. `'capture'` waits for the first schedule after the host
502
+ * applies the final camera; `'holding'` freezes that coverage set.
497
503
  */
498
504
  private initialRevealPhase;
499
- /** Frozen nearby-detail runs for {@link initialRevealPhase} `'holding'`. */
505
+ /** Which hold, if any, was armed at construction. Survives release for recapture. */
506
+ private readonly initialRevealHold;
507
+ /** Frozen nearby-detail / in-view coverage runs for {@link initialRevealPhase} `'holding'`. */
500
508
  private frozenCriticalRuns;
501
509
  /** Timestamp of the final-camera capture that began the current hold. */
502
510
  private initialRevealStartedAt;
@@ -815,16 +823,17 @@ export declare class StreamedSplatMesh extends SplatMesh {
815
823
  get isLodLevelDebug(): boolean;
816
824
  /**
817
825
  * Startup-hold progress for {@link StreamedSplatMeshOptions.initialReveal}.
818
- * Classic `.lcc` hosts using the default (or explicitly opting into
819
- * `'hold-near-l0'`) should keep the mesh invisible while
820
- * `status === 'pending'`, then reveal on `'ready'` or `'degraded'`.
826
+ * Hosts using `'hold-near-l0'` or `'hold-coverage'` should keep the mesh
827
+ * invisible while `status === 'pending'`, then reveal on `'ready'` or
828
+ * `'degraded'`.
821
829
  */
822
830
  get initialRevealState(): InitialRevealState;
823
831
  /**
824
- * Captures a fresh classic `.lcc` nearby-detail startup set on the next
825
- * {@link update}. Hosts that apply their final initial camera pose after the
826
- * mesh first receives frames should call this before lifting their loading
827
- * cover. It is a no-op for every other format and for progressive startup.
832
+ * Captures a fresh startup-hold set on the next {@link update}. Hosts that
833
+ * apply their final initial camera pose after the mesh first receives frames
834
+ * should call this before lifting their loading cover. It is a no-op when
835
+ * the hold was never armed (progressive startup, or a format without the
836
+ * matching LodSource hook).
828
837
  */
829
838
  recaptureInitialReveal(): void;
830
839
  private writeLodLevelChannel;
@@ -881,6 +890,12 @@ export declare class StreamedSplatMesh extends SplatMesh {
881
890
  private criticalRunsFitCapacity;
882
891
  private publishInitialRevealProgress;
883
892
  private releaseInitialReveal;
893
+ /**
894
+ * `.lcc2` coverage hold: freeze coarsest covering runs for in-view cells.
895
+ * Missing `coverageRunsFor` (or an empty result after fallback) releases
896
+ * immediately so the mesh does not stay hidden with nothing to fetch.
897
+ */
898
+ private captureCoverageHold;
884
899
  private captureOrContinueInitialReveal;
885
900
  /** After staging/commits, release the hold when every frozen run is resident. */
886
901
  private finishInitialRevealIfComplete;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@voluma/vlam",
3
- "version": "0.2.1",
3
+ "version": "0.2.2",
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",
@@ -1 +0,0 @@
1
- {"version":3,"file":"splat-budget-PSojLJPO.js","sources":["../src/lib/splat-budget.ts"],"sourcesContent":["/**\n * Device profiling and the default active-splat budget.\n *\n * Streaming is splat-count budgeted rather than byte budgeted: every cost in\n * the renderer (pool textures, sort buffers) scales with the number of\n * resident splats - roughly 64 bytes of GPU memory per splat (three RGBA32F\n * data textures + one RGBA8, plus the sort index/order/bucket buffers), or\n * about 48 bytes when `poolFloatTextures: 'float16'` halves centers and\n * covarianceA; plus about 52 more bytes of CPU-side backing per splat of\n * pool capacity. Capping the active splat count therefore caps memory\n * directly, which is what matters on mobile GPUs.\n */\n\nimport type { StreamedSplatFormat } from './loading';\nimport { shCoefficientCount } from './sh-pack';\n\n/**\n * Desktop GPU capability class for budget / quality defaults.\n *\n * Mobile still keys off {@link SplatDeviceProfile.isMobile}; this splits\n * non-mobile machines that would otherwise share the ~8M workstation path.\n * Unset means \"unknown\" - keep the pre-existing desktop defaults (fail open).\n */\nexport type SplatGpuClass = 'discrete' | 'integrated' | 'fallback';\n\n/** Browser/device signals used for deterministic budget selection. */\nexport interface SplatDeviceProfile {\n /** Coarse memory estimate in GiB, when exposed by the browser. */\n deviceMemoryGb?: number;\n /** Whether the runtime is an iOS/iPadOS-class device. */\n isIOS?: boolean;\n /** Whether the runtime is a phone/tablet-class device (includes iOS). */\n isMobile?: boolean;\n /**\n * Whether the runtime is a standalone XR headset browser (Quest, Pico, …).\n * Headsets are mobile-class GPUs asked to fill a stereo framebuffer larger\n * than a 4K desktop, so they get their own, tighter defaults.\n */\n isHeadset?: boolean;\n /**\n * Whether this is a *budget* phone rather than a flagship one.\n *\n * `isMobile` cannot tell a Galaxy A51 from an iPhone 15 Pro, and the memory\n * signal cannot either - Chrome privacy-caps `deviceMemory` at 8 GiB, so the\n * flagship and the mid-ranger both land on the same ceiling despite an order\n * of magnitude between their GPUs. A coarse signal, and a *downward* one: a\n * reading of ≤4 is trustworthy because the cap only ever lowers it, while a\n * reading of 8 says nothing. {@link hasWebGpu} is the sharper signal where it\n * applies, since it names a difference in how the sort runs rather than\n * guessing capability from RAM.\n */\n isLowPower?: boolean;\n /**\n * Whether the runtime exposes WebGPU at all.\n *\n * `false` means the renderer will take the WebGL2 fallback, where the depth\n * sort runs on the CPU rather than as a GPU compute pass - a different cost\n * curve, not just a slower one. See {@link resolveSplatBudget}.\n *\n * Detected from the presence of `navigator.gpu`, which is a *browser support*\n * signal rather than an adapter one: a runtime that exposes the API but whose\n * `requestAdapter` fails (driver blocklist) still reports `true` here and will\n * fall back to WebGL2 anyway. A host that knows its renderer's real backend\n * can correct this by passing its own profile.\n */\n hasWebGpu?: boolean;\n /**\n * Desktop GPU class from {@link probeSplatGpuClass} / {@link classifySplatGpuClass}.\n * Omit when unknown so workstations without adapter info keep the 8M path.\n */\n gpuClass?: SplatGpuClass;\n}\n\n/** Adapter identifying fields used by {@link classifySplatGpuClass}. */\nexport interface SplatGpuAdapterInfo {\n vendor?: string;\n architecture?: string;\n device?: string;\n description?: string;\n isFallbackAdapter?: boolean;\n}\n\n/**\n * How expensive a format's splats are *per splat*, which is not the same across\n * formats and is the reason one mobile budget cannot serve them all.\n *\n * - `'sampled'` - coarser LOD levels are subsamples of the same surface, so a\n * splat costs about the same however deep the cut is. Streamed SOG.\n * - `'lcc'` - XGRIDS' levels are decimated *alternatives* whose splats merge\n * into wide flat discs (see {@link liftBudgetToFinestLevel}). Cost per splat\n * therefore *rises* as the budget falls, because a tighter budget serves\n * coarser levels and each of their splats covers more pixels. `.rad`, `.lcc`,\n * `.lcc2`.\n *\n * Measured on one iPhone 15 Pro, which is what the numbers below are worth:\n * `oldtimers-route` (`.rad`) ran 31-39 fps at 750k and 45-50 at 600k, while\n * `sandwijck` (streamed SOG) held 52-57 fps at 675k resident. Two streamed\n * scenes, near-identical splat counts, ~20 fps apart - splat count is a poor\n * proxy for cost, and the format is the only better signal available for free\n * before a single byte is fetched.\n */\nexport type SplatCostClass = 'lcc' | 'sampled';\n\n/** The mobile ceilings, per {@link SplatCostClass}. */\ninterface MobileClassBudget {\n /**\n * The most a mobile GPU is asked to keep resident, whatever its RAM says.\n *\n * `deviceMemory` is a *memory* signal, but a mobile GPU runs out of fill rate\n * and bandwidth long before memory: every splat is an alpha-blended quad, and\n * a busy view stacks hundreds of them per pixel. Chrome also privacy-caps\n * `deviceMemory` at 8 GiB, so every Android flagship reports 8 and would\n * otherwise land on the 8M desktop ceiling - measured at 5-24 fps on an\n * Adreno 750 (S24 Ultra), against 45 fps for the same scene on an iPhone at\n * 1M. Peer viewers land in the same band: SuperSplat budgets mobile at 1-2M,\n * Spark targets 1M on Android / 1.5M on iOS.\n */\n ceiling: number;\n /**\n * The budget for a mobile device that exposes no `deviceMemory` at all -\n * which is every iPhone, since mobile Safari does not implement it. This is\n * the branch the measurements above were taken on, so it is a separate number\n * rather than a fraction of {@link ceiling}.\n */\n withoutMemorySignal: number;\n}\n\nconst MOBILE_BUDGETS: Readonly<Record<SplatCostClass, MobileClassBudget>> = {\n // Both measured: 600k held 45-50 fps where 750k managed 31-39. The ceiling\n // matches the default because the evidence is about the class, not the RAM -\n // an Android flagship reporting 8 GiB has no more fill rate for wide discs\n // than an iPhone that reports nothing.\n lcc: { ceiling: 600_000, withoutMemorySignal: 600_000 },\n // Today's numbers, unchanged. `sandwijck` has visible headroom here (it holds\n // 52-57 fps while losing centre detail to the budget), but the replacement is\n // an A/B on device, not a guess.\n sampled: { ceiling: 1_000_000, withoutMemorySignal: 750_000 },\n};\n\n/**\n * Desktop *integrated* / unified GPU ceilings (laptop iGPU, Apple Silicon).\n *\n * These machines report as desktop in the UA and often claim 8 GiB\n * `deviceMemory`, so without a GPU class they inherit the workstation 8M path.\n * LCC stays at 1M to match the demo performance-mode ceiling; streamed SOG can\n * hold a bit more because sampled levels do not inflate per-splat fill the way\n * XGRIDS coarse discs do.\n */\nconst INTEGRATED_BUDGETS: Readonly<Record<SplatCostClass, number>> = {\n lcc: 1_000_000,\n sampled: 2_000_000,\n};\n\n/**\n * Classifies a WebGPU adapter from its identifying strings.\n *\n * Heuristics only - browsers may blank fields for privacy. Prefer\n * {@link probeSplatGpuClass} when both power-preference adapters are available.\n */\nexport function classifySplatGpuClass(info: SplatGpuAdapterInfo | undefined): SplatGpuClass {\n if (info?.isFallbackAdapter === true) return 'fallback';\n const vendor = (info?.vendor ?? '').toLowerCase();\n const architecture = (info?.architecture ?? '').toLowerCase();\n const device = (info?.device ?? '').toLowerCase();\n const description = (info?.description ?? '').toLowerCase();\n const blob = `${vendor} ${architecture} ${device} ${description}`;\n\n // Apple Silicon is always unified memory / shared GPU.\n if (vendor === 'apple' || blob.includes('apple')) return 'integrated';\n\n // Intel integrated families commonly exposed by Chrome's adapter.info.\n if (\n vendor === 'intel' ||\n architecture.startsWith('gen-') ||\n /iris|uhd|xe-lp|xe-hpg|alderlake|tigerlake|meteorlake|arrowlake/.test(blob)\n ) {\n // Discrete Intel Arc often carries \"arc\" or dg2-class strings; treat those\n // as discrete when clearly named, otherwise Intel desktop WebGPU is usually iGPU.\n if (/\\barc\\b|dg2|battlemage|xe2-hpg/.test(blob) && !/iris|uhd|xe-lp/.test(blob)) {\n return 'discrete';\n }\n return 'integrated';\n }\n\n // AMD APUs / explicit iGPU architecture tokens.\n if (vendor === 'amd' || vendor.includes('amd')) {\n if (/igpu|vega-igpu|gfx1\\d-igpu|radeon\\s*graphics(?!\\s*pro)/.test(blob)) {\n return 'integrated';\n }\n // Bare \"amd\" without a discrete cue still often means an APU on laptops;\n // Radeon RX / Radeon Pro name the discrete cards.\n if (/radeon\\s*rx|radeon\\s*pro|navi|rdna/.test(blob)) return 'discrete';\n }\n\n return 'discrete';\n}\n\n/** Minimal `navigator.gpu` surface for {@link probeSplatGpuClass}. */\nexport interface SplatGpuProbeEntry {\n requestAdapter(options?: {\n powerPreference?: 'low-power' | 'high-performance';\n }): Promise<SplatGpuProbeAdapter | null>;\n}\n\n/** Adapter handle with optional `.info` (WebGPU GPUAdapterInfo). */\nexport interface SplatGpuProbeAdapter {\n readonly info?: SplatGpuAdapterInfo;\n}\n\nfunction ambientProbeGpu(): SplatGpuProbeEntry | null {\n const nav = typeof navigator !== 'undefined' ? (navigator as { gpu?: unknown }) : undefined;\n const gpu = nav?.gpu;\n return gpu ? (gpu as SplatGpuProbeEntry) : null;\n}\n\nfunction adapterIdentityKey(info: SplatGpuAdapterInfo | undefined): string {\n return [\n info?.vendor ?? '',\n info?.architecture ?? '',\n info?.device ?? '',\n info?.description ?? '',\n ].join('\\0');\n}\n\n/**\n * Probes WebGPU adapters to choose a {@link SplatGpuClass}.\n *\n * Requests both `low-power` and `high-performance` adapters when possible. A\n * hybrid laptop that exposes two different devices is `discrete`; a single\n * shared / unified GPU (Apple Silicon, many iGPU-only machines) is classified\n * from {@link classifySplatGpuClass}. Returns `undefined` when WebGPU is absent\n * or the probe fails, so budget resolution keeps the legacy desktop path.\n */\nexport async function probeSplatGpuClass(\n gpu: SplatGpuProbeEntry | null | undefined = typeof navigator !== 'undefined'\n ? ambientProbeGpu()\n : null,\n): Promise<SplatGpuClass | undefined> {\n if (!gpu) return undefined;\n let low: SplatGpuProbeAdapter | null;\n let high: SplatGpuProbeAdapter | null;\n try {\n const adapters = await Promise.all([\n gpu.requestAdapter({ powerPreference: 'low-power' }),\n gpu.requestAdapter({ powerPreference: 'high-performance' }),\n ]);\n low = adapters[0] ?? null;\n high = adapters[1] ?? null;\n } catch {\n return undefined;\n }\n if (!low && !high) return undefined;\n\n const lowInfo = low?.info;\n const highInfo = high?.info;\n if (lowInfo?.isFallbackAdapter || highInfo?.isFallbackAdapter) return 'fallback';\n\n const lowKey = adapterIdentityKey(lowInfo);\n const highKey = adapterIdentityKey(highInfo);\n const both = low != null && high != null;\n // Distinct non-empty identities ⇒ hybrid dGPU available.\n if (both && lowKey.length > 3 && highKey.length > 3 && lowKey !== highKey) {\n return 'discrete';\n }\n\n const info = highInfo ?? lowInfo;\n return classifySplatGpuClass(info);\n}\n\n/**\n * Whether fill-rate / laptop-class defaults apply (mobile, or desktop\n * integrated / software fallback). Exported so hosts and the demo share one\n * predicate for performance-mode defaults and adaptive DPR.\n */\nexport function isFillConstrainedSplatDevice(\n profile: SplatDeviceProfile | undefined = detectSplatDeviceProfile(),\n): boolean {\n return (\n profile?.isMobile === true ||\n profile?.gpuClass === 'integrated' ||\n profile?.gpuClass === 'fallback'\n );\n}\n\n/**\n * The cost class of a streamed format. Unknown and absent formats read as\n * `'sampled'`, which is the pre-existing behaviour for every caller that does\n * not name one.\n */\nfunction splatCostClass(format?: StreamedSplatFormat): SplatCostClass {\n return format === 'rad' || format === 'lcc' || format === 'lcc2' ? 'lcc' : 'sampled';\n}\n\n/**\n * The headset ceiling, below the phone one.\n *\n * A headset is a phone-class GPU asked to fill a stereo framebuffer larger\n * than a 4K desktop (~1680×1760 *per eye* on a Quest 3), sharing the SoC with\n * a compositor that must hit 72 Hz. Every splat is drawn twice, so the\n * fill-rate wall that sets {@link MOBILE_BUDGET_MAX} arrives proportionally\n * sooner. This is a *cap*, not a floor: a genuinely small device still scales\n * below it on its memory signal.\n */\nconst HEADSET_BUDGET_MAX = 600_000;\n\n/**\n * The ceiling for a budget phone, below the flagship one.\n *\n * A mid-range mobile GPU is not a slightly slower flagship: a Mali-G72 MP3\n * (Galaxy A51) has a small fraction of an Adreno 750's fill rate, while both\n * report the same privacy-capped 8 GiB `deviceMemory` and the same `isMobile`.\n * Starting such a device at the flagship ceiling means it thrashes from the\n * first frame. This is a *cap*: a device whose memory signal is lower still\n * scales below it.\n */\nconst LOW_POWER_BUDGET_MAX = 500_000;\n\n/**\n * The ceiling for a mobile device with no WebGPU at all.\n *\n * This is the tightest tier, and the signal behind it is the most direct: with\n * no WebGPU there is no compute path, so the depth sort runs on the CPU in a\n * worker, and that cost scales with the splat count far worse than a GPU radix\n * sort does. A phone still on the WebGL2 fallback is also, in practice, old -\n * WebGPU has shipped on Android 12+ and iOS 18 - so the two costs arrive\n * together.\n *\n * Measured on a Galaxy S7 (2016, Mali-T880, WebGL2) at **750k**, which was the\n * low-power tier at the time: **5 fps, 194 ms frames**. That device is out of\n * scope as a target, but it is evidence that the memory-derived tier alone lands\n * far too high once the sort is on the CPU. The tiers have since been lowered\n * across the board, so the figure is the measurement's, not this constant's.\n *\n * Desktop is deliberately exempt: a desktop that falls back to WebGL2 is\n * sorting on a far stronger CPU, and capping it here would punish a\n * driver-blocklist fallback on capable hardware.\n */\nconst NO_WEBGPU_BUDGET_MAX = 400_000;\n\n/** Reads the available browser device signals without requiring a DOM runtime. */\nexport function detectSplatDeviceProfile(): SplatDeviceProfile | undefined {\n if (typeof navigator === 'undefined') return undefined;\n const nav = navigator as Navigator & { deviceMemory?: number };\n const isIOS =\n /iPhone|iPad|iPod/.test(nav.userAgent) ||\n (nav.platform === 'MacIntel' && nav.maxTouchPoints > 1);\n // UA first (it names the platform outright); the coarse-pointer probe then\n // catches mobile browsers that hide or reword their UA.\n const isMobile =\n isIOS ||\n /Android/i.test(nav.userAgent) ||\n (nav.maxTouchPoints > 0 &&\n typeof matchMedia === 'function' &&\n matchMedia('(pointer: coarse)').matches);\n // Best-effort *hint* only - see `resolveXrSplatBudget`, which is what\n // actually sizes an XR session. Most standalone headsets are Android under\n // the hood (Quest, Pico, Vive, Android XR), so `isMobile` already catches\n // them even when this misses; the named flag just lets first paint start at\n // a headset-appropriate size instead of resizing after the session opens.\n //\n // It cannot be relied on. visionOS Safari presents as *desktop* Safari, so\n // Apple Vision Pro matches neither this nor `isMobile` and would take the\n // desktop budget; and every new headset misses until its string is added.\n // That is the whole reason budgets key off presentation state instead.\n const isHeadset = /OculusBrowser|Quest|Pico(?: Neo)?[ /]|Wolvic|VRBrowser|Vive|XRBrowser/i.test(\n nav.userAgent,\n );\n // A budget phone, best-effort. `deviceMemory` is privacy-capped at 8 GiB but\n // *not* raised, so a device reporting ≤4 really does have ≤4 - that makes a\n // low reading trustworthy even though a high one says nothing. Deliberately\n // not `hardwareConcurrency`: it would get this exactly backwards, since the\n // Galaxy A51 this exists for is octa-core while an iPhone 15 Pro reports 6.\n const isLowPower =\n (isMobile || isHeadset) && nav.deviceMemory !== undefined && nav.deviceMemory <= 4;\n return {\n ...(nav.deviceMemory === undefined ? {} : { deviceMemoryGb: nav.deviceMemory }),\n isIOS,\n isMobile: isMobile || isHeadset,\n isHeadset,\n isLowPower,\n hasWebGpu: 'gpu' in nav,\n };\n}\n\n/** Scene-side signals for {@link resolveSplatBudget}. */\nexport interface SplatBudgetOptions {\n /**\n * The format about to be loaded, which selects the {@link SplatCostClass}\n * whose mobile tier applies. Omit when it is not yet known - the `'sampled'`\n * numbers are what every caller resolved before cost classes existed.\n */\n format?: StreamedSplatFormat;\n /**\n * A ceiling on the resolved default, for callers that want to tighten without\n * overriding what this function knows.\n *\n * `override` is absolute: it wins over the device tier, the cost class and\n * everything else, because a caller who names a number has said they know\n * better. That is the right contract and the wrong tool for \"the same as\n * usual, but no more than N\" - which is what a performance toggle or a host\n * default actually means. Pinning a number there has twice shipped as a bug:\n * a demo performance mode that *raised* the load on the weakest device tested,\n * and a host default that bypassed every device tier.\n *\n * Applied only when `override` is omitted, and only downward.\n */\n cap?: number;\n}\n\n/**\n * Chooses a default active-splat budget for the current device.\n *\n * The default is derived from the coarsest device-memory signal the platform\n * exposes; callers who know better (or want a hard cap for a mobile test on\n * desktop) should pass an explicit override.\n *\n * @param override - Explicit budget in splats; wins over device detection when\n * positive. Throws `RangeError` if it is not a positive finite number.\n * @param profile - Device signals to decide from; defaults to detecting them.\n * @param options - Scene signals. `format` selects the {@link SplatCostClass}\n * whose mobile tier applies; omitting it keeps the `'sampled'` numbers, which\n * are what every caller resolved before cost classes existed. `cap` is a\n * ceiling on the *resolved default*, for callers who want to tighten without\n * overriding - see {@link SplatBudgetOptions.cap}.\n * @returns A splat-count budget, clamped to a sensible range.\n */\nexport function resolveSplatBudget(\n override?: number,\n profile: SplatDeviceProfile | undefined = detectSplatDeviceProfile(),\n options: SplatBudgetOptions = {},\n): number {\n const cap = options.cap;\n if (cap !== undefined && (!Number.isFinite(cap) || cap <= 0)) {\n throw new RangeError('Splat budget cap must be a positive finite number.');\n }\n if (override !== undefined) {\n if (!Number.isFinite(override) || override <= 0) {\n throw new RangeError('Splat budget must be a positive finite number.');\n }\n // Deliberately *not* capped: `override` is the caller saying they know\n // better than every default, and `cap` is a ceiling on a default. Applying\n // it here would make it a second, quieter override.\n return Math.floor(override);\n }\n const capped = (budget: number): number =>\n cap === undefined ? budget : Math.min(budget, Math.floor(cap));\n\n // The device ceiling, tightest signal first. Expressed as a cap rather than\n // a flat headset default so a low-memory headset still scales *below* it\n // instead of being pinned up to it - and so the memory validation below\n // still runs for headsets.\n // Every applicable cap, then the tightest of them. A ternary chain would make\n // this order-dependent, and the order is not obvious - a device can be mobile\n // *and* low-power *and* on the WebGL2 fallback at once, and the answer must be\n // the smallest cap regardless of which test happens to run first.\n //\n // Only the mobile cap is per-format. The headset, low-power and no-WebGPU\n // tiers were each measured on their own hardware against a limit the format\n // cannot move - stereo fill, a mid-range GPU, a CPU-side sort - so they stay\n // absolute, and a raised `'sampled'` tier never reaches those devices.\n const mobile = MOBILE_BUDGETS[splatCostClass(options.format)];\n const costClass = splatCostClass(options.format);\n const caps: number[] = [];\n if (profile?.isHeadset) caps.push(HEADSET_BUDGET_MAX);\n if (profile?.isLowPower) caps.push(LOW_POWER_BUDGET_MAX);\n if (profile?.isMobile) caps.push(mobile.ceiling);\n // Mobile only: a desktop on the WebGL2 fallback sorts on a far stronger CPU.\n if (profile?.isMobile && profile.hasWebGpu === false) caps.push(NO_WEBGPU_BUDGET_MAX);\n // Desktop GPU class: laptop / unified / software must not inherit the 8M path.\n if (!profile?.isMobile && profile?.gpuClass === 'integrated') {\n caps.push(INTEGRATED_BUDGETS[costClass]);\n }\n if (!profile?.isMobile && profile?.gpuClass === 'fallback') {\n caps.push(NO_WEBGPU_BUDGET_MAX);\n }\n const ceiling = caps.length === 0 ? Infinity : Math.min(...caps);\n\n // `deviceMemory` (Chrome/Edge/Android) reports GiB, spec-capped at 8.\n const deviceMemoryGb = profile?.deviceMemoryGb;\n if (deviceMemoryGb !== undefined) {\n if (!Number.isFinite(deviceMemoryGb) || deviceMemoryGb <= 0) {\n throw new RangeError('Device memory must be a positive finite number.');\n }\n // 1M splats per reported GiB → Chrome's 8 GiB privacy cap yields the 8M\n // desktop default. Mobile/headset/integrated caps above still win when tighter.\n const scaled = clamp(Math.round(deviceMemoryGb * 1_000_000), 500_000, 8_000_000);\n return capped(Math.min(scaled, ceiling));\n }\n\n // No `deviceMemory`: mobile Safari (iOS) and privacy-restricted mobile\n // browsers land here, and must not fall through to the desktop default.\n if (profile?.isMobile) return capped(Math.min(mobile.withoutMemorySignal, ceiling));\n\n // Integrated / fallback desktop without a memory signal still needs the class\n // ceiling (Apple Silicon Safari often omits deviceMemory entirely).\n if (profile?.gpuClass === 'integrated') {\n return capped(Math.min(INTEGRATED_BUDGETS[costClass], ceiling));\n }\n if (profile?.gpuClass === 'fallback') {\n return capped(Math.min(NO_WEBGPU_BUDGET_MAX, ceiling));\n }\n\n // An absent profile can mean SSR, Node tooling, or a privacy-restricted\n // browser. Known non-iOS desktop without a memory signal still gets the\n // 8M default; everything else stays on the conservative portable floor.\n return capped(profile?.isIOS === false ? 8_000_000 : 1_000_000);\n}\n\n/**\n * The budget to run at **while an immersive session presents**, given whatever\n * budget the page is using outside one.\n *\n * Stereo is the cost, and stereo is a property of the *session*, not of the\n * device: every splat is drawn twice, into two eye viewports that together\n * exceed a 4K desktop, on a GPU that must hold 72–90 Hz or the compositor\n * reprojects. That is true of a standalone headset and equally true of a\n * desktop machine driving a tethered one - which is exactly the case device\n * sniffing cannot see, since such a machine is a desktop right up until the\n * moment it is not.\n *\n * Keying off presentation instead of identity is also the only approach that\n * survives new hardware. `detectSplatDeviceProfile`'s `isHeadset` is a\n * user-agent guess: it misses Apple Vision Pro outright (visionOS Safari\n * presents as desktop Safari, so a headset would otherwise take the multi-\n * million desktop budget) and misses every headset released after it is\n * written. This function needs to know none of that.\n *\n * Apply it on `sessionstart` and restore the original on `sessionend` - via\n * `BudgetGovernor.setBudget` when several meshes share a pool, or a streamed\n * mesh's own budget setter otherwise.\n *\n * @param pageBudget - The budget in use outside the session, typically from\n * {@link resolveSplatBudget}. Throws `RangeError` if not a positive finite\n * number.\n * @returns `pageBudget` lowered to the stereo ceiling; never raised - a device\n * already rendering below the ceiling stays where it is.\n */\nexport function resolveXrSplatBudget(pageBudget: number): number {\n if (!Number.isFinite(pageBudget) || pageBudget <= 0) {\n throw new RangeError('Splat budget must be a positive finite number.');\n }\n return Math.min(Math.floor(pageBudget), HEADSET_BUDGET_MAX);\n}\n\n/**\n * The largest finest-level scene taken whole rather than streamed. At ~64 B\n * of GPU pool per splat this is ~380 MB - affordable on a desktop, and far\n * cheaper than it looks next to the alternative, since a scene held whole\n * never swaps, never compacts and never re-fetches.\n */\nconst FINEST_LEVEL_BUDGET_MAX = 8_000_000;\n\n/**\n * Raises `budget` far enough to hold a scene's finest level in full, when\n * that level is small enough to be worth taking whole.\n *\n * The LOD budget assumes coarser levels are cheap *approximations* of the\n * same surface, so trading detail for memory is nearly free. XGRIDS' LCC\n * LCC breaks that assumption: its five levels are decimated alternatives\n * whose splats merge into wide flat discs (correct at distance, streaked up\n * close), so any budget shortfall costs visible quality - sub-chunking gives\n * the scheduler ~128k-splat granularity to thin cells with, but a thinned\n * fine level is still sparser than the capture intends. A capture whose\n * finest level fits under the desktop ceiling is better shown whole: Casino's\n * level 0 is 4.74M splats and sits under the 8M default.\n *\n * Mobile and fill-constrained desktops (integrated / fallback GPU class) are\n * exempt: their cap is a fill-rate limit, not a sizing accident.\n *\n * @param budget - The resolved device budget.\n * @param finestLevelSplats - Splats in the scene's finest level.\n * @returns `budget`, or the finest level's size when that is the better fit.\n */\nexport function liftBudgetToFinestLevel(\n budget: number,\n finestLevelSplats: number,\n profile: SplatDeviceProfile | undefined = detectSplatDeviceProfile(),\n): number {\n if (isFillConstrainedSplatDevice(profile)) return budget;\n if (!Number.isFinite(finestLevelSplats) || finestLevelSplats <= budget) return budget;\n if (finestLevelSplats > FINEST_LEVEL_BUDGET_MAX) return budget;\n return Math.floor(finestLevelSplats);\n}\n\n/** Options for {@link estimateSplatPoolBytes}. */\nexport interface SplatPoolBytesOptions {\n /**\n * Pool texture precision, matching `SplatMeshOptions.poolFloatTextures`.\n * `'float16'` halves centers and covarianceA. Default `'float32'`.\n */\n floatTextures?: 'float32' | 'float16';\n /** Per-splat SH bands the pool allocates for. Default `0`. */\n shBands?: 0 | 1 | 2 | 3;\n /**\n * Pool capacity as a multiple of `splats`. `StreamedSplatMesh` allocates\n * 1.5× (the default here) so per-run row alignment and the\n * append-before-remove window during LOD swaps have somewhere to go; pass\n * `1.4` to model `experimentalStagedSwaps: false`, or `1` for a static mesh.\n */\n capacityFactor?: number;\n /**\n * Whether to include the CPU-side backing arrays. Default `true` - they are\n * real host memory a device has to find, so the honest answer to \"can I\n * afford this ceiling\" includes them.\n */\n includeCpuBacking?: boolean;\n}\n\n/**\n * Estimates the memory a splat pool of `splats` costs.\n *\n * This exists to make a streamed mesh's `maxBudget` a computation rather than a\n * guess. A pool is allocated **once, from the ceiling** and never\n * grows, so several governed meshes cost the sum of their ceilings whatever the\n * shared budget is set to - a `BudgetGovernor` redistributes *sharpness* within\n * that envelope, it does not shrink it. Price the ceilings before choosing them:\n *\n * ```js\n * // 1 main + 4 markers, each able to reach 1.5M splats\n * const bytes = estimateSplatPoolBytes(4_000_000) + 4 * estimateSplatPoolBytes(1_500_000);\n * ```\n *\n * Per splat of *capacity* (`splats × capacityFactor`), counted from what the\n * constructor actually allocates:\n *\n * - **Pool textures** 52 B - centers RGBA32F 16, colors RGBA8 4,\n * covarianceA RGBA32F 16, covarianceB RGBA32F 16. `'float16'` drops centers\n * and covarianceA to 8 each (36 B); covarianceB stays float32 because it\n * packs integer IDs.\n * - **Packed SH** 16 B per `RGBA32UI` texture, `ceil(coefficients / 4)` of them\n * - so 16 / 32 / 64 B at 1 / 2 / 3 bands.\n * - **Sort storage** 16 B - the radix sorter's ping-pong key/value buffers.\n * - **CPU backing** 68 B - the float32/uint8 arrays kept for partial uploads\n * (always full precision, even under `'float16'`): centers 16, colors 4,\n * covarianceA 16, covarianceB 16, plus four u32-per-splat arrays - draw-order\n * indices, the active-list source index, the pool-slot map, and the picker's\n * pool-index template (allocated lazily, counted because a picked scene pays\n * it). Under `'float16'` add a further 16 B: the half-encoded texture images\n * are held alongside the float32 backing, not instead of it, so that\n * precision saves GPU bytes only. Included unless `includeCpuBacking` is\n * `false`.\n *\n * The module header's \"roughly 64 bytes per splat\" rounds the GPU side of this.\n *\n * @param splats - The ceiling in splats (e.g. a mesh's `maxBudget`).\n * @returns Estimated bytes. Indicative, not a device-memory guarantee: driver\n * texture padding, staging allocations and the decoded-chunk CPU cache\n * ({@link resolveCpuCacheBytes}) sit outside it.\n * @throws {RangeError} if `splats` is not a positive finite number, or\n * `capacityFactor` is not a finite number `>= 1`.\n */\nexport function estimateSplatPoolBytes(\n splats: number,\n options: SplatPoolBytesOptions = {},\n): number {\n if (!Number.isFinite(splats) || splats <= 0) {\n throw new RangeError('Splat count must be a positive finite number.');\n }\n const capacityFactor = options.capacityFactor ?? 1.5;\n if (!Number.isFinite(capacityFactor) || capacityFactor < 1) {\n throw new RangeError('Pool capacityFactor must be a finite number >= 1.');\n }\n const float16 = options.floatTextures === 'float16';\n const shTextures = Math.ceil(shCoefficientCount(options.shBands ?? 0) / 4);\n const shBytes = shTextures * 16;\n\n const centers = float16 ? 8 : 16;\n const covarianceA = float16 ? 8 : 16;\n const poolTextures = centers + 4 /* colors */ + covarianceA + 16 /* covarianceB */ + shBytes;\n const sortBuffers = 16; // radix ping-pong: keys A/B + values A/B, u32 each\n // Backing arrays are float32/uint32 regardless of the texture precision, and\n // under 'float16' the half-encoded texture images are held *in addition* to\n // them (the constructor keeps both), so that precision saves GPU bytes only.\n const halfImages = float16 ? 8 + 8 : 0; /* centersImage + covarianceAImage */\n const cpuBacking =\n options.includeCpuBacking === false\n ? 0\n : 16 /* centers */ +\n 4 /* colors */ +\n 16 /* covarianceA */ +\n 16 /* covarianceB */ +\n shBytes +\n 4 /* draw order (splatIndexes) */ +\n 4 /* active-list source index */ +\n 4 /* activeSlotByPoolIndex */ +\n 4 /* picker pool-index template */ +\n halfImages;\n\n const capacity = Math.ceil(splats * capacityFactor);\n return capacity * (poolTextures + sortBuffers + cpuBacking);\n}\n\n/**\n * Suggested ceiling for the renderer's pixel ratio on this device.\n *\n * Splat rendering is fragment-bound, so render resolution is one of the\n * largest costs on a high-DPI phone: a 2.6x display renders ~7x the pixels of\n * a 1x one, and every one of them blends the full depth-sorted splat stack.\n * The library cannot apply this itself (it draws into a renderer the app\n * owns), so it exports the policy - pass it to `renderer.setPixelRatio`:\n *\n * ```js\n * renderer.setPixelRatio(Math.min(window.devicePixelRatio, recommendedMaxPixelRatio()));\n * ```\n *\n * This is the *quality* ceiling. Viewers that offer a performance mode\n * (SuperSplat halves mobile resolution in its own) should go lower still when\n * it is on.\n */\nexport function recommendedMaxPixelRatio(\n profile: SplatDeviceProfile | undefined = detectSplatDeviceProfile(),\n): number {\n return isFillConstrainedSplatDevice(profile) ? 1.5 : 2;\n}\n\n/**\n * The Gaussian cutoff a `.rad` renders at, in standard deviations, or\n * `undefined` to accept the device-wide default.\n *\n * Spark hard-codes `sqrt(8)` (≈2.83σ) for every device, and matching it is what\n * makes a `.rad` look like Spark's render on a desktop. On a phone it is the\n * wrong trade: rendering is fill-bound on mobile, so a format override bypasses\n * the device policy that every other format accepts.\n *\n * Returning `undefined` on mobile lets `SplatMesh` apply its own 3σ cutoff and\n * undersized-splat floor; `.rad` must not escape that mobile policy.\n *\n * @returns √8 on discrete desktop; `undefined` on fill-constrained devices,\n * meaning \"no format override\".\n */\nexport function recommendedRadMaxStdDev(\n profile: SplatDeviceProfile | undefined = detectSplatDeviceProfile(),\n): number | undefined {\n return isFillConstrainedSplatDevice(profile) ? undefined : Math.SQRT2 * 2;\n}\n\n/**\n * Suggested WebXR framebuffer scale for this device. On three 0.185.x this is\n * a **WebGL XR** policy: apply it once before the session starts with\n * `renderer.xr.setFramebufferScaleFactor`. three's WebGPU XR path creates its\n * `XRGPUBinding` projection layer at native scale and does not consume that\n * setting, so WebGPU hosts should leave the native scale and use the presenting\n * splat budget plus fixed foveation for runtime headroom instead.\n *\n * Splat rendering is fill-bound, and a headset's default framebuffer is\n * already supersampled past its panels (~1680×1760 per eye on Quest 3):\n * 0.8 cuts fragment work ~36% for a barely visible softening. Non-headset\n * XR (desktop-tethered) keeps the native 1.0.\n */\nexport function recommendedXrFramebufferScale(\n profile: SplatDeviceProfile | undefined = detectSplatDeviceProfile(),\n): number {\n return profile?.isHeadset ? 0.8 : 1;\n}\n\n/** Inputs for {@link suggestAdaptivePixelRatio}. */\nexport interface AdaptivePixelRatioInput {\n /** Latest wall-frame time in milliseconds. */\n frameMs: number;\n /** Currently applied pixel ratio. */\n current: number;\n /** Quality ceiling (typically {@link recommendedMaxPixelRatio}). */\n max: number;\n /** Floor; defaults to `1`. */\n min?: number;\n /** EMA of frame time from the previous call; omit on the first sample. */\n emaMs?: number;\n /**\n * Comfortable frame time (ms). Below this (with headroom) the helper may\n * step the ratio up. Default `18` (~55 fps).\n */\n targetFrameMs?: number;\n /**\n * Sustained frame time (ms) that triggers a step down. Default `22`\n * (~45 fps) so brief spikes do not thrash the canvas size.\n */\n pressureFrameMs?: number;\n}\n\n/** Result of {@link suggestAdaptivePixelRatio}. */\nexport interface AdaptivePixelRatioResult {\n /** Suggested pixel ratio after hysteresis (quarter steps). */\n pixelRatio: number;\n /** Updated EMA to pass back on the next call. */\n emaMs: number;\n}\n\n/**\n * Suggests a pixel ratio under frame-time pressure.\n *\n * The library cannot call `renderer.setPixelRatio` (the host owns the\n * renderer); this is a pure policy helper. Pass the previous result's\n * `emaMs` each frame for a stable EMA, and only re-size the canvas when\n * `pixelRatio` changes.\n *\n * Steps are quarter-units with asymmetric thresholds (pressure to lower,\n * comfortable headroom to raise) so the ratio does not oscillate.\n */\nexport function suggestAdaptivePixelRatio(\n input: AdaptivePixelRatioInput,\n): AdaptivePixelRatioResult {\n const min = input.min ?? 1;\n const max = Math.max(min, input.max);\n const targetFrameMs = input.targetFrameMs ?? 18;\n const pressureFrameMs = input.pressureFrameMs ?? 22;\n const frameMs = Number.isFinite(input.frameMs) ? Math.max(0, input.frameMs) : targetFrameMs;\n const alpha = 0.15;\n const emaMs = input.emaMs === undefined ? frameMs : input.emaMs * (1 - alpha) + frameMs * alpha;\n\n let next = clamp(input.current, min, max);\n if (emaMs > pressureFrameMs && next > min) {\n next = Math.max(min, roundPixelRatio(next - 0.25));\n } else if (emaMs < targetFrameMs * 0.85 && next < max) {\n next = Math.min(max, roundPixelRatio(next + 0.25));\n }\n return { pixelRatio: clamp(next, min, max), emaMs };\n}\n\n/** Quarter-step pixel ratios (1, 1.25, 1.5, …) keep canvas resizes coarse. */\nfunction roundPixelRatio(value: number): number {\n return Math.round(value * 4) / 4;\n}\n\n/**\n * Chooses a decoded-chunk CPU cache cap from the same safe device profile.\n *\n * **The unknown-memory fallback must not read as \"tiny\".** iOS Safari does not\n * implement `navigator.deviceMemory` at all, so every iPhone lands on this\n * branch - and an earlier version resolved it to 1 GiB, i.e. the 32 MiB floor,\n * on hardware with 8 GiB. That is not a conservative guess, it is a wrong one,\n * and it is invisible on `.rad`, whose page-table cache has its own floor.\n *\n * On streamed SOG there is no such floor and the cost is immediate: measured on\n * an iPhone 15 Pro against `sandwijck`, the scheduler asked for 539,734 splats\n * and the mesh could only hold 466,499 of them across 3 chunk files (desktop:\n * 5), evicting continuously. The finest level is wanted *nearest the camera* and\n * lives in the largest files, so those are what fail to stay resident - the\n * middle of the view drops out and the scene renders as a donut.\n *\n * A device that declines to report its memory is far likelier to be a modern\n * phone withholding a fingerprinting signal than an actual 1 GiB device, so the\n * fallback assumes 4 GiB (128 MiB of cache). The floor stays for the genuinely\n * profile-less case - SSR and Node tooling, which never stream a scene anyway.\n */\nexport function resolveCpuCacheBytes(\n profile: SplatDeviceProfile | undefined = detectSplatDeviceProfile(),\n): number {\n const gb = profile === undefined ? 1 : (profile.deviceMemoryGb ?? 4);\n const mib = 1024 * 1024;\n return Math.min(256 * mib, Math.max(32 * mib, gb * 32 * mib));\n}\n\nfunction clamp(value: number, min: number, max: number): number {\n return Math.min(max, Math.max(min, value));\n}\n"],"names":["MOBILE_BUDGETS","INTEGRATED_BUDGETS","classifySplatGpuClass","info","vendor","architecture","device","description","blob","ambientProbeGpu","nav","gpu","adapterIdentityKey","probeSplatGpuClass","low","high","adapters","lowInfo","highInfo","lowKey","highKey","isFillConstrainedSplatDevice","profile","detectSplatDeviceProfile","splatCostClass","format","HEADSET_BUDGET_MAX","LOW_POWER_BUDGET_MAX","NO_WEBGPU_BUDGET_MAX","isIOS","isMobile","isHeadset","isLowPower","resolveSplatBudget","override","options","cap","capped","budget","mobile","costClass","caps","ceiling","deviceMemoryGb","scaled","clamp","resolveXrSplatBudget","pageBudget","FINEST_LEVEL_BUDGET_MAX","liftBudgetToFinestLevel","finestLevelSplats","estimateSplatPoolBytes","splats","capacityFactor","float16","shBytes","shCoefficientCount","centers","covarianceA","poolTextures","sortBuffers","halfImages","cpuBacking","recommendedMaxPixelRatio","recommendedRadMaxStdDev","recommendedXrFramebufferScale","suggestAdaptivePixelRatio","input","min","max","targetFrameMs","pressureFrameMs","frameMs","alpha","emaMs","next","roundPixelRatio","value","resolveCpuCacheBytes","gb","mib"],"mappings":";AA+HA,MAAMA,IAAsE;AAAA;AAAA;AAAA;AAAA;AAAA,EAK1E,KAAK,EAAE,SAAS,KAAS,qBAAqB,IAAA;AAAA;AAAA;AAAA;AAAA,EAI9C,SAAS,EAAE,SAAS,KAAW,qBAAqB,KAAA;AACtD,GAWMC,IAA+D;AAAA,EACnE,KAAK;AAAA,EACL,SAAS;AACX;AAQO,SAASC,EAAsBC,GAAsD;AAC1F,OAAIA,KAAA,gBAAAA,EAAM,uBAAsB,GAAM,QAAO;AAC7C,QAAMC,MAAUD,KAAA,gBAAAA,EAAM,WAAU,IAAI,YAAA,GAC9BE,MAAgBF,KAAA,gBAAAA,EAAM,iBAAgB,IAAI,YAAA,GAC1CG,MAAUH,KAAA,gBAAAA,EAAM,WAAU,IAAI,YAAA,GAC9BI,MAAeJ,KAAA,gBAAAA,EAAM,gBAAe,IAAI,YAAA,GACxCK,IAAO,GAAGJ,CAAM,IAAIC,CAAY,IAAIC,CAAM,IAAIC,CAAW;AAG/D,MAAIH,MAAW,WAAWI,EAAK,SAAS,OAAO,EAAG,QAAO;AAGzD,M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