diff --git a/content/Architecture/hbgpu-vulkan-hud.md b/content/Architecture/hbgpu-vulkan-hud.md new file mode 100644 index 0000000..558c1d2 --- /dev/null +++ b/content/Architecture/hbgpu-vulkan-hud.md @@ -0,0 +1,70 @@ +--- +title: Single-Draw-Call HarfBuzz hb-gpu Vulkan HUD +description: How Rust to Dust renders all combat HUD typography, radar vectors, and target overlays in one Vulkan draw call at 0.229 ms on a GTX 1070 with zero steady-state GC allocations. +--- + +Combat HUDs with shifting numeric readouts, world-projected lock boxes, radar blips, and multi-cell thermal schematics stress retained UI trees. Updating dozens of Godot `Control` labels and `_Draw()` widgets every frame rebuilds canvas items, fragments dynamic font atlases, allocates managed strings, and multiplies draw calls across the frame loop. + +To remove widget-tree overhead from the combat frame, `RustToDust.HbGpu` and `HbGpuCanvas` batch every combat HUD glyph, bar, bracket, and radar ring into one `RenderingDevice` draw call backed by HarfBuzz 15.2.0 `hb-gpu`. + +![Combat HUD over Sion rendered in one Vulkan draw call using HarfBuzz hb-gpu and Monaspace Krypton](../media/hud-hbgpu-sion.webp) + +## Native `rtd_hbgpu.dll` Footprint + +The C17 shim under `native/rtd_hbgpu/` links HarfBuzz 15.2.0 (`harfbuzz` and `harfbuzz-gpu`) statically and exports eight C functions covering version reporting, embedded shader retrieval, variable-font lifecycle, UTF-16 text shaping, glyph curve encoding, and 2D vector path encoding. `CMakeLists.txt` disables ICU, FreeType, Cairo, Glib, font subsetting, rasterization, and CPU vector backends, compiling with whole-program optimization (`/O2 /GL /Gy` and `/OPT:REF /OPT:ICF /LTCG`). + +The resulting Win64 `rtd_hbgpu.dll` weighs **`1.37 MiB`** and imports only `KERNEL32.dll`. It loads unmodified `Monaspace Krypton v1.400` (`Krypton.ttf`, `1,363,340` bytes at `2000` units per em) in compliance with SIL Open Font License 1.1 redistribution terms, caching font instances in `HbGpuFontCache` by `(FontId, weight, width, slant)`. + +## Atlas Partitioning & Upload Flow + +```mermaid +flowchart LR + H["Hud.Sync (C#)"] --> W["HbGpuCommandWriter (80 B/quad, <= 4096 quads)"] + H --> S["HbGpuBlobCache (glyphs + vector shapes)"] + S --> A["HbGpuAtlasAllocator (262,144 texels RGBA16I)"] + A --> U["RenderingDevice.TextureUpdate (1024x256 R16G16B16A16Sint)"] + W --> B["SSBO Upload (<= 320 KiB)"] + U --> D["1x DrawListDraw (6 procedural verts x quadCount)"] + B --> D + D --> T["R8G8B8A8Unorm Texture2Drd (PremultAlpha)"] +``` + +`HbGpuAtlasAllocator` partitions a `1024 × 256` signed-integer texture (`HB_GPU_ATLAS_2D`, `R16G16B16A16Sint`, `262,144` texels or `2.0 MiB`) into two regions: texels `[0..229,376)` form a persistent cache for shaped glyphs and static icons that resets between frames once occupancy passes `75%`, while texels `[229,376..262,144)` act as a per-frame ring for transient geometry such as curved heat arcs. + +On the CPU side, `Hud` maintains pre-allocated character scratch buffers, pre-wrapped broadcast chyron line caches, and fixed staging arrays (`4096` `HbGpuQuadInstance` records at `80` bytes each). Both `HbGpuNativeTests` and the headless `Smoke` suite assert `0 B` of managed heap allocations across steady-state `Hud.Sync` loops. On the render thread, `HbGpuVulkanBackend` pushes newly encoded atlas spans in place via `RenderingDevice.TextureUpdate`, uploads the active slice of the quad storage buffer, and issues one `DrawListDraw` call generating six procedural vertices per quad instance into a premultiplied `R8G8B8A8Unorm` `Texture2Drd`. + +## Analytic `FlagSolidRect` Fast Path vs Slug Bezier Bands + +HarfBuzz's `_hb_gpu_slug` fragment evaluator decodes quadratic Bezier bands stored in the integer atlas at `v_blob_loc` to compute exact coverage for arbitrary curves. Running that band loop on every axis-aligned health bar, panel background, and crosshair tick spends unnecessary ALU cycles on straight edges. + +`HbGpuQuadInstance` introduces `FlagSolidRect` (`v_flags & 2u`), mapping solid rectangles into em-space `[-500, 500]^2` and taking a direct analytic branch in the fragment shader, while glyphs and curved shapes enter `_hb_gpu_slug` with optional `hb_gpu_stem_darken` (`v_flags & 1u`): + +```glsl +if ((v_flags & 2u) != 0u) { + vec2 edgeDist = (500.0 - abs(v_em)) * pixelsPerEm; + cov = clamp(min(edgeDist.x, edgeDist.y) + 0.5, 0.0, 1.0); +} else { + cov = _hb_gpu_slug(v_em, pixelsPerEm, v_blob_loc); + if ((v_flags & 1u) != 0u) { + float ppem = hb_gpu_ppem(v_em, v_blob_loc); + if (cov > 0.0 && cov < 1.0) { + float brightness = dot(v_color.rgb, vec3(1.0 / 3.0)); + cov = hb_gpu_stem_darken(cov, brightness, ppem); + } + } +} +``` + +Euclidean box coverage for `FlagSolidRect` reduces to four scalar ALU operations per fragment: + +$$\text{cov} = \text{clamp}\!\left(\min\!\left((500 - |v_{\text{em}}.x|)\,p_x,\ (500 - |v_{\text{em}}.y|)\,p_y\right) + 0.5,\ 0,\ 1\right)$$ + +where $p = (1 / \|\nabla v_{\text{em}}.x\|,\ 1 / \|\nabla v_{\text{em}}.y\|)$ is the inverse em-per-pixel Jacobian derived once from `dFdx` and `dFdy`. On a GTX 1070 at `1080p`, the entire combat HUD pass completes in **`0.229 ms` GPU time** in **`1` draw call**. + +## Thermal Raster Under Vector Brackets + +In the lower-left schematic panel, `InventoryGridControl` pairs a stateless interior cell shader (`inventory_grid.gdshader`) with `HbGpuCanvas` vector overlays. The interior shader samples a nearest-filtered `3W × H` metadata texture (encoding armor/module tints, an 8-bit neighbor mismatch mask for corner folding, cell flags, and hit flashes) together with a bilinear `W × H` thermal texture mapping `[20°C..200°C]` to continuous heat glow and `45°` fracture hatching across stripped cells. `HbGpuCanvas` then draws hardpoint L-brackets, hull outlines, stripped X-marks, compatibility highlights, and Krypton cell tags (`W` for Weapon, `E` for Engine, `R` for Radiator) into the parent HUD draw call. + +## Planned Migration Off Godot Modal Controls + +Pre-match menu screens (`MainMenu`, `LobbyScreen`, `ServerBrowser`, `SettingsOverlay`, and the `[F9]` network debug panel) still rely on Godot `Control` nodes styled through `ImperialChrome` and `panel_chrome.gdshader`. Upcoming UI work migrates those modal panels and text inputs across the `thing_ffi` boundary into GameCult's `Thing 2` layout engine onto `HbGpuCanvas`, unifying the entire front end onto one renderer. diff --git a/content/Architecture/index.md b/content/Architecture/index.md index bd981ee..a2d2b7f 100644 --- a/content/Architecture/index.md +++ b/content/Architecture/index.md @@ -1,13 +1,18 @@ --- title: Architecture -description: Technical architecture and subsystem dossiers for Rust to Dust. +description: Engineering teardowns and captures for Rust to Dust subsystems. --- -Technical dossiers covering core subsystems are incoming: +Six subsystem teardowns: four covering shipped systems on the live `RustToDust` engine stack (`Godot 4.7.2` Forward+ Vulkan, `Ymir.Box3D` rigid-body physics, `CultNet` multiplayer, and `HarfBuzz 15.2.0` `hb-gpu`), and two covering active systems still in build. -1. **`hb-gpu` Vulkan HUD** — GPU-driven cockpit instrumentation and frame telemetry. -2. **Sion Terrain & Destruction** — `0.5 m` swisstopo DEM ingestion, building footprints, and persistent terrain deformation. -3. **Watertight Sion City** — Procedural architectural grammar and manifold urban geometry. -4. **Zero-Ambient SDFGI & Volumetrics** — Signed-distance global illumination and flow-field volumetric smoke. -5. **Vehicles & Walkers** — Chassis suspension, articulated locomotion, and damage kinematics. -6. **Multiplayer & Distribution** — Dedicated Sion lobby server (`UDP 3076`) and Win64 release packaging. +## Shipped Subsystems + +1. **[Single-Draw-Call HarfBuzz `hb-gpu` Vulkan HUD](hbgpu-vulkan-hud.md)** — Batches all combat HUD typography, radar rings, and target lock boxes into one Vulkan draw call at `0.229 ms` (`1080p`, GTX 1070) with `0 B/frame` steady-state managed allocations. +2. **[0.5 m swisstopo DEM, Unified Compute Terrain & Tiled Box3D Physics](sion-dem-and-tiled-physics.md)** — Streams a `6145×6145` Swiss Alpine heightmap across shared `192 m` tiles for GPU compute crater baking (`0.37 ms/frame` on GTX 1070), demand-paged physics, and persistent match-to-match scars. +3. **[Zero-Ambient SDFGI Lighting & Gradient-Offset Volumetric Plumes](sdfgi-lighting-and-volumetrics.md)** — Removes flat ambient offsets in favor of half-resolution indirect lighting and AgX tonemapping (`62 FPS`, `p95 = 13.28 ms` at `1080p` on GTX 1070) paired with four-pass compute plumes and live graphics controls. +4. **[Thermal Grid Chassis, Ballistics & Netcode (`CultNet` + `Ymir`)](thermal-grid-ballistics-netcode.md)** — Ties conductive 2D chassis grids, mid-match module salvage, and multi-stage ordnance graphs to a `60 Hz` authoritative server under a `1,152 B` UDP snapshot cap and a `3×3` client prediction window. + +## Active Work in Progress & Planned Pipeline + +5. **[Upright Mech Walkers (`Ymir` Box3D ABI 22 — Work in Progress)](upright-mech-walkers.md)** — Migrates bipedal and quadruped walkers from virtual ground-reaction-force box balancing to upright angular-locked capsules and Zero-Moment Point pelvis kinematics. +6. **[Watertight CGA Destructible Sion City & Real Species Foliage (Planned / In Build)](watertight-cga-sion-and-foliage.md)** — Turns `2,319` Sion buildings into closed, destructible shape-grammar zones and populates the valley with Valais-accurate tree stands bent by blast wind. diff --git a/content/Architecture/sdfgi-lighting-and-volumetrics.md b/content/Architecture/sdfgi-lighting-and-volumetrics.md new file mode 100644 index 0000000..c4f1792 --- /dev/null +++ b/content/Architecture/sdfgi-lighting-and-volumetrics.md @@ -0,0 +1,48 @@ +--- +title: Zero-Ambient SDFGI Lighting & Gradient-Offset Volumetric Plumes +description: Removing flat black-floor lifters in favor of zero-ambient 3-cascade SDFGI + AgX, plus a 4-pass PostSky compute pipeline for gradient-offset volumetric plumes and 3D blast flow. +--- + +Early outdoor captures looked flat under harsh alpine sun because three separate lighting compensators were lifting shadow floors simultaneously: non-zero `AmbientLightEnergy`, shadowless fill lights, and self-emitting fog and smoke floors. While those offsets kept dark steel readable, they washed out sunlit walls and turned dense smoke cores milky gray. + +Removing all ambient lifters and tuning Godot 4.7 Forward+ SDFGI, AgX tonemapping, and a four-pass `PostSky` compute volumetric pipeline brought frame time on a GTX 1070 at `1080p` to **`62 FPS` (`p95 = 13.28 ms`)** while restoring deep charcoal smoke contours and hard valley shadow contrast. + +![Zero-ambient indirect lighting across Sion with AgX tonemapping and post-tonemap contrast grading](../media/lighting-sdfgi-sion.webp) + +![Zero-ambient indirect lighting across the procedural desert mesas and dunes](../media/lighting-sdfgi-desert.webp) + +## Killing Black-Floor Lifters & Calibrating SDFGI + +`AtmosphereSystem` enforces zero flat ambient injection across every lighting layer. `WorldEnvironment` runs with `AmbientLightEnergy = 0.0` (`AmbientSource.Disabled`), pulling indirect sky and terrain bounce strictly from 3-cascade half-resolution SDFGI (`SdfgiMinCellSize = 0.8 m`, `SdfgiYScale = 75%`, `SdfgiBounceFeedback = 0.60`, `SdfgiEnergy = 0.85`, 4 rays per probe, 10-frame convergence) paired with SSAO (`Radius = 1.15 m`, `Intensity = 1.85`) for foot and tire grounding. + +Atmospheric haze avoids shadow-floor lifting as well: near froxel volumetric fog (`0..460 m` on Sion, `0..380 m` on Desert) runs with `VolumetricFogAmbientInject = 0.0` and `VolumetricFogEmissionEnergy = 0.0`, while far depth-based aerial perspective (`FogSkyAffect = 0.0`) leaves the analytical sky lookup tables untouched. + +`TonemapMode = Agx` (`TonemapAgxWhite = 6.0`, `TonemapAgxContrast = 1.50`, `TonemapExposure = 0.84`) rolls off bright muzzle flashes and blackbody fireballs without hue-shifting amber plumes to yellow. Immediately afterward—at `CanvasLayer 5`, strictly after AgX and normalized additive HDR bloom (`GlowHdrThreshold = 1.0`) and before the `Layer 10` HUD—`film_grain.gdshader` applies `pow(src.rgb, vec3(1.32))` (`post_gamma = 1.32`) plus midtone-weighted interleaved gradient noise to deepen compressed shadow rolloff without touching HUD crispness. + +## Gradient-Offset Volumetric Plumes (`PostSky`) + +```mermaid +flowchart LR + P0["Pass 0: flow_field_step.glsl (64x24x64 RGBA16F ping-pong)"] --> GF["Global rtd_flow_field (Texture3Drd)"] + GF --> P2["Pass 2: volumetric_raymarch.glsl (sweep-line + gradient-offset SDF)"] + P1["Pass 1: volumetric_tile_cull.glsl (16x16 tiles, 128-slot Bitonic sort)"] --> P2 + P2 --> P3["Pass 3: volumetric_composite.glsl (2x2 depth bilateral upsample pre-tonemap)"] +``` + +Pass 1 (`volumetric_tile_cull.glsl`) subdivides the march target into `16 × 16` tiles, tests up to `128` active emitter capsules against each tile's frustum and maximum linearized depth, and runs an adaptive shared-memory Bitonic sort over packed `(entryDistance, emitterIndex)` keys so only the `24` closest emitters reach the raymarcher sorted front-to-back. Pass 2 (`volumetric_raymarch.glsl`) intersects each pixel against its tile's `<= 24` capsules, sorts hit intervals by entry distance `t0`, and advances a monotonic sweep-line cursor—admitting and retiring capsules across each step interval and leaping straight to the next `t0` whenever no emitter is active. + +Multiplying a radial plume density by 3D noise breaks silhouette continuity and creates floating disconnected blobs. Instead, `volumetric_raymarch.glsl` applies a gradient-offset SDF law where two octaves of `triNoise3d` ($n_1, n_2$) only displace the normalized radial coordinate $d_{\text{norm}}$: + +$$d_{\text{warped}} = \text{clamp}\!\left(d_{\text{norm}} - \left((n_1 - 0.45 n_2 - 0.11)\cdot 0.88\cdot(0.35 + 0.65\min(d_{\text{norm}}, 1))\right),\ 0,\ 1.2\right)$$ + +Because $d_{\text{norm}}$ increases monotonically outward, displacing $d_{\text{norm}}$ curls outer smoke billows while keeping interiors solid. Accumulated smoke density $\rho$ and core combustion temperature `coreSignal` (radial falloff $(1 - d_{\text{warped}})^{2.35}$ modulated by $n_1, n_2$) then separate scattering from emission: an inverse-density soot factor $\frac{1}{1 + 4.6 \rho}$ keeps thick interiors dark charcoal while focusing Henyey-Greenstein sun scattering onto thin outer vapor edges, and `smoothstep(0.72, 1.05, coreSignal)` gates `blackbodyRamp` emission strictly through turbulent crevices. Pass 3 (`volumetric_composite.glsl`) performs a `2 × 2` depth-aware bilateral upsample back onto the HDR scene buffer before tonemapping. + +![Close-up of a gradient-offset volumetric smoke and combustion plume rendered before tonemapping](../media/plume-closeup.webp) + +## Blast Advection (`rtd_flow_field`) & Live Graphics Settings + +`flow_field_step.glsl` updates a camera-snapped `64 × 24 × 64` `RGBA16F` volume (`3.0 m` voxels covering `192 × 72 × 192 m`) every frame, advecting planetary wind alongside radial `ShockShell` blast impulses (`rgb` velocity and `a` shock pressure). `AtmosphereSystem` publishes that `Texture3Drd` globally as `rtd_flow_field`, driving plume shear, shock cavity carving, `GpuSparksSystem`, `ParticlePool`, and upcoming tree wind shaders from one vector field. + +![Settings -> Graphics modal overlay with live-applied VFX resolution, sample count, and SDFGI controls](../media/settings-graphics.webp) + +`GraphicsSettings` (`user://graphics_settings.json`) and `SettingsOverlay` expose live rendering controls through the `272 B` `VolumetricFrame` uniform buffer and `WorldEnvironment`. Switching `VFX / Fog Resolution` (`Half 0.5x`, `High 0.75x`, `Full 1.0x`) reallocates the march target and bypasses the `2 × 2` upsample at native `1.0x`, `Volumetric Sample Count` (`Low 8`, `Medium 10`, `High 16`, `Ultra 24`) scales raymarch step density in place without shader recompilation, and `SDFGI Quality` (`Off`, `Balanced`, `High`) reconfigures GI cascades immediately. diff --git a/content/Architecture/sion-dem-and-tiled-physics.md b/content/Architecture/sion-dem-and-tiled-physics.md new file mode 100644 index 0000000..3d3ea3b --- /dev/null +++ b/content/Architecture/sion-dem-and-tiled-physics.md @@ -0,0 +1,43 @@ +--- +title: 0.5 m swisstopo DEM, Unified Compute Terrain & Tiled Box3D Physics +description: Streaming a 6145x6145 Swiss Alpine elevation grid across shared 192 m tiles for compute height baking, lazy Box3D physics, and persistent match-to-match scars. +--- + +The initial Sion prototype sampled `swissALTI3D` at `3 m` (`1025 × 1025`) and rebuilt the terrain heightfield monolithically inside `Ymir.Box3D`, GameCult's custom native rigid-body physics library. Three-meter spacing blurred road embankments, terraced vineyard walls, and canal banks, while stepping up to `0.5 m` (`6145 × 6145` samples) meant a full-map float heightfield consumed `~144 MiB` per copy (`~288 MiB` across rebuild buffers). Rebuilding that whole mesh whenever an artillery shell dug a crater stalled the `60 Hz` physics loop. + +Both the `3,072 m × 3,072 m` Sion valley and the `1,536 m × 1,536 m` Desert arena now share one `192 m` tile lattice (`16 × 16` tiles on Sion, `8 × 8` on Desert) across simulation, GPU compute baking, physics collision, and network replication. + +![Sion 0.5 m swisstopo terrain with crater deformation and legacy building tiles](../media/sion-05m-dem.webp) + +## `0.5 m` swisstopo DEM Ingestion + +Offline tool `tools/maps/sion/bake_sion.py` mosaics 16 `swissALTI3D` `0.5 m` tiles (`EPSG:2056`) centered on Valère and Tourbillon (`E 2594150, N 1120050`, base elevation `483.41 m` ASL), covering `310.841 m` of local vertical relief (`-5.885 m` to `+304.957 m` relative to the `483.41 m` datum): + +$$y_{\text{world}} = y_{\min} + s \cdot h_{\text{u16}}, \qquad s = 0.00474314\text{ m/step}$$ + +`heightmap_05m.u16z` encodes the `6145 × 6145` grid using zig-zag delta encoding and zlib (`rdhm_v2_u16_zigzag_zlib`), packing `37.76M` elevation samples into `31.9 MB` (`31,924,416` bytes) with **`4.74 mm`** vertical quantization precision. At load time, `SionMapLoader` decodes one immutable `ushort[]` base array shared across matches so `TerrainField` allocates zero full-map float copies; only tiles modified by runtime brushes allocate sparse `385 × 385` float height patches. `TerrainField` tracks two independent version counters per tile—`StructuralTileVersions[tx, tz]` for elevation edits and `VisualTileVersions[tx, tz]` for albedo, scorch, and tire-track updates—allowing physics, GPU baking, and network sync to track their own last-synced tile versions without clearing shared dirty state. + +## Unified Compute Terrain (`terrain_tile_bake.glsl`) + +```mermaid +flowchart LR + DEM["Sion 6145x6145 Half-Float DEM + Albedo/Mask PNGs (Read-Only)"] --> SH["terrain_surface.gdshader"] + BR["TerrainField Dynamic Brushes (Crater / Scorch / Track / Rubble)"] --> CS["terrain_tile_bake.glsl (8x8 Compute)"] + CS --> LRU["96-Slot LRU Pool (388x388 RGBA16F + RGBA8, 2-texel gutter)"] + LRU --> SH + FB["1x1 Neutral Fallback (Unscarred Tiles)"] --> SH + LOD["3 Shared PlaneMesh LODs (192 / 48 / 12 subdivs)"] --> SH +``` + +`TerrainRenderer` uploads the base elevation map once into a read-only single-channel half-float (`Rh`) `Texture2Drd` alongside `terrain_surface.png` (`4096 × 4096`) and `terrain_surface_mask.png` (`2048 × 2048`). Any tile scarred by craters, tracks, scorches, or rubble claims a slot from a `96`-entry LRU `Texture2Drd` pool baked by `terrain_tile_bake.glsl`: + +- **Seam-free gutters:** Each `192 m` tile spans `384` intervals at `0.5 m` spacing (`385 × 385` shared-edge physics vertices). On the GPU, `terrain_tile_bake.glsl` writes a `388 × 388` texture (`RGBA16F` height, roughness, and scorch deltas plus `RGBA8` albedo deltas) whose inner `384 × 384` texel-center span aligns to those `0.5 m` grid intervals while adding a 2-texel overlap border (`gutter`) on every side so bilinear filtering in `terrain_surface.gdshader` stays seamless across tile edges. +- **Fixed per-frame budget:** At most `4` dirty tiles bake per sync (`0.37 ms/frame` on GTX 1070). Unscarred tiles bind shared `1 × 1` neutral textures at zero extra VRAM cost, and visible tiles draw from three shared `PlaneMesh` LODs (`192`, `48`, and `12` subdivisions) with vertex edge morphing in `terrain_surface.gdshader`. + +## Lazy `Box3DPhysicsTileSync` & Persistent `CultCache` Scars + +In `RustToDust.Ymir`, `Box3DPhysicsTileSync` maps each `192 m` lattice cell to an independent `Ymir.Box3D` `StaticHeightField` body (`stableId 10_000..10_255` for terrain tiles; `11_000+` and `12_000+` reserved for upcoming destructible building and tree-trunk tiles) extracted from `385 × 385` float heights on demand: + +1. **Demand paging:** Server `ArenaSession` mounts a `3 × 3` tile neighborhood (`halfTileRadius: 1`) around active contenders, single tiles (`0`) around stationary actors and descending orbital pods, and DDA-traversed tiles along weapon rays via `EnsureTilesAlongRay` before `CastRayClosest`. +2. **Throttled crater rebuilds:** Dirty heightfields queue into `FlushDirtyHeightfields(maxTilesPerTick: 4)` so simultaneous barrage impacts rebuild at most four `192 m` patches per `60 Hz` step. +3. **Match-to-match scar persistence:** `ArenaScarLedger` records up to `4,096` terrain scars (`0.75 m` spatial coalescing for overlapping craters and scorches) into `CultCache`, GameCult's persistent MessagePack cache, keyed by `AssetFingerprint`. On multiplayer join or match reset, `ServerMatchHost` transmits the full ledger compressed with ZLib inside `InitialMatchStateDto.PersistentScars`, then streams live `TerrainStampEvent` updates whenever a peer moves within a `576 m` circular radius around a stamp. diff --git a/content/Architecture/thermal-grid-ballistics-netcode.md b/content/Architecture/thermal-grid-ballistics-netcode.md new file mode 100644 index 0000000..370203a --- /dev/null +++ b/content/Architecture/thermal-grid-ballistics-netcode.md @@ -0,0 +1,53 @@ +--- +title: Thermal Grid Chassis, Ballistics & Netcode (CultNet + Ymir) +description: Conductive 2D chassis thermal grids, cell-level armor stripping, multi-stage ordnance graphs, 60 Hz Ymir.Box3D physics, <= 1152 B UDP snapshots, and 3x3 client prediction. +--- + +Hitpoint pools treat a vehicle as one number until it explodes. *Rust to Dust* simulates every hull as a conductive 2D grid of armor cells and hardpoint rectangles, ties weapon fire and impacts directly to local cell temperature, and replicates combat state and terrain deformation across `CultNet`—GameCult's UDP networking stack—under a `1,152 B` unreliable datagram cap. + +## Conductive 2D Chassis Grids + +`Catalog` loads `15` distinct chassis spanning wheeled buggies, tracked tanks, VTOL craft, quadruped walkers, and bipedal mechs, alongside `9` human salvage modules and `6` Imperial Tourist modules. Wheeled, tracked, VTOL, and quadruped hulls map onto a top-down `Dorsal` grid; bipedal walkers map onto an upright front-facing `Coronal` silhouette grid. + +```mermaid +flowchart TD + F["Weapon Fire / Engine Thrust / Beam Hit"] --> INJ["InjectHeat(x, y) / Cell Thermal Mass"] + INJ --> SUB["50 Hz+ Substeps (subDt <= 0.02 s)"] + SUB --> COND["4-Neighbor Conduction: pairCond * (T_nb - T) * subDt"] + SUB --> RAD["Border-Only T^4 Radiative Cooling + Active Radiators"] + RAD --> PERF["Trapezoidal Performance(T) Curve per Mounted Module"] + PERF --> EFF["Weapon Cooldown / Drive Thrust / Cooling Power"] +``` + +Inside `ChassisGrid.StepHeat`, thermal simulation advances in substeps clamped to `subDt <= 0.02 s`. Each active cell exchanges heat symmetrically across its east and south edges using the pair's mean conductivity, visiting every four-neighbor boundary once per substep while conserving energy across hardpoint boundaries. Only perimeter cells (`BorderCells[x, y]`) radiate heat according to $T^4$, while active radiators subtract `CoolingPower * Performance(T)` across their footprint cells. + +Every mounted module evaluates `ModuleSpec.Performance(T)`, returning `1.0` across `[OptimalTemp - PlateauWidth/2, OptimalTemp + PlateauWidth/2]` and ramping linearly down to `0` at `MinTemp` and `MaxTemp`. Because cells initialize at `20°C` (`AmbientTemp`) while high-output weapons and supercharged engines enter full plateau efficiency around `30°C–40°C`, cold gear warms up slightly during initial fire before excess sustained heat pushes past the upper shoulder into thermal stall. + +## Localized Armor Stripping & Mid-Match Salvage + +When a round hits, `ChassisGrid.ApplyHit` projects the local impact point differently by grid plane: `Dorsal` hulls project `(right, forward)` outward toward the nearest perimeter cell facing the impact vector, whereas `Coronal` bipedal walkers map `(right, height)` directly onto the nearest active silhouette cell. Damage subtracts from that cell's armor first, spilling any overflow into `CoreHp`. + +A mounted weapon, engine, or radiator remains functional while at least one cell under its hardpoint holds armor above zero (`IsHardpointOperational`). On walkers, left and right leg-cell armor ratios feed `GetLegIntegrities`, reducing drive thrust and turn rate as legs lose plating. Crates and destroyed hulls drop physical modules and wrecks: `TryQuickBoltOrCargo` mounts picked-up gear straight into the first matching empty hardpoint rectangle or stashes it in cargo, and `SwapChassis` transfers compatible mounted gear into a field wreck while preserving core health ratio. + +## Multi-Stage `OrdnanceGraph` & `60 Hz` `Ymir.Box3D` Physics + +`OrdnanceGraph` models hitscan beams, ballistic shells, rocket-boosted salvos, homing missiles, loitering laser drones, and stationary mines as directed trees (`OrdnanceNodeDef`). Nodes attach `WhileAlive` periodic pulse emitters and up to six trigger conditions (`Impact`, `Timeout`, `Altitude`, `Proximity`, `StageElapsed`, `Apex`) driving `Detonate`, `Split`, `Transition`, or `Fizzle` outcomes—for example, a sabot carrier splitting into homing sub-munitions at apex or an airburst flak shell detonating on proximity. + +At load or weapon-generation time, `OrdnanceGraphValidator.ValidateAndFlatten` rejects cyclic graphs and non-finite fields, enforces a maximum tree depth of `4` and `<= 16` peak sub-spawns per shot, and flattens the tree into `<= 32` indexed nodes so `OrdnanceRuntime` steps projectiles in flat arrays with zero runtime recursion or heap allocation. Server `ArenaSession` owns the authoritative `60 Hz` `Ymir.Box3D` simulation (GameCult's custom native rigid-body physics library; `Box3DSoaWorld`, capacity `1024`), calling `Box3DPhysicsTileSync.EnsureTilesAlongRay` to page in `192 m` terrain tiles along raycasts before `CastRayClosest`. + +## `CultNet` Replication & `3×3` Prediction Window + +```mermaid +flowchart LR + IN["ClientInputPacket (36 B UDP)"] --> SRV["ServerMatchHost + ArenaSession (60 Hz Ymir.Box3D)"] + SRV -->|"latest (unreliable <= 1152 B UDP)"| CLI["RemoteArenaSession Client View"] + SRV -->|"schema (reliable ZLib scars + SimEvents + 576 m radius bubble)"| CLI + CLI --> PRED["Client Prediction World (60 Hz, cap 256)"] + SYNC["Box3DPhysicsTileSync 3x3 Window (576 m x 576 m)"] --> PRED +``` + +`SnapshotCodec` splits replication across two channels on `CultMesh` (GameCult's channel-framing and message-routing layer inside `CultNet`): + +- **`"latest"` (unreliable, latest-state-wins UDP):** Strictly capped at **`1,152 B`** on the wire (`42 B` `CultNetRudp` packet header plus `52 B` `CultMesh` frame header leaves **`1,058 B`** maximum payload per datagram). `EncodeCorePvs` packs quantized poses, velocities, health, heat, and visibility-filtered contender, walker, and spectator states inside that ceiling even at worst-case 12-contender density. +- **`"schema"` (reliable ordered UDP):** Delivers `InitialMatchStateDto` (including ZLib-compressed `PersistentScars` from `ArenaScarLedger`), reliable loadout, drop, and broadcast `SimEvent`s, and `TerrainStampEvent`s streamed as peers enter a **`576 m` circular radius** around each terrain scar. +- **`3 × 3` client prediction window:** `RemoteArenaSession` runs a `256`-body local `Ymir.Box3D` prediction world replaying buffered `36 B` `ClientInputPacket`s on rollback, while `Box3DPhysicsTileSync.SyncWindow` slides a `3 × 3` grid (`halfTileRadius: 1`, spanning `576 m × 576 m` around the player) of `0.5 m` heightfield tiles so predicted movement stays deterministic without holding the entire `3,072 m` valley in prediction memory. diff --git a/content/Architecture/upright-mech-walkers.md b/content/Architecture/upright-mech-walkers.md new file mode 100644 index 0000000..4b628b1 --- /dev/null +++ b/content/Architecture/upright-mech-walkers.md @@ -0,0 +1,46 @@ +--- +title: Upright Mech Walkers (Ymir Box3D ABI 22 — Work in Progress) +description: Active work in progress migrating bipedal and quadruped walkers from Hybrid B virtual-GRF box balancing to upright angular-locked Box3D capsules and Zero-Moment Point pelvis kinematics. +--- + +> [!WARNING] Work in Progress +> In the current build, walkers run **Hybrid B** virtual ground-reaction-force (GRF) box balancing in `WalkerLocomotion.cs`. `Ymir.Box3D` (GameCult's custom native rigid-body physics library) ABI 22 already exports `LockAngularX/Y/Z`, `DisableContactRecycling` (preventing the solver from reusing stale contact manifolds across vertical steps), `CastCapsuleClosest`, and `SetBodyMotion`, while the `RustToDust` integration (`AddCapsule` bodies, `WalkerSurfaceProbe`, `PreStepWalker`/`PostStepWalker`, and `+5 B` pelvis/lean network sync) is currently in build and not yet merged. + +Seven of the 15 chassis (five bipeds and two quadrupeds) walk on articulated legs solved with 2-bone and 3-bone inverse kinematics (`WalkerLocomotion`) and synchronized to `VehicleRigAnimator` and `WalkerFootstepTracker`. + +## Current Shipped Model: Hybrid B Virtual GRF + +In the live build, `ArenaSession` spawns walkers as `AddBox` rigid bodies in `Box3DSoaWorld`. Each `60 Hz` tick, `WalkerLocomotion.StepWalker` computes a centroidal vertical spring-damper force toward the target ride height above sampled ground: + +$$F_{y,\text{des}} = \max\!\left(0,\ m g + m k_p (y_{\text{target}} - y) + m k_d (\dot{y}_{\text{terrain}} - v_y)\right)$$ + +along with virtual pitch and roll restoring torques computed from `ComputeHullSlopeNormal` and `AlignUpToSlope`. Swing feet compute capture-point landing offsets: + +$$\Delta \mathbf{p}_{\text{step}} = \mathbf{v}_H \,(0.56\,T) + \mathbf{v}_{\text{err}}\,k_{\text{capture}}$$ + +where $\mathbf{v}_H$ is current horizontal hip velocity, $T$ is effective stride duration, $\mathbf{v}_{\text{err}} = \mathbf{v}_H - \mathbf{v}_{H,\text{des}}$ is velocity tracking error, and $k_{\text{capture}} = 0.22 / \omega_0$ is the inverted-pendulum capture gain. Targets clamp inside `MaxLegReach` and advance along a normalized swing phase $u \in [0, 1]$ with a $\sin(\pi u)$ vertical clearance arc. + +## Failure Modes on `0.5 m` Sion Terrain & Curbs + +Testing Hybrid B against Sion's `0.5 m` elevation steps and building perimeters exposed two rigid-body solver failures alongside a separate footstep probing mismatch: + +1. **Box hull snagging on `0.5 m` relief:** Sharp bottom corners on an `AddBox` collision proxy catch on `0.5 m` terrain terraces and vertical curb risers, forcing `StepWalker` to run extra forward height probes that inject upward lift during movement. +2. **Virtual torque fighting contact manifolds:** When one box corner clips a crater rim or building ledge, `Box3D` emits contact impulses that fight Hybrid B's virtual righting torque, causing pitch oscillation on steep slopes. + +Separately from rigid-body balance, `WalkerFootstepTracker` currently clamps footstep dust and audio height down to `terrain.SampleHeight`, which pulls elevated curb footsteps below building plinths. + +## In-Progress Target: ABI 22 Angular-Locked Capsules + +```mermaid +flowchart LR + SP["WalkerSurfaceProbe (TerrainField + Box3D)"] --> PRE["PreStepWalker (TryStep 0.65 m + Slope Guard + Yaw)"] + PRE --> STEP["Box3DSoaWorld.Step (AddCapsule + LockAngularX/Z + DisableContactRecycling)"] + STEP --> POST["PostStepWalker (Reground 0.75 m + ZMP PelvisOffset + SecondaryLean)"] + POST --> NET["SnapshotCodec (+5 B/walker) & VehicleRigAnimator"] +``` + +The migration replaces virtual-GRF box balancing with kinematic-assisted rigid capsules built on `Ymir.Box3D` ABI 22: + +- **Solver-enforced upright capsule:** Walkers spawn via `AddCapsule` with `LockAngularX | LockAngularZ | DisableContactRecycling`, letting the physics solver handle wall deflection and vertical support cleanly without pitch or roll tipping fights. +- **Unified `WalkerSurfaceProbe`:** Queries both `TerrainField` and `Box3D` static geometry so `TryStep(0.65 m)` clears curbs and rubble piles before `Box3DSoaWorld.Step`, and `Reground(0.75 m)` keeps walkers grounded over crest transitions in `PostStepWalker`. +- **Zero-Moment Point (ZMP) pelvis & lean kinematics:** `PostStepWalker` computes a damped `PelvisOffset` and dynamic acceleration-driven `SecondaryLean` (`±8°` per axis, `<= 14.5°` combined tilt) in `WalkerVisualSnapshot`, replicated in `SnapshotCodec` (`+5 B` per walker). `VehicleRigAnimator` applies `PelvisOffset` and `(LeanPitch, LeanRoll)` onto `ModelRoot.Transform` while transforming world-space `FootNormal` into the leaned body's local coordinate frame via the inverse body rotation so foot plates stay parallel to terrain slopes. diff --git a/content/Architecture/watertight-cga-sion-and-foliage.md b/content/Architecture/watertight-cga-sion-and-foliage.md new file mode 100644 index 0000000..491cc81 --- /dev/null +++ b/content/Architecture/watertight-cga-sion-and-foliage.md @@ -0,0 +1,38 @@ +--- +title: Watertight CGA Destructible Sion City & Real Species Foliage (Planned / In Build) +description: Upcoming pipeline turning swissBUILDINGS3D 3.0 footprints into <= 64-zone closed 2-manifold RCGA v1 destructible buildings and swisstopo Valais tree species driven by rtd_flow_field wind. +--- + +> [!NOTE] Planned / In Build +> In the current build, Sion buildings render via `SionMapRenderer` from `36` static `512 m` tiles (`6 × 6` grid, `2,319` buildings) using `lod1/lod2_*.glb` meshes and legacy static triangle collision chunks (`RCOL v1`), and no runtime tree field is active yet. The `RCGA v1` destructible city and `cosmo_tree_gen` foliage pipelines described below are the active next stages. + +Two visual and structural gaps remain in the Sion arena: its `2,319` `swissBUILDINGS3D 3.0` structures are indestructible open shells on a legacy `6 × 6` tile grid, and the alpine hillsides lack the orchards, pines, and vineyards that cover the real Rhône valley floor. + +## Watertight `RCGA v1` Destructible Sion Buildings + +Raw `swissBUILDINGS3D 3.0` exports carry open bottom faces, intersecting gable caps, and coplanar party walls that fail closed-volume fracture and produce thin collision slivers. The offline `cga_builder.py` baker uses a Computer Generated Architecture (CGA) shape grammar to extrude and partition those footprints into closed 2-manifold building packs (`RCGA v1`) aligned to the same `16 × 16` (`192 m`) lattice used by terrain and physics: + +```mermaid +flowchart LR + SB["swissBUILDINGS3D 3.0 Footprints"] --> CGA["cga_builder.py (Watertight RCGA v1, <= 64 zones/building)"] + CGA --> CAT["SionCityCatalog (16x16 192 m Lattice)"] + CAT --> REND["WorldCityRenderer + sion_building.gdshader"] + CAT --> DEST["SionCityDestructionState (uint64 CollapsedMask + SupportMask DAG)"] + DEST -->|"BuildingFractureEvent"| SCAR["ArenaScarLedger + TerrainBrushKind.Rubble"] + DEST --> PHYS["Box3DPhysicsTileSync (Building Tiles 11_000+)"] +``` + +Each building subdivides into `<= 64` structural zones—floors, bays, and roof sections—tracked via a 64-bit `CollapsedMask` and `DamagedMask`. Every zone $z$ stores a static 64-bit `SupportMask[z]` listing its load-bearing neighbors below; when incoming fire collapses a support zone, any dependent zone satisfying $(\text{SupportMask}[z]\ \&\ \sim\text{CollapsedMask}) = 0$ cascades into collapse, emitting `BuildingFractureEvent`, spawning `DebrisSystem` masonry, and stamping `TerrainBrushKind.Rubble` onto `TerrainField`. Retiring `SionMapRenderer` and `RCOL v1` aligns building physics tiles (`stableId 11_000+`) and fracture event replication inside the `576 m` radius geometry bubble. + +## Real-Species Valais Foliage (`cosmo_tree_gen` + `rtd_flow_field`) + +The central Valais valley around Sion sits in a dry inner-alpine rain shadow. Placing generic temperate broadleaf mixes puts wild beech (*Fagus sylvatica*) onto slopes where it does not grow naturally, so the planned `bake_sion_trees.py` pipeline invokes `cosmo_tree_gen` (an MIT-licensed procedural tree generator) against swisstopo vegetation masks to populate `trees_sion.bin` with species native to the Sion basin: + +- **Valley floor & warm south slopes:** Pubescent oak, Scots pine, silver birch, sweet chestnut, and cultivated orchard rows along vineyard terraces. +- **Higher alpine flanks:** European larch and Norway spruce climbing the upper valley walls. + +On the valley floor and lower slopes, wild beech is excluded altogether. + +## Flow-Field Wind & Destructible Trunks + +At runtime, `FoliageRenderer` binds `tree_leaves.gdshader` and `tree_bark.gdshader` to the global `rtd_flow_field` `Texture3Drd` already stepped every frame by `flow_field_step.glsl`. Nearby shell detonations and expanding `ShockShell` blast waves push canopies outward in real time using the same 3D velocity volume that advects smoke plumes and sparks. Felled trunks update `SionTreeDestructionState`, emit `TreeStateEvent`, add or remove trunk physics tiles (`Box3DPhysicsTileSync` `stableId 12_000+`), and persist across matches inside `ArenaScarLedger`. diff --git a/content/index.md b/content/index.md index dae62b2..6faa9eb 100644 --- a/content/index.md +++ b/content/index.md @@ -1,6 +1,6 @@ --- title: Rust to Dust -description: Vehicular combat in a destructible Sion valley. +description: Salvage-grid vehicular and mech combat in a 3 km Swiss Alpine valley, with engineering teardowns and live Sion lobby telemetry. ---
@@ -9,7 +9,7 @@ description: Vehicular combat in a destructible Sion valley.

