import type { SplatLoadStatus } from '../loaders/loading'; import type { Lcc2QualityPolicy } from '../formats/lcc/lcc2'; export * from './streamed-splat-mesh-utils'; import * as THREE from 'three/webgpu'; import { SplatMesh, type SplatChannelOptions, type SplatMeshOptions, type SplatUpdateOptions, type SplatUpdateTimings } from '../core/splat-mesh'; import { type LodRun } from './lod-scheduler'; import { type StreamedScene } from './lod-source'; import type { CollisionMeshTile } from '../formats/lcc/collision-mesh'; import { type SplatDatasetSource } from './dataset-source'; import { SplatLoadError, type SplatRequestOptions, type StreamedSplatFormat } from '../loaders/loading'; import { type SplatDeviceProfile } from '../core/splat-budget'; import { type FrontierFoveation, type FrontierPlanMessage, type FrontierPlanReason, type FrontierSkipSample, type FrontierSnapshotReply } from '../formats/rad/frontier-worker-protocol'; import type { ChunkFetchScheduler } from './chunk-fetch-scheduler'; import type { ChunkCacheBudget } from './chunk-cache-budget'; import { type BrushStroke, type BrushStrokeSelectionOptions } from '../selection/brush-stroke'; type FrontierGenerationTraceEvent = { at: number; event: 'next-reschedule' | 'traversal-complete' | 'staging-start' | 'staging-complete' | 'active-list-replacement' | 'sort-ready' | 'rendered' | 'gather-sort-publication' | 'worker-ack'; generation: number | null; candidateSize?: number; candidateNewSlots?: number; candidateReusedSlots?: number; writes?: number; activeCount?: number; planReason?: FrontierPlanReason | null; traversalId?: number; revealReady?: boolean; maxCentralProjectedRatio?: number; maxVisibleProjectedRatio?: number; }; /** * Rough decoded size of a whole streamed scene, for sizing the cache floor: * positions (12 B) + colors (4 B) + covariances (24 B) per splat, plus the LOD * tree arrays a `.rad` chunk carries (`childCount` 4 B + `childStart` 4 B + * `size` 4 B) and packed SH when the scene carries it. Deliberately an * over-estimate - the floor should never be the reason a capture cannot hold * itself, and it must match what the frontier worker charges its cache, or a * capture the cap was sized to hold starts evicting itself mid-load. * * Exported for unit testing only; not part of the public API. */ export declare function estimateSceneDecodedBytes(scene: StreamedScene): number; /** * Page-table pool for chunk residency, or why the mesh keeps the indexed path. * * `profile` defaults to the detected device like every budget resolver: hosts * normally omit `deviceProfile`, and without it the device memory clamp never * applied, so an iPhone reserved the full 256-page target and the tab crashed * loading. Phones keep chunk pages under {@link MOBILE_RAD_CHUNK_POOL_BYTES} * rather than falling back: on the iPhone the indexed path never published a * main cut, and shared-pool markers could not reserve its two-cut slots. * * Exported for unit testing only; not part of the public API. */ export declare function radChunkResidencyPages(scene: StreamedScene, profile: SplatDeviceProfile | undefined, options: StreamedSplatMeshOptions, budget: number): { pages: number; chunkSize: number; } | { fallback: string; }; /** * Read-only startup-hold progress for {@link StreamedSplatMeshOptions.initialReveal}. * Exported for hosts that gate visibility on the first useful coverage frame * (classic `.lcc` nearby L1 / far coarsest, `.lcc2` in-view base coverage, or an * explicit nearby-L0 hold). */ export type InitialRevealState = { readonly status: 'disabled'; } | { readonly status: 'pending'; readonly stagedSplats: number; readonly totalSplats: number; readonly readyGroups: number; readonly totalGroups: number; } | { readonly status: 'ready'; } | { readonly status: 'degraded'; readonly reason: 'capacity' | 'fetch-failed' | 'timeout'; readonly stagedSplats: number; readonly totalSplats: number; readonly readyGroups: number; readonly totalGroups: number; }; /** Per-update CPU stages a streamed mesh adds to the base timings, all in milliseconds. */ declare const createUpdateStageTimings: () => { cameraSyncMs: number; shouldRescheduleMs: number; rescheduleMs: number; baseUpdateMs: number; demandPoseMs: number; demandStateMs: number; demandReconcileMs: number; workerPostMs: number; diagnosticTraceMs: number; lcc2LevelUpdateMs: number; lcc2BudgetSelectMs: number; lcc2CollectCutMs: number; diagnosticSnapshotMs: number; classicCameraSelectMs: number; classicDesiredBookkeepingMs: number; classicGroupBuildMs: number; classicSwapApplyMs: number; classicFinalizeMs: number; performanceEventMs: number; applyGroupMs: number; substituteCoverageMs: number; canStageGroupMs: number; groupFullyStagedMs: number; stageGroupMs: number; }; /** * {@link StreamedSplatMesh.lastUpdateTimings}: the base mesh timings plus the * streaming stages (demand, LOD selection, staging). The stage names are * diagnostic and may change between minor releases. */ export type StreamedSplatUpdateTimings = SplatUpdateTimings & Readonly>; /** Options for {@link StreamedSplatMesh.load}. */ export interface StreamedSplatMeshOptions extends SplatMeshOptions { /** Reports bootstrap load work only; background LOD changes use the mesh's streaming state. */ onStatus?: (status: SplatLoadStatus) => void; /** Active-splat budget. Defaults to {@link resolveSplatBudget}. */ budget?: number; /** * A ceiling on the *resolved default* budget, for callers that want to * tighten without overriding what the library knows. * * `budget` is absolute: it wins over the device tier, the format's cost class * and everything else, because a caller who names a number has said they know * better. That is the right contract, and the wrong tool for "the same as * usual, but no more than N" - which is what a performance toggle or a host * default actually means. Pinning a number there has twice shipped as a bug: * a demo performance mode that *raised* the load on the weakest device tested, * and a host whose default bypassed every device tier. * * Applied only when `budget` is omitted, and only downward - it never raises * a budget the device would not otherwise have taken. It also suppresses the * finest-level lift, which exists to raise a budget far enough to hold a * scene whole and is exactly what "no more than N" rules out. Unrelated to * {@link maxBudget}, which sizes the pool and bounds * {@link StreamedSplatMesh.setBudget}. * * Forwarded to `resolveSplatBudget` as `SplatBudgetOptions.cap`. * * @throws {RangeError} at load if not a positive finite number. */ budgetCap?: number; /** * Device signals for budget / quality defaults. Defaults to * {@link detectSplatDeviceProfile}. Pass a profile enriched with * {@link probeSplatGpuClass} so desktop integrated GPUs take the laptop * tier instead of the workstation 8M path. */ deviceProfile?: SplatDeviceProfile; /** * Ceiling {@link StreamedSplatMesh.setBudget} may raise this mesh to, and the * size its pool is allocated from. Defaults to `budget`. * * Set this above `budget` when a `CameraBudgetGovernor` or `BudgetGovernor` * should be able to *grow* this mesh's share: the pool is allocated once at * construction and never grows, so without headroom reserved here a governed * mesh can only ever be shrunk below the budget it was built with. That is * the whole reason a hand-split `pool / N` mesh stays coarse near the * camera - every mesh's ceiling was fixed at a quarter of the pool. * * It is not free: the pool costs its *ceiling* in memory whether or not the * budget ever reaches it (~64 B of GPU pool plus ~56 B of CPU backing per * splat, 1.5× for capacity slack, 1.75× on a discrete desktop GPU). Price it with `estimateSplatPoolBytes` * before choosing - for several additional meshes the * sum of the ceilings is what has to fit, not the shared budget. A ceiling * around 1.5–2× a member's fair share is usually the right trade. * * @throws {RangeError} at load if below `budget`, or not a positive finite * number. */ maxBudget?: number; /** Optional format-specific desktop LCC2 detail policy; ignored by other formats. */ lcc2Policy?: Lcc2QualityPolicy; /** * Lets a host that pins {@link budget} and/or {@link maxBudget} still take the * finest-level lift for `.rad` strategy selection and pool sizing. Without it, * pinning either option disables the lift and a capture whose leaf count sits * between the host ceiling and {@link FOVEATION_LEAF_THRESHOLD} incorrectly * lands on the foveated page-table path instead of the prefix reader. * * {@link budgetCap} still vetoes the lift when set. Mobile and fill-constrained * desktops remain exempt inside {@link liftBudgetToFinestLevel}. */ allowFinestLevelLift?: boolean; /** * Multiplier on this mesh's LOD detail, matching Spark's per-mesh `lodScale`: * `> 1` refines further (finer cut, more splats drawn), `< 1` coarsens. * Default `1`. * * **`.rad` `foveationMode: 'page-table'` only** - it scales the frontier cut * the page-table traversal is given (`pixel_scale × lodScale ≤ limit`, exactly * Spark's formula). It does nothing on a mesh with no per-splat cut to scale: * a moderate `.rad` read as a chunk prefix, or a Streamed SOG / LCC scene. For * the GPU cut modes (`'band'` / `'frontier'`) the equivalent is * {@link SplatMeshOptions.foveationTargetPx} at `1 / lodScale`. * * The draw budget still bounds the result, so raising this past the point * where the budget binds sharpens nothing - give the mesh budget as well. */ lodScale?: number; /** Explicit format; by default the manifest's extension decides. */ format?: StreamedSplatFormat; /** * RAD LOD strategy. `'auto'` preserves the normal prefix/page-table choice; * `'page-table'` forces the selected-index page table for a fitting capture * while keeping the resolved budget, device-cap, and finest-level safety * rules. * * The option is ignored for non-RAD formats. Invalid runtime values are * rejected consistently by the streamed loader. */ radStrategy?: 'auto' | 'page-table'; /** Serializable fetch settings for the manifest and its chunks. */ request?: SplatRequestOptions; /** * Cancels the load: the manifest fetch aborts, and {@link StreamedSplatMesh.load} * rejects with a `DOMException` named `AbortError`. A mesh partially built * when the signal fires is disposed - nothing leaks. Only read during load; * later streaming is stopped by {@link SplatMesh.dispose}. */ signal?: AbortSignal; /** Base URL a relative manifest URL resolves against (like {@link loadSplatData}). */ baseUrl?: string | URL; /** World-unit distance inside which the finest LOD is used. Default 10. */ lodBaseDistance?: number; /** Distance ratio between successive LOD levels. Default 2. */ lodMultiplier?: number; /** Cap on decoded chunk arrays cached on the CPU. Default by device memory. */ cpuCacheBytes?: number; /** * Foveation ramp for the `.rad` page-table frontier: detail is full inside * `coneFov0` degrees of the view direction, falls off to `coneFoveate` by * `coneFov`, and to `behindFoveate` directly behind the camera. Off-cone * content is kept **coarse**, never dropped, so turning or zooming out never * exposes an unpainted region. Defaults match Spark * ({@link FRONTIER_FOVEATION_DEFAULTS}). */ frontierFoveation?: Partial; /** * Keeps a complete multi-run replacement hidden while its uploads are * spread over frames, then switches the region atomically. Enabled by * default; set `false` only for legacy A/B comparison. */ experimentalStagedSwaps?: boolean; /** * Maximum splats copied into the pool per LOD mutation tick. Classic * streaming defaults to 32,000; RAD page-table delivery defaults to 16,000. * An explicit value controls either path. Lower debug values trade refinement * latency for shorter frames. */ maxSplatsPerSwap?: number; /** * First-frame reveal policy for streamed formats that can hide empty cells. * * - `'progressive'`: cells become visible as each swap group commits — can * show sparse near-detail (classic `.lcc`) or empty octree squares * (`.lcc2`) while siblings load. * - `'hold-near-l0'` (opt-in): hide the mesh until the camera's home coverage * group is resident (L0 when it fits; otherwise coarsen via the leaf ladder * L1→L2). Neighbours are not part of the hold - they compete via * screenImportance and would steal the first fetch slots. Home selection * uses distance within `lodBaseDistance` and does not require frustum * intersection (HiRes tiles often fail `inView` when the camera stands * inside looking out). Coarser rungs come from `LodSource.runsAtLevelFor`. * Only home files are fetched during the hold. A one-minute watchdog also * degrades if the cut cannot finish. Classic `.lcc` uses the **resolved** * cut from the first schedule (after camera + format transform), not * distance ambition alone. * - `'hold-coverage'` (the default for classic `.lcc` and `.lcc2` when * unset): hide the mesh until every in-view finest cell has covering * coverage resident, and until the always-resident environment tile is in * the pool when the scene ships one and it starts enabled. Classic `.lcc` * freezes nearby cells (within `lodBaseDistance · lodMultiplier`) at * finest+1 (L1, never L0) and farther in-view cells at coarsest. A cell * counts as in-view when the camera stands inside it, or when the unpadded * AABB hits the frustum and pokes in front of the camera plane (support * vertex — centres behind the look still count), **or** the cell is within * `lodBaseDistance` and pokes forward (30 m neighbours that fill the * frame while the look is off-axis). `.lcc2` still waits on * coarsest root-children. Does not wait for finest tiles or the rest of * the stream. An empty frustum falls back to the nearest cell. Requires * `LodSource.coverageRunsFor`; other formats treat this as disabled. * * A one-minute watchdog degrades to progressive if the frozen set cannot * finish. Does not make detail downloads instantaneous. Other streamed * formats default to `'progressive'`. */ initialReveal?: 'progressive' | 'hold-near-l0' | 'hold-coverage'; /** * First-reveal policy for page-table `.rad`. Display correctness is independent * of this gate: every published cover is a complete hierarchy selection with a * matching sort. * * - `progressive` (default): publish the first complete staged cover as soon as * it exists, including early coarse coverage while descendants are still * loading. The main single-scene loader selects this explicitly. * - `allocation-fraction`: hold the first publication until the complete cover * reaches {@link radInitialDisplayFraction} of the granted draw allocation. * Incoming captures in a multi-splat crossover select this with `0.5`. RAD * storage chunks and hierarchy nodes are not separate captures. * - `projected-quality`: keep complete rendered generations hidden until * selected internal nodes are within the projected-pixel reveal thresholds. * * An explicit policy takes precedence. If no policy is supplied, a numeric * {@link radInitialDisplayFraction} still selects `allocation-fraction` so * existing callers keep their hold. Unsupported strings throw rather than * silently enabling an allocation hold. */ radInitialRevealPolicy?: 'progressive' | 'allocation-fraction' | 'projected-quality'; /** * Chunk-page `.rad` in a shared pool: let a suspended mesh (budget 1) give * the pool page of its coarsest chunk (chunk 0) to a drawing sibling, and * reinstall it from the decoded chunk kept in memory, with no download, * when it draws again. A `.rad` scene already keeps that chunk (its * bootstrap chunk, about 3 MB), so this costs no extra memory there. * * Without it every constructed capture pins that page for its lifetime, * drawn or not. A host that keeps many captures constructed but suspended * (a timeline it scrubs through) then runs a small pool out of pages: the * capture on screen cannot hold one complete cut and evicts its own pages * forever. Default `false`: the page stays pinned. */ retainCoarsestChunk?: boolean; /** * Crossover first-image target, as a fraction of the granted draw allocation. * Used with `radInitialRevealPolicy: 'allocation-fraction'`. Default `0.5`. * This is a splat-count threshold, not a fraction of downloaded bytes or of * nearby projected quality. `0` restores the older target-detail hold. */ radInitialDisplayFraction?: number; /** Receives lightweight LOD mutation events for performance attribution. */ onPerformanceEvent?: (event: StreamedSplatPerformanceEvent) => void; /** * View-dependent color (higher-order SH). This is the streaming counterpart * of {@link SplatMeshOptions.shBands}: besides sizing the pool it decides * whether SH is fetched/decoded at all. Sources that carry SH are a `Quality` * LCC (`.lcc`) capture, which stores coefficients per splat, and Streamed * SOG / `.lcc2` tiles, whose per-file palette shN is converted to that same * packed form at decode (see `docs/formats/streamed-shn-notes.md`). * * **Unset (the default) means every band the capture carries**, so a Quality * LCC scene and a Streamed SOG / `.lcc2` tile with `shN` in `meta.json` show * view-dependent color without the caller knowing the format. Those SOG * manifests never declare bands, so the loader peeks one tile (a small JSON * GET, or a ranged ZIP tail plus `meta.json`) and stays at 0 when the tile * has no `shN` or the server ignores Range. The exception is a `smooth` * performance profile (the default on mobile), which defaults this to 0: SH * adds up to 64 B/splat of pool textures (~384 MB over a 6M-splat pool at 3 * bands) and extra per-chunk bytes - precisely the costs that profile avoids. * * Set it explicitly to override either way: 0 forces SH off, and 1, 2 or 3 * keep 3, 8 or 15 coefficients per channel. For LCC the value is clamped to * what the scene actually has (a `Portable` capture fetches and allocates * nothing regardless); for SOG / `.lcc2` a scene with fewer bands zero-pads * and one with no shN simply renders DC color, wasting the allocated * textures if you asked for bands the file does not have. * * Only read at load: the pool's SH textures are allocated once, so a later * {@link SplatMesh.setPerformanceProfile} does not change this. */ shBands?: 0 | 1 | 2 | 3; /** * Whether the scene's always-resident environment/background tile (the * `.lcc2` sky) starts visible. Default `true`. Toggle it live afterwards with * {@link StreamedSplatMesh.setEnvironmentEnabled}. No effect on a scene that * ships no environment tile. */ environmentEnabled?: boolean; /** * This mesh's share of the scene's fetch bandwidth, as a camera-projected * weight - normally `() => governor.weightOf(mesh) ?? 0`, so fetching is * ordered by the same measure that already orders drawing. * * Read on demand, so it always reflects the current camera. Zero means hidden * or suspended, and has one effect on its own: the background sweep that * pre-warms the whole capture into the page-table cache stops. That sweep is * pure speculation about a camera move that has not happened, and on a * multi-mesh scene it is most of the traffic competing with the mesh the * viewer is actually looking at. * * Unset (the default) leaves fetching exactly as it was: every mesh sweeps. * Supply a {@link fetchScheduler} as well to also bound the total. */ fetchWeight?: () => number; /** * Scene-wide fetch arbitration, shared by every streamed mesh the way a * {@link SplatMeshOptions.pool} is - see {@link ChunkFetchScheduler}. Without * one, each mesh fetches toward its own in-flight cap and a near mesh's * detail queues behind a dozen far meshes' background traffic. * * The scheduler is *not* owned by the mesh: dispose unregisters this mesh and * leaves the scheduler running for its siblings. Weights come from * {@link fetchWeight}; without that every mesh weighs the same and the * scheduler only bounds the total. */ fetchScheduler?: ChunkFetchScheduler; /** * Scene-wide decoded-chunk cache ceiling, shared exactly as * {@link fetchScheduler} and {@link SplatMeshOptions.pool} are - see * {@link ChunkCacheBudget}. * * Without one, each `.rad` page-table mesh caps its own cache at * `max(cpuCacheBytes, min(2 GiB, this capture's decoded size))`: the right * number for a lone streamed scene, and no bound at all across a scene of * additional meshes, because every mesh gets its own and each is sized to its own * capture. With one, that figure becomes this mesh's *ceiling* and the budget * splits a scene total across every registered mesh by camera weight. * * This bounds retention, not prefetching: the background sweep still runs and * still warms the cache, it just stops at the scene's allowance instead of at * the size of the capture. * * The budget is *not* owned by the mesh: dispose unregisters this mesh and * leaves it running for its siblings. Weights come from {@link fetchWeight}. */ cacheBudget?: ChunkCacheBudget; } /** One streamed-mesh update frame, measured on the main thread. */ export interface StreamedSplatPerformanceEvent { /** Timestamp after the tick, on the same clock as requestAnimationFrame. */ timestamp: number; /** Main-thread time spent rescheduling and applying this tick. */ cpuMs: number; /** Same-frame packed active-index rebuild time, after the LOD mutation. */ activeListMs: number; /** Same-frame partial texture upload submission time. */ uploadMs: number; /** CPU submission time for the depth-sort passes. */ sortSubmitMs: number; /** Main-thread preparation breakdown, populated only when an event listener is attached. */ cameraSyncMs?: number; rescheduleMs?: number; baseUpdateMs?: number; /** Exact-height staging textures allocated during this update. */ stagingTextureAllocations: number; /** Texture copies submitted this update (core, SH and custom channels). */ textureCopyCount: number; /** Live destination bytes copied, excluding padded staging rows. */ textureCopyBytes: number; /** WebGPU source-index ranges queued for upload before this tick's sort. */ activeListUpdateRanges: number; /** Accepted sort submissions and implementation stages for this update. */ sortSubmissions?: number; sortPasses?: number; /** Projection submissions and stages for this update, when enabled. */ projectionSubmissions?: number; projectionPasses?: number; appendedCount: number; removedCount: number; stagedCount: number; uploadCount: number; activeCount: number; forcedSort: boolean; compacted: boolean; sortReadyGeneration?: number | null; renderedGeneration?: number | null; workerAcknowledgedGeneration?: number | null; } /** Options for {@link StreamedSplatMesh.definePersistentChannel}. */ export interface PersistentChannelOptions extends SplatChannelOptions { /** * Cap on the number of `(chunk, splat)` edits stored for this channel. * Editing past the cap is dropped with a one-time warning. Default 1,000,000. */ maxEdits?: number; } /** Opens a URL-resolving dataset with explicit format and resource ownership. */ export interface StreamedSplatSourceLoadOptions extends Omit { /** Dataset format; custom sources do not use URL extension inference. */ format: Exclude; /** Borrowed by default. Owned sources are released on failure or mesh disposal. */ sourceOwnership?: 'borrowed' | 'owned'; } /** * Streams a large splat scene - a Streamed SOG dataset (`lod-meta.json`), or * an XGRIDS `.lcc2` or `.lcc` (manifest v3–v5) dataset - into the pool of a * dynamic-capacity {@link SplatMesh}, keeping the resident splat count within * a per-device budget. * * Each frame it asks the scene's {@link LodSource} which spatial regions * should be resident for the current camera, fetches and decodes the chunk * files that back them (off the main thread, via {@link ChunkLoader}), and * appends/removes pool ranges to match - loading coarse first so the scene * appears quickly and refining near the camera. A coarse full-scene shell * always fits the budget, so the view is never blank and the budget is * never exceeded. * * WebGPU only (inherited from the dynamic-capacity pool). View-dependent color * (higher-order SH) works for every streamed format: LCC `Quality` captures store it per * splat, and a SOG scene's per-file palette shN is converted to that same * per-splat packed form at decode so it too survives the shared pool (opt * in via {@link StreamedSplatMeshOptions.shBands}; see * `docs/formats/streamed-shn-notes.md`). */ export declare class StreamedSplatMesh extends SplatMesh { private readonly scene; /** Only RAD prefixes need a global publish wave; manifest cuts are region-atomic. */ private readonly usesRadWave; private readonly desktopLcc2Quality; private readonly loader; /** * Cap the *classic* (non-page-table) chunk cache evicts against. * * Mutable because a shared {@link ChunkCacheBudget} re-splits it as the camera * moves; without a budget it stays at the value `options.cpuCacheBytes` or the * device default set at construction. */ private cpuCacheBytes; private budgetValue; private readonly maximumBudget; /** Spark's per-mesh `lodScale`; divides the page-table cut limit. */ private lodScaleValue; /** Set once the governed budget has been reported as exceeding an explicit * `foveationDrawBudget`, so the warning is issued at most once. */ private warnedDrawTargetCap; private readonly stagedSwapsEnabled; /** Classic LCC must keep old cell coverage while a replacement is pending. */ private readonly neverRetireCoverageEarly; private readonly appendCap; /** Worker-side RAD plan cap; separate default, shared explicit override. */ private readonly pageTableWriteCap; private readonly onPerformanceEvent; private readonly updateStageTimings; private compactionCount; private readonly cache; /** Running byte total of {@link cache}; maintained by {@link cacheChunk}, eviction and dispose. */ private cacheBytesTotal; /** In-flight chunk fetches. The kind is kept so a weight change can shed the * speculative ones without touching the detail that is actually on screen. */ private readonly fetching; /** This mesh's camera-projected share of the scene's fetch bandwidth. */ private fetchWeight; /** Scene-wide fetch arbitration, when the host shares one; see `requestChunk`. */ private readonly fetchScheduler; private readonly fetchHandle; /** * Blob-URL dataset from {@link loadLocal}, owned by this mesh so its object * URLs are revoked on {@link dispose} rather than leaking for the document's * lifetime. Undefined for every network-loaded mesh. */ private ownedSource; /** Scene-wide chunk-cache ceiling, when the host shares one. */ private readonly cacheBudget; private cacheBudgetHandle; /** * The cap this mesh's frontier worker is currently evicting against. * * Mirrored on the main thread so `applyCacheAllowance` can skip no-op posts * and so `fetchCounts.cacheLimitBytes` stays truthful between plans. */ private cacheLimitBytes; private readonly resident; /** Replacement runs hidden while their pool data is uploaded in bounded segments. */ private readonly staged; /** Files awaiting a backoff retry after a transient fetch/decode error. */ private readonly retrying; /** Files given up on after {@link MAX_CHUNK_ATTEMPTS} failures. */ private readonly failedFiles; /** * When true, each resident run writes its LOD `level` into the `lodLevel` * float channel for false-color debug modifiers. */ private lodLevelDebug; private lodLevelChannelReady; private lodLevelScratch; /** Desired-but-not-resident files this tick; protected from cache eviction. */ private readonly neededFiles; /** Non-null in `foveationMode: 'page-table'`: the worker that owns the chunk * cache + traversal + pager off the main thread, and the always-active slab it * pages the returned frontier into. */ private readonly frontierWorker; /** * The frontier's slots, as a list of equally sized pages rather than one * contiguous run. * * Slot `i` lives in page `i / slabPageSplats` at offset `i % * slabPageSplats`. The pager only ever addresses slots, so where those * pages sit in the pool is the mesh's business - which is what lets a mesh * hold non-contiguous storage, and ultimately lets several meshes interleave * in one pool instead of each reserving its whole ceiling as one block. * (Spark's pager does the same thing one level down, binding fixed pages to * `(source, chunk)` pairs.) */ private readonly slabPages; /** Whole RAD chunks backed by stable row ranges in chunk-page mode. */ private readonly radChunkPages; private readonly radChunkAllocator; /** Shared pools must leave governed headroom for sibling marker meshes. */ private readonly radChunkUsesSharedPool; private readonly radChunkSharedPoolPages; /** {@link StreamedSplatMeshOptions.retainCoarsestChunk}. */ private readonly radRetainCoarsestChunk; /** The decoded coarsest chunk, kept to reinstall its page after a suspended mesh shed it. */ private radCoarsestChunkData; private readonly radChunkPageLookup; private radChunkPageLookupRevision; private readonly radChunkResidency; private readonly radResidencyRequestedValue; private readonly radResidencyFallbackReasonValue; private radChunkDisplayedGlobals; private readonly radChunkDisplayedFiles; private radChunkDisplayedSelectionHashA; private radChunkDisplayedSelectionHashB; private radChunkPendingGlobals; private radChunkPendingFiles; private radChunkPendingSelectionHashA; private radChunkPendingSelectionHashB; private radChunkPendingBudgetSettled; private radChunkMappedSlots; /** * Pool slot of column 0 for every global texture row of resident chunks, and * that row's valid length (0 = not resident). Rebuilt per mapping pass; only * ~32 rows per resident chunk, so the rebuild is negligible. */ private radChunkRowBase; private radChunkRowLength; private radChunkPublishGeneration; private radChunkPublishRevision; private radChunkPublishActiveListVersion; private radChunkSelectionIdValue; private radChunkCommittedSelectionIdValue; private radChunkPendingSelectionIdValue; private radChunkHardValidityRevisionValue; private radChunkPendingHardValidityRevisionValue; private radChunkPendingPageIdentity; private radChunkSelectionCompletedAtValue; private radChunkSortSubmittedAtValue; private radChunkRenderedAtValue; private radChunkCameraObsoleteValue; private radChunkLastInvalidationReasonValue; private radChunkPendingRevealQuality; /** Most slots the slab may ever hold - the construction capacity. */ private slabCeiling; /** Slot count the worker's pager was last told about. */ private pagerSlots; /** Consecutive ticks the wave gate has held retirements back. */ private retireHeldTicks; /** * Latest drawable cut for {@link applyRadWave}. Prefix-reader discovery * deepens every tick; the published picture waits until the pipe is idle so * intermediate depths (including chunk 0's overview) never become the frame. */ /** True after the prefix-reader wave has presented a cut. */ private waveHasPublished; /** Backing store for {@link planTimings}. */ private readonly planTimingsValue; /** * Backing store for {@link fetchCounts}. Lifetime totals, because the question * they answer is about a *steady state* - "this keeps streaming after the view * settled" - which a per-frame or windowed number cannot express. */ private readonly fetchCountsValue; /** * The screen-radius band the scene asked for, kept so the band can be scaled * with the solved frontier cut and always relative to the original - scaling * the live values repeatedly would drift. Null when the scene has no band. */ private readonly frontierBandBase; /** * Splats per slab page for this mesh: {@link SLAB_PAGE_SPLATS}, or the whole * capacity when that is smaller. Spark can use one fixed page size because * its pool is a single large arena; here a mesh may be smaller than a page, * and rounding it up to one would waste most of the reservation. */ private readonly slabPageSplats; /** Target drawn-splat count for the page-table frontier; see the constructor. */ private pageTableDrawBudget; /** * Slab slots to reserve for the current draw grant. Indexed page-table * staging may use up to 2× that grant (capped at the pool ceiling) so * newcomers land in unused slots until the matching sort is published. */ private get pageTableStagingSlots(); /** The unclamped draw target (`foveationDrawBudget` or the default), kept so * `setBudget` can re-derive the effective draw budget when the pool budget * moves (e.g. under a `BudgetGovernor`). */ private pageTableDrawTarget; /** Whether {@link pageTableDrawTarget} came from an explicit * `foveationDrawBudget` - a caller-chosen hard cap worth warning about when a * governed budget outgrows it, rather than the library's own default. */ private pageTableDrawTargetExplicit; /** Last frontier's drawn (non-degenerate) splat count - the true on-screen size * in `page-table` mode, where the slab is fully "active" but mostly degenerate. */ private pageTableDrawn; /** Occupied page-table slots, including a replacement staged behind the drawn prefix. */ private pageTableResident; /** Page-table slot → stable `.rad` global splat ID. */ private pageTableGlobals; private pageTableDisplayGeneration; private indexedPageTable; private indexedPublishGeneration; private indexedPublishActiveListVersion; private indexedPublishRevision; private indexedPublishedGeneration; private sortReadyGenerationValue; private renderedGenerationValue; private workerAcknowledgedGenerationValue; private indexedDisplayedSlots; private indexedPendingDisplaySlots; private indexedStagingGeneration; private indexedQueuedPose; private indexedResizeAwaiting; private radRevealPolicy; private radDisplayFraction; /** Draw grant the host asked for, before storage reservation clamps it. */ private pageTableRequestedDraw; private frontierConverged; private pendingFrontierSplats; private staleResidentSplats; private lastPlanAppends; private lastPlanMoves; private lastPlanGeneration; private lastPlanBudget; private lastPlanCamera; private firstFrontierCamera; private frontierTraversal; private lastPlanReason; private candidateCancellationCount; private boundedCutRefusalReason; private protectedCacheBytesValue; private lastSkipSamples; private readonly frontierGenerationTrace; private readonly radPublicationDiagnostics; private indexedPendingDiagnostic; private radDiagnosticRenderer; private revealReadyValue; private maxCentralProjectedRatioValue; private maxVisibleProjectedRatioValue; private firstRevealCentralProjectedRatioValue; private firstRevealVisibleProjectedRatioValue; private firstRevealGenerationValue; private indexedPendingRevealQuality; private frontierTraceStagingGeneration; private lastWorkerSnapshot; private nextSnapshotRequestId; private pageTableHostCacheRevision; /** * Decoded RAD chunks waiting for a full chunk-page budget's walk to finish. * Installing one evicts a page, and a walk that started before the eviction * selected that page: every candidate then missed a page and was rejected, * so the displayed cut froze while fetches and evictions churned. */ private readonly radChunkInstallQueue; /** Governor-suspended: the displayed cut was released and detail is not fetched. */ private radChunkSuspended; private readonly snapshotWaiters; private lastPostedCamera; private lastPostedForward; private lastPostedProjection; private lastPostedLimit; private lastCountedTraversalId; /** Monotonic reschedule id; a stale plan (superseded by a newer request) is * dropped. `pageTableInFlight` coalesces to one outstanding traversal. */ private pageTableSeq; private pageTableInFlight; /** Sequence currently allowed to clear the in-flight traversal state. */ private pageTableActiveSeq; /** Replacement walk waiting for its first partial or complete demand. */ private replacementAwaitingFirstDemandSeq; /** Replacement allowed to finish while subsequent movement coalesces. */ private pageTableReplacementSeq; /** Finish the worker's current bounded cut before solving the latest camera. */ private pageTableContinuePending; private pageTableDisposed; private startupMainRadLodHold; private lastLiveCamera; /** Terminal page-table worker fault; retained for hosts to present recovery UI. */ private streamingErrorValue; /** Files whose data has been forwarded to the worker (so we don't refetch). */ private readonly pageTableCachedFiles; /** Chunks the last frontier wanted but did not have, biggest-on-screen first. * These outrank the background sweep - they are the detail actually on screen. */ private pageTableFetchPriority; private demandGeneration; /** Current camera revision whose unchanged, budget-full cut needs no more pages. */ private radChunkDemandSettledRevision; private radChunkDemandSettledCamera; private radChunkDemandSettledForward; private radChunkDemandSettledLimit; private radChunkDemandSettledConfig; /** Changes with each queued camera/configuration identity, before posting. */ private cameraEpoch; private demandKey; private latestDemandCamera; /** True when the latest camera/config has not yet been posted to the worker. */ private demandNeedsNewRevision; private radFrame; private demandWants; private readonly demandFirstSeen; private demandReadyGeneration; /** Prevents repeated reclamation while one hard relocation is still queued. */ private hardRelocationPending; /** Internal benchmark counters; never part of the exported mesh interface. */ private readonly demandDiagnostics; /** Frontier-cut target node size (px) and foveation ramp; see `frontierView`. */ private pageTableTargetPx; private pageTableFoveation; /** Drawing-buffer height, sampled in `update` so `reschedule` can derive the * cut limit the same way the material does (`targetPx / focalY`). */ private pageTableViewportY; /** Frontier cut on foveated `size / distance`. Re-derived each reschedule once * the drawing buffer is known; the initial value only covers the first frame. */ private pageTableLimit; /** Per-splat channels whose edits survive chunk eviction/reload. */ private readonly persistentChannels; /** Chunk-file index of the always-resident environment tile, if the scene ships one. */ private readonly envFile; /** Whether the environment tile should be visible; toggled live. */ private envEnabled; /** Pool handle of the environment tile once it has loaded (kept for toggling). */ private envHandle; /** Env splat count, measured when the tile decodes; 0 until then. */ private envSplatCount; /** Set when the env tile is larger than the whole pool - terminal, warned once. */ private envUnfit; /** * Startup hold. `'capture'` waits for the first schedule after the host * applies the final camera; `'holding'` freezes that coverage set. */ private initialRevealPhase; /** Which hold, if any, was armed at construction. Survives release for recapture. */ private readonly initialRevealHold; /** Frozen nearby-detail / in-view coverage runs for {@link initialRevealPhase} `'holding'`. */ private frozenCriticalRuns; /** Timestamp of the final-camera capture that began the current hold. */ private initialRevealStartedAt; private initialRevealStateValue; /** Fetch settings this mesh was loaded with, reused for collision meshes. */ private readonly requestOptions; /** In-flight or settled collision load; see {@link loadCollisionMeshes}. */ private collisionTiles; private collisionAbort; private pendingWork; /** * A classic visible cut is ready but a GPU sort still owns `splatIndex`. * Retry next tick without claiming {@link isStreaming}: hosts treat that * flag as "the first view has not settled." */ private lodCommitBlockedBySort; private lastScheduleTime; /** Heartbeat gate for the per-plan `[vlam:rad-*]` traces (see rad-trace-gate.ts). */ private readonly radTraceGate; /** Reused leaf-coverage bitmap for {@link substituteCoverage}; grows only. */ private coverageScratch; /** Shared deadline so multiple swap groups use one per-update work allowance. */ private interactiveStageDeadline; private lastClassicProgressAt; private interactiveStageBatchSplats; private readonly lastCameraPos; private readonly lastCameraQuat; /** * Fetches a scene manifest and prepares a mesh sized to the budget. * Accepts a Streamed SOG manifest (`lod-meta.json`) or an XGRIDS `.lcc2` or * `.lcc` (manifest v3–v5) dataset - all stream through the same machinery. Both LCC * generations are normalized to the established XGRIDS/Spark Three.js * coordinate frame; streamed SOG orientation is unchanged. * * A `.lcc` dataset needs a server that answers HTTP range requests: its * splats live in one large `data.bin` that is never fetched whole. * * @param manifestUrl - URL of the scene's `lod-meta.json`, `.lcc2` or `.lcc` * file; relative URLs resolve against `options.baseUrl` (or the page). * @throws Rejects with {@link SplatLoadError} on any resolve/fetch/parse * failure, or a `DOMException` named `AbortError` when `options.signal` fires. */ static load(manifestUrl: string | URL, options?: StreamedSplatMeshOptions): Promise; /** * Prepares a mesh from a folder dropped into the page - the same streamed * formats, read straight off the user's disk with no server and no upload. * * Every file becomes a `blob:` URL, which answers range requests exactly as * an HTTP origin does, so a multi-hundred-megabyte `.lcc` `data.bin` streams * chunk-by-chunk rather than being read whole. * * @param files - The folder's files, keyed by path relative to its root * (as the demo drop-zone `readDirectory` walk produces). * @throws Rejects with {@link SplatLoadError} - phase `'manifest'` when the * folder holds no (or more than one) recognizable scene manifest - or a * `DOMException` named `AbortError` when `options.signal` fires. */ static loadLocal(files: ReadonlyMap, options?: StreamedSplatMeshOptions): Promise; /** * Opens a custom dataset whose URLs remain fetchable by the chunk workers. * Borrowed sources remain the caller's responsibility for the mesh's lifetime. * Owned sources are released exactly once on rejection or mesh disposal. */ static loadSource(source: SplatDatasetSource, options: StreamedSplatSourceLoadOptions): Promise; private static loadDataset; /** Shared load path: fetch the manifest from a source, then build the scene. */ private static fromSource; private constructor(); /** Slots the currently reserved pages can hold. */ private get slabSlots(); /** * Reserves or releases slab pages so the slab can hold `wanted` slots, and * tells the worker's pager the new slot count. * * This is the mechanism that makes a shared pool worth having: storage follows * the governed budget, so approaching a mesh grows its pages while the ones * behind you hand theirs back, instead of every mesh holding its ceiling for * the whole session. Growth stops at the construction ceiling and at whatever * the pool can actually spare - a mesh that cannot grow simply stays coarse * rather than throwing. */ private syncSlabPages; /** * Writes `data` at slot `slot`, splitting the write where it crosses a page * boundary. The pager's runs are contiguous in *slot* space, which page * storage no longer guarantees is contiguous in the pool. */ private writeSlabSlots; /** Indexed candidates write stable, possibly sparse slots without relocation. */ private writeIndexedSlabSlots; /** Converts worker-local slab slots to the actual indices of shared pool pages. */ private poolIndicesForSlabSlots; private filesForIndexedSlots; private resumeIndexedRefinementAfterPublication; /** Chunk pages own stable slots and do not use the reverse active-slot map. */ protected tracksActivePoolSlots(): boolean; private sampleRadDiagnosticValues; private sortedRadDiagnosticIndices; private finishRadPublicationDiagnostic; private beginRadPublicationDiagnostic; private rejectRadPublicationDiagnostic; private recordRadPublicationDiagnostic; private indexedPublicationIsCurrent; /** Maps a complete selection once while retaining the page summary used by protection. */ private mapRadChunkSelection; /** Flat global-row table for {@link mapRadChunkSelection}; see `radChunkRowBase`. */ private buildRadChunkRowTable; /** A page may not be reused while its selection is being sorted or rendered. */ private radChunkPendingPageIdentityIsCurrent; private discardIndexedPublication; protected onActiveListReady(activeListVersion: number): void; protected onActiveListRendered(activeListVersion: number): void; /** * A stale unified token must not discard the live page-table candidate. * Large RAD cuts wait on `published` before the worker can replace a 7.5M * selection; dropping that generation stalls refinement on the first cover. * `onActiveListRendered` already ignores a mismatched snapshot, so the next * gather of the live list is what acks the worker. */ protected onActiveListSuperseded(_activeListVersion: number): void; protected rebuildActiveList(): void; /** Zeros slots `[slot, slot + count)`, splitting at page boundaries like * {@link writeSlabSlots}, so freed slots hold nothing drawable. */ private degenerateSlabSlots; /** * Draws exactly the first `resident` slots: pages below the boundary are * fully active, the page containing it is partially active, the rest are * inactive. Freed tail slots simply leave the active list; they are also * degenerated (see {@link degenerateSlabSlots}) so that even a slot drawn by * mistake shows nothing. */ private setSlabResident; /** Typed post to the frontier worker. */ private postToWorker; private recordFrontierTrace; /** Most recent terminal page-table worker failure, or `null` while healthy. */ get streamingError(): SplatLoadError | null; /** Applies a worker reply, turning malformed messages into a terminal fault. */ private handleFrontierMessage; private applyFrontierSnapshot; private applyIndexedResizeSafe; /** Clamps the accepted draw grant to what reserved storage can hold twice. */ private acceptDrawReservation; /** Page-table demand comes from the worker's authoritative walk, not a second scanner. */ private get pageTableDemand(); private applyDemand; /** * Incomplete replies may fill free slots. Only a complete reply for the * current camera/configuration may cancel unpinned downloads. */ private reconcileDemand; /** Keeps the previous same-camera demand useful while the next cooperative * walk runs, without letting an obsolete full list churn a saturated pool. */ private boundChunkPageCarryoverDemand; /** * Stops page-table refinement after a worker fault while retaining the last * committed slab. Rendering therefore continues with the last drawable cut * instead of clearing the scene or continuously posting to a dead worker. */ private failFrontierWorker; /** * Applies a new decoded-chunk allowance from the scene's shared * {@link ChunkCacheBudget}. * * Only the cap moves; nothing is dropped here. Both cache implementations * evict lazily against it - the page-table worker inside its next * `reschedule`, against a frontier that is still current, and the classic * path in `evictChunks` on the next tick. Dropping chunks synchronously would * pull them out from under resident splats. * */ private applyCacheAllowance; /** * Whether this scene ships collision meshes - true for an XGRIDS `.lcc` / * `.lcc2` dataset that carries them, false for a Streamed SOG scene, which * has none. */ get hasCollisionMeshes(): boolean; /** * Fetches and parses this scene's collision geometry: the triangle meshes an * XGRIDS `.lcc` (`collision.lci`) or `.lcc2` (`data/mesh/*.ply`) capture * ships beside its splats, for hosts that want collision, ground probes or * other spatial queries. * * The geometry is source-local, like {@link StreamedScene.bounds} - apply * this mesh's `matrixWorld` to put it in the frame the splats render in. * VLAM! builds no acceleration structure over it and never consults it. * * Tiles are fetched once and cached; concurrent callers share one load, and * a failed load can be retried by calling again. Resolves `[]` for a scene * without collision. * * @throws a `DOMException` named `AbortError` if cancelled, or if * {@link dispose} is called while the load is in flight. */ loadCollisionMeshes(options?: { signal?: AbortSignal; }): Promise; /** * Whether this scene ships an always-resident environment/background tile - * true for an XGRIDS `.lcc2` capture that carries one (its `env.sog` sky), * false for Streamed SOG, `.lcc`, `.rad`, or an `.lcc2` without one. */ get hasEnvironment(): boolean; /** Whether the environment tile is currently set to render. */ get environmentEnabled(): boolean; /** * Splats in the environment tile, measured when it decoded - the manifest * does not carry the count. 0 until the tile has loaded (or if the scene * ships none). These sit outside the LOD budget, drawing from the pool's * capacity headroom. */ get environmentSplatCount(): number; /** * Shows or hides the scene's environment/background tile. The switch is * instant and never refetches: once loaded, the tile stays in the pool and * only its active flag flips. Enabling before the tile has loaded triggers * its (one-time) load on the next update. No-op on a scene without one. */ setEnvironmentEnabled(enabled: boolean): void; /** The active-splat budget this mesh keeps within. */ get budget(): number; /** * The ceiling {@link setBudget} clamps to - {@link StreamedSplatMeshOptions.maxBudget} * when one was given, otherwise the construction budget. * * The pool was allocated for this number and cannot grow, so it is a hard * limit on what any governor can hand this mesh. Read it to check that a * shared-budget setup can actually deliver the share it is computing. */ get maxBudget(): number; /** Alias used by hosts that manage static and streamed auto-LOD uniformly. */ get budgetCeiling(): number; /** * The capture's real content size, when the format declares it (`.rad` reports * its leaf count) - the splat count needed to hold this mesh at full * resolution, independent of the budget it was constructed with. * * A host splitting one budget across several streamed meshes should clamp each * share to this: a mesh cannot spend more than it contains, so budget handed * past it buys nothing and is better given to a mesh that can use it. Note it * is *not* `maxBudget`: a foveated `.rad` reports `maxResidentSplats` as the * requested budget, because its pool holds a camera-directed resident set * rather than the whole tree. * * `undefined` when the format does not declare a content size. */ get contentSplatCount(): number | undefined; /** * Which `.rad` streaming strategy this mesh selected at load, or `null` when * the scene is not a Spark `.rad` capture. */ /** * True when this mesh keeps its decoded coarsest chunk * ({@link StreamedSplatMeshOptions.retainCoarsestChunk} on a chunk-page * `.rad` in a shared pool): suspended, it holds no pool page a drawing * sibling needs. */ get retainsCoarsestChunk(): boolean; get radStrategy(): 'prefix' | 'page-table' | null; /** Internal RAD residency decision surfaced to host diagnostics. */ get radResidency(): Readonly<{ requestedMode: 'indexed' | 'chunk-pages'; effectiveMode: 'indexed' | 'chunk-pages'; fallbackReason: string | null; residentPages: number; capacityPages: number; }> | null; /** First-reveal policy selected for this streamed RAD mesh. */ get radInitialRevealPolicy(): 'progressive' | 'allocation-fraction' | 'projected-quality'; /** * The drawn-splat target currently driving the `.rad` page-table frontier - * the governed budget, capped by * {@link SplatMeshOptions.foveationDrawBudget}. `0` on a mesh that is not in * `foveationMode: 'page-table'`, which has no frontier to target. * * This is the number that decides how deep the traversal descends, so it is * what to watch when checking that a near mesh really did receive more * detail: {@link budget} is the pool's allowance, this is what is spent. */ get drawBudget(): number; /** Draw allowance the host requested before storage reservation. */ get requestedDrawAllowance(): number; /** Draw allowance actually granted after reserved storage and device caps. */ get acceptedDrawAllowance(): number; /** Slots currently reserved for this mesh, including the unpublished staging copy. */ get reservedSlots(): number; /** * True once a complete generation has crossed the active rendering path. * Staging occupancy and nearby percentage are not publication. */ get hasPublishedGeneration(): boolean; /** * Page-table frontier coherence for hosts that gate preload/transitions. * `undefined` fields stay 0 when this mesh is not in page-table mode. */ get frontierState(): Readonly<{ frontierConverged: boolean; pendingFrontierSplats: number; staleResidentSplats: number; lastPlanAppends: number; lastPlanMoves: number; planGeneration: number; planBudget: number; lastPlanCamera: readonly [number, number, number] | null; firstFrontierCamera: readonly [number, number, number] | null; awaitingIndexedPublication: boolean; sortReadyGeneration: number | null; renderedGeneration: number | null; workerAcknowledgedGeneration: number | null; revealReady: boolean; maxCentralProjectedRatio: number; maxVisibleProjectedRatio: number; firstRevealGeneration: number | null; firstRevealCentralProjectedRatio: number | null; firstRevealVisibleProjectedRatio: number | null; planReason: FrontierPlanReason | null; candidateCancellationCount: number; boundedCutRefusalReason: FrontierPlanMessage['boundedCutRefusalReason']; protectedCacheBytes: number; activePageTableFetches: number; selectionId: number; committedSelectionId: number; demandRevision: number; cameraEpoch: number; demandKey: string; requestedCameraPosition: readonly [number, number, number] | null; staleCancellationReason: string | null; staleRequestsCancelled: number; protectedFilesRetained: readonly number[]; activeRequestsBeforeReclamation: number; activeRequestsAfterReclamation: number; hardRelocationDetectedAt: number | null; replacementTraversalPostedAt: number | null; oldTraversalCancelledAt: number | null; firstReplacementSliceAt: number | null; firstCurrentRevisionDemandAt: number | null; firstCurrentRevisionFetchAt: number | null; completedTraversalAt: number | null; firstPublicationAt: number | null; cameraToFirstFetchMs: number | null; hardValidityRevision: number; selectionCompletedAt: number | null; sortSubmittedAt: number | null; renderedAt: number | null; cameraObsolete: boolean; lastInvalidationReason: string | null; skipSamples: readonly FrontierSkipSample[]; generationTrace: readonly FrontierGenerationTraceEvent[]; traversal: Readonly<{ strategy: 'one-pass' | 'heap' | 'bounded-threshold'; fallback: boolean; fallbackCount: number; rootCoverInfeasible: boolean; traversalMs: number; traversalId: number; }>; }>; /** Holds RAD traversal on the authored startup pose while the viewer camera settles. */ beginStartupMainRadLodHold(camera?: THREE.Camera): void; /** Records the settled pose; live RAD traversal resumes after real translation. */ completeStartupMainRadLodHold(camera?: THREE.Camera): void; /** Refreshes the startup hold using Spark's translation-only release rule. */ refreshStartupMainRadLodHold(camera?: THREE.Camera): void; /** * Exact page-table stall inputs: camera, projection, model, threshold, cached * chunks, and the generations at the last plan. Use with `skipSamples` to * re-run selection against the same state. */ get pageTableStallSnapshot(): Readonly<{ cameraLocal: readonly [number, number, number] | null; cameraForward: readonly [number, number, number] | null; projection: readonly number[]; modelWorld: readonly number[]; limit: number; lodScale: number; targetPx: number; drawBudget: number; cachedFiles: readonly number[]; displayGeneration: number; publishedGeneration: number; publishedCount: number; candidateGeneration: number | null; publishGeneration: number | null; displayedCount: number; reservedSlots: number; planReason: FrontierPlanReason | null; skipSamples: readonly FrontierSkipSample[]; traversalId: number; awaitingIndexedPublication: boolean; worker: FrontierSnapshotReply | null; hostNow: Readonly<{ cameraLocal: readonly [number, number, number] | null; revision: number; cacheRevision: number; cachedFiles: readonly number[]; pendingFetches: number; }>; }>; /** Requests one worker-owned page-table snapshot for an explicit diagnostic. */ requestPageTableSnapshot(): Promise; /** * Spark's per-mesh `lodScale` (see {@link StreamedSplatMeshOptions.lodScale}). * Mutable: raise it to sharpen a focused mesh, lower it to coarsen a * background one. Page-table `.rad` only. * * @throws {RangeError} if set to a value that is not positive and finite. */ get lodScale(): number; set lodScale(value: number); /** In `page-table` mode the slab is fully active but mostly degenerate, so the * base `activeSplatCount` (slab size) is not the on-screen count - report the * frontier's drawn size instead. */ get activeSplatCount(): number; /** * Updates the LOD budget used for future scheduling within allocated capacity. * * @returns the budget actually in effect, which is `budget` clamped to * {@link maxBudget}. A `BudgetGovernor` reads this return value to detect a * capped member and hand the remainder to the others, so the clamp is * reported rather than hidden. */ setBudget(budget: number): number; /** * What the LOD scheduler last decided, or `undefined` on sources that do not * schedule by leaf (the `.rad` page table, prefix readers). * * Distinct from {@link activeSplatCount}, and the distinction is the whole * point: `desired` is what the scheduler asked for, `activeSplatCount` is * what the pool ended up drawing. Equal means the cut is applied; `desired` * far below the budget means the *scheduler* declined to spend it, which is a * different bug from the mesh failing to apply what it was given. */ get lodStats(): Readonly<{ inFrustum: number; leaves: number; desired: number; filled: number; }> | undefined; /** Number of chunk files currently decoded and held. In page-table mode the * worker owns the cache - the main-thread map is always empty there, so report * what has been forwarded to it instead of a permanent zero. */ get residentChunkCount(): number; /** Chunk fetches currently in flight. */ get pendingChunkCount(): number; /** * Main-thread cost of applying paging plans in `foveationMode: 'page-table'`. * * A plan is applied whole, off the render loop's own timing, so its cost does * not appear in {@link getUpdateTimings} - but it lands on the same thread and * a churning frontier can make it the largest stall in a frame. `worst*` * accumulate over the mesh's lifetime; the rest describe the most recent plan. */ get planTimings(): Readonly<{ applyMs: number; handlerMs: number; worstApplyMs: number; writeMs: number; residentMs: number; mappingMs: number; pageIdentityMs: number; activeListMs: number; installMs: number; protectionMs: number; unifiedGatherMs: number; sortMs: number; moves: number; appends: number; worstSplats: number; }>; /** * Lifetime chunk-fetch totals by kind, plus page-table cache state. * * Diagnostic for the question "why is this still streaming after the view * settled?", which the three fetch sources answer differently and which no * other reading distinguishes: * * - **`sweep` climbing** - speculative file-order pre-warming of the whole * capture. Declined by the `smooth` profile. * - **`priority` / `base` climbing while `evicted` climbs too** - the * frontier's touched set does not fit the worker cache, so chunks are * evicted and immediately refetched. Streaming never ends because it cannot. * - **`priority` / `base` climbing with `evicted` flat** - ordinary refinement * still converging on the cut; it should stop on its own. * * `uncovered` and `retiredEarly` answer a different question - "why are there * holes?" - and between them cover both ways this class can render nothing * where it should render something: * * - **`uncovered` climbing after the scene settles** - `substituteCoverage` * wanted a leaf's coarsest level as a stand-in and its chunk was not * cached. Expected briefly during initial load; afterwards it should not * move, because the coarsest files are pinned against eviction. * - **`retiredEarly` climbing** - coverage was retired before its replacement * landed, under pool pressure or past the retirement hold bound. This is * the swap path rather than the substitute path, and it is the one that * scales with the budget. * * Both are counted in whole leaves/groups, monotonically: they answer "did * this happen, and is it still happening", not "how much is missing now". */ get fetchCounts(): Readonly<{ priority: number; base: number; sweep: number; evicted: number; pageInstalls: number; pageInstallMs: number; uncovered: number; retiredEarly: number; cacheFull: boolean; cacheBytes: number; cacheLimitBytes: number; activePageTableFetches: number; }>; /** Chunk files given up on after repeated fetch/decode failures. */ get failedChunkCount(): number; /** * Forgets all permanent chunk failures so their regions are fetched again. * Failures are otherwise terminal for the mesh's lifetime - call this when * the cause was transient (e.g. connectivity restored, `online` event). */ retryFailedChunks(): void; /** * Whether the scene is still resolving toward its target detail - chunks * are fetching, or a retry/append is pending. Goes false once the view * has settled or streaming has stopped after failure/disposal (useful to * drive a loading indicator). */ get isStreaming(): boolean; /** The LOD distance model (mutable; e.g. raise to force the finest level). */ get lodBaseDistance(): number; set lodBaseDistance(value: number); protected getUpdateTimings(): StreamedSplatUpdateTimings; /** The base timings plus the streaming stages; a new object on every read. */ get lastUpdateTimings(): StreamedSplatUpdateTimings; /** * True while this mesh has queued work for a coming {@link update}: a * schedule, an append, a retry or a staged commit. Unlike * {@link isStreaming} it does not count chunk fetches that are still in * flight, so a host can tell "nothing left to apply" from "nothing left to * download". */ get hasPendingWork(): boolean; /** * True while a staged classic LOD cut waits for the running GPU sort before * it can commit. {@link isStreaming} stays false for this wait. */ get isLodCommitBlockedBySort(): boolean; /** * The `.rad` page-table generation the draw currently shows, `-1` before the * first one and on a mesh without a page table. A host that sequences work * around a camera move compares two readings: a higher number means a newer * selection reached the screen. */ get displayGeneration(): number; update(camera: THREE.PerspectiveCamera, renderer: THREE.WebGPURenderer, options?: SplatUpdateOptions): void; /** Root bounds of the whole scene, valid before any chunk has loaded. */ computeSplatBounds(): THREE.Box3; /** * Keep counting-sort quantization anchored to the complete capture bounds. * Streaming writes arrive in cache-dependent order, so an incrementally * accumulated bound can describe only the staged cut when the first sort * runs. Centers outside that temporary range then clamp into an end bucket * and look exactly like an unsorted patch. * Include decoded centers too: an LCC environment tile is outside the LOD * tree and can extend far beyond its root bounds. The accumulated bound is * grow-only, so unloading a range cannot shrink the quantization interval. */ protected refreshSortBounds(): void; /** * Enables or disables writing each resident run's **resolved** LOD level into * the `lodLevel` float channel (0 = finest), which `lodLevelDebugModifier` * from `@voluma/vlam/effects` paints in false color. * Values come from applied desired runs after budget resolution - not from * distance ambition alone. Call before assigning a modifier that reads the channel. */ setLodLevelDebug(enabled: boolean): void; /** Whether {@link setLodLevelDebug} is currently writing levels. */ get isLodLevelDebug(): boolean; /** * Startup-hold progress for {@link StreamedSplatMeshOptions.initialReveal}. * Hosts using `'hold-near-l0'` or `'hold-coverage'` should keep the mesh * invisible while `status === 'pending'`, then reveal on `'ready'` or * `'degraded'`. */ get initialRevealState(): InitialRevealState; /** * Captures a fresh startup-hold set on the next {@link update}. Hosts that * apply their final initial camera pose after the mesh first receives frames * should call this before lifting their loading cover. It is a no-op when * the hold was never armed (progressive startup, or a format without the * matching LodSource hook). */ recaptureInitialReveal(): void; private writeLodLevelChannel; /** * Declares a per-splat channel whose values **persist across LOD churn**: * edits are stored sparsely keyed by `(chunk file, local index)` and geometric * strokes are replayed whenever another coarse/fine run is appended. Paint a * region with {@link paintPersistent}, orbit away until it is evicted, come * back, and the same world-space region is painted on the new LOD cut. * * Wraps {@link SplatMesh.defineChannel}; read it from a modifier with * `ctx.channel(name)` as usual. */ definePersistentChannel(name: string, options?: PersistentChannelOptions): void; /** * Sets a persistent channel to `value` for every currently-resident splat * whose center is within `radius` (world units) of `worldPoint`. The * world-space sphere remains correct under non-uniform mesh scale. The * geometric edit is replayed on later resident LOD runs; direct * {@link SplatMesh.writeChannel} writes are not recorded. * * @returns the number of splats edited this call. * @throws {Error} if the channel was not declared with * {@link definePersistentChannel}. */ paintPersistent(name: string, worldPoint: THREE.Vector3, radius: number, value: number): number; /** * Applies and records a geometric brush stroke on a persistent channel. * The immutable operation is replayed when other LOD runs become resident, * so the painted region follows the surface rather than one transient cut. * * @returns the number of currently resident splats newly edited. */ paintPersistentStroke(name: string, stroke: BrushStroke, options: BrushStrokeSelectionOptions, value: number): number; /** * Clears every stored edit for a persistent channel and zeroes the value on * all currently-resident splats. Chunks that are not resident are covered by * the emptied store - they reload at the channel's fill value. * * @throws {Error} if the channel is not a persistent channel. */ clearPersistentChannel(name: string): void; dispose(): void; private shouldReschedule; /** Snapshots pose without cloning the scene graph every frame. */ private captureLiveCamera; private reschedule; private rowAlignedSplats; /** * Startup hold seeds: the coverage group containing (or nearest to) the * camera within {@link LodSource.lodBaseDistance}. HiRes tiles often fail the * frustum test when most of the cell sits behind the camera - do **not** * require `inView`, or the hold seeds a screen-facing neighbour instead. * Coarser home levels come from {@link LodSource.runsAtLevelFor}. */ private selectHomeSeedRuns; private coarsenHomeRuns; private criticalRunsFitCapacity; private publishInitialRevealProgress; private releaseInitialReveal; /** * Coverage hold: freeze covering runs for in-view cells (classic `.lcc` * physical cells at L1 near / coarsest far, `.lcc2` octree root-children). * Missing `coverageRunsFor` (or an empty result after fallback) releases * immediately so the mesh does not stay hidden with nothing to fetch. * If the mixed set overflows the pool, coarsen only the near (non-coarsest) * groups one more rung before degrading to progressive. */ private captureCoverageHold; /** * Bump each coverage run one coarser rung when the source has one. Already- * coarsest (far) runs stay put so a tight pool only drops near L1 → L2. */ private coarsenCoverageNearRuns; private captureOrContinueInitialReveal; /** Reserve the decoded environment's rows for desktop LCC2 selection, even while hidden. */ private syncDesktopLcc2EnvironmentCapacity; /** Keep the frozen startup region, but fall back when its base cannot coexist with the environment. */ private fitDesktopLcc2CoverageToEnvironment; /** After staging/commits, release the hold when every frozen run is resident. */ private finishInitialRevealIfComplete; /** * Startup hold still needs the environment tile when the scene ships one * and it starts enabled. Failed / unfit / disabled tiles do not block reveal. */ private environmentPendingForReveal; /** Creates a performance event for a changed streamed-LOD tick, if any. */ private createPerformanceEvent; /** * Snapshot the latest drawable desired runs. Live discovery still drives * fetches; nothing in this list is presented until {@link radWaveShouldPublish}. */ private captureWaveRuns; /** * Page-table `publish` equivalent for the prefix reader. * * Speculative prefetch runs are not part of the presented cut and must not * hold it hostage. Cache-full and pool pressure provide a valve for both * first paint and refinement; the regression guard prevents a coarser * replacement from reaching the screen. Otherwise publish only when every * drawable run's file is cached or failed — staging completeness itself is * enforced by {@link applyRadWave}'s `readyComplete` check. */ private radWaveShouldPublish; /** True when `incoming` would put a coarser prefix on screen than the resident cut. */ private radWaveIsRegression; /** * Prefix quality: lower `level` is finer, and a deeper prefix usually draws * more splats. Weighted so a same-count finer cut still outranks a coarser one. * * Level bases must clear the largest level a format assigns. Prefix `.rad` * uses `level = numChunks - chunkIndex`, which routinely exceeds 32 on real * captures; a too-small base makes every deep cut score *worse* than the * overview and permanently blocks refinement after first paint. */ private radWaveCutQuality; /** * Two-phase commit for hierarchical sources that cannot pair a parent with * its children in one swap group (prefix-reader `.rad`). * * Cached replacements upload into inactive ranges; still-fetching prefetch * does not participate. Adds stay hidden until {@link radWaveShouldPublish}, * so the first presented cut is the one the stream has actually caught up * to. A tick bound still force-applies if the hold would otherwise last the * whole session. */ private applyRadWave; /** * Classic cuts must not replace the drawn ranges while a GPU sort still * owns `splatIndex`. The in-flight scatter was dispatched against the * previous source list; letting it finish over a new cut is the unsorted * flash on Tempel/LCC2. Page-table publication already retains the previous * instance count until the matching sort is visible. * * The hidden startup hold and the first cover still publish: blocking them * leaves `initialReveal` pending and {@link isStreaming} true until the * host settle timeout. Later swaps wait on a private flag so the spinner * can clear. */ private deferVisibleLodSwap; private groupFullyStaged; /** * Activates every fully staged group in `ready` and applies pure removals. * `force` also applyGroups leftovers (after dropping partial staging) so a * stuck wave can still make progress - that is the retiredEarly hole. */ private commitRadWave; /** Returns whether all new rows can coexist with the currently visible region. */ private canStageGroup; /** * Uploads a bounded part of a replacement without rendering it. * Skips runs whose chunks are not yet cached so siblings can stage out of order. */ private stageGroup; /** * Read-only LCC2 owner/depth progress. Rendered owners, convergence and pending * network bytes stay unavailable until the actual draw/fetch boundary supplies * them; neither a RAD frontier flag nor a published active list proves them. */ get lcc2QualityState(): { fetched: (LodRun & { readonly depth: number; })[]; staged: { uploadedCount: number; file: number; level: number; offset: number; count: number; leafStart: number; leafEnd: number; coverageGroup?: number; distance?: number; inView?: boolean; screenImportance?: number; fetchIntent?: boolean; depth: number; }[]; published: { depth: number; file: number; level: number; offset: number; count: number; leafStart: number; leafEnd: number; coverageGroup?: number; distance?: number; inView?: boolean; screenImportance?: number; fetchIntent?: boolean; }[]; rendered: null; converged: null; pendingBytes: null; blockageReason: string | null; timeSinceProgressMs: number | null; reservedSlots: number; freeSlots: number; profile: "desktop" | "distance"; totalLevels: number; baseDepth: number | null; budget: number; manifestNodeDepthCounts: Readonly>; desired: readonly (LodRun & { readonly depth: number; })[]; } | null; /** Switches a fully staged region from old to new visibility in one tick. */ private commitStagedGroup; /** * Applies one swap group atomically within this tick: removals first * (freeing pool rows for the replacements), then all adds. Returns false * without touching anything when the group cannot fit even after its own * removals - the caller defers it and the old runs keep rendering. */ private applyGroup; /** Appends one run from the cache, compacting the pool on fragmentation. */ private appendRun; /** Applies a new stroke to the page-table slab already resident on the CPU. */ private paintPersistentPageTable; /** Replays stored geometry for newly written page-table slots, then uploads channels. */ private applyPersistentSlabRun; /** Writes stored values for a contiguous slab run, clearing stale slot occupants. */ private writePersistentSlabValues; /** Records one stable page-table identity while preserving first-paint-wins. */ private recordPersistentGlobal; /** * Writes the stored edits for one run's `[offset, offset + count)` splats * into its freshly appended pool range. No-op when the file has no edits. */ private applyPersistentRun; /** * Covers a deferred group's leaves that no resident run covers with each * leaf's coarsest (pinned, hence cached) level, so a region waiting on a * fetch shows coarse detail instead of nothing. The substitutes are * intentionally not "desired": the next reschedule swaps them for the * real level once its chunk has arrived. * * Classic LCC may explicitly hold for finest detail. Manifest octrees always * fill gaps with coarse coverage, including near-camera regions. */ private substituteCoverage; /** Issues pending classic-path chunk wants in group-priority order. */ private flushClassicFetches; /** * A camera turn must not wait for all eight old visible requests to finish. * Only classic requests carry a precise rank; page-table work retains its * own scheduler and is never cancelled here. */ private preemptClassicFetches; /** * Loads the always-resident environment tile once, on the first update after * it is wanted. The tile has no LOD ladder and no manifest count, so it is * appended whole (measuring its splat count at decode) and thereafter toggled * by flipping its pool range active - never scheduled, refetched, or evicted. * When `pending` is supplied, a miss is ranked as an `'environment'` want so * it issues ahead of LOD coverage. */ private updateEnvironment; /** Ranks the env tile ahead of every LOD want in {@link flushClassicFetches}. */ private enqueueEnvironmentFetch; /** * Page-table reschedule (`foveationMode: 'page-table'`): posts the camera to the * worker, which owns the cache + traversal + pager and replies asynchronously * with a paging plan. Coalesced to one outstanding request so the main thread * never blocks. Also drives chunk fetching, in priority order. */ private reschedulePageTable; /** * Applies a paging plan from the worker to the slab - fast memcpy writes only, * no traversal or gather on the main thread - then fetches the chunks the * frontier wants next, and reschedules again if chunks are still streaming. */ private applyFrontierPlan; /** Files that must keep their whole GPU page until the matching draw retires. */ private protectedRadChunkFiles; /** Stops demand once a complete budget-full walk reproduces the displayed cut. */ private settleRadChunkDemand; private radChunkDrawBudgetSaturated; private radChunkDemandSettlementIsCurrent; private radChunkDemandConfig; /** * Releases the least-recently-used unprotected chunk page. `includeCoarsest` * also offers chunk 0, which is otherwise never evicted: only a suspended * mesh that retained its data may give it up (see {@link shedPoolRows}). */ private evictRadChunkPage; /** * A private RAD pool may use the full standalone residency target. In a * shared pool, cap physical pages near the governed draw budget so an * outgoing marker cannot consume the storage needed for its incoming peer. */ private radChunkSharedPageLimit; private radChunkSharedDrawCapacity; private trimRadChunkPagesToBudget; /** Uploads a decoded RAD chunk once into its stable page. */ private installRadChunkPage; /** * Page bound for a chunk-page cut that cannot keep the whole capture resident: * the draw-budget pages the limit was sized from (limit / 1.25), leaving the * rest free for the next view's chunks while the displayed cut stays pinned. */ private radChunkCutFileBound; /** * Pages one displayed cut may span. In a shared pool that is also the * governed budget's pages, even when the page limit could hold the whole * capture: split panes give each capture half of a pool the budgets fill, so * a cut spanning every page of its capture starved the other pane's capture. */ private radChunkCutPages; /** * Pool tenant hook: drops least-recently-used pages outside the displayed * and pending cuts while this mesh holds more than one cut's pages. A * suspended mesh displays nothing, so it gives up every page: the pages it * keeps (its coarsest chunk, for an instant resume) are held only while no * drawing sibling needs the rows. */ shedPoolRows(rows: number): number; /** Pool rows this mesh's resident chunk pages occupy. */ private radChunkPoolRows; /** * Drops a suspended chunk-page mesh's displayed cut so its pages can return to * the shared pool. A suspended source is not drawn (split panes skip it, a * timeline hides it), but its pinned pages kept the next marker's capture from * paging in at all. It streams again when the governor restores its budget. */ private releaseRadChunkDisplay; /** True when a full page budget has a page outside the displayed and pending cuts. */ private hasEvictableRadChunkPage; /** True when installing another chunk page would first evict one. */ private radChunkPagesFull; /** * Whether the shared pool can take a chunk of `count` splats. Asks siblings to * shed pages beyond their share first, then (when `evictOwn`) evicts this * mesh's own pages outside its displayed and pending cuts. Split panes and the * suspended captures' root pages can fill a pool below this mesh's page limit; * installing anyway threw "SplatMesh capacity exceeded" and dropped the chunk. */ private radChunkPoolHasRoom; /** Installs chunks deferred during a walk, once its plan is applied and protected. */ private flushRadChunkInstallQueue; /** Mirrors stable page presence to the traversal worker. */ private syncRadChunkPages; /** Maps worker-selected RAD globals directly to pool indices. */ private poolIndicesForRadGlobals; /** Forwards a decoded chunk's arrays to the worker (buffers transferred) so the * worker's cache/traversal/gather can use it. */ private forwardChunkToWorker; /** Parallel chunk fetches. HTTP/2 multiplexes them; on HTTP/1.1 the browser's * per-host cap simply queues. Same cap for classic and page-table so near * detail is not structurally starved on the non-page-table path. */ private get maxInflight(); private pageTableActiveFetches; /** * Sets this mesh's share of the scene's fetch bandwidth, as * {@link StreamedSplatMeshOptions.fetchWeight} does at load. * * The weight normally closes over the mesh itself (`() => * governor.weightOf(mesh)`), which a host cannot express until `load` * resolves - hence a setter as well as an option. Pass `undefined` to go back * to unarbitrated sweeping. */ setFetchWeight(weight: (() => number) | undefined): void; /** Aborts in-flight fetches of one kind; their slots return through `finally`. */ private abortFetches; /** Camera translation, in local units, that supersedes the previous walk outright. */ private hardRelocationDistance; /** Reclaims old-camera RAD priority slots after a translation-only cut. */ private reclaimStalePriorityFetches; private requestChunk; /** * Stores a decoded chunk while keeping {@link cacheBytesTotal} in step. The * counter replaces a full-cache re-sum on every reschedule; every mutation * of {@link cache} (this method, eviction, dispose's clear) maintains it. */ private cacheChunk; private evictChunks; }