Skip to content

Engine architecture ​

The engine is a C++20 Linux process combining a QuickJS scene runtime, OpenVR tracking and overlays, a GLES 3 renderer, retained panels, and Jolt rigid-body physics. It renders models into stereo overlay textures and submits those textures to SteamVR. SteamVR composes them with the user's VR environment.

This guide describes the shipped pipeline and resource ownership. Public contracts live in the JavaScript API and subsystem guides; precise maintenance constraints live in the maintainer handoff. Measurements and rejected alternatives are linked separately below.

Pipeline at a glance ​

text
Catalog scripts + GLB assets + optional saved scenes
                 |
      per-script QuickJS candidate scenes
                 |
      validation / staged commit
                 |
          active scenes <----- owned input callbacks / update(dt)
                 |                         ^
       animation + interaction      OpenVR / vrserver
                 |
         Jolt fixed-step advance
                 |
     asset / pose uploads + render snapshot
                 |
    LOD + cached bounds + surface/group layout
                 |
       per-surface, per-eye GLES passes
       external depth -> opaque/masked -> blended
                 |
        GPU completion / overlay submission
                 |
           SteamVR compositor

The diagram shows data flow. The exact host-loop order, including when queued input is delivered, is described below. Panels use a separate retained-canvas and overlay submission path rather than the model passes.

Processes ​

The engine is one process holding every running script, the single OpenVR connection, the EGL context and the compositor submission loop. Two separate clients manage it over the private control socket: pocketspace-cli for terminals and programs, and pocketspace-dashboard for the SteamVR dashboard tab. Neither links the engine, so either can exit or restart without affecting scripts. Systemd user units run the engine, start it with SteamVR when engineAutostart is set, and run the dashboard while SteamVR runs; none of them starts SteamVR.

Process startup and execution model ​

The executable initializes OpenVR overlay services, EGL/GLES, and the GBM/DRM resources used for shared textures. It starts with no user scripts by default; each catalog --launch entry creates an independent scene. The shared scene anchor provides the transform between script coordinates and OpenVR standing space. Scripts use meters, with positive Z forward; the host converts this convention when building OpenVR transforms and shader axes.

QuickJS bindings, scene mutation, interaction, and rendering execute on the host thread. Scripts run as globals and may define update(dt); there is no browser DOM, Node.js runtime, or general JavaScript timer service. Getters normally read cached native snapshots. Jolt may use worker threads during a simulation step, but these threads never call JavaScript or mutate the host's scene vectors.

The host targets 90 iterations per second. update(dt) receives 1 / 90, while native animation and physics consume measured elapsed time. Missed deadlines are dropped rather than repaid through bursts of frames. Engine FPS therefore measures loop throughput, not headset or compositor presentation rate.

Scene state, ownership, and transactions ​

A scene owns assets, model instances, panels, animation playback, a physics world, input callback references, and container metadata. Model instances refer to shared assets; each animated instance owns its independent pose and playback. Removing an instance releases its instance resources but retains its shared asset until explicit unused-asset release, scene replacement or shutdown.

Objects and panels have increasing IDs stored in sorted vectors. Binary lookup resolves IDs when needed. Callbacks can create, remove, restore, or dispose objects, so pointers into these vectors cannot survive mutations. Frame-local member lists and bounds are rebuilt after updates.

Containers form an acyclic cleanup hierarchy, not transform nodes. They own related objects/panels/lights, child containers and optionally the input callback. Disposing a subtree uses the same cleanup paths as individual removal, including held state, bodies, and attached joints, while retaining scene-shared assets. Snapshots preserve the hierarchy and direct resource ownership.

unloadModel rejects any live instance user, then releases model payload and asset-keyed physics shape caches. Stable asset IDs use non-reused vector slots; unloaded slots are empty, not valid assets. The 32-asset limit counts loaded slots. Runtime instancing/diagnostic geometry caches reset before rendering after release; feature-keyed shader programs own no model pointers and can remain cached.

Modification of a running script triggers evaluation in a new QuickJS context and candidate scene. Successful evaluation replaces only that script's scene after detaching its old surfaces and clearing its stale interaction and input state. Failure preserves that script's active scene and callback. Other scripts continue running. File writes and other external side effects are not rolled back. See lifecycle for disconnect and shutdown behavior.

Scene persistence uses versioned snapshots of logical state: asset references, models, panels, animation and transitions, bodies, and joints. It does not serialize GL names, native overlay handles, or live pointers. Restore validates detached data and stages assets, overlays, poses, and physics before publishing fresh IDs. Failed staging releases its reservations and leaves the active scene intact. Restored poses rebuild independently owned GPU resources.