RUST TO DUST

-

Vehicular combat in a destructible Sion valley. Field dossiers and briefing incoming.

+

Salvage-grid vehicular and mech combat across a 3 km Swiss Alpine valley around Sion. Twelve contenders drop in by orbital pod inside a shrinking ring, fighting rival pilots and gilded Imperial spectators while bolting salvaged weapons onto live thermal chassis mid-match.

@@ -40,13 +40,31 @@ description: Vehicular combat in a destructible Sion valley. +![Jackal buggy engaging gilded Imperial walkers on the Sion valley floor under a single-draw-call Vulkan HUD](media/hud-hbgpu-sion.webp) + +## What the Game Is + +*Rust to Dust* drops 12 contenders—solo or in squads—into a live arena ring. The last contender or squad left standing after final-ring orbital redeployments close wins the match. On the ground, you pilot one of 15 chassis spanning wheeled buggies, tracked tanks, VTOL craft, four-legged walkers, and tall bipedal mechs. Around the perimeter orbit three tiers of Imperial spectators—heavy gilded Tourist walkers, agile Patron hunters, and stealthy Exemplar escorts—who stay neutral until provoked. Opening fire near them triggers a lethal hunt under live Imperial Broadcast commentary, while bringing one down drops high-tier Imperial weapons and multi-stage ordnance onto the field. + +Every vehicle and mech is simulated as a physical 2D thermal grid: + +- **Conductive heat and operating bands:** Firing weapons or pushing a supercharged engine heats the cells under that hardpoint; heat then spreads into neighboring cells and cools through exposed hull edges and active radiators. Each weapon, engine, and radiator peaks across a warm operating plateau: cold idle engines and heavy guns run slightly below peak output until combat warms them up, and sustained fire past the upper threshold drops efficiency to zero, stalling weapons or cutting thrust. +- **Localized armor and module stripping:** Incoming shots hit specific grid cells mapped from the impact point on the hull. Once a cell's armor strips to zero, overflow damage hits the core hull and any hardpoint whose supporting cells are all destroyed goes offline; on bipedal and quadruped walkers, leg armor loss slows movement and turning. +- **Field salvage and multi-stage weapons:** Destroyed hulls and orbital supply drops scatter 9 human salvage modules, 6 Imperial Tourist parts, and procedurally rolled multi-stage weapons—from airburst flak and prism lances to MIRV sub-munition carriers and loitering laser drones. Pull alongside a crate or wreck to bolt salvaged gear straight into an open hardpoint or swap into an intact chassis mid-match. + +That combat plays out over a `3,072 m × 3,072 m` Swiss Alpine valley centered on Sion alongside a `1,536 m × 1,536 m` desert testbed. Artillery craters, blast scorches, and tire tracks stamp straight into the shared `192 m` terrain grid, altering physics collision and surviving from match to match in a persistent scar cache. + +![Sunlight and deep valley shadows across Sion Old Town and the Valère citadel during a skirmish](media/lighting-sdfgi-sion.webp) + +![Artillery smoke plumes drifting across the Sion arena behind a Jackal buggy and hostile walkers](media/plume-sion.webp) + ## Sections
01 // ARCHITECTURE Subsystem Teardowns - Vulkan HUD, destructible Sion terrain, procedural city geometry, and vehicle kinematics. + Six engineering teardowns: single-draw-call Vulkan HUD, 0.5 m swisstopo terrain and tiled physics, lighting and volumetric plumes, thermal-grid netcode, upright mech walkers, and destructible Sion buildings. ACCESS CHANNEL -> diff --git a/content/media/hud-hbgpu-sion.webp b/content/media/hud-hbgpu-sion.webp new file mode 100644 index 0000000..389d2df Binary files /dev/null and b/content/media/hud-hbgpu-sion.webp differ diff --git a/content/media/lighting-sdfgi-desert.webp b/content/media/lighting-sdfgi-desert.webp new file mode 100644 index 0000000..e1f1d9f Binary files /dev/null and b/content/media/lighting-sdfgi-desert.webp differ diff --git a/content/media/lighting-sdfgi-sion.webp b/content/media/lighting-sdfgi-sion.webp new file mode 100644 index 0000000..d852140 Binary files /dev/null and b/content/media/lighting-sdfgi-sion.webp differ diff --git a/content/media/plume-closeup.webp b/content/media/plume-closeup.webp new file mode 100644 index 0000000..d9a42e7 Binary files /dev/null and b/content/media/plume-closeup.webp differ diff --git a/content/media/plume-sion.webp b/content/media/plume-sion.webp new file mode 100644 index 0000000..fdd9202 Binary files /dev/null and b/content/media/plume-sion.webp differ diff --git a/content/media/settings-graphics.webp b/content/media/settings-graphics.webp new file mode 100644 index 0000000..77339fe Binary files /dev/null and b/content/media/settings-graphics.webp differ diff --git a/content/media/sion-05m-dem.webp b/content/media/sion-05m-dem.webp new file mode 100644 index 0000000..210c47c Binary files /dev/null and b/content/media/sion-05m-dem.webp differ