From bea1074bcfe77f5463a96fa645e1ee7066252c4a Mon Sep 17 00:00:00 2001 From: brasga Date: Wed, 18 Nov 2026 08:33:14 -0300 Subject: [PATCH 1/2] feat(render): add 3D mesh staging uploads and camera-relative occlusion --- AGENTS.md | 6 +- Cargo.lock | 33 + Cargo.toml | 1 + crates/spawn-render/AGENTS.md | 35 +- crates/spawn-render/Cargo.toml | 8 +- crates/spawn-render/src/handle.rs | 16 + crates/spawn-render/src/lib.rs | 22 +- crates/spawn-render/src/mesh.rs | 629 ++++++++ crates/spawn-render/src/renderer.rs | 62 +- crates/spawn-render/src/types.rs | 16 + crates/spawn-render/src/vulkan/frame.rs | 240 ++- crates/spawn-render/src/vulkan/memory.rs | 71 + crates/spawn-render/src/vulkan/mesh.rs | 202 +++ crates/spawn-render/src/vulkan/mod.rs | 349 ++++- crates/spawn-render/src/vulkan/pipeline.rs | 11 +- .../tests/f3d_t12_mesh_occlusion_gpu.rs | 1292 +++++++++++++++++ .../tests/f3d_t13_render_hygiene.rs | 58 +- docs/DEPENDENCIES.md | 2 +- docs/first-3d/PLAN.md | 4 +- docs/first-3d/VERIFICATION.md | 11 +- tests/foundation_verification.rs | 27 +- tools/spawn-cli/tests/shader_cook.rs | 5 +- 22 files changed, 2952 insertions(+), 148 deletions(-) create mode 100644 crates/spawn-render/src/mesh.rs create mode 100644 crates/spawn-render/src/vulkan/mesh.rs create mode 100644 crates/spawn-render/tests/f3d_t12_mesh_occlusion_gpu.rs diff --git a/AGENTS.md b/AGENTS.md index 6e44498..b66faab 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -63,7 +63,7 @@ Integration layer: `mlua` with the `luau` feature (`PLANNED`; not a dependency). ## Workspace -Root `Cargo.toml` (verified): `resolver = "3"`, members `.`, `crates/*`, `tools/*` (excluding the standalone Gate G2 fuzz workspace `crates/spawn-render/fuzz`); `[workspace.package]` provides `version`, `edition` (2024), `license` (MIT) and `rust-version` (1.99.1), inherited by every member; `[workspace.lints]` (ADR-0007) is inherited by every member through `[lints] workspace = true`; dev profile uses `opt-level = 1` (dependencies `opt-level = 3`). `[workspace.dependencies]` pins `libm` (pure-Rust deterministic transcendentals in `spawn-math`, `default-features = false`), `ash` (used by `spawn-render` behind its optional `vulkan` feature), `raw-window-handle` (both crates' optional backend features), `rustix`, `wayland-client`, `wayland-protocols` (`spawn-platform`'s optional `wayland` feature), `clap` and `rspirv` (used by the offline tool `spawn-cli`), and test/oracle crates `arbitrary`, `glam`, `insta`, and `proptest`; with default features **every engine library crate except `spawn-math` (which links only pure-Rust `libm`) has zero third-party normal dependencies**. The inter-crate edges are `spawn-input` depending on `spawn-core` and `spawn-platform` (both with `default-features = false`, so no native windowing backend is linked; ADR-0002, FND-T09), `spawn-cli` depending on `spawn-render` (`default-features = false`, sharing the headless cooked-shader binary contract without linking Vulkan; ADR-0014), and the root composition package `spawn-engine` depending on `spawn-core`, `spawn-input`, `spawn-platform` and `spawn-render` (`default-features = false` globally, plus `spawn-platform/wayland` and `spawn-render/vulkan` on `cfg(target_os = "linux")`); no library crate in `crates/` depends on `spawn-engine` or `tools/`, and all other inter-crate edges in nested documents are `PLANNED`. +Root `Cargo.toml` (verified): `resolver = "3"`, members `.`, `crates/*`, `tools/*` (excluding the standalone Gate G2 fuzz workspace `crates/spawn-render/fuzz`); `[workspace.package]` provides `version`, `edition` (2024), `license` (MIT) and `rust-version` (1.99.1), inherited by every member; `[workspace.lints]` (ADR-0007) is inherited by every member through `[lints] workspace = true`; dev profile uses `opt-level = 1` (dependencies `opt-level = 3`). `[workspace.dependencies]` pins `libm` (pure-Rust deterministic transcendentals in `spawn-math`, `default-features = false`), `ash` and `bytemuck` (used by `spawn-render` behind its optional `vulkan` feature), `raw-window-handle` (both crates' optional backend features), `rustix`, `wayland-client`, `wayland-protocols` (`spawn-platform`'s optional `wayland` feature), `clap` and `rspirv` (used by the offline tool `spawn-cli`), and test/oracle crates `arbitrary`, `glam`, `insta`, and `proptest`; with default features **every engine library crate has zero window/GPU or C/FFI normal dependencies (only `spawn-math`, directly and via `spawn-render`, links pure-Rust `libm`)**. The inter-crate edges are `spawn-render` depending on `spawn-math` (`default-features = false`; ADR-0004, ADR-0010), `spawn-input` depending on `spawn-core` and `spawn-platform` (both with `default-features = false`, so no native windowing backend is linked; ADR-0002, FND-T09), `spawn-cli` depending on `spawn-render` (`default-features = false`, sharing the headless cooked-shader binary contract without linking Vulkan; ADR-0014), and the root composition package `spawn-engine` depending on `spawn-core`, `spawn-input`, `spawn-platform` and `spawn-render` (`default-features = false` globally, plus `spawn-platform/wayland` and `spawn-render/vulkan` on `cfg(target_os = "linux")`); no library crate in `crates/` depends on `spawn-engine` or `tools/`, and all other inter-crate edges in nested documents are `PLANNED`. Conventions: - One crate per subsystem with a narrow public API; names `spawn-`. @@ -89,7 +89,7 @@ Intended layering (`PLANNED`, non-binding until code exists): foundations (math, | [spawn-reflect](crates/spawn-reflect/AGENTS.md) | Runtime type metadata for serialization, editor, script exposure | SCAFFOLD | | [spawn-platform](crates/spawn-platform/AGENTS.md) | OS integration: windows, system events, surfaces | EXISTS (raw events, relative motion, cursor constraints; Wayland backend); X11, Win32 PLANNED | | [spawn-input](crates/spawn-input/AGENTS.md) | Input devices, state, actions, mappings | EXISTS (keyboard/mouse state, semantic mappings, tick sampling); gamepads, touch, persistence PLANNED | -| [spawn-render](crates/spawn-render/AGENTS.md) | GPU abstraction, resources, shaders, materials, frame execution | EXISTS (Vulkan clear & `dynamicRendering` triangle, in-house GPU block allocator, `D32_SFLOAT` reversed-Z depth, cooked-shader validator, offscreen readback); rest PLANNED | +| [spawn-render](crates/spawn-render/AGENTS.md) | GPU abstraction, resources, shaders, materials, frame execution | EXISTS (Vulkan clear, `dynamicRendering` triangle & 3D indexed meshes, GPU block allocator + staging, `D32_SFLOAT` reversed-Z depth, camera-relative draws, cooked-shader validator, offscreen readback); rest PLANNED | | [spawn-physics](crates/spawn-physics/AGENTS.md) | Rigid-body simulation, collision, spatial queries | SCAFFOLD | | [spawn-animation](crates/spawn-animation/AGENTS.md) | Skeletal/property animation runtime, blending, state machines | SCAFFOLD | | [spawn-audio](crates/spawn-audio/AGENTS.md) | Audio playback, mixing, spatialization | SCAFFOLD | @@ -102,7 +102,7 @@ Intended layering (`PLANNED`, non-binding until code exists): foundations (math, | [spawn-editor](tools/spawn-editor/AGENTS.md) | Graphical authoring tools | SCAFFOLD | | [spawn-mcp](tools/spawn-mcp/AGENTS.md) | MCP server for external AI agents/tools | SCAFFOLD | -Verified state: `spawn-core` contains the fixed-step clock (`FixedStepClock`, `FixedStepConfig`, `FixedStepUpdate`, `Tick`, `ClockError`) with unit, verification (FND-T01, FND-T02) and doc tests; `spawn-math` contains `#![forbid(unsafe_code)]` local `f32` primitives (`Vec2/3/4`, column-major `Mat3/4`, `Quat`, `Transform`, `Aabb`, `Ray`, `Plane`, `Sphere`), distinct `f64` world coordinates (`WorldPos`, `DVec3`, `camera_relative_f32`), reversed-Z Vulkan projections with single-site NDC Y-flip, pure-Rust `libm` deterministic subset `det`, and `MathError` (`MATH-0001`..`MATH-0005`) with headless unit, `proptest`, `glam` oracle, golden-bit, snapshot, and hygiene tests (F3D-T01..T04, Phase 1 F3D-T13); `spawn-platform` contains the raw event types (including `PointerRelativeMotion` and `CursorGrabChanged`), `CursorGrabMode`, `WindowDescriptor` and `PlatformError` (always compiled) and, behind the `wayland` feature, the Wayland backend (`Platform`, `Window`, `PumpMode`, `zwp_relative_pointer_v1`, `zwp_pointer_constraints_v1`) with headless translation tests (FND-T05, FND-T10 platform part, Phase 2b relative motion and cursor constraint lifecycle) and a manual smoke example; `spawn-input` contains allocation-free keyboard/mouse `DeviceState`, data-driven `InputMap` (`ActionId`, `AxisId`, `ContextId`, `AxisConfig`), tick-indexed `InputCommand` sampling and untrusted-command validation (`InputState`, `InputError`, `#![forbid(unsafe_code)]`) with headless unit, verification (FND-T03, FND-T04, Phase 2b relative-motion wiring, replay determinism) and doc tests; `spawn-render` contains `#![forbid(unsafe_code)]` public types, generational handles (`ShaderHandle`, `PipelineHandle`, `OffscreenTargetHandle`), `RenderError` (`REND-0001..0014`), the versioned cooked-shader binary codec and untrusted SPIR-V/reflection layout validator (`CookedShader`, `PipelineLayoutDesc`, `#![deny(clippy::indexing_slicing)]`, F3D-T07 + Gate G2 fuzz target), the pure GPU block suballocator and timeline-retirement tracker (`PureGpuAllocator`, `GpuMemoryBudget`, `GpuAllocatorStats`, F3D-T08), the pure presentation, `D32_SFLOAT` reversed-Z depth-lifecycle, and device-selection controllers (always compiled, FND-T06/T07, F3D-T09) and, behind the `vulkan` feature, `Renderer` over a private Vulkan 1.3 RHI (`dynamicRendering` triangle pipelines, `D32_SFLOAT` depth, offscreen `R8G8B8A8_UNORM` readback, Wayland + headless surfaces) verified clean under `VK_LAYER_KHRONOS_validation` + synchronization validation with opt-in GPU tests (F3D-T11), Phase 3 hygiene checks (F3D-T13), and the `vulkan_clear` / `vulkan_triangle` smoke examples; `spawn-cli` (`[[bin]] name = "spawn"`, `#![forbid(unsafe_code)]`) implements `spawn shaders build` over pinned `slangc` `2026.22` (`SLANGC_VERSION`, `SlangCompiler` seam, `rspirv` reflection extraction, `CLI-0001..0006`, F3D-T06 + F3D-T13 shader-toolchain checks) with authored `shaders/{triangle,mesh_3d}.slang`; the root `spawn-engine` package (`src/`, `tests/foundation_verification.rs`) composes all four foundation subsystems (`EngineError`, `RuntimeOptions`, `run_session`, `run_native`, `#![forbid(unsafe_code)]`) with headless verification tests (FND-T08, FND-T09, FND-T10, FND-INV-06) and recorded Wayland/Vulkan smoke runs; every other `lib.rs` contains only a crate-level doc comment (no items, no tests). +Verified state: `spawn-core` contains the fixed-step clock (`FixedStepClock`, `FixedStepConfig`, `FixedStepUpdate`, `Tick`, `ClockError`) with unit, verification (FND-T01, FND-T02) and doc tests; `spawn-math` contains `#![forbid(unsafe_code)]` local `f32` primitives (`Vec2/3/4`, column-major `Mat3/4`, `Quat`, `Transform`, `Aabb`, `Ray`, `Plane`, `Sphere`), distinct `f64` world coordinates (`WorldPos`, `DVec3`, `camera_relative_f32`), reversed-Z Vulkan projections with single-site NDC Y-flip, pure-Rust `libm` deterministic subset `det`, and `MathError` (`MATH-0001`..`MATH-0005`) with headless unit, `proptest`, `glam` oracle, golden-bit, snapshot, and hygiene tests (F3D-T01..T04, Phase 1 F3D-T13); `spawn-platform` contains the raw event types (including `PointerRelativeMotion` and `CursorGrabChanged`), `CursorGrabMode`, `WindowDescriptor` and `PlatformError` (always compiled) and, behind the `wayland` feature, the Wayland backend (`Platform`, `Window`, `PumpMode`, `zwp_relative_pointer_v1`, `zwp_pointer_constraints_v1`) with headless translation tests (FND-T05, FND-T10 platform part, Phase 2b relative motion and cursor constraint lifecycle) and a manual smoke example; `spawn-input` contains allocation-free keyboard/mouse `DeviceState`, data-driven `InputMap` (`ActionId`, `AxisId`, `ContextId`, `AxisConfig`), tick-indexed `InputCommand` sampling and untrusted-command validation (`InputState`, `InputError`, `#![forbid(unsafe_code)]`) with headless unit, verification (FND-T03, FND-T04, Phase 2b relative-motion wiring, replay determinism) and doc tests; `spawn-render` contains `#![forbid(unsafe_code)]` public types, generational handles (`ShaderHandle`, `PipelineHandle`, `OffscreenTargetHandle`, `MeshHandle`), `RenderError` (`REND-0001..0014`), the versioned cooked-shader binary codec and untrusted SPIR-V/reflection layout validator (`CookedShader`, `PipelineLayoutDesc`, `#![deny(clippy::indexing_slicing)]`, F3D-T07 + Gate G2 fuzz target), 3D mesh descriptors and camera-relative `128`-byte push-constant packing (`MeshVertex`, `MeshDescriptor`, `CameraRelativeView`, `MeshDraw`, `PackedMeshPushConstants`), the pure GPU block suballocator and timeline-retirement tracker (`PureGpuAllocator`, `GpuMemoryBudget`, `GpuAllocatorStats`, F3D-T08), the pure presentation, `D32_SFLOAT` reversed-Z depth-lifecycle, and device-selection controllers (always compiled, FND-T06/T07, F3D-T09) and, behind the `vulkan` feature, `Renderer` over a private Vulkan 1.3 RHI (`dynamicRendering` triangle & 3D indexed mesh pipelines, `vkCmdCopyBuffer2` staging uploads, `D32_SFLOAT` depth, offscreen `R8G8B8A8_UNORM` readback, Wayland + headless surfaces) verified clean under `VK_LAYER_KHRONOS_validation` + synchronization validation with opt-in GPU tests (F3D-T11, F3D-T12), Phase 3/4 hygiene checks (F3D-T13), and the `vulkan_clear` / `vulkan_triangle` smoke examples; `spawn-cli` (`[[bin]] name = "spawn"`, `#![forbid(unsafe_code)]`) implements `spawn shaders build` over pinned `slangc` `2026.22` (`SLANGC_VERSION`, `SlangCompiler` seam, `rspirv` reflection extraction, `CLI-0001..0006`, F3D-T06 + F3D-T13 shader-toolchain checks) with authored `shaders/{triangle,mesh_3d}.slang`; the root `spawn-engine` package (`src/`, `tests/foundation_verification.rs`) composes all four foundation subsystems (`EngineError`, `RuntimeOptions`, `run_session`, `run_native`, `#![forbid(unsafe_code)]`) with headless verification tests (FND-T08, FND-T09, FND-T10, FND-INV-06) and recorded Wayland/Vulkan smoke runs; every other `lib.rs` contains only a crate-level doc comment (no items, no tests). Ownership rule: each piece of state has exactly one owning system; others use its API. If a responsibility seems to fit two crates, stop and report rather than duplicate it. diff --git a/Cargo.lock b/Cargo.lock index 4349961..65fd727 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -35,6 +35,26 @@ version = "2.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" +[[package]] +name = "bytemuck" +version = "1.25.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797" +dependencies = [ + "bytemuck_derive", +] + +[[package]] +name = "bytemuck_derive" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a1f896587b6f2c069c73d2f0913e2d590c3990285cd2f0b6aa02b786b4c679c" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + [[package]] name = "cc" version = "1.11.2" @@ -472,9 +492,11 @@ version = "0.1.0" dependencies = [ "arbitrary", "ash", + "bytemuck", "insta", "proptest", "raw-window-handle", + "spawn-math", ] [[package]] @@ -508,6 +530,17 @@ version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + [[package]] name = "tempfile" version = "3.27.0" diff --git a/Cargo.toml b/Cargo.toml index 16d8edd..e2e21ab 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,6 +13,7 @@ rust-version = "1.99.1" [workspace.dependencies] arbitrary = { version = "1.5.0", default-features = false } ash = { version = "0.38.0", default-features = false } +bytemuck = { version = "1.25.2", default-features = false } clap = { version = "4.6.8", default-features = false } glam = { version = "0.34.3", default-features = false } insta = { version = "1.49.0", default-features = false } diff --git a/crates/spawn-render/AGENTS.md b/crates/spawn-render/AGENTS.md index fdf714c..0ebe489 100644 --- a/crates/spawn-render/AGENTS.md +++ b/crates/spawn-render/AGENTS.md @@ -8,7 +8,7 @@ Rendering infrastructure: GPU abstraction, resources, shaders, materials, pipeli ## Responsibilities -- GPU device/queue/surface management, in-house block memory suballocation, and timeline-gated resource lifetime (in-house graphics API over Vulkan as a private module, accepted in [ADR-0004](../../docs/adr/0004-in-house-graphics-api.md); `wgpu` is a design reference, not a dependency). Clear-frame presentation, GPU block suballocation, swapchain-matched `D32_SFLOAT` reversed-Z depth attachments, `dynamicRendering` graphics pipelines, unindexed triangle draws, and offscreen RGBA8 readback `EXISTS` behind the `vulkan` feature; static 3D mesh/index uploads, camera-relative draws, render graphs, and materials are `PLANNED`. +- GPU device/queue/surface management, in-house block memory suballocation, and timeline-gated resource lifetime (in-house graphics API over Vulkan as a private module, accepted in [ADR-0004](../../docs/adr/0004-in-house-graphics-api.md); `wgpu` is a design reference, not a dependency). Clear-frame presentation, GPU block suballocation, swapchain-matched `D32_SFLOAT` reversed-Z depth attachments, `dynamicRendering` graphics pipelines, unindexed triangle draws, static 3D vertex/index staging uploads, camera-relative indexed mesh draws, and offscreen RGBA8 readback `EXISTS` behind the `vulkan` feature; render graphs, bindless descriptor tables, and materials are `PLANNED`. - Shaders, materials, pipelines, render graph/passes, camera/view abstraction, mesh/texture GPU resources. - Extraction of renderable state from simulation into presentation state (simulation never touches GPU). - Debug draw primitives if a feature requires them. @@ -21,15 +21,15 @@ Rendering infrastructure: GPU abstraction, resources, shaders, materials, pipeli ## Architectural Boundaries -- May depend on `spawn-math`, `spawn-assets`, and a window handle (per [ADR-0004](../../docs/adr/0004-in-house-graphics-api.md), accepted: through `raw-window-handle` traits, without depending on `spawn-platform`); must not depend on `spawn-physics`, `spawn-network`, `spawn-scripting`, or tools. (`spawn-math` edge is `PLANNED` for Milestone 2 Phase 4; currently zero `spawn-*` dependencies.) +- Depends on `spawn-math` (`default-features = false`, `EXISTS`); may depend on `spawn-assets` (`PLANNED`) and a window handle (per [ADR-0004](../../docs/adr/0004-in-house-graphics-api.md), accepted: through `raw-window-handle` traits, without depending on `spawn-platform`); must not depend on `spawn-physics`, `spawn-network`, `spawn-scripting`, or tools. - `spawn-ui` and `spawn-editor` integrate through render-facing contracts, not by reaching into GPU internals. - Server/headless builds must not require this crate. ## Public API Guidelines -- Hide the graphics backend; no Vulkan, `ash` or RHI-internal types in public APIs. -- The only third-party types accepted at the public boundary are the `raw-window-handle` traits/handles needed to create a surface from a window (SPN-INV-011); keep that surface minimal. -- Resources are referenced by generational handles (`ShaderHandle`, `PipelineHandle`, `OffscreenTargetHandle`); frame data is plain data. +- Hide the graphics backend and POD byte-casting internals; no Vulkan, `ash`, `bytemuck`, or RHI-internal types in public APIs (`SPN-INV-011`). +- The only third-party types accepted at the public boundary are the `raw-window-handle` traits/handles needed to create a surface from a window (`SPN-INV-011`); keep that surface minimal. +- Resources are referenced by generational handles (`ShaderHandle`, `PipelineHandle`, `OffscreenTargetHandle`, `MeshHandle`); frame data is plain data (`MeshVertex`, `MeshDescriptor`, `CameraRelativeView`, `MeshDraw`). ## Internal Design Principles @@ -52,25 +52,26 @@ Rendering infrastructure: GPU abstraction, resources, shaders, materials, pipeli ## Current Implementation Status -`EXISTS` (foundation Phase 3: clear frame through Vulkan, Wayland + headless surfaces; Milestone 2 Phase 2: versioned cooked-shader binary contract and untrusted SPIR-V/reflection layout validator; Milestone 2 Phase 3: in-house GPU block suballocator + timeline retirement, swapchain-matched `D32_SFLOAT` reversed-Z depth attachment, generational handles, Vulkan 1.3 `dynamicRendering` graphics pipelines, colored triangle draws, and offscreen RGBA8 readback); 3D mesh/index staging, camera-relative draws, render graph, and materials are `PLANNED`. +`EXISTS` (foundation Phase 3: clear frame through Vulkan, Wayland + headless surfaces; Milestone 2 Phase 2: versioned cooked-shader binary contract and untrusted SPIR-V/reflection layout validator; Milestone 2 Phase 3: in-house GPU block suballocator + timeline retirement, swapchain-matched `D32_SFLOAT` reversed-Z depth attachment, generational handles, Vulkan 1.3 `dynamicRendering` graphics pipelines, colored triangle draws, and offscreen RGBA8 readback; Milestone 2 Phase 4: `spawn-math` integration, static 3D vertex/index staging uploads via `vkCmdCopyBuffer2` + `synchronization2`, `128`-byte camera-relative `MeshDraw` push constants, and reversed-Z `GREATER_OR_EQUAL` indexed mesh occlusion); render graph, bindless descriptor tables, and materials are `PLANNED`. -**Cargo features:** `default = []` (zero normal dependencies; `#![forbid(unsafe_code)]`; presentation policy, depth lifecycle policy, device selection, GPU block suballocator bookkeeping, generational handle pool, cooked-shader binary codec/validator, and public types compile and test without a GPU; dev-dependencies `arbitrary`, `insta`, `proptest`). `vulkan` adds `ash` 0.38 (`loaded`, `std`: `libvulkan.so.1` is loaded at runtime, so building needs no system packages) and `raw-window-handle`. Never depends on `spawn-platform` (`cargo tree -p spawn-render --features vulkan -e normal`). +**Cargo features:** `default = []` (depends only on `spawn-math` with `default-features = false` → pure-Rust `libm`, zero window/GPU or C/FFI dependencies; `#![forbid(unsafe_code)]`; presentation policy, depth lifecycle policy, device selection, GPU block suballocator bookkeeping, generational handle pool, cooked-shader binary codec/validator, 3D mesh descriptor validation, camera-relative `128`-byte push-constant packing, and public types compile and test without a GPU; dev-dependencies `arbitrary`, `insta`, `proptest`). `vulkan` adds `ash` 0.38 (`loaded`, `std`: `libvulkan.so.1` is loaded at runtime, so building needs no system packages), `bytemuck` 1.25 (`derive`, confined strictly inside `src/vulkan/`), and `raw-window-handle`. Never depends on `spawn-platform` (`cargo tree -p spawn-render --features vulkan -e normal`). | Item | Module | Availability | Notes | | --- | --- | --- | --- | | `SurfaceSize`, `ClearColor`, `RendererDescriptor`, `PresentModePreference`, `Validation` | `types` | always | Physical pixels; linear clear color, sanitized (non-finite → 0, clamped) and encoded per swapchain format | | `FrameOutcome`, `PresentationState`, `RendererInfo`, `GpuKind`, `ValidationMessage`, `ValidationSeverity` | `types` | always | Explicit presentation outcomes and diagnostics | -| `PipelineTarget`, `FrontFace`, `CullMode`, `GraphicsPipelineDescriptor`, `OffscreenReadback` | `types` | always | Reversed-Z, CCW front-face, backface-culled `dynamicRendering` pipeline config and host RGBA8 readback | +| `PipelineTarget`, `FrontFace`, `CullMode`, `GraphicsPipelineDescriptor`, `OffscreenReadback` | `types` | always | Reversed-Z, CCW front-face, backface-culled `dynamicRendering` pipeline config (`new`, `new_mesh_3d`) and host RGBA8 readback | | `GpuMemoryBudget`, `GpuAllocatorStats`, `DEFAULT_*_BYTES` | `allocator` | always | Configurable `DEVICE_LOCAL` / `HOST_VISIBLE` budgets, block sizes, and live/retired/peak accounting | | `PureGpuAllocator` | `allocator` | always (crate-private) | `#![forbid(unsafe_code)]`, `#![deny(clippy::indexing_slicing)]`; fixed-size block suballocation, dedicated oversized fallback, `bufferImageGranularity` page separation, free-range coalescing, timeline retirement (`F3D-T08`) | | `REVERSED_Z_CLEAR_DEPTH`, `DepthAttachmentController` | `depth` | `REVERSED_Z_CLEAR_DEPTH` public; controller crate-private (always) | `#![forbid(unsafe_code)]`; swapchain-matched `D32_SFLOAT` lifecycle (`0.0` clear, never allocates `0x0`, idempotent extent sync; `F3D-T09`) | -| `ShaderHandle`, `PipelineHandle`, `OffscreenTargetHandle`, `GenerationalPool` | `handle` | handles public; pool crate-private (always) | `#![forbid(unsafe_code)]`, `#![deny(clippy::indexing_slicing)]`; stale/forged/foreign handles return `REND-0013` (`SPN-INV-035`) | +| `ShaderHandle`, `PipelineHandle`, `OffscreenTargetHandle`, `MeshHandle`, `GenerationalPool` | `handle` | handles public; pool crate-private (always) | `#![forbid(unsafe_code)]`, `#![deny(clippy::indexing_slicing)]`; stale/forged/foreign handles return `REND-0013` (`SPN-INV-035`) | +| `MeshVertex`, `MeshDescriptor`, `CameraRelativeView`, `MeshDraw`, `PackedMeshPushConstants`, `MESH_VERTEX_STRIDE`, `MESH_VERTEX_ATTRIBUTES`, `MESH_PUSH_CONSTANT_BYTES`, `MESH_PUSH_CONSTANT_RANGE`, `MAX_MESH_VERTICES`, `MAX_MESH_INDICES` | `mesh` | always | `#![forbid(unsafe_code)]`, `#![deny(clippy::indexing_slicing)]`; pre-upload descriptor validation (`REND-0014`), CPU `f64` `WorldPos` → `f32` camera-relative conversion (`SPN-INV-052`), and `128`-byte push-constant packing matching `shaders/mesh_3d.slang` | | `CookedShader`, `ShaderStage`, `ShaderStageFlags`, `VertexFormat`, `VertexInputAttribute`, `DescriptorKind`, `DescriptorBinding`, `PushConstantRange`, `ShaderLayoutExpectation`, `PipelineLayoutDesc`, `validate_graphics_pipeline_shaders` | `shader` | always | `#![forbid(unsafe_code)]`, `#![deny(clippy::indexing_slicing)]`; versioned `SPNSHDR\0` binary format (`from_bytes` / `decode`), pre-allocation bounds/alignment checks, SPIR-V header/`OpEntryPoint` check, and pipeline layout compatibility validator (ADR-0014, `SPN-INV-034`) | | `RenderError`, `RenderErrorKind` | `error` | always | Located, coded (`REND-0001..0014`), detail, flattened cause, optional backtrace (ADR-0009) | | Presentation controller | `presentation` | always (crate-private) | Pure state machine: suspend, recreate, surface recovery, bounded retries, fatal stop | | Device and swapchain choices | `selection` | always (crate-private) | Pure: ADR-0004 + `D32_SFLOAT` depth + push-constant/vertex-input limit check with per-GPU rejection reasons, ranking, format/present-mode/image-count/extent choices | -| `Renderer<'window>` | `renderer` | `vulkan` | Public API: `new`, `new_with_budget`, `new_headless`, `new_headless_with_budget`, `resize`, `load_shader`, `load_shader_named`, `destroy_shader`, `create_graphics_pipeline`, `destroy_pipeline`, `create_offscreen_target`, `destroy_offscreen_target`, `render_clear`, `render_triangle`, `render_offscreen_triangle`, `state`, `info`, `allocator_stats`, `wait_idle_and_reclaim`, `close`, `drain_validation_messages`, `validation_error_count`. Borrows the window for its lifetime; not `Send`/`Sync` | -| Vulkan RHI | `vulkan/` (`instance`, `surface`, `device`, `swapchain`, `memory`, `pipeline`, `frame`, `mod`) | `vulkan` | Only place with `ash` types and `unsafe`; every block has a `// SAFETY:` comment | +| `Renderer<'window>` | `renderer` | `vulkan` | Public API: `new`, `new_with_budget`, `new_headless`, `new_headless_with_budget`, `resize`, `load_shader`, `load_shader_named`, `destroy_shader`, `create_graphics_pipeline`, `destroy_pipeline`, `create_offscreen_target`, `destroy_offscreen_target`, `upload_mesh`, `destroy_mesh`, `render_clear`, `render_triangle`, `render_meshes`, `render_offscreen_triangle`, `render_offscreen_meshes`, `state`, `info`, `allocator_stats`, `wait_idle_and_reclaim`, `close`, `drain_validation_messages`, `validation_error_count`. Borrows the window for its lifetime; not `Send`/`Sync` | +| Vulkan RHI | `vulkan/` (`instance`, `surface`, `device`, `swapchain`, `memory`, `mesh`, `pipeline`, `frame`, `mod`) | `vulkan` | Only place with `ash` / `bytemuck` types and `unsafe`; every block has a `// SAFETY:` comment | **Error codes:** @@ -88,30 +89,30 @@ Rendering infrastructure: GPU abstraction, resources, shaders, materials, pipeli | `REND-0010` | `InvalidShaderArtifact` | Cooked shader payload is corrupt, truncated, unaligned, oversized, wrong version, or missing its SPIR-V `OpEntryPoint` | | `REND-0011` | `ShaderLayoutMismatch` | Cooked shader stage, vertex attributes, push constants, or descriptor bindings mismatch the pipeline layout | | `REND-0012` | `GpuMemoryExhausted` | GPU block suballocation, memory-type selection, or `vkAllocateMemory` failed or exceeded `GpuMemoryBudget` | -| `REND-0013` | `InvalidResourceHandle` | Generational resource handle (`ShaderHandle`, `PipelineHandle`, `OffscreenTargetHandle`) is stale, destroyed, or forged | -| `REND-0014` | `InvalidResourceDescriptor` | Invalid pipeline or render-target descriptor (e.g. `0x0` offscreen extent, stride/attribute mismatch, or target-format mismatch) | +| `REND-0013` | `InvalidResourceHandle` | Generational resource handle (`ShaderHandle`, `PipelineHandle`, `OffscreenTargetHandle`, `MeshHandle`) is stale, destroyed, or forged | +| `REND-0014` | `InvalidResourceDescriptor` | Invalid pipeline, mesh, draw, or render-target descriptor (e.g. `0x0` offscreen extent, empty/oversized/non-finite/out-of-bounds mesh slices, stride/attribute mismatch, or target-format mismatch) | **Vulkan initialization, memory, depth and pipeline execution:** - Instance: Vulkan 1.3; extensions `VK_KHR_surface` + `VK_KHR_wayland_surface` (or `VK_EXT_headless_surface` for `Renderer::new_headless`), plus `VK_EXT_debug_utils` and `VK_EXT_validation_features` (synchronization validation) when the validation layer is active. Loader/instance setup and teardown are serialized across threads (`LOADER_LOCK`, cold path only). - Device requirements (ADR-0004 + Milestone 2): API ≥ 1.3; `VK_KHR_swapchain`; `dynamicRendering`, `synchronization2`, `timelineSemaphore`, `descriptorIndexing`, `runtimeDescriptorArray`, `descriptorBindingPartiallyBound`, `descriptorBindingVariableDescriptorCount`, `shaderSampledImageArrayNonUniformIndexing`, `descriptorBindingSampledImageUpdateAfterBind`, `descriptorBindingStorageBufferUpdateAfterBind`; optimal-tiling `VK_FORMAT_D32_SFLOAT` with `DEPTH_STENCIL_ATTACHMENT`; `maxPushConstantsSize >= 128`, `maxVertexInputAttributes >= 3`, `maxVertexInputBindings >= 1`, `maxVertexInputBindingStride >= 40`; one queue family with graphics and presentation; at least one surface format and present mode. - GPU memory suballocator (`PureGpuAllocator` + `VulkanMemoryAllocator`): suballocates `16 MiB` `DEVICE_LOCAL` blocks and persistently mapped `4 MiB` `HOST_VISIBLE | HOST_COHERENT` blocks (configurable via `GpuMemoryBudget`) with dedicated-block fallback for oversized requests, exact `bufferImageGranularity` page isolation between linear (`VkBuffer`) and optimal (`VkImage`) suballocations, deterministic adjacent free-range coalescing, and timeline-semaphore-gated retirement of both Vulkan child handles and suballocations before `vkFreeMemory`. +- Static 3D mesh staging & camera-relative draws: `upload_mesh` validates `MeshDescriptor` (`REND-0014`), writes vertices and `u32` indices into a suballocated `HOST_VISIBLE | HOST_COHERENT` staging buffer, submits `vkCmdCopyBuffer2` into `DEVICE_LOCAL` `VERTEX_BUFFER` and `INDEX_BUFFER` allocations followed by `synchronization2` `VkBufferMemoryBarrier2` (`COPY/TRANSFER_WRITE → VERTEX_ATTRIBUTE_INPUT/VERTEX_ATTRIBUTE_READ` and `INDEX_INPUT/INDEX_READ`), and retires the staging buffer on the timeline semaphore without stalling. `render_meshes` and `render_offscreen_meshes` push `128`-byte camera-relative `MeshPushConstants` (`0..64` `mvp_camera_relative`, `64..112` `normal_col0..2` with `normal_col0.w = shade_weight`, `112..128` `base_color`) and issue `vkCmdDrawIndexed`. - Swapchain and `D32_SFLOAT` reversed-Z depth: swapchain requests `VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT` only (`SPN-INV-092`) paired with a `DEVICE_LOCAL` `VK_FORMAT_D32_SFLOAT` depth image/view matching the active swapchain `VkExtent2D` (never allocated at `0x0` when `Suspended`, retired/recreated idempotently across resize and surface recovery). Per-frame `synchronization2` barriers transition color (`UNDEFINED → COLOR_ATTACHMENT_OPTIMAL → PRESENT_SRC_KHR`) and depth (`UNDEFINED → DEPTH_ATTACHMENT_OPTIMAL` across `EARLY_FRAGMENT_TESTS | LATE_FRAGMENT_TESTS`, cleared to `0.0`). - Dynamic-rendering pipelines & offscreen readback: `CookedShader::from_bytes` and `validate_graphics_pipeline_shaders` run before `vkCreateShaderModule` (`SPN-INV-034`). Pipelines use `VkPipelineRenderingCreateInfo` (zero `VkRenderPass`/`VkFramebuffer`), `TRIANGLE_LIST`, `VK_FRONT_FACE_COUNTER_CLOCKWISE`, `VK_CULL_MODE_BACK_BIT`, reversed-Z `VK_COMPARE_OP_GREATER_OR_EQUAL`, and positive-height `[0.0, 1.0]` `VkViewport`. Offscreen readback renders into a dedicated `DEVICE_LOCAL` `VK_FORMAT_R8G8B8A8_UNORM` (`COLOR_ATTACHMENT | TRANSFER_SRC`) + `D32_SFLOAT` target and copies via `vkCmdCopyImageToBuffer2` (`COPY → HOST_READ` barrier) into a suballocated `HOST_VISIBLE | HOST_COHERENT` buffer. Memory blocks, buffers, depth/offscreen images, views, shader modules, pipeline layouts, and pipelines carry `VK_EXT_debug_utils` names when active. -**Ownership and shutdown order:** `Renderer` borrows the window, so the window (and its display connection) outlives every Vulkan object. `teardown` / `Drop`: `vkDeviceWaitIdle` → offscreen targets → pipelines → shader modules → swapchain depth → frames → swapchain → allocator (`VkDeviceMemory` blocks, verified zero leaks) → device → surface → validation messenger → instance. +**Ownership and shutdown order:** `Renderer` borrows the window, so the window (and its display connection) outlives every Vulkan object. `teardown` / `Drop`: `vkDeviceWaitIdle` → offscreen targets → uploaded meshes → pipelines → shader modules → swapchain depth → frames → swapchain → allocator (`VkDeviceMemory` blocks, verified zero leaks) → device → surface → validation messenger → instance. **Tests:** -- Headless, always run (CI): 45 unit/property tests (`errors`, `types`, `presentation` FND-T06/T07, `selection` + F3D-T09 rejections, `shader`, `handle`, `allocator` F3D-T08 + `proptest` + `insta`, `depth` F3D-T09 lifecycle) + 7 `shader_validation` tests (`F3D-T07`) + 1 `f3d_t13_render_hygiene` audit test without `vulkan`, plus standalone Gate G2 `cargo-fuzz` package `crates/spawn-render/fuzz`. With `vulkan`: +2 unit tests (`ValidationSink`, `VkFailure`). -- GPU, opt-in (`VK_INSTANCE_LAYERS=VK_LAYER_KHRONOS_validation VK_KHRONOS_VALIDATION_VALIDATE_SYNC=true cargo test -p spawn-render --features vulkan -- --ignored`): 4 Foundation headless-surface tests + `tests/f3d_t11_triangle_gpu.rs` (`F3D-T11`: offscreen CCW colored triangle `vkCmdCopyImageToBuffer2` RGBA8 readback, CW backface culling, reversed-Z `z = 0.0` vs clipped `z = -0.25`, negative shader/layout/stale-handle/OOM checks, `VK_EXT_headless_surface` swapchain + `D32_SFLOAT` depth draw/resize/`0x0` suspend, `0` validation/sync errors, leak-free close & drop). All 5 pass on the reference AMD Radeon RX 460 (`radv Mesa 26.2.5-arch1.1`). +- Headless, always run (CI): 48 unit/property tests (`errors`, `types`, `presentation` FND-T06/T07, `selection` + F3D-T09 rejections, `shader`, `handle`, `mesh` descriptor/50 km push-constant packing, `allocator` F3D-T08 + `proptest` + `insta`, `depth` F3D-T09 lifecycle) + 7 `shader_validation` tests (`F3D-T07`) + 1 `f3d_t13_render_hygiene` audit test without `vulkan`, plus standalone Gate G2 `cargo-fuzz` package `crates/spawn-render/fuzz`. With `vulkan`: +3 unit tests (`ValidationSink`, `VkFailure`, `bytemuck` POD byte equivalence). +- GPU, opt-in (`VK_INSTANCE_LAYERS=VK_LAYER_KHRONOS_validation VK_KHRONOS_VALIDATION_VALIDATE_SYNC=true cargo test -p spawn-render --features vulkan -- --ignored`): 4 Foundation headless-surface tests + `tests/f3d_t11_triangle_gpu.rs` (`F3D-T11`: offscreen CCW colored triangle `vkCmdCopyImageToBuffer2` RGBA8 readback, CW backface culling, reversed-Z `z = 0.0` vs clipped `z = -0.25`, negative shader/layout/stale-handle/OOM checks, `VK_EXT_headless_surface` swapchain + `D32_SFLOAT` depth draw/resize/`0x0` suspend) + `tests/f3d_t12_mesh_occlusion_gpu.rs` (`F3D-T12`: 2 tests covering synthesized SPIR-V 1.6 and live `slangc 2026.22`-cooked `shaders/mesh_3d.slang` for far-after-near `-2.0 m` vs `-5.0 m` reversed-Z occlusion across finite & infinite projections, `+Y` world-up orientation, backface culling + directional-shaded 3D cube, byte-exact `±50 km` `2 mm` camera-relative depth separation, swapchain multi-mesh resize/`0x0` suspend, and negative `REND-0012..0014` unwind checks). All 7 pass on the reference AMD Radeon RX 460 (`radv Mesa 26.2.5-arch1.1`) with `0` validation/sync errors. **Manual smoke tests:** `examples/vulkan_clear.rs` (Foundation Phase 3) and `examples/vulkan_triangle.rs` (Milestone 2 Phase 3) in the root package. Records: [Foundation VERIFICATION](../../docs/foundation/VERIFICATION.md#recorded-smoke-runs) and [First 3D VERIFICATION](../../docs/first-3d/VERIFICATION.md#recorded-smoke-runs). **Not implemented / deferred:** - X11, Win32 and other native window surfaces (`REND-0002`); Windows is not claimed. -- Static vertex/index buffer staging uploads and camera-relative 3D mesh draws (`PLANNED` for Milestone 2 Phase 4). - Separate graphics/present queue families, async compute, transfer queues, descriptor-set binding tables, render graph, HDR color spaces, device-loss recovery. ## Agent Instructions diff --git a/crates/spawn-render/Cargo.toml b/crates/spawn-render/Cargo.toml index ce5cf64..b91f7c0 100644 --- a/crates/spawn-render/Cargo.toml +++ b/crates/spawn-render/Cargo.toml @@ -9,16 +9,18 @@ rust-version.workspace = true workspace = true [features] -# No backend by default: presentation policy and selection logic compile and -# test without a GPU or Vulkan loader. +# No backend by default: presentation policy, depth/allocator logic, mesh packing, +# cooked-shader validation, and public types compile and test without a GPU. default = [] # Vulkan backend (ADR-0004). The Vulkan loader is loaded at runtime, so building # needs no system libraries and a missing loader is a startup error. -vulkan = ["dep:ash", "dep:raw-window-handle"] +vulkan = ["dep:ash", "dep:bytemuck", "dep:raw-window-handle"] [dependencies] ash = { workspace = true, optional = true, features = ["loaded", "std"] } +bytemuck = { workspace = true, optional = true, features = ["derive"] } raw-window-handle = { workspace = true, optional = true } +spawn-math = { version = "0.1.0", path = "../spawn-math", default-features = false } [dev-dependencies] arbitrary = { workspace = true } diff --git a/crates/spawn-render/src/handle.rs b/crates/spawn-render/src/handle.rs index fdf4a3a..b6ae565 100644 --- a/crates/spawn-render/src/handle.rs +++ b/crates/spawn-render/src/handle.rs @@ -97,6 +97,12 @@ define_render_handle!( "OffscreenTargetHandle" ); +define_render_handle!( + /// Generational handle referencing an uploaded indexed 3D mesh (`DEVICE_LOCAL` vertex + index buffers). + MeshHandle, + "MeshHandle" +); + pub(crate) trait HandleType: Copy { const KIND: &'static str; fn from_raw_pool(raw: RawHandle) -> Self; @@ -133,6 +139,16 @@ impl HandleType for OffscreenTargetHandle { } } +impl HandleType for MeshHandle { + const KIND: &'static str = Self::KIND_LABEL; + fn from_raw_pool(raw: RawHandle) -> Self { + Self::from_pool(raw) + } + fn into_raw_pool(self) -> RawHandle { + self.raw() + } +} + #[derive(Debug)] struct Slot { generation: u32, diff --git a/crates/spawn-render/src/lib.rs b/crates/spawn-render/src/lib.rs index 92f2f0b..f55a8d6 100644 --- a/crates/spawn-render/src/lib.rs +++ b/crates/spawn-render/src/lib.rs @@ -9,8 +9,13 @@ //! [`REVERSED_Z_CLEAR_DEPTH`]. //! - Generational resource handles and pipeline/offscreen descriptors (`SPN-INV-035`): //! [`ShaderHandle`], [`PipelineHandle`], [`OffscreenTargetHandle`], -//! [`PipelineTarget`], [`FrontFace`], [`CullMode`], +//! [`MeshHandle`], [`PipelineTarget`], [`FrontFace`], [`CullMode`], //! [`GraphicsPipelineDescriptor`], [`OffscreenReadback`]. +//! - Static 3D mesh descriptors and camera-relative draw contracts (`SPN-INV-052`, +//! `SPN-INV-053`): [`MeshVertex`], [`MeshDescriptor`], [`CameraRelativeView`], +//! [`MeshDraw`], [`PackedMeshPushConstants`], [`MESH_VERTEX_STRIDE`], +//! [`MESH_VERTEX_ATTRIBUTES`], [`MESH_PUSH_CONSTANT_BYTES`], +//! [`MESH_PUSH_CONSTANT_RANGE`]. //! - Cooked-shader binary contract and untrusted layout validator (ADR-0014): //! [`CookedShader`], [`ShaderStage`], [`ShaderStageFlags`], [`VertexFormat`], //! [`VertexInputAttribute`], [`DescriptorKind`], [`DescriptorBinding`], @@ -21,10 +26,11 @@ //! With the `vulkan` Cargo feature, the Vulkan 1.3 backend (ADR-0004) adds //! `Renderer`: it manages in-house GPU block suballocation, swapchain-matched //! `D32_SFLOAT` reversed-Z depth attachments, `dynamicRendering` graphics -//! pipelines, offscreen RGBA8 readback targets, and presentation to a window +//! pipelines, static 3D vertex/index staging uploads, camera-relative indexed +//! mesh draws, offscreen RGBA8 readback targets, and presentation to a window //! given through the `raw-window-handle` traits (or a headless surface). Vulkan -//! types never appear in the public API; the in-house RHI is the private -//! `vulkan` module. +//! and `bytemuck` types never appear in the public API; the in-house RHI is the +//! private `vulkan` module. //! //! Ownership, boundaries and rules are in this crate's `AGENTS.md`. @@ -34,6 +40,7 @@ mod allocator; mod depth; mod error; mod handle; +mod mesh; #[cfg(feature = "vulkan")] mod renderer; mod shader; @@ -53,7 +60,12 @@ pub use allocator::{ }; pub use depth::REVERSED_Z_CLEAR_DEPTH; pub use error::{RenderError, RenderErrorKind}; -pub use handle::{OffscreenTargetHandle, PipelineHandle, ShaderHandle}; +pub use handle::{MeshHandle, OffscreenTargetHandle, PipelineHandle, ShaderHandle}; +pub use mesh::{ + CameraRelativeView, MAX_MESH_INDICES, MAX_MESH_VERTICES, MESH_PUSH_CONSTANT_BYTES, + MESH_PUSH_CONSTANT_RANGE, MESH_VERTEX_ATTRIBUTES, MESH_VERTEX_STRIDE, MeshDescriptor, MeshDraw, + MeshVertex, PackedMeshPushConstants, +}; #[cfg(feature = "vulkan")] pub use renderer::Renderer; pub use shader::{ diff --git a/crates/spawn-render/src/mesh.rs b/crates/spawn-render/src/mesh.rs new file mode 100644 index 0000000..b2140b2 --- /dev/null +++ b/crates/spawn-render/src/mesh.rs @@ -0,0 +1,629 @@ +//! Plain-data 3D mesh descriptors, camera-relative draw contracts, and 128-byte +//! push-constant packing matching `shaders/mesh_3d.slang` (`ADR-0004`, `ADR-0010`, +//! `SPN-INV-050..053`, `F3D-FR-02`, `F3D-FR-08`, `F3D-FR-10`). +//! +//! Always compiled (`default-features = false`), GPU-free, `#![forbid(unsafe_code)]`, +//! and `#![deny(clippy::indexing_slicing)]`. No `bytemuck` or Vulkan type appears +//! in the public API (`SPN-INV-011`), and `f64` [`WorldPos`] coordinates are +//! subtracted in `f64` on the CPU via [`camera_relative_f32`] before entering +//! [`MeshDraw`] (`SPN-INV-052`). + +#![forbid(unsafe_code)] +#![deny(clippy::indexing_slicing)] + +use spawn_math::{Mat3, Mat4, Quat, Transform, Vec3, Vec4, WorldPos, camera_relative_f32}; + +use crate::error::{RenderError, RenderErrorKind}; +use crate::handle::MeshHandle; +use crate::shader::{PushConstantRange, ShaderStageFlags, VertexFormat, VertexInputAttribute}; + +/// Byte stride of [`MeshVertex`] (`3 + 3 + 4` IEEE `f32` scalars = `40` bytes). +pub const MESH_VERTEX_STRIDE: u32 = 40; + +/// Canonical vertex input attribute layout of [`MeshVertex`] matching `shaders/mesh_3d.slang`. +pub const MESH_VERTEX_ATTRIBUTES: [VertexInputAttribute; 3] = [ + VertexInputAttribute::new(0, VertexFormat::Float32x3), + VertexInputAttribute::new(1, VertexFormat::Float32x3), + VertexInputAttribute::new(2, VertexFormat::Float32x4), +]; + +/// Exact byte size of the `MeshPushConstants` block in `shaders/mesh_3d.slang` (`128` bytes). +pub const MESH_PUSH_CONSTANT_BYTES: u32 = 128; + +/// Pipeline push-constant range for `shaders/mesh_3d.slang` (`128` bytes in vertex stage). +pub const MESH_PUSH_CONSTANT_RANGE: PushConstantRange = + PushConstantRange::new(MESH_PUSH_CONSTANT_BYTES, ShaderStageFlags::VERTEX); + +/// Upper sanity cap on vertices per static mesh upload (`4,194,304` vertices = `160 MiB`; `SPN-INV-034`). +pub const MAX_MESH_VERTICES: usize = 4 * 1024 * 1024; + +/// Upper sanity cap on `u32` indices per static mesh upload (`16,777,216` indices = `64 MiB`; `SPN-INV-034`). +pub const MAX_MESH_INDICES: usize = 16 * 1024 * 1024; + +/// Single 3D mesh vertex (`40` bytes: local position, local normal, linear RGBA color) +/// matching `VertexInput` in `shaders/mesh_3d.slang`. +#[repr(C)] +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct MeshVertex { + /// Local-space 3D position (`location 0`, `R32G32B32_SFLOAT`, byte offset `0`). + pub position: Vec3, + /// Local-space surface normal (`location 1`, `R32G32B32_SFLOAT`, byte offset `12`). + pub normal: Vec3, + /// Linear RGBA vertex color (`location 2`, `R32G32B32A32_SFLOAT`, byte offset `24`). + pub color: Vec4, +} + +impl MeshVertex { + /// Creates a 3D mesh vertex. + #[inline] + pub const fn new(position: Vec3, normal: Vec3, color: Vec4) -> Self { + Self { + position, + normal, + color, + } + } + + /// Returns `true` when `position`, `normal`, and `color` contain only finite scalars. + #[inline] + pub fn is_finite(&self) -> bool { + self.position.is_finite() && self.normal.is_finite() && self.color.is_finite() + } +} + +/// CPU-side indexed `TRIANGLE_LIST` mesh upload descriptor (`u32` indices). +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct MeshDescriptor<'a> { + /// Debug label attached via `VK_EXT_debug_utils` (`spawn.mesh.