Host-loop order ​

Each iteration follows this order in src/main.cpp:

  1. Process SteamVR quit events and refresh tracked controller roles and poses.
  2. Reread changed engine settings, retry due automatic restarts, periodically check each running script's timestamp and attempt scoped transactional reload, then answer queued control socket requests, apply lifecycle requests queued by scratch's scripts object, and send watch events.
  3. Advance native animation from elapsed time and evaluate changed poses.
  4. Synchronize model surfaces and panels.
  5. Poll requested tracking actions and the raw controller stream. Apply connection cleanup, compute engine-laser mesh hits, and attempt bounded reconnection.
  6. Dispatch each scene's queued input callbacks, update its native grabs, then call its update(dt).
  7. Advance each scene's physics and synchronize resulting object poses/events. After every scene, deliver one budgeted turn of inter-script bus messages, then close each script's frame of measured callback time.
  8. Upload newly loaded assets and dirty animation data.
  9. Refresh head/eye poses, choose frame-level LOD, rebuild current bounds and surface membership/layout, then render visible model surfaces.
  10. Complete GPU rendering and submit coherent overlay frames. Update statistics and pace the next iteration. Once a second, the statistics sample also estimates each script's GPU allocations, closes its callback-time window and, while a client watches, queues a resources event.

Physics events produced after callback dispatch enter the queues for subsequent delivery. Scripts can also poll events. Rendering uses the state after callbacks, manipulation, and physics; interaction picking occurs earlier in the iteration.

Input, tracking, and interaction ​

OpenVR supplies HMD/controller poses, role assignment, action input, haptics, optional gaze, and system foveation centers. A separate local vrserver WebSocket monitor supplies global controller boolean/scalar component deltas, including finger capacitance/contact values. That interface is undocumented and depends on SteamVR implementation details. These values are finger sensors rather than a skeletal hand-tracking system.

The host normalizes these sources into cached hand/tracking snapshots and independent polling/callback queues. Gaze polling is opt-in and subject to its coexistence restrictions; optional calibration corrects the reported gaze ray. See input architecture, tracking, and eye calibration for validity and source contracts.

Model overlays take no SteamVR pointer input. The engine laser tests transformed model triangles and selects the nearest mesh hit, skipping pass-through objects unless they are grabbable. Grabs, thumbstick control and custom presses read the raw controller stream. Per-object grab configuration allows grip, trigger, or both. Native manipulation maintains the controller/object relationship; physics-backed holds feed targets into the physics world and release through its velocity/throw handling. Disconnect, removal, disposal, and reload cancel stale holds through common cleanup paths. Temporary pose loss and actual controller disconnection have different behavior.

Asset loading and geometry ​

src/model_asset.cpp imports GLB data with cgltf: primitives, embedded base-color textures, material state, transforms, supported animation channels, skins, and morph targets. Shared assets retain expanded CPU triangles for picking, bounds, and collider construction. A picking BVH accelerates exact triangle tests. Loading and the first upload both block the frame loop, so the independent work in them runs on up to one thread per core: a model's referenced images decode in parallel before its primitives are built, and PBR LOD simplification prepares every primitive, with both levels concurrently, before uploads publish them in order (model loading).

Shape assets come from src/shape_mesh.h instead of a file. Each part's shape is generated at its size with explicit normals, transformed with object conventions and grouped into one untextured PBR primitive per distinct color and finish. The result is then centered and normalized and gets the same picking BVH, upload, LOD and colliders as an imported model. Building is synchronous on the calling script's frame (build cost).

Static GPU geometry deduplicates exact position/UV tuples into vertex and index buffers, choosing 16- or 32-bit indices as appropriate. This changes storage, not the CPU geometry. Optional vertex-cache optimization reorders eligible static opaque/masked triangles only when explicitly requested; default triangle order remains unchanged. Animated and blended geometry retain their required order and paths.

Automatic LOD retains the full mesh and adds up to two reduced levels for eligible opaque static primitives: index buffers for unlit indexed meshes, and owned position/surface buffers with optional compact indices for PBR meshes. One projected-size/distance decision per object is reused by both eyes, surfaces, and depth passes. Hysteresis limits switching; nearby or grabbed models use full detail. Picking and physics continue to use full CPU geometry. lod: false disables this quality/performance policy.

Animation and deformation ​

Playback belongs to the object, while clips and source data belong to the asset. The evaluator samples channels, blends transitions, composes node transforms, and updates geometry/bounds. Stopping returns to the supported default pose; save/restore retains independent playback and transition state. See the animation guide for supported glTF features.

