# Scene HLOD authoring

These dedicated commands operate on a sealed local Scene v2 bundle. They do not change the character simplification or material-atlas tools.

```sh
helix scene hlod tag ./scene.json --nodes node.bridge node.landmark --mode include --layer large-features
helix scene hlod tag ./scene.json --nodes node.moving-door --mode exclude
helix scene hlod inspect ./scene.json
helix scene hlod bake ./scene.json
```

Parent policies are inherited. Untagged objects are excluded by default. An explicit child `include`, `exclude`, or `inherit` policy controls that subtree;
an optional layer may be inherited separately. Cell membership remains the scene's existing native distance-streaming layout.
Only selected geometry is represented in the HLOD. Lights, collision and excluded objects keep their own behavior.

`tag` reseals the scene and invalidates its previous HLOD declaration, retaining old content-addressed files for cache reuse.
Configure a layer while tagging with `--distance 128 --max-distance 2048 --fade 350 --ratio 0.2 --error 0.1 --atlas 512`.
Distances and simplification error are metres. The triangle ratio is a target constrained by maximum geometric error.
Atlas sizes are 128, 256, 512, or 1024. The scene's HLOD capability, layer and coverage metadata are portable platform contracts.

`bake` merges selected source surfaces per cell/layer, simplifies geometry, creates fresh UVs, and projects original PBR appearance onto color,
normal, roughness/metalness/occlusion and optional emissive atlases. Output is a GLB with one opaque PBR material and KTX2 mip chains by default.
Use `--compression png` for portable PNG atlases or `--force` to ignore cached results. Every source pin is verified even on a cache hit.

Assets land under `hlod/<sha256>.glb`. Receipts under `.helix/hlod-cache/` include source/output triangles, source draw calls, geometry error,
projection misses, bake timings and memory estimates. JSON output also reports total wall time, output bytes and cache hits.
The scene file is replaced only after every cluster succeeds and the resulting document validates. Cancellation, input corruption or concurrent scene edits
leave that file intact. The command never publishes or contacts asset services.

Supported inputs are static `render.primitive` boxes and embedded local GLBs with opaque metallic/roughness materials (double-sided ones bake both faces).
Meshopt compression, mesh quantization, Basis KTX2, PNG/JPEG/WebP textures, authored tangents, transforms and TEXCOORD_0 texture transforms are supported.
The finest declared resource LOD supplies the bake unless the node declares `hlod.bakeResource`, a pinned local bundle GLB in the same local space.
This optional, non-inherited reference lets an opaque exterior supply HLOD while the ordinary resource/LOD retains near glass and shared textures.
The source reference and resource pins participate in stale-bake detection; generated proxies cannot serve as bake inputs. Retagging preserves the
reference unless excluding the node. Material factors and source texture channels are transferred without scene lighting.

Unsupported inputs fail explicitly: animations/skinning/morphs, vertex colors, transparency/cutouts, double-sided materials, non-triangle primitives,
additional UV sets, unsupported glTF extensions, external GLB texture/buffer references, runtime behavior on covered nodes/ancestors,
mutable surfaces and authored replacement materials. Exclude these objects or convert their immutable appearance into a supported source GLB first.
Terrain, scene mounts, item-instance collections and mixed light components use their existing systems and cannot be merged into this static coverage.

Each cluster is limited to 500,000 input triangles, 1,024 selected nodes, 128 MiB of decoded textures and one output atlas set.
Individual inputs are limited to a 256 MiB GLB and 4,096 × 4,096 texture pixels. A failed projection or a bake reducing neither triangles nor draw calls is rejected.
If a cluster exceeds limits, split its distance cell or select fewer large features. Baking runs serially to bound native/WASM scratch memory.

Library exports: `tagSceneHlod`, `inspectSceneHlod`, `planSceneHlod`, `bakeSceneHlod`, and the independent `bakeHlodSurface` API.