The deformation backend is selected from asset capabilities:

PathWork and resource ownership
GPU skeletal skinningEligible assets are entirely skinned, non-morph, have one four-lane influence set per primitive, and at most 1,024 joints per skin. Indexed skin geometry is shared by the asset; each pose owns its joint-palette textures. Color and depth shaders use the same skin transform.
CPU skinning/morph fallbackUnsupported GPU combinations remain on the CPU. Morph deltas precede skinning. Each pose owns its deformed geometry and uploads dirty vertex data.
CPU rigid animationExact world-matrix caches reuse unchanged non-morph parts, including their bounds. Changed parts update geometry and pending upload ranges. Any changed part causes a whole picking-BVH refit.

GPU-skinned bounds use conservative transformed joint-influence boxes. A ray that misses those bounds avoids CPU deformation. A candidate requiring exact picking computes CPU geometry/BVH lazily, cached once per evaluated pose and shared between both hands. This avoids running full CPU skinning beside every GPU update while preserving exact selection.

Eligible rigid animated poses use one owned expanded vertex stream instead of per-part VBOs. Fixed offsets allow dirty ranges to upload once and individual parts to draw from that same stream. Adjacent untextured opaque/masked parts with identical material state merge into one draw, preserving triangle and object order. Textured/material barriers remain separate draws; skin, morph, and static paths keep their own behavior. Stream ownership is never aliased into per-part buffer fields, and unchanged evaluation never clears a pending upload.

Physics ​

Each scene owns one Jolt world. The API creates static, dynamic, and kinematic bodies with supported primitive, convex, or static mesh colliders. Collider shape construction/caching is distinct from visual LOD and animation deformation; animated render meshes do not imply deforming physics colliders. Fixed, hinge, and distance constraints provide the implemented motors, limits, springs, and break thresholds. See physics coverage.

Elapsed time accumulates into fixed 1/90-second steps with at most eight steps of backlog. Small scenes step without additional workers. Automatic mode enables a bounded pool at 64 active bodies, up to two additional workers subject to available CPU threads; scripts may override the worker setting. Sleeping-body synchronization avoids repeatedly copying unchanged poses, while retaining the final sleep pose.

Held unconstrained bodies follow kinematic targets. Joint-connected dynamic holds use bounded velocity control so the solver can enforce their constraints. Contact callbacks aggregate synchronized native data; JavaScript delivery occurs after the solver barrier. Joint breaking is evaluated after solving, removes the constraint, and queues an event. Joint adjacency and shared collider caches avoid repeated relationship/shape work and are maintained through removal and restore.

Surface layout and visibility ​

By default, model instances render through independent surfaces. Scripts may instead assign a render group, sharing a stereo surface among multiple objects. Grouping reduces compositor overlays and repeated render targets without changing mesh interaction or logical object identity. Both approaches remain supported.

A FrameBoundsCache transforms current visible-object bounds once after scene updates. Grouped layout and occluder checks reuse per-eye angular projections; independent surfaces reuse world corners in their own projection basis. Invalid or near-plane bounds fall back conservatively rather than dropping geometry.

Stereo projected bounds crop transparent margins. Reference resolution sets the maximum sampling density; render groups are also capped at 1.25 times the headset's pixels per meter at their depth, from the projection already used for LOD. Allocated pixels and physical overlay width change together to retain it. Group tiles share one head-facing, anchor-centered plane so compositor reprojection does not separate color edges from depth cutouts on other tiles. Density uses axial depth and oblique magnification rather than radial range.

Group allocations grow with headroom and bucketed sizes; shrinking is delayed. Per-eye dimensions are capped by 4,096 pixels and hardware limits. The grouped buffer budget admits color/depth generations, including retained replacements, against 512 MiB. A new group is created at the largest size that fits, or waits unallocated without failing its scene. It excludes independent surfaces, assets, panels, and driver or compositor memory, so it is not a total GPU memory cap.

Optional automatic subdivision evaluates bounded angular cuts that save at least 20% of allocation while keeping stereo bounds and sampling constraints. Optional merge/rebalance uses stable proposals and cooldowns. Logical group IDs and object IDs stay fixed; only internal tile membership changes. Structural replacements retain complete old snapshots until every required output is ready for handoff.

Stereo render passes and draw submission ​

Each model surface has a side-by-side stereo color target. Each eye uses its actual eye position projected onto the surface plane, with perspective-correct depth for the modeled geometry. For each eye the renderer performs:

  1. Depth-only occlusion from visible opaque/masked objects outside this surface. Conservative bounds reject non-occluders and scissor work to padded target bounds. Members are excluded from their own external occluder pass. Static opaque/masked primitives of at least 4,096 triangles keep a second index buffer of their full-detail triangles in spatially sorted 256-triangle clusters. At full detail such an occluder draws only the clusters whose bounds pass the same test, merging adjacent runs into one draw.
  2. Opaque/masked color rendering for surface members with depth testing.
  3. Blended material rendering in preserved scene/primitive order.

There is no general transparency sorting guarantee. Material support includes base-color textures/factors, UV transforms, alpha modes, and an approximate sheen tint. Opt-in PBR assets use src/pbr_asset.h, src/surface_frame.h and src/pbr_program.h: retained normals/tangents and morph deltas, MikkTSpace tangent generation, a separate expanded surface-frame VBO, sRGB color/emissive textures, linear data textures, and a directional-light GGX metallic/roughness shader with optional baked image-based lighting. src/lighting_environment.cpp validates PSENV001 resources, shares them by exact path through weak cache entries, and lazily uploads an HDR prefiltered cubemap and BRDF lookup. The split-sum IBL design separates roughness-filtered radiance from the integrated BRDF. The offline NumPy baker supplies GGX roughness levels and nine diffuse SH coefficients; the render loop performs no convolution. Intensity and Y rotation belong to each model asset; shared environment data is immutable. Rotation sine/cosine are prepared on the CPU. Environment upload preserves caller texture bindings and unpack alignment. Units 6/7 are reserved for the cube/LUT during PBR draws and cleared before subsequent draws. GPU estimates count each referenced environment once, with RGB16F padding allowance. Native correctness, incremental cost and headset visual acceptance are recorded as separate validation evidence. Scene point lights, spotlights and directional lights are logical CPU records (up to eight combined), with independent IDs and container ownership. The renderer resolves object-local meter offsets after interaction/physics into one frame snapshot, shared by all eyes and surfaces. A reusable frame-local array builds an ordered light subset for each visible PBR object. Fewer than four active lights keep the full list to avoid selection and per-object upload overhead. A double-precision range/sphere test uses the full current pose's origin-centered bounds, with conservative padding and invalid-bound fallback. Only lights unable to reach the enclosing sphere are removed. For spotlights, conservative cone tangent/apex-plane tests can reject the entire sphere too. Direction length and a widened CPU cone account for the shader's float inputs; hemispherical/wider or invalid cones retain range-only behavior. Per-fragment spotlight falloff remains unchanged. These subsets are reused across eyes, primitives, LODs and surfaces without per-draw selection or allocations. Empty light frames clear counts without rebuilding geometry tests. No scene IDs or light settings change. See the range-selection validation and measured comparison and cone-selection comparison. PBR shaders receive positions relative to each surface in the same model axes as surface normals. Each PBR program keeps the value it last set for every uniform and skips sets that match bit for bit, which is exact because uniform values persist per program and only PbrProgram sets them. After a draw it unbinds only the texture units it bound (GL call reduction). The bounded forward loop adds GGX point illumination with smooth range cutoff and inverse-square attenuation; disabled/zero-intensity lights are excluded. Unlit materials and external-depth draws bypass the lighting work. Spotlights additionally rotate/normalize emitted direction with attachments and multiply direct illumination by a squared cone fade, with an explicit hard-edge case for equal cone angles. Uniform payloads include direction and cone cosines; point lights bypass the cone branch. Directional lights use normalized ray travel direction, unit attenuation and the same GGX BRDF; translation/range/cones do not affect them. They always survive per-object range/cone filtering. The existing uniform payload uses an internal negative-range sentinel, keeping the eight-light layout and prepared-program keys unchanged. Spot/directional lights can opt into the shared shadow pass. Snapshots store each light's type and settings, stage owned lights, remap attachments and publish fresh IDs; cross-container capture attachments are rejected. Removal, container disposal and reload share normal scene cleanup. See the point-light API and regression and bounded Frame comparison. Spotlight correctness and matched point/spot timings are recorded in the spotlight comparison. Scene directional correctness, shader costs and headset acceptance are recorded separately.