`approximateHlodGeometry(surface, { voxelSizeM, maxErrorM, triangleRatio, signal })` supplies an alternative geometry stage
for distant static assemblies. It voxelizes source triangles, floods exterior space, removes enclosed interiors, extracts a
continuous surface and simplifies it. Returned metrics include voxel dimensions, scratch allocation, triangles and stage timings.
Input is capped at 500,000 triangles, the grid at 16M voxels and the extracted surface at 1M triangles. Excessive resolution fails;
the helper never silently increases voxel size. Callers still bake source appearance onto the returned geometry.

Its `errorM` measures simplification relative to the reconstructed surface, not against the original asset. Voxel resolution also
changes silhouettes and can close narrow gaps. Validate geometry and appearance at the intended viewing distance. The ordinary
`scene hlod bake` command continues to use its existing geometry stage; the new helper is available through the library API.

`npm run test:scene-hlod` runs the offline full-bake/cache/integrity/cancellation integration test. The same test is included in the normal suite gate.
Runtime selection and readiness/fading belong to `@helix/scene` and its optional `@helix/visual` bridge; consult the platform Scene HLOD reference for runtime setup.

Maintainer validation scripts also cover authored geometry (`scene-hlod-authored-bench.mjs`), source/proxy images (`scene-hlod-visual-bench.mjs`),
full scene movement/per-pass source counts (`scene-hlod-runtime-bench.mjs`) and visual/context-recovery smoke (`scene-hlod-runtime-smoke.mjs`).
The smoke captures an intermediate fade as well as completed replacements. Runtime scripts take an output directory and an engine checkout path;
the smoke's optional final `visual` argument enables the full visual runtime.

`scene-hlod-package-proof.mjs <installed-directory> <engine-directory>` expects a fresh directory installed from packed CLI/manifest/SDK/scene/visual
artifacts, Three, TypeScript, Vite and Three declarations. For unpublished work, substitute exact local dependency archives only in the temporary CLI
package metadata. The script checks real paths stay in that install, invokes its CLI exports, uses `installWorld` to wire pinned system payloads,
compiles declarations, builds a standalone world and tests far/near/far through a localhost browser. The engine path supplies copied hosted Three/Basis
artifacts; the resulting world has no source checkout imports. All test browsers and servers close on success or failure.

Add the final `complete` argument to the package proof, runtime smoke or runtime benchmark to exercise version-2 complete coverage.
The package proof verifies that one coarse mesh keeps the second native cell visible while only the first cell changes to fine content.

## Texture filtering at distance

The surface transfer derives each output texel's source UV footprint from the proxy and original triangle geometry, including texture transforms.
It selects and blends area-filtered source mip levels. Color/emissive samples are averaged in linear light; normal and ORM channels stay linear.
Fine mortar, brick relief and other subtexel texture details therefore contribute by covered area instead of becoming oversized bright speckles.
This is offline filtering: output atlas dimensions, geometry budgets and runtime draw counts do not increase. It does not remove authored trim.

Rebake existing scenes to use it. Local-cell baker version 3 and complete/refinement prototype baker version 2 invalidate earlier appearance caches;
these internal cache versions do not change the Scene HLOD capability/schema versions. Rebuild complete coverage before rebaking refinements.
Mip caches are scoped to one transfer and share pixel data across material bindings. Projection, silhouette and atlas-budget limits still apply.
Inspect the rebaked result at its actual transition distance; filtering does not repair coarse geometry or insufficient chart space.
Complete/refinement bakes accept tiles up to 1024 pixels for large, detailed facades, with the same 16M-texel shared-atlas cap.
Increasing `maxTileSize` can grow the shared texture allocation; inspect the bake receipt and keep decoded reservations within the scene budget.
The packer trims unused outer rows/columns after placing tiles. Atlas edges need not be powers of two; gutters and mipmapped KTX2 remain supported.
KTX2 encoding sizes its output buffer from the full UASTC block/mip chain instead of the upstream wrapper?s fixed 10 MiB buffer.
The image bound remains 4096 pixels per edge, and the WASM encoder is released after each image.
Use an updated manifest validator for these settings. The shared material carrier includes normal/UV attributes so glTF loaders preserve
the smooth vertex-normal and derivative-tangent behavior of the cell meshes that borrow its material. Rebuilding complete coverage regenerates it.