Static PBR supports full-input indexing with optimizeVertexCache: true (default false). Every 14-float shader-input tuple participates in identity, preserving position, both UV inputs, normal/tangent seams and material boundaries. Only static opaque/masked primitives whose compact buffers save space are eligible; blend and deforming uploads remain expanded. Cache/fetch ordering is required in production: plain indexing regressed, whereas explicitly enabled ordering improved native full-detail throughput. CPU triangles and animated uploads stay expanded. Position, surface and element buffers are staged together, allocation sizes are verified, and failed staging releases partial buffers and falls back to expanded uploads. The existing uploaded-vertex/index counts account for compact storage; shared asset deletion releases each buffer once. See production validation and the broader material/default assessment. Production surface-aware PBR LOD in src/pbr_lod.h uses full-input CPU indexing while simplifying. It locks coincident surface seams and primitive borders, then stores selected original inputs in owned position/surface VBOs. With optimizeVertexCache: true, reduced streams also receive cache/fetch ordering and compact 16/32-bit indices when that saves storage. Each level owns its index type and uploaded vertex count independently of full detail; draw and surface bindings select the complete level together. Without the option, reduced streams remain expanded. Simplification targets/error policy and selected triangles are unchanged by this storage optimization. See reduced indexing validation. Full streams stay resident for near and held objects. The existing object-level selector supplies the same detail choice to color/depth passes and both eyes. Budgeted production validation records the quality, throughput and extra-memory tradeoff.

src/pbr_lod_budget.h admits optional PBR buffer sets under one 32 MiB payload limit across assets. Each exact buffer-set reservation precedes GPU allocation/publication; failed allocation or CPU staging exceptions release staged buffers and the reservation. Missing levels fall back to a finer level or full geometry without rejecting an asset or restore. Admission follows upload order, with no eviction or retry for already uploaded assets. Asset destruction returns the charge; object instances and their held state do not own separate charges. The budget excludes full geometry, textures, unlit LOD indices and surfaces. Derived levels and reservations are rebuilt rather than serialized. Material UV0 transforms and sampler settings are independent. Surface frames use inverse-transpose normals and orthogonalized tangents, including mirrored node handedness. PBR CPU poses update surface buffers alongside positions and bounds; shared textures remain asset-owned. PBR currently bypasses legacy indexing, instancing, rigid batching and GPU skinning to preserve seams and deformation. All model paths share a per-pass ModelCulling owner: it applies doubleSided and node-transform winding consistently to member-color, alpha and external-depth draws, and skips redundant driver state calls. Instanced batches use the same material state; rigid merging stops at incompatible animated winding. Culling and front-face state reset before panel/other passes. The native comparison found no repeatable overall throughput gain; this policy implements glTF sidedness. Unlike the old unlit path, single-sided back faces are now culled for unlit assets too. PBR scene preparation uploads initial assets and precompiles up to 16 color program variants at startup and after a successful script reload. For scenes starting with four or more active lights, it visits live objects/materials in scene order and prepares filtered-light counts four through eight for their current map/alpha/sidedness/environment features. Failed keys consume bounded slots and use general PBR. Render-time lookup never compiles shaders.

Only surfaces allocated at least 1024 pixels per eye and lit materials with four or more contributing lights use ready variants. Smaller/lightweight draws, unknown keys, new assets and changed environment/light combinations fall back to the general program. Restore/removal retain safe feature-keyed programs; successful script reload replaces the set, while failed reload leaves it intact. Programs hold no asset/object pointers and are released while the GL context is alive. The cap covers owned programs, not opaque driver caches or total GPU memory. See prepared-policy validation; the original lazy prototype remains recorded separately.

Legacy, PBR color and PBR depth programs link during startup, before live scene publication; reloads do not compile a new shader after committing their candidate scene. The separate program restores legacy program, texture-unit and attribute state before subsequent objects/panels. Both member-color and external occluder passes use the same geometry and alpha policy. Directional/environment lighting state is per shared asset and is captured in snapshots, with transactional cache-conflict validation. External PBR depth draws use a dedicated program with the same vertex shader, geometry, deformation, LOD, winding and UV policy. Opaque depth returns before texture sampling; masked depth evaluates base alpha times factor and the identical strict alpha-cutoff discard before returning. Blended primitives remain excluded from external depth. Depth draws skip lighting/environment setup and surface-frame attributes; normal color draws retain their original shader. Sampler units are initialized before a possible first depth draw, preserving the caller's program. No extra geometry or texture storage is introduced. See the depth-pass validation for matched workloads and limits. See lighting API for controls, color mapping and limitations.

Ordered GPU instancing is enabled by default for eligible consecutive same-asset, single-primitive, static opaque/masked objects. Runs must also match selected LOD. A reusable streamed instance buffer carries current transforms. No asset sorting or cross-object reordering is performed; multipart, deforming, blended, and ineligible objects fall back to normal draws. Attribute divisors and skin state are reset before other draw paths and panel work.

GPU buffers and compositor handoff ​

A model surface owns three compositor-facing GBM color buffers. DMA-BUF file descriptors back EGL images used by GLES renderbuffers and OpenVR shared texture handles. Their FBOs share one owned depth attachment; only color is imported by the compositor. Resource destruction releases imports, GL objects, descriptors, and GBM allocations through their owning surface.

Production renders every running scene, waits once per frame with glFinish, then publishes each scene's rendered surfaces. This proves producer completion, not compositor consumption. Three buffers and successful visual checks are not a consumer-completion protocol; changing synchronization requires preserving the existing ownership contract rather than assuming frame pacing or a GL fence acknowledges compositor use.

Grouped presentation stages transform, width, and texture on a hidden overlay, then shows the replacement and hides the old front before swapping roles. Resize and split/merge generations retain old coherent frames until submission succeeds. Failures preserve/retry fallbacks instead of exposing partially updated content. Independent interactive surfaces retain their handle-preserving path.

Panels ​

Panels maintain retained canvas pixels/layout, text through FreeType, and images. Raster updates advance a texture revision even when the GL texture name is reused. Each native panel overlay caches successful texture, transform, and visibility submissions, retrying failed calls. Head-locked and viewer-facing transforms are computed from current tracking. Panels are not SteamVR input overlays: the engine intersects each hand's ray with their rigid transforms in src/panel_pointer.h, and that ray also drives the model triangle picker.

Removal detaches overlays before deferred texture destruction. Persistence stores bounded panel pixel/layout data and recreates normal canvas handles during staged restore. See panels for canvas and input behavior.

Removal and shutdown ​

Object removal cancels hover/grabs, removes its physics body and attached joints, and releases instance-owned poses and independent surfaces. Group surfaces remain while other members need them. Panel cleanup detaches the native overlay before releasing its texture. Successful reload retires the old scene, including shared assets, per-pose buffers/palettes, streamed instance state, and retained surface generations; failed reload leaves those active resources in place. After any script teardown, the frame ends with one malloc_trim(0), returning the freed scene's heap pages to the system; it takes up to about 40 ms after a large scene. Driver GPU memory is not trimmed: Mesa keeps freed buffers for reuse and releases them later (memory retention).

Ctrl-C, SIGTERM, and acknowledged SteamVR quit unwind native overlays, GPU/shared buffers, EGL, input, and OpenVR resources through scoped cleanup. The engine exits on SteamVR shutdown and must be relaunched after SteamVR restarts. Forced process termination cannot execute cleanup.

Statistics and performance policy ​

getEngineStats() reads cached process CPU/RSS, optional DRM process GPU totals, engine FPS, scene counts, allocation estimates, and latest physics timings. Process samples update roughly once a second; getters do not synchronize the GPU. Shared memory means RAM and GPU values can overlap. The allocation estimate counts owned buffers/textures, deduplicates shared depth, and includes retained surface generations, pose streams, palette textures, unlit LOD indices, PBR LOD buffer sets, and instance data. It excludes driver/compositor overhead and is not measured GPU residency.

Script-facing defaults, opt-ins and tradeoffs are collected in performance options. The production optimizations and their controls are:

OptimizationProduction policyEvidence
Cropped stereo targets, bounds/scissor reuse, shared depth attachments per surfaceAutomatic; retain conservative fallback and sampling densityRender passes, fast motion
Clustered external depth drawsAutomatic for static opaque/masked primitives of at least 4,096 triangles at full detailDepth clusters
Grouped rendering and adaptive tilesScript-selected groups; subdivision/merge/rebalance opt-inOverlay comparison, subdivision, regrouping
Exact indexed geometryAutomatic for supported shared geometryMaintainer contracts
Vertex-cache reorderingExplicit asset opt-inVertex cache
Automatic static-model LODDefault on; asset opt-out; PBR extras capped at 32 MiBUnlit LOD, PBR LOD
Ordered static instancingDefault on; asset opt-outInstancing
GPU skinning and lazy exact pickingAutomatic when eligible; CPU fallbackSkinning
Rigid pose cachingAutomatic for rigid non-morph partsPose cache
Adjacent rigid draws in one owned streamAutomatic when eligibleRigid batches
Panel submission caching, sorted-ID lookup, physics sleeping/workers/cachesAutomatic with explicit physics worker overrideRuntime contracts, physics API

Controlled comparisons check complete member geometry as well as allocation; matching allocation estimates alone does not establish equivalent work. A grouping tie-break comparison found negligible native gains and was not adopted.

PBR assets continue to use original draws rather than the ordinary instancing path. The PBR submission profile distinguishes render-thread CPU, enqueue wall time and GPU time; it does not establish a submission bottleneck in the tested workloads. PBR batching remains conditional on compatible light/material state, preserved ordering and measured benefit.