## Complete distant scene coverage

```sh
helix scene hlod bake-complete ./scene.json --cell-size 512 --voxel-size 2 --texels-per-metre 1 --min-tile 64 --max-tile 256
```

This dedicated bake produces HLOD version 2 (`helix.scene-hlod/2`): one merged mesh/material per independent coarse cell,
complete coarse residency, shared immutable appearance and per-source fine replacement. Tag ordinary static nodes first;
the existing native cell selection and ordinary object LODs remain in charge of nearby detail. The command also accepts
up to 16 scene files in the same bundle, sharing appearance across their separately sealed roots. Keep coarse regions inside
scene partitions; do not split one region across multiple documents if it must remain one mesh.

Layer `--error` and `--ratio` still control geometric simplification. Start with appropriate distant values when tagging,
such as `--error 2 --ratio 0.005`; old conservative layer settings are preserved. The new bake compares ordinary simplification
with bounded exterior approximation and retries a failing material projection only for the affected prototype. No projection
misses are accepted. Voxelization can still remove narrow openings: inspect silhouettes at the actual fine-cell boundary.

Input hashes, inherited transforms (including scale/shear), bake settings, source ordering and membership are sealed.
Warm bakes verify source bytes and reuse prototype geometry/appearance; cell artifacts and shared texture encoding are deterministic.
All outputs validate before scenes are resealed. Each scene replacement is atomic; a multi-document caller should publish
its bundle index only after the command succeeds. No network, credentials or remote publication are used by this operation.

## Streamed regional refinement

After `bake-complete`, run `helix scene hlod bake-refinements ./scene.json --distance 896 --error 0.5 --ratio 0.01
--voxel-size 0.5 --texels-per-metre 4 --min-tile 64 --max-tile 256` (one command). Multiple scene arguments share the prototype cache.
This preserves the original complete mesh/material pins and ordered source coverage, and adds one sharper mesh and regional material per cell.
`--atlas 1024` bounds each regional atlas edge (256/512/1024/2048). To fit that upload/decode budget, repeated and larger prototypes keep more
texels while smaller features can use smaller tiles down to `--min-tile`. This avoids an otherwise small cell acquiring a large atlas reservation.
The scene requires `helix.scene-hlod/3`. The runtime streams optional upgrades from spare memory and retains coarse coverage as fallback.
Do not increase every regional atlas globally: inspect silhouettes and texture detail at the actual loading range, then measure decoded residency.
The library equivalent is `bakeSceneHlodRefinements`; its receipt reports geometry, per-cell material sizes, triangles and bake time.
`bake-complete` deliberately rebuilds the coarse level and removes the refinement tier; run `bake-refinements` again afterwards.

## Shared appearance and compact cell artifacts

The HLOD library also exposes `planSharedHlodAtlas` / `bakeSharedHlodAtlas` for repeated immutable source appearances.
Power-of-two prototype tiles share a bounded 16M-texel rectangle, with outer gutters, half-resolution normal maps and
quarter-resolution ORM maps. `writeSharedHlodMaterialGlb` writes its single PBR material as a pinned GLB resource;
the carrier triangle is for loading only. Reservations include the uncompressed RGBA fallback and complete mip chains.

`writeHlodCellGlb` writes one mesh with 16-bit positions/UVs, 8-bit normals and lossless meshopt compression. Its returned
`quantizationErrorM` bounds the additional position error. Every triangle has a constant `_HELIX_HLOD_SOURCE` index into
the cluster's ordered source nodes, allowing independent replacement within a merged cell. Geometry is limited to
500,000 triangles and 1,024 owners. Appearance is supplied by the shared material at runtime. These are HLOD-specific
library operations; ordinary model/character simplification and the existing scene bake command retain their behavior.