Measurements are workload-specific, not FPS guarantees. Tests/results document correctness, measured performance, and user headset acceptance separately. The rejected uniform-cache, owned-VAO, primitive and cluster occluder-culling, specialized opaque shader, shared-scene-depth and alternate GPU synchronization experiments were removed in commit 92f4137; their reports remain, and the test index explains how to recover the code. So were the static-only ordinary vertex shader prototype and its mixed-program integration, after inconsistent native gains; production retains the general skin-capable vertex program. The minimal PBR depth-only shader investigation closed without adoption: exact pixels and headset acceptance passed, but controlled engine comparisons did not establish a repeatable benefit. External PBR depth retains the shipped early-return program and its original vertex source. GPU morph work is deferred until a workload establishes sufficient CPU cost.

Source map and maintenance ​

AreaMain sources
Frame loopsrc/main.cpp
Surfaces, layout, passessrc/render_host.cpp, src/render_host.h
JavaScript bindings and script loadingsrc/script_api.cpp
Scene types and shared engine statesrc/engine_state.h
Import, CPU geometry, animation evaluation, pose uploadsrc/model_asset.cpp, src/model_asset.h, src/animation.h
GPU skinning, rigid batching, indexing, LOD, instancingsrc/gpu_skinning.h, src/gpu_skinning_asset.h, src/rigid_batching.h, src/mesh_index.h, src/model_lod.h, src/pbr_lod.h, src/model_instancing.h
Projection/material shaders and pickingsrc/model_shaders.h, src/picking_bvh.h
Tracking and inputsrc/controller_input.cpp, src/frame_input.cpp, src/tracking_state.h, src/eye_calibration.h, cfg/
Physicssrc/physics_world.cpp, src/physics_world.h
Panelssrc/panel.cpp, src/panel_submission.h
Snapshots and ownership lookupsrc/scene_persistence.h, src/scene_*_snapshot.h, src/scene_lookup.h
Statistics and buffer admissionsrc/runtime_stats.h, src/group_buffer_budget.h, src/pbr_lod_budget.h
Script instances, catalog, settings and recoverysrc/script_registry.h, src/script_catalog.h, src/engine_settings.h
Inter-script bus and cross-script pickingsrc/event_bus.h, src/input_arbitration.h, src/native_resource_key.h
Control socket, operations and CLIsrc/control_server.h, src/control_service.h, src/control_client.h, src/pocketspace_cli.cpp
Dashboard tabsrc/dashboard.cpp, src/dashboard.h, src/dashboard_main.cpp, src/canvas.cpp
Per-script heap and callback timesrc/script_telemetry.h

Keep this guide aligned with shipped behavior when changing a pipeline stage or production default. Keep exact implementation invariants in the handoff, public options in API guides, and benchmark histories in recorded results. Follow AGENTS.md for verification and resource-lifetime rules.

Fabric sheen pipeline ​

PBR import reads KHR_materials_sheen color/roughness factors and embedded maps into material slots 4/5. Sheen color uses sRGB storage; roughness is linear alpha. Map transforms and UV0 validation follow the other PBR maps. Legacy rendering keeps its approximate sheen tint.

src/sheen.h numerically integrates the Charlie BRDF/visibility into a shared 32×32 directional-albedo table during first owning asset load. The table uses 32 elevation × 64 azimuth midpoint samples per entry. Upload uses one RG16F texture (4 KiB), storing albedo and a reciprocal, roughness-dependent normalization for excess grazing energy in the fitted visibility. Asset ownership and a weak cache govern its lifetime. It is included once in estimated GPU storage, and last-owner unload releases it.

src/pbr_program.h layers direct sheen over the base BRDF with incident/view albedo attenuation. Roughness is bounded to 0.07–1. Indirect sheen uses diffuse SH irradiance times view albedo, a low-frequency approximation rather than a Charlie-prefiltered environment cubemap. The base GGX environment path remains separate. Zero sheen and unlit materials bypass the layer. General and prepared variant programs use the same sheen uniforms, so sheen changes do not add shader variant keys or draw-time compilation. Texture units 8/9 hold the two maps and 10 holds the lookup; PBR release clears them and restores active unit zero.

See fabric API and example and the sheen regression.

Pocketspace file and overlay identifiers ​

The engine's SteamVR application key is com.pocketspace.app. It registers that manifest, named "Pocketspace Engine", only while it runs, for its controller actions, so it never stays in the Steam library. The library entry is a Steam shortcut that opens the dashboard; the dashboard registers no manifest. Native overlay keys start with pocketspace.; the dashboard tab is pocketspace.dashboard. Scene saves use the pocketspace state directory and format string. Lighting-environment writers emit PSENV001 (.psenv), the sole accepted lighting-environment header. Readers validate dimensions, payload size and values before publishing shared environment resources.

Spotlight shadow pipeline ​

src/spot_shadows.h owns one depth-only framebuffer/texture, a transient private VAO, prepared caster program and asynchronous timer query. Settings are logical light state in src/spot_shadow_settings.h, with transactional API/snapshot validation. At most one enabled light of any type reserves the slot. The normal engine compiles the caster program during startup.

After animation/physics and GPU pose uploads, the engine renders full visible opaque/masked geometry into one scene-space light projection, once per frame before surface/eye rendering. The spotlight's range and outer cone define its perspective camera; attachments are resolved by ID. CPU poses and GPU skinning use the same current geometry as color rendering. Alpha blend casters are skipped. Each light view draws only casters whose bounds reach its clip volume, and static casters with depth clusters draw only the clusters that reach it; geometry outside a view rasterizes nothing there, so the map is unchanged. A private VAO and scoped framebuffer, viewport, texture, program, depth, mask, blend, scissor and culling restoration isolate the pass from compositor surfaces. The depth texture is never shared with the compositor. The private VAO is deleted after each update so its attribute/index bindings cannot retain unloaded asset or removed pose buffers between frames.

PBR general/prepared programs sample texture unit 11 using four comparison- filtered taps. Geometry derivatives, evaluated before alpha discard and light branches, determine receiver-plane depth variation across the filter footprint. The resulting resolution-scaled slope bias supplements configured bias without using normal-map perturbations; external-depth draws skip this calculation. A per-draw light index is resolved from the filtered light IDs; other lights, IBL and emission stay unshadowed. The matrix consumes scene-space coordinates, including each surface origin, and is shared across both eyes. PBR release clears unit 11. No shadow state is added to the shader variant key.

Resolution is bounded to 256/512/1024, with at most 4 MiB active estimated depth payload. Full-detail work is capped at 128 caster objects and a configurable triangle budget no larger than one million. Exceeding geometry limits renders unshadowed lighting and retries when the workload fits. The nonblocking GPU watchdog ignores the first three updates and disjoint samples, then compares a rolling average of 24 valid results against its configured elapsed-time limit. An over-budget average latches the pass off; a brief spike alone does not. It is a delayed safeguard, not GPU preemption. Fallback never samples an old map. Explicit shadow-setting changes, light disable/re-enable or successful script reload reset the watchdog. Disabled, removed, disposed or unresolved lights release their map; failed reload leaves the active resources intact. Map storage is counted once in engine estimates.

Snapshots store shadow settings for every light type. Conflicting restores are rejected before native reservation. See public API and example and shadow regression.

Directional shadow coverage ​

The shared shadow pass also accepts directional lights. A fixed world-space center and explicit square size/depth define an orthographic volume in the resolved light basis, with symmetric depth around the center. Attachment rotation aims rays and rotates that basis; attachment translation and headset motion do not move coverage. Receivers outside the volume remain unshadowed, and casters outside are clipped. There are no cascades or camera-relative fitting. The existing comparison sampler, surface-origin transform, filtered light ID lookup, full-pose casters, allocation/work/watchdog limits and resource lifetime are shared with spotlights. No additional map or shader variant is introduced.

See directional shadow API and example.

Point shadow atlas ​

Point lights reuse the prepared caster program, transient VAO and shared slot. Six 90-degree perspective views along shader-space ±X/±Y/±Z render into a 3×2 DEPTH_COMPONENT24 atlas. Face resolution is bounded to 256/512 (1.5/6 MiB estimated payload). One timer brackets all views. Work budgeting multiplies eligible full-detail triangles by six before rendering; the 128-caster cap stays shared. Each face receives the current CPU/GPU pose and masked silhouettes.

PBR receivers select a face by dominant light-relative coordinate, transform through that face matrix, and use the existing slope-aware comparison filter. World-position derivatives are projected through the selected face before computing receiver slope, avoiding discontinuous UV derivatives at face transitions. Normal offsets may cross XY face bounds; point receivers clamp those taps rather than returning unshadowed light. Taps clamp inside each face rather than crossing unrelated atlas tiles. Filtering is not seamless across cube edges. Unit 11 remains a 2D comparison texture, so no extra texture unit or shader variant is required. Map allocation includes atlas shape in its reuse condition, and existing state/lifetime/reset contracts apply. See API and example.

Released under the GNU AGPL v3.0 only.