concinnity_core/render/backend.rs
1//! RenderBackend trait: the union of methods every graphics backend
2//! implements, dispatched dynamically by GraphicsSystem so the per-frame
3//! step + setup logic lives in one cfg-free copy instead of three.
4//!
5//! Each concrete backend (MtlContext / DxContext / VkContext) supplies a
6//! thin forwarder impl that delegates to the existing inherent methods
7//! (see metal/backend.rs, directx/backend.rs, vulkan/backend.rs).
8//!
9//! Two cross-backend signature variances are handled here:
10//! - `upload_skinned`: Metal uses three shader payloads (vert + frag +
11//! shadow); DX/VK use one (frag). The trait method takes all three;
12//! DX/VK ignore the unused bytes.
13//! - `setup_chunk_streaming`: Metal binds chunk textures per draw and
14//! ignores the (texture_slot, normal_map_slot) args; DX/VK bake them
15//! into a shared descriptor at setup time.
16//!
17//! `render_stats` has a default no-op impl so a backend with no draw-call /
18//! object counters need not override it; all three shipping backends do.
19
20use crate::gfx::auto_exposure::AutoExposureSettings;
21use crate::gfx::mesh_payload::{SkinnedVertex, Vertex};
22use crate::gfx::profile::RenderStats;
23use crate::gfx::render_types::{
24 LineVertex, MaterialUniforms, PostProcessTunables, SkinnedDrawObject, TextDrawCall,
25};
26use crate::gfx::rt_reflections::RtReflectionSettings;
27use crate::gfx::ssao::SsaoSettings;
28use crate::gfx::ssgi::SsgiSettings;
29use crate::gfx::ssr::SsrSettings;
30use crate::render::backend_init::{BackendInit, ShaderBytes, SwapchainConfig};
31use crate::render::error::{RenderError, RenderResult};
32use crate::render::input::RenderInput;
33use crate::render::keymap::KeyMap;
34use crate::render::scene_flow::SceneControl;
35use crate::render::volumetric_fog::FogSettings;
36use alloc::string::String;
37use alloc::string::ToString;
38use alloc::vec::Vec;
39
40/// Per-frame inputs for [`RenderBackend::draw_frame`]. `world_hidden` is set when
41/// an opaque menu backdrop covers the scene: the backend skips every world pass
42/// and presents only the overlay (`text_calls`) over a cleared target.
43#[derive(Clone, Copy)]
44pub struct FrameParams<'a> {
45 /// Seconds since the world started, for time-driven effects.
46 pub elapsed: f32,
47 /// Vertical field of view in radians.
48 pub fov_y_radians: f32,
49 /// Near clip distance in world units.
50 pub near: f32,
51 /// Far clip distance in world units.
52 pub far: f32,
53 /// World-space camera position.
54 pub cam_pos: [f32; 3],
55 /// Overlay draw calls for this frame.
56 pub text_calls: &'a [TextDrawCall],
57 /// Expanded line ribbons (`lines::build_vertices`) for this frame's camera,
58 /// drawn depth-tested into the scene after the world passes. Empty on any
59 /// frame that submits no lines, which also drops the pass from the graph.
60 pub lines: &'a [LineVertex],
61 /// `true` when an opaque menu backdrop covers the scene.
62 pub world_hidden: bool,
63 /// Viewport view mode + show flags for the frame (`ViewOverrides` when the
64 /// editor publishes one, defaults otherwise). Backends run their seeded
65 /// graph inputs through `render_graph::apply_view` and steer the composite
66 /// by the mode.
67 pub view_mode: crate::gfx::view_modes::ViewMode,
68 /// Feature passes to run this frame.
69 pub show: crate::gfx::view_modes::ShowFlags,
70}
71
72/// One streamed chunk's geometry plus placement, supplied to
73/// [`RenderBackend::add_chunk_mesh`]. `frame` reclaims retired deferred frees
74/// before the chunk is placed in the streaming headroom.
75#[derive(Clone, Copy)]
76pub struct ChunkMesh<'a> {
77 /// Chunk vertices.
78 pub verts: &'a [Vertex],
79 /// Chunk indices, mesh-relative.
80 pub idxs: &'a [u16],
81 /// Column-major placement matrix.
82 pub model: [[f32; 4]; 4],
83 /// Index into the shared texture pool for the albedo map.
84 pub texture_slot: usize,
85 /// Index into the shared texture pool for the normal map.
86 pub normal_map_slot: usize,
87 /// Per-chunk material scalars.
88 pub material: MaterialUniforms,
89 /// Current frame number, used to reclaim retired deferred frees.
90 pub frame: u64,
91}
92
93/// One draw slot's fresh geometry, supplied to
94/// [`RenderBackend::rebuild_static_geometry`] when an asset hot-reload
95/// changed its vertex / index count and the slot can no longer hold the new
96/// data in place. The backend rebuilds the entire shared vertex / index
97/// buffer; draws not named here keep their current geometry, copied byte-for-
98/// byte from the live buffers. `indices` are mesh-relative (0-based); the
99/// backend rebases them onto whatever new vertex region the draw lands in.
100pub struct DrawGeometryUpdate {
101 /// The draw slot whose geometry is replaced.
102 pub draw_idx: usize,
103 /// Replacement vertices.
104 pub vertices: Vec<Vertex>,
105 /// Replacement indices, mesh-relative.
106 pub indices: Vec<u16>,
107 /// One slice per additional LOD, ordered mip 0 → mip N-1. Each is
108 /// `(switch_distance, mesh-relative indices)`. Empty for meshes
109 /// declared `lod_levels <= 1`.
110 pub lod_alternates: Vec<(f32, Vec<u16>)>,
111}
112
113/// One skinned draw slot's fresh geometry, supplied to
114/// [`RenderBackend::rebuild_skinned_geometry`] when an asset hot-reload
115/// changed its vertex / index count and the slot can no longer hold the new
116/// data in its existing region of the shared skinned vertex / index buffers.
117/// The backend rebuilds both shared buffers; slots not named here keep their
118/// current geometry, copied byte-for-byte from the live buffers and re-based
119/// onto whatever new vertex region they land in. `indices` are mesh-relative
120/// (0-based); the backend rebases them onto the new vertex region.
121pub struct SkinnedDrawGeometryUpdate {
122 /// The skinned slot whose geometry is replaced.
123 pub skinned_index: usize,
124 /// Replacement vertices.
125 pub vertices: Vec<SkinnedVertex>,
126 /// Replacement indices, mesh-relative.
127 pub indices: Vec<u16>,
128}
129
130/// The post-rebuild layout for one skinned slot, returned by
131/// [`RenderBackend::rebuild_skinned_geometry`] so the asset hot-reload
132/// helper can refresh its `SkinnedMeshSourceEntry`s'
133/// `vertex_base` / `vertex_count` / `index_count` to point at the new
134/// regions. Returned for every slot (both the ones whose geometry was
135/// replaced and the ones whose geometry was carried over) because the
136/// rebuild may have shifted every slot's `vertex_base`.
137/// Constructed only by the `cn debug` binary's skinned-rebuild reload pass;
138/// reads as dead under `cargo check --lib`.
139pub struct SkinnedSlotLayout {
140 /// The skinned slot this layout describes.
141 pub skinned_index: usize,
142 /// First vertex of the slot's region in the shared skinned buffer.
143 pub vertex_base: u32,
144 /// Vertices in the slot's region.
145 pub vertex_count: usize,
146 /// Indices in the slot's region.
147 pub index_count: usize,
148}
149
150/// The resolved per-feature quality settings for [`RenderBackend::apply_quality_settings`].
151/// `GraphicsSystem` derives these from its stored `PostProcessConfig` (with the
152/// user's persisted toggle overrides applied) whenever a Quality-group toggle
153/// changes, so the backend receives ready-to-use settings rather than re-deriving
154/// from the asset. Each `Option` mirrors the init-time gate: `None` means the
155/// feature is off and its passes / resources should be torn down; `Some` means it
156/// is on and its resources should exist. A backend without a live-rebuild path
157/// ignores this (the choice still persists and applies at the next launch).
158pub struct QualitySettings {
159 /// Temporal anti-aliasing on/off (the `Taa` anti-aliasing mode). The backend
160 /// additionally suppresses TAA while temporal upscaling is active (the scaler
161 /// does its own accumulation). The other anti-aliasing modes are the composite
162 /// FXAA edge filter, which rides `PostProcessTunables.fxaa` (pushed via
163 /// `update_post_process`), not this pass-rebuild payload.
164 pub taa: bool,
165 /// Screen-space ambient occlusion, or `None` when off.
166 pub ssao: Option<SsaoSettings>,
167 /// Screen-space reflections, or `None` when off.
168 pub ssr: Option<SsrSettings>,
169 /// Hardware ray-traced reflections. The backend further gates this on GPU
170 /// ray-tracing support, falling back to leaving it off when unsupported.
171 pub rt_reflections: Option<RtReflectionSettings>,
172 /// Screen-space global illumination, or `None` when off.
173 pub ssgi: Option<SsgiSettings>,
174 /// Per-axis divisor for the roughness-aware reflection blur target (the
175 /// reduced-resolution first pass of the SSR / RT reflection composite),
176 /// resolved from `PostProcessConfig.reflection_blur_resolution`. Every backend
177 /// sizes its blur target at render / this on a live reflection rebuild.
178 pub reflection_blur_scale: u32,
179 /// Auto-exposure, or `None` when off.
180 pub auto_exposure: Option<AutoExposureSettings>,
181 /// The authored exposure bias (stops) auto-exposure applies on top of its
182 /// adapted value; carried so a live auto-exposure enable matches init.
183 pub auto_exposure_bias_ev: f32,
184}
185
186/// GPU/device capability flags, queried from the backend once it is built.
187/// Surfaced so the settings menu can gray out (and make inert) toggles the
188/// device cannot honor -- e.g. ray-traced reflections on a GPU without hardware
189/// ray tracing. Mirrors an RHI-style capability set: a handful of bools held in
190/// memory and re-queried each launch, never persisted, so it is always correct
191/// for the current device + driver.
192#[derive(Clone, Copy, Debug)]
193pub struct DeviceCapabilities {
194 /// Hardware ray tracing for the RT-reflections pass: DXR 1.1 on DirectX, the
195 /// ray-query device extensions on Vulkan (and not under XeSS), and
196 /// `MTLDevice::supportsRaytracing` on Metal.
197 pub ray_tracing: bool,
198 /// Whether the upscaler implementation is a choice (FSR3 / DLSS / XeSS)
199 /// rather than fixed. DirectX and Vulkan offer the selection; Metal always
200 /// upscales through MetalFX, so the row has nothing to pick.
201 pub selectable_upscaler: bool,
202 /// Whether a retired build-time draw slot may be recycled by a runtime
203 /// clone. Metal's per-frame RT topology refresh re-admits recycled
204 /// build-time slots; DirectX / Vulkan key their cull BVH + RT tables to
205 /// fixed build-time indices and cannot refit, so only the runtime-append
206 /// region recycles there. Read by the engine's draw-slot allocator.
207 pub reuses_build_slots: bool,
208 /// Whether a built draw slot's material and cull distance may be rewritten
209 /// in place ([`RenderBackend::set_draw_material`] /
210 /// [`RenderBackend::set_draw_cull_distance`]). Metal rebuilds its per-object
211 /// buffer from the draw list every frame, so a rewritten slot draws with the
212 /// new material next frame; DirectX / Vulkan bake per-object material state
213 /// at build time and would keep drawing the old one. Read by the editor's
214 /// live draw seam, which sends the edit to a world rebuild instead.
215 pub rewrites_draws: bool,
216}
217
218impl DeviceCapabilities {
219 /// Every capability present. The trait default, so a backend that does not
220 /// report capabilities never wrongly disables a toggle (it keeps the prior
221 /// behavior: the feature no-ops with a warning on an incapable device).
222 pub const ALL: Self = Self {
223 ray_tracing: true,
224 selectable_upscaler: true,
225 reuses_build_slots: true,
226 rewrites_draws: true,
227 };
228}
229
230impl Default for DeviceCapabilities {
231 fn default() -> Self {
232 Self::ALL
233 }
234}
235
236/// Coarse GPU vendor class, derived per backend from the adapter's reported
237/// vendor id (DirectX / Vulkan) or unified-memory / Apple-family signals (Metal).
238/// Used only to pick default quality and to gate vendor-specific options (e.g.
239/// which upscalers to offer); never persisted.
240#[derive(Clone, Copy, Debug, PartialEq, Eq)]
241pub enum GpuVendor {
242 /// Apple silicon.
243 Apple,
244 /// NVIDIA.
245 Nvidia,
246 /// AMD.
247 Amd,
248 /// Intel.
249 Intel,
250 /// A vendor the probe does not recognise.
251 Other,
252}
253
254/// Coarse performance class for default-quality selection, ordered low -> high so
255/// callers can compare with `>=`. Each backend maps its native signals (memory
256/// budget, discrete / integrated, Apple GPU family) onto this via `classify_tier`.
257#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
258pub enum GpuTier {
259 /// Unknown hardware: the conservative default, never the top preset. Sorts
260 /// lowest so a comparison-based resolver treats it as the floor.
261 Unknown,
262 /// Integrated / low-power GPU: the lowest quality tier.
263 Integrated,
264 /// Older or small discrete GPU, or an Apple base M-series: entry quality.
265 EntryDiscrete,
266 /// Mainstream discrete GPU, or an Apple Pro: mid quality.
267 MidDiscrete,
268 /// Enthusiast discrete GPU, or an Apple Max / Ultra: high quality.
269 HighDiscrete,
270}
271
272/// A coarse, Copy snapshot of the active GPU's class, queried from the backend
273/// once it is built (mirrors `DeviceCapabilities`). Read at init to choose
274/// sensible default graphics quality; never persisted, re-queried each launch so
275/// it is always correct for the current device + driver. The GPU *name* is
276/// deliberately omitted (it is not `Copy`); a backend exposes the name separately
277/// when a UI needs it.
278#[derive(Clone, Copy, Debug)]
279pub struct GpuProfile {
280 /// The GPU's vendor.
281 pub vendor: GpuVendor,
282 /// The performance tier the probe placed the GPU in.
283 pub tier: GpuTier,
284 /// Dedicated VRAM on a discrete GPU, or the recommended working-set on a
285 /// unified-memory GPU. 0 when the backend / driver cannot report it.
286 pub memory_budget_bytes: u64,
287 /// Whether the GPU shares memory with the host.
288 pub unified_memory: bool,
289 /// Whether the GPU is a discrete card.
290 pub discrete: bool,
291}
292
293impl GpuProfile {
294 /// Conservative fallback for a backend that does not report a profile:
295 /// unknown hardware picks the cautious baseline, never a high preset. The
296 /// opposite default from `DeviceCapabilities::ALL` -- a feature gate fails
297 /// open (assume capable, no-op with a warning if not), but quality
298 /// auto-config fails safe (assume modest, never overdrive a weak GPU).
299 pub const UNKNOWN: Self = Self {
300 vendor: GpuVendor::Other,
301 tier: GpuTier::Unknown,
302 memory_budget_bytes: 0,
303 unified_memory: false,
304 discrete: false,
305 };
306}
307
308impl Default for GpuProfile {
309 fn default() -> Self {
310 Self::UNKNOWN
311 }
312}
313
314/// The cheap signals every backend can gather about its GPU, mapped to a coarse
315/// `GpuTier` by one shared rule so the three backends classify consistently and
316/// the mapping is unit-testable without a GPU. The backends differ in what they
317/// can report (Apple exposes a GPU family; DirectX / Vulkan expose a VRAM figure
318/// and a discrete / integrated flag), so this carries the union and the rule
319/// uses whichever signals are present.
320pub struct GpuClassInput {
321 /// The GPU's vendor.
322 pub vendor: GpuVendor,
323 /// Device memory the driver reports as budgeted for this process.
324 pub memory_budget_bytes: u64,
325 /// Whether the GPU is a discrete card.
326 pub discrete: bool,
327 /// Apple GPU family generation rank (7 = M1 .. 10 = M4), or 0 for a non-Apple
328 /// GPU. Apple silicon classifies by generation; everything else by VRAM.
329 pub apple_family: u8,
330}
331
332/// The Apple GPU family generation rank a device name implies, or 0 when the name
333/// is not an Apple silicon GPU. Metal reads the rank straight off the device
334/// (`MTLDevice::supportsFamily`); Vulkan has no equivalent query, so a MoltenVK
335/// build recovers it from the reported device name ("Apple M2 Max"). Without it
336/// Apple silicon falls through `classify_tier`'s integrated branch and the two
337/// backends disagree on the same GPU. `M<n>` maps to `n + 6`, matching Metal's
338/// `MTLGPUFamily::Apple7` = M1.
339pub fn apple_family_from_device_name(name: &str) -> u8 {
340 let Some(rest) = name.strip_prefix("Apple M") else {
341 return 0;
342 };
343 let digits: String = rest.chars().take_while(char::is_ascii_digit).collect();
344 match digits.parse::<u8>() {
345 Ok(n) if n >= 1 => n.saturating_add(6),
346 _ => 0,
347 }
348}
349
350/// Map the gathered GPU signals to a coarse performance tier. Apple silicon is
351/// classified by GPU family generation (family alone cannot separate base from
352/// Pro / Max / Ultra within a generation -- a working-set refinement can split
353/// them later); a non-Apple integrated / low-power GPU is the lowest tier; a
354/// discrete GPU is bucketed by dedicated VRAM. An unreporting device (no memory,
355/// not discrete) stays `Unknown` so the resolver uses the conservative baseline.
356pub fn classify_tier(input: &GpuClassInput) -> GpuTier {
357 const GB: u64 = 1 << 30;
358 // Apple silicon: classify by GPU family generation.
359 if input.vendor == GpuVendor::Apple && input.apple_family >= 7 {
360 return match input.apple_family {
361 7 => GpuTier::EntryDiscrete, // M1 class
362 8 => GpuTier::MidDiscrete, // M2 class
363 _ => GpuTier::HighDiscrete, // M3 / M4 and newer
364 };
365 }
366 // Any non-Apple integrated / low-power GPU is the lowest tier (Apple silicon
367 // is unified too, but it returned above via its family branch).
368 if !input.discrete {
369 return GpuTier::Integrated;
370 }
371 // Discrete GPU: bucket by dedicated VRAM.
372 match input.memory_budget_bytes {
373 0 => GpuTier::Unknown,
374 b if b >= 12 * GB => GpuTier::HighDiscrete,
375 b if b >= 6 * GB => GpuTier::MidDiscrete,
376 _ => GpuTier::EntryDiscrete,
377 }
378}
379
380/// The set of operations GraphicsSystem performs on a graphics backend.
381/// Implementations are thin forwarders to the inherent methods on
382/// MtlContext / DxContext / VkContext.
383///
384/// The asset hot-reload mutators below (`update_color_lut`,
385/// `rebuild_*_geometry`, `clone_static_draw_object`, etc.) are provided
386/// methods that default to a no-op, so a backend implements only the reload
387/// paths it actually supports.
388pub trait RenderBackend: SceneControl + Send {
389 /// Window / input lifecycle.
390 fn window_closed(&mut self) -> bool;
391 /// Confine the cursor to the window.
392 fn capture_cursor(&mut self);
393 /// Take the input sampled since the last call.
394 fn take_input(&mut self) -> RenderInput;
395 /// Block until the GPU has drained every submitted frame.
396 fn wait_idle(&self);
397
398 /// Per-frame drive. See [`FrameParams`] for the inputs.
399 fn draw_frame(&mut self, params: FrameParams<'_>) -> RenderResult<()>;
400 /// Push the camera's view matrix, column-major.
401 fn update_view(&mut self, matrix: [[f32; 4]; 4]);
402
403 /// Push this frame's changed model matrices, one `(draw slot, matrix)`
404 /// entry per moved draw object, applied in order. Batched so the trait is
405 /// crossed once per frame rather than once per entity; the caller sends
406 /// only slots whose matrix actually changed. An out-of-range slot is
407 /// ignored.
408 fn update_models(&mut self, updates: &[(u32, [[f32; 4]; 4])]);
409
410 /// Retire a draw object: hide it from every pass (main, shadow, velocity)
411 /// and exclude it from the ray-tracing acceleration structure, so a
412 /// despawned entity's slot leaves no ghost. The slot's geometry buffers are
413 /// untouched; the engine's draw-slot allocator returns the index to its
414 /// free list so a later `clone_static_draw_object` can recycle it. A no-op
415 /// if the index is out of range.
416 fn retire_draw_object(&mut self, draw_idx: usize);
417
418 /// Skinning. `vert_bytes` and `shadow_bytes` are Metal-only payloads;
419 /// DX/VK ignore them.
420 fn upload_skinned(
421 &mut self,
422 vertices: &[SkinnedVertex],
423 indices: &[u32],
424 draw_objects: Vec<SkinnedDrawObject>,
425 vert_bytes: &[u8],
426 frag_bytes: &[u8],
427 shadow_bytes: &[u8],
428 ) -> RenderResult<()>;
429 /// Push one skinned slot's joint matrices for this frame.
430 fn update_skinned_pose(&mut self, skinned_index: usize, matrices: &[[[f32; 4]; 4]]);
431
432 /// Attach morph-target data to the skinned draw objects, called once after
433 /// `upload_skinned`: `morphs[i]` belongs to draw object `i` (instance
434 /// copies share their template's data via the `Arc`). Default no-op for a
435 /// backend without a morph deformation path.
436 fn upload_skinned_morphs(
437 &mut self,
438 _morphs: Vec<Option<alloc::sync::Arc<crate::gfx::mesh_payload::PayloadMorphs>>>,
439 ) {
440 }
441
442 /// Push a skinned object's current morph-target weights, sampled by the
443 /// animation system each frame. A no-op when the index is out of range or
444 /// the object carries no morph targets.
445 fn update_morph_weights(&mut self, _skinned_index: usize, _weights: &[f32]) {}
446
447 // Runtime skinned spawn (pre-reserved instance pool): a backend pre-reserves
448 // hidden bind-pose copies at load (`SkinnedMesh.max_instances`) and reveals
449 // one per skinned SpawnRequest. The default no-op implementations are a
450 // fallback for a backend that has not wired runtime skinned spawn, where a
451 // skinned SpawnRequest finds nothing to claim and is dropped.
452
453 /// Reveal the pre-reserved skinned instance at `instance_index` (a hidden
454 /// bind-pose copy expanded at load): show it at `model` and reset its
455 /// palette to bind so it does not flash a previous occupant's pose. Which
456 /// instance to use is decided by the engine's instance pool; the backend
457 /// only applies it. A no-op if the index is out of range.
458 fn reveal_skinned_instance(&mut self, _instance_index: usize, _model: [[f32; 4]; 4]) {}
459
460 /// Hide a live skinned instance. The engine's instance pool returns the
461 /// slot for reuse; the backend only hides it. A no-op if the index is out
462 /// of range.
463 fn retire_skinned_draw_object(&mut self, _skinned_index: usize) {}
464
465 /// Push this frame's changed skinned model-to-world matrices, one
466 /// `(skinned index, matrix)` entry per moved instance, applied in order
467 /// (a skinned object animates in place unless something moves it). Cheap:
468 /// the per-frame cull rebuild reads the object's model directly, so this
469 /// just writes the fields. Out-of-range indices are ignored; default
470 /// no-op for a backend without movable skinned instances.
471 fn update_skinned_models(&mut self, _updates: &[(u32, [[f32; 4]; 4])]) {}
472
473 /// Texture streaming. Albedo and normal maps share one handle-indexed pool,
474 /// so every streamed texture (whatever its role) flows through these. The
475 /// image carries its GPU format and mip chain: RGBA8 regenerates mips on
476 /// upload, block-compressed formats upload their chain verbatim.
477 fn evict_texture_slot(&mut self, slot: usize) -> Result<(), String>;
478 /// Replace a texture slot's image after a streaming upload.
479 fn update_texture_slot(
480 &mut self,
481 slot: usize,
482 image: &crate::build::texture::TextureImage,
483 ) -> RenderResult<()>;
484
485 /// Mesh streaming.
486 fn evict_mesh(&mut self, draw_idx: usize, retire_frame: u64) -> Result<(), String>;
487 /// Upload a streamed mesh's geometry into a draw slot.
488 fn upload_mesh(
489 &mut self,
490 draw_idx: usize,
491 verts: &[Vertex],
492 idxs: &[u16],
493 frame: u64,
494 ) -> RenderResult<()>;
495
496 /// Seed the streamed-mesh sub-allocators with one reserved headroom block
497 /// (byte ranges in the shared vertex / index buffers) instead of the
498 /// per-mesh build-time regions. Used by the shrinkable-seed path: the
499 /// streamed geometry is no longer baked into the buffers at build time, so
500 /// the renderer hands the allocators one contiguous block sized to the
501 /// cap-many resident meshes rather than the whole streamed set. Implemented
502 /// on Metal + DirectX + Vulkan. Default no-op: a backend without the
503 /// shrinkable seed keeps freeing each mesh's build-time region in
504 /// `setup_mesh_streaming`.
505 fn seed_mesh_streaming(
506 &mut self,
507 vtx_offset: u64,
508 vtx_bytes: u64,
509 idx_offset: u64,
510 idx_bytes: u64,
511 ) {
512 let _ = (vtx_offset, vtx_bytes, idx_offset, idx_bytes);
513 }
514
515 /// Voxel-world chunk streaming. `texture_slot` and `normal_map_slot`
516 /// are ignored by Metal (it binds chunk textures per draw).
517 fn setup_chunk_streaming(
518 &mut self,
519 chunk_vtx_bytes: usize,
520 chunk_idx_bytes: usize,
521 texture_slot: usize,
522 normal_map_slot: usize,
523 ) -> RenderResult<()>;
524 /// The destination draw slot comes from the engine's allocator, like
525 /// `clone_static_draw_object`; the freed slot is likewise returned to it by
526 /// the caller of `remove_chunk_mesh`.
527 fn add_chunk_mesh(
528 &mut self,
529 mesh: ChunkMesh<'_>,
530 dst: crate::render::draw_slot::SlotAlloc,
531 ) -> RenderResult<()>;
532 /// Free a streamed chunk's geometry, retiring it after `retire_frame`.
533 fn remove_chunk_mesh(&mut self, draw_idx: usize, retire_frame: u64) -> Result<(), String>;
534 /// Move a streamed chunk by replacing its placement matrix.
535 fn set_chunk_model(&mut self, draw_idx: usize, model: [[f32; 4]; 4]) -> Result<(), String>;
536
537 /// Device capability flags, queried from the GPU once the backend is built.
538 /// Read by GraphicsSystem to gray out + disable settings rows the device
539 /// cannot honor. Default: all capable, so a backend that does not report
540 /// capabilities keeps every toggle live (the feature then no-ops with a
541 /// warning on an incapable device, as before).
542 fn capabilities(&self) -> DeviceCapabilities {
543 DeviceCapabilities::ALL
544 }
545
546 /// Coarse GPU performance profile, queried once the backend is built. Read at
547 /// init to pick default graphics quality on first launch. Default: `UNKNOWN`
548 /// (the conservative tier), so a backend that does not report a profile never
549 /// makes the resolver auto-select a high preset.
550 fn gpu_profile(&self) -> GpuProfile {
551 GpuProfile::UNKNOWN
552 }
553
554 /// The overlay coordinate space: the window's content size in logical,
555 /// DPI-independent units (points on macOS, client pixels on Windows, window
556 /// coordinates on Linux). Every backend reports the cursor in these same
557 /// units, so UI hit-testing, text layout, and the overlay shader's divide to
558 /// NDC all share one space regardless of the backing scale. A backend
559 /// converts to attachment pixels only where a pixel rect is unavoidable,
560 /// through `fullscreen::clip_rect_to_scissor`.
561 ///
562 /// Default `(0.0, 0.0)` for a headless backend with no window.
563 fn logical_size(&self) -> (f32, f32) {
564 (0.0, 0.0)
565 }
566 /// Per-frame draw-call / object counters. Default no-op so a backend that
567 /// tracks none still satisfies the trait; all three shipping backends
568 /// override it.
569 fn render_stats(&self) -> RenderStats {
570 RenderStats::default()
571 }
572
573 /// Show or hide the OS cursor for an in-engine UI cursor (e.g. a MainMenu),
574 /// independent of camera capture. Edge-triggered by the backend, so calling
575 /// it every frame with the same value is cheap. Default no-op: a backend
576 /// without a free-mode cursor hide leaves the system cursor visible (DX /
577 /// Vulkan today).
578 fn set_ui_cursor_hidden(&mut self, hidden: bool) {
579 let _ = hidden;
580 }
581
582 /// Whether the real cursor has left the window, so an in-engine UI cursor
583 /// should stop drawing (windowed / borderless). The backend confines the
584 /// cursor to the active screen while in fullscreen, so it reports `false`
585 /// there. Default `false` (inside): backends without window-bounds tracking
586 /// (DX / Vulkan today) always draw the in-engine cursor.
587 fn cursor_outside_window(&self) -> bool {
588 false
589 }
590
591 /// Tell the backend a togglable menu (a Screen toggled by an Escape KeyBinding)
592 /// coexists with a captured camera. In this mode Escape routes to the ECS
593 /// (so the menu shows/hides) instead of releasing the cursor inline, and a
594 /// click never recaptures the cursor (it fires a UI action). Set once at
595 /// setup. Default no-op: backends without dynamic capture (DX / Vulkan today)
596 /// keep the static behavior.
597 fn set_menu_mode(&mut self, on: bool) {
598 let _ = on;
599 }
600
601 /// Drive cursor capture from the menu state each frame: capture for camera
602 /// control, release while a menu is open. Edge-triggered by the backend.
603 /// Default no-op (DX / Vulkan): they keep their startup capture decision.
604 fn set_camera_capture(&mut self, capture: bool) {
605 let _ = capture;
606 }
607
608 /// Supply the reflection-probe placements (from declared `ReflectionProbe`
609 /// assets, or empty to auto-seed from the scene bounds). The backend bakes a
610 /// cube per placement and samples the nearest for the specular reflection.
611 /// Pushed once after construction. Default no-op: backends without probe
612 /// support (DX / Vulkan today) keep the sky reflection.
613 fn set_reflection_probes(
614 &mut self,
615 probes: &[crate::render::reflection_probe::ProbePlacement],
616 ) {
617 let _ = probes;
618 }
619
620 /// Turn display sync (vsync) on or off at runtime, applied to presentation.
621 /// Edge-triggered by the backend, so calling it with the unchanged value is
622 /// cheap. Default no-op: a backend that only honors vsync at init ignores
623 /// runtime changes.
624 fn set_vsync(&mut self, on: bool) {
625 let _ = on;
626 }
627
628 /// Switch the window between windowed / borderless / fullscreen at runtime.
629 /// The change flows through the backend's normal resize path (no GPU rebuild
630 /// beyond the resize it triggers). Default no-op for backends without a
631 /// window (embedded / preview) or that don't yet implement it.
632 fn set_window_mode(&mut self, mode: crate::components::WindowMode) {
633 let _ = mode;
634 }
635
636 /// Resize the window's content area at runtime (meaningful in windowed mode).
637 /// Drives the same resize path as a user-dragged resize. Default no-op for
638 /// backends without a window or that don't yet implement it.
639 fn set_window_size(&mut self, width: u32, height: u32) {
640 let _ = (width, height);
641 }
642
643 /// The display modes (pixel resolution + refresh rate) the display this
644 /// backend renders to supports, unshaped (the caller dedups + sorts).
645 /// Default empty: a backend that cannot enumerate (or has no window) makes
646 /// the Resolution row fall back to the static preset list.
647 fn display_modes(&self) -> Vec<crate::render::display_mode::DisplayMode> {
648 Vec::new()
649 }
650
651 /// The mode the display is currently running, if the backend can read it.
652 /// Shown by the Resolution row when the user has never chosen a mode (the
653 /// display keeps its desktop mode until one is chosen). Default `None`.
654 fn current_display_mode(&self) -> Option<crate::render::display_mode::DisplayMode> {
655 None
656 }
657
658 /// Select the display mode to hold while the window is in fullscreen. The
659 /// backend applies it whenever the window is (or becomes) fullscreen and
660 /// restores the display's original mode when the window leaves fullscreen
661 /// or shuts down; outside fullscreen the choice is only remembered. Default
662 /// no-op: a backend without mode switching leaves the display alone.
663 fn set_display_mode(&mut self, mode: crate::render::display_mode::DisplayMode) {
664 let _ = mode;
665 }
666
667 /// Replace the live post-process tunables (bloom / exposure / vignette /
668 /// LUT blend / FXAA). These are pushed to the bloom + composite shaders each
669 /// frame, so a change takes effect on the next draw with no allocation or
670 /// pipeline rebuild. Only the authored half travels here: the composite's
671 /// display-output flags belong to the display the backend negotiated with
672 /// at init, so a push cannot disturb them. Default no-op: a backend that
673 /// only reads the tunables at init ignores runtime changes.
674 fn update_post_process(&mut self, tunables: PostProcessTunables) {
675 let _ = tunables;
676 }
677
678 /// Set the live ambient (IBL) light scale. Unlike the post-process params
679 /// above, `ambient_intensity` lives in the shared `LightUniforms` (uploaded
680 /// each frame by the main lighting pass), so it takes its own setter rather
681 /// than `update_post_process`. Default no-op: only Metal mutates it live
682 /// today; DirectX / Vulkan keep the init-time value (they read it at init).
683 fn set_ambient_intensity(&mut self, value: f32) {
684 let _ = value;
685 }
686
687 /// Replace the live directional-light set (the sun). Unlike the local
688 /// lights, which ride a per-scene storage buffer sized once at init, the
689 /// directional slots are a fixed-size array in the shared `LightUniforms`,
690 /// so a new set is written in place: the backend re-packs the array and
691 /// re-caches whatever it derived from the first light at init (the cascade
692 /// shadow direction, the fog sun). Default no-op: a backend that only reads
693 /// the lights at init keeps the init-time sun.
694 fn update_directional_lights(&mut self, lights: &[crate::components::DirectionalLight]) {
695 let _ = lights;
696 }
697
698 /// Push the gameplay movement key map. The backend resolves each canonical
699 /// `InputKey` to its native key code and decodes physical key events through the
700 /// map (instead of hardcoded keys), so a settings-menu rebind takes effect on
701 /// the next key event. Pushed once after the backend is built and again on
702 /// each rebind. Default no-op: a backend without keymap decode keeps its
703 /// built-in defaults.
704 fn set_keymap(&mut self, keymap: &KeyMap) {
705 let _ = keymap;
706 }
707
708 /// Apply a change to the quality-feature toggles (TAA / SSAO / SSR / RT
709 /// reflections / SSGI / auto-exposure) live. Unlike the post-process params,
710 /// these gate render passes whose GPU resources (pipelines, render targets,
711 /// ray-tracing acceleration structures) are built once at init, so applying a
712 /// change rebuilds the affected resources in place rather than flipping a
713 /// uniform. Default no-op: a backend that only reads these at init ignores
714 /// runtime changes (DirectX / Vulkan today), so the choice persists and takes
715 /// effect at the next launch there.
716 fn apply_quality_settings(&mut self, settings: QualitySettings) {
717 let _ = settings;
718 }
719
720 /// Set the shadow cascade re-render cadence live. The cascade scheduler reads
721 /// the policy at the start of each shadow pass, so a change takes effect on the
722 /// next draw with no pipeline rebuild or allocation (unlike the shadow map
723 /// resolution, which is sized once at init). Default no-op: a backend that only
724 /// reads the cadence at init keeps the init-time value (DirectX / Vulkan
725 /// today), so the choice persists and takes effect at the next launch there.
726 fn set_shadow_update(&mut self, update: crate::components::ShadowUpdate) {
727 let _ = update;
728 }
729
730 /// Set the shadow distance (world units the cascades cover, capped at the
731 /// camera far plane) live. The per-frame cascade-split computation reads it
732 /// each draw, so a change takes effect on the next frame with no allocation or
733 /// rebuild (it sizes no GPU resource, unlike the shadow map resolution).
734 /// Default no-op: a backend that only reads the distance at init keeps the
735 /// init-time value (DirectX / Vulkan today), so the choice persists and takes
736 /// effect at the next launch there.
737 fn set_shadow_distance(&mut self, distance: u32) {
738 let _ = distance;
739 }
740
741 /// Set the live shadow cascade count (1..=4). The cascade-split math + the
742 /// re-render schedule read it each frame and only the first `count` cascades
743 /// are projected, rendered, and sampled (the array capacity stays 4), so a
744 /// change takes effect on the next frame with no resize or rebuild. Default
745 /// no-op: a backend that only reads the count at init keeps the init-time
746 /// value (DirectX / Vulkan today), so the choice persists and takes effect at
747 /// the next launch there.
748 fn set_shadow_cascades(&mut self, count: u32) {
749 let _ = count;
750 }
751
752 /// Update the live scalar sub-tunables of the SSAO / SSR / SSGI / auto-exposure
753 /// passes (radius, intensity, distance, EV bounds, adaptation speed). Unlike
754 /// `apply_quality_settings`, this rebuilds nothing: each backend re-reads these
755 /// values from its stored `*Settings` structs into a per-frame uniform every
756 /// draw, so mutating them takes effect on the next frame with no pipeline /
757 /// target rebuild and no TAA-history reset. Only the fields of a feature that is
758 /// currently on are honoured (its settings are present); a value for an off
759 /// feature is ignored here and applies when the feature next turns on. The
760 /// structural sub-knobs (gather resolution, ray / step counts) are NOT live and
761 /// still ride `apply_quality_settings`. Default no-op: a backend that reads
762 /// these only at init keeps the init-time values (DirectX / Vulkan today), so
763 /// the choice persists and takes effect at the next launch there.
764 fn update_quality_params(&mut self, settings: QualitySettings) {
765 let _ = settings;
766 }
767
768 /// Shared atomic flag the backend polls at frame start to trigger a
769 /// shader rebuild. `Some` only under `cn debug` on backends that ship
770 /// hot-reload (Metal today); `None` on production runs and on backends
771 /// that have not implemented hot-reload yet. The debug server reads this
772 /// to forward `reload-shaders` commands; the filesystem watcher writes
773 /// it directly. Default: `None`.
774 fn shader_reload_flag(&self) -> Option<alloc::sync::Arc<core::sync::atomic::AtomicBool>> {
775 None
776 }
777
778 /// Replace the live colour-grading LUT with a fresh `size³` RGBA8 payload.
779 /// Driven by asset hot-reload (`cn debug` only). Default no-op: backends
780 /// that have not implemented the swap leave the LUT bound at whatever
781 /// payload was uploaded at init.
782 fn update_color_lut(&mut self, size: u32, data: &[u8]) -> Result<(), String> {
783 let _ = (size, data);
784 Ok(())
785 }
786
787 /// `(vertex_count, index_count)` for the static draw at `draw_idx`, or
788 /// `None` when the index is out of range / the backend does not expose
789 /// the field. Used by asset hot-reload to detect size-changing
790 /// reloads before attempting [`Self::update_mesh_geometry`], which
791 /// rejects size mismatches. Default returns `None`; backends that
792 /// implement the rebuild path also override this.
793 fn draw_geometry_size(&self, draw_idx: usize) -> Option<(usize, usize)> {
794 let _ = draw_idx;
795 None
796 }
797
798 /// Per-LOD-alternate index counts for the static draw at `draw_idx`,
799 /// ordered from LOD1 upward (LOD0 is reported by
800 /// [`Self::draw_geometry_size`]). Returns `None` when the index is out of
801 /// range or the backend does not expose its LOD layout. Used by asset
802 /// hot-reload alongside [`Self::draw_geometry_size`] to detect
803 /// size-changing reloads: a `.glb` that re-exports with a different LOD
804 /// breakdown queues the entry for [`Self::rebuild_static_geometry`]
805 /// instead of [`Self::update_mesh_geometry`]'s in-place write.
806 fn draw_lod_index_counts(&self, draw_idx: usize) -> Option<Vec<usize>> {
807 let _ = draw_idx;
808 None
809 }
810
811 /// Rebuild the shared static-mesh vertex + index buffers, replacing the
812 /// geometry of each `DrawGeometryUpdate.draw_idx` with the new
813 /// vertices / indices / LOD alternates. Draws not named in `changes`
814 /// keep their current geometry, copied byte-for-byte from the live
815 /// buffers. The slot's `vertex_count`, `index_count`, and
816 /// `lod_alternates` index offsets are rewritten as the new buffers are
817 /// laid out. Driven by asset hot-reload (`cn debug` only) when a
818 /// size-changing `.glb` re-export means the existing
819 /// [`Self::update_mesh_geometry`] in-place write no longer fits.
820 /// `wait_idle` first; the rebuild swaps the GPU buffers wholesale.
821 /// Default no-op: backends that have not implemented the rebuild
822 /// return `Ok(())` and the size-changing reload is logged + skipped at
823 /// the caller (the existing in-place path already errored on size
824 /// mismatch).
825 fn rebuild_static_geometry(&mut self, changes: Vec<DrawGeometryUpdate>) -> RenderResult<()> {
826 let _ = changes;
827 Ok(())
828 }
829
830 /// Replace a `SkinnedMesh` draw slot's vertex + index data in place.
831 /// Driven by asset hot-reload (`cn debug` only). Reuses the slot's
832 /// existing vertex region + index region in the shared skinned vertex /
833 /// index buffers (created once by [`Self::upload_skinned`]), so the new
834 /// geometry must match the slot's init-time vertex count + index count
835 /// and the new skeleton must keep the same joint count; pipelines stay
836 /// untouched, only the bytes change. `vertex_base` is the init-time
837 /// vertex offset (in vertex units) into the shared buffer; indices are
838 /// rebased onto it before writing. Default no-op.
839 fn update_skinned_mesh_geometry(
840 &mut self,
841 skinned_index: usize,
842 vertex_base: u32,
843 verts: &[SkinnedVertex],
844 idxs: &[u16],
845 ) -> Result<(), String> {
846 let _ = (skinned_index, vertex_base, verts, idxs);
847 Ok(())
848 }
849
850 /// Rebuild the shared skinned-mesh vertex + index buffers, replacing the
851 /// geometry of each `SkinnedDrawGeometryUpdate.skinned_index` with the
852 /// new vertices / indices. Slots not named in `changes` keep their
853 /// current geometry, copied byte-for-byte from the live buffers and
854 /// re-based onto the new vertex region they land in. Returns the
855 /// post-rebuild layout (one [`SkinnedSlotLayout`] per slot, in
856 /// `skinned_index` order) so the caller can refresh its source-map
857 /// `vertex_base` / `vertex_count` / `index_count` to point at the new
858 /// regions. Driven by asset hot-reload (`cn debug` only) when a
859 /// size-changing `.glb` re-export means the existing
860 /// [`Self::update_skinned_mesh_geometry`] in-place write no longer fits.
861 /// The backend `wait_idle`s first; the rebuild swaps the GPU buffers
862 /// wholesale. The skinned pipelines, shadow + velocity + SSAO + SSR
863 /// variants, and `skinned_draw_objects` slot metadata
864 /// (`texture_slot` / `normal_map_slot` / `material` / `joint_count`)
865 /// all stay untouched; only the `index_offset` / `index_count` on each
866 /// `SkinnedDrawObject` (and the buffers themselves) move. Default no-op
867 /// (returns an empty layout vec): backends that have not implemented
868 /// the rebuild leave the size-changing reload as logged + skipped at
869 /// the caller, the same behaviour as before, since the in-place path
870 /// already errored on size mismatch.
871 fn rebuild_skinned_geometry(
872 &mut self,
873 changes: Vec<SkinnedDrawGeometryUpdate>,
874 ) -> Result<Vec<SkinnedSlotLayout>, String> {
875 let _ = changes;
876 Ok(Vec::new())
877 }
878
879 /// Update a skinned slot's joint count and resize the backend's per-slot
880 /// joint-matrix buffers to match. Driven by asset hot-reload (`cn debug`
881 /// only) when a re-imported `.glb`'s skeleton has a different joint
882 /// count than the slot was initialised with. Shrinking truncates the
883 /// per-slot Vec; growing seeds the new entries to identity so the slot
884 /// renders undeformed on the next `update_skinned_pose`. The skinned
885 /// shaders consume the joints buffer through a pointer (not a fixed-
886 /// size array) and use vertex-attribute-encoded joint indices, so no
887 /// pipeline or shader rebuild is required for a joint-count change;
888 /// only the CPU-side per-slot buffer and `SkinnedDrawObject.joint_count`
889 /// change. Default no-op: backends that have not implemented the resize
890 /// leave the skeleton-shape change logged + skipped at the caller.
891 fn update_skinned_skeleton(
892 &mut self,
893 skinned_index: usize,
894 new_joint_count: usize,
895 ) -> Result<(), String> {
896 let _ = (skinned_index, new_joint_count);
897 Ok(())
898 }
899
900 /// Replace a `Mesh` draw slot's vertex + index data in place. Driven by
901 /// asset hot-reload (`cn debug` only). Reuses the slot's existing offset
902 /// in the shared vertex / index buffers, so the new geometry must match
903 /// the slot's init-time vertex count + index count; a size-changing
904 /// reload returns an error so the caller can queue
905 /// [`Self::rebuild_static_geometry`] instead, which repacks the shared
906 /// buffers. Each entry in
907 /// `lod_alternates` (`(switch_distance, mesh-relative indices)`) is
908 /// written to the matching slot's pre-allocated LOD index region; the
909 /// number of LODs and each LOD's index count must match the slot's
910 /// init-time layout, otherwise the call returns an error so the caller
911 /// can queue [`Self::rebuild_static_geometry`]. `switch_distance` is
912 /// re-stored per LOD so a JSON-side tweak to `lod_distances` propagates
913 /// without a process restart. Default no-op.
914 fn update_mesh_geometry(
915 &mut self,
916 draw_idx: usize,
917 verts: &[Vertex],
918 idxs: &[u16],
919 lod_alternates: &[(f32, Vec<u16>)],
920 ) -> Result<(), String> {
921 let _ = (draw_idx, verts, idxs, lod_alternates);
922 Ok(())
923 }
924
925 /// Replace the live IBL environment map with a freshly precomputed payload.
926 /// `payload` is the serialised byte format emitted by
927 /// `crate::build::environment_map::compile_environment_map_payload`
928 /// (header + irradiance cube + prefilter mip chain), so init and hot-reload
929 /// share a single byte format. Driven by asset hot-reload (`cn debug`
930 /// only). Default no-op: backends that have not implemented the swap leave
931 /// the IBL cubes bound at whatever payload was uploaded at init.
932 fn update_environment_map(&mut self, payload: &[u8]) -> RenderResult<()> {
933 let _ = payload;
934 Ok(())
935 }
936
937 /// Replace the live volumetric-fog settings, or disable the fog pass when
938 /// `None`. Driven by world.jsonl hot-reload (`cn debug` only). Default
939 /// no-op: backends that have not implemented the swap leave the fog pass
940 /// at whatever settings were resolved at init.
941 ///
942 /// A backend that built its fog pipeline lazily based on the world's
943 /// init-time `VolumetricFog` cannot enable the pass via this call when
944 /// the world started with no fog declared; re-enabling fog on a world
945 /// that did not declare it at startup requires a relaunch.
946 fn update_fog_settings(&mut self, settings: Option<FogSettings>) {
947 let _ = settings;
948 }
949
950 /// Capture the last presented frame to a PNG at `path` and return the saved
951 /// path. Driven by the `cn debug` WS `screenshot` command for headless
952 /// on-GPU render verification. Default `Err`: a backend without a capture
953 /// path reports it unsupported (all current backends override this).
954 fn screenshot(&mut self, path: &str) -> Result<String, String> {
955 let _ = path;
956 Err("screenshot capture not supported on this backend".to_string())
957 }
958
959 /// Instantiate a runtime copy of an existing draw object at a new transform:
960 /// re-use the source slot's geometry region (`vertex_offset` / `vertex_count`
961 /// / `index_offset` / `index_count` / `base_vertex` / `lod_alternates`) and
962 /// copy its texture slots, material, and cull distance, swapping only the
963 /// model matrix. The new slot reuses one freed by `retire_draw_object` before
964 /// growing the draw-object vec. The destination slot comes from the
965 /// engine's draw-slot allocator: `Reuse` overwrites a vacated entry,
966 /// `Append` grows the vec (the index always equals the current length,
967 /// which implementations debug-assert). Driven by runtime entity spawn
968 /// (`SpawnRequest`). The copy is non-cullable (sentinel AABB) and drawn
969 /// every frame, since the init-time BVH cannot refit to admit a slot added
970 /// at runtime; moving copies (the common case) opt out of the static BVH
971 /// exactly like streamed chunks and held items. Default no-op (returns
972 /// `Err`): backends without an implementation leave the spawn path
973 /// logged + skipped at the caller.
974 fn clone_static_draw_object(
975 &mut self,
976 src_draw_idx: usize,
977 model: [[f32; 4]; 4],
978 dst: crate::render::draw_slot::SlotAlloc,
979 ) -> Result<(), String> {
980 let _ = (src_draw_idx, model, dst);
981 Err("clone_static_draw_object: not implemented on this backend".to_string())
982 }
983
984 /// Rewrite a draw slot's material parameters + texture/normal-map pool
985 /// indices in place. Driven by the editor's live draw seam when a Prop edits
986 /// its `material` arg. Default no-op; a backend that implements it reports
987 /// [`DeviceCapabilities::rewrites_draws`], which is what the caller gates on
988 /// rather than pushing an edit that would not land.
989 fn set_draw_material(
990 &mut self,
991 draw_idx: usize,
992 material: MaterialUniforms,
993 texture_slot: usize,
994 normal_map_slot: usize,
995 ) {
996 let _ = (draw_idx, material, texture_slot, normal_map_slot);
997 }
998
999 /// Rewrite a draw slot's `cull_distance` in place. Driven by the editor's
1000 /// live draw seam when a Prop edits its `cull_distance` arg. Default no-op,
1001 /// gated by the same [`DeviceCapabilities::rewrites_draws`] flag.
1002 fn set_draw_cull_distance(&mut self, draw_idx: usize, cull_distance: f32) {
1003 let _ = (draw_idx, cull_distance);
1004 }
1005
1006 /// Append a projected-decal record at runtime, returning a stable slot
1007 /// index the caller hands to [`Self::remove_decal`] later. Lets a
1008 /// gameplay system stamp bullet holes, footprints, or other ad-hoc
1009 /// decals after the world has built. Backends that have not implemented
1010 /// the runtime path return `Err`; the caller logs and drops the request.
1011 fn add_decal(&mut self, record: crate::render::decal::DecalRecord) -> Result<usize, String> {
1012 let _ = record;
1013 Err("add_decal: not implemented on this backend".to_string())
1014 }
1015
1016 /// Tombstone a runtime decal slot. The id returned by
1017 /// [`Self::add_decal`] becomes invalid; the next add may reuse it.
1018 /// Default no-op-with-Err: backends without a runtime path leave the
1019 /// remove logged + skipped at the caller.
1020 fn remove_decal(&mut self, decal_id: usize) -> Result<(), String> {
1021 let _ = decal_id;
1022 Err("remove_decal: not implemented on this backend".to_string())
1023 }
1024
1025 /// Append a particle-emitter record at runtime, returning a stable slot
1026 /// index. The backend allocates the per-emitter GPU pool + atomic
1027 /// spawn counter (matching the init-time path) so the compute kernel
1028 /// can begin ticking on the next frame. Default no-op-with-Err.
1029 fn add_emitter(
1030 &mut self,
1031 record: crate::render::particles::ParticleEmitterRecord,
1032 ) -> Result<usize, String> {
1033 let _ = record;
1034 Err("add_emitter: not implemented on this backend".to_string())
1035 }
1036
1037 /// Tombstone a runtime emitter slot and release its GPU pool +
1038 /// counter buffers (the GPU keeps them alive via its own refcount
1039 /// until any in-flight command buffer that referenced them completes).
1040 /// Default no-op-with-Err.
1041 fn remove_emitter(&mut self, emitter_id: usize) -> Result<(), String> {
1042 let _ = emitter_id;
1043 Err("remove_emitter: not implemented on this backend".to_string())
1044 }
1045
1046 /// Rebuild the live main / instanced / shadow render pipelines from
1047 /// freshly compiled world-loaded shader stage bytes. Driven by asset
1048 /// hot-reload (`cn debug` only) when one of the captured `Shader`
1049 /// source files is saved or a debug-WS `reload-assets` command fires.
1050 /// Each `Some(bytes)` replaces the matching live pipeline (and any
1051 /// dependent state: bindless-texture argument encoder, cull pipeline,
1052 /// instanced variant, shadow variant); `None` leaves the pipeline
1053 /// untouched (e.g. a world without an instanced shader passes `None`
1054 /// for the instanced slot). The backend should build every replacement
1055 /// into a temporary first and only swap when every build succeeds;
1056 /// mirrors the safety pattern in the Metal backend's `hot_reload` so a
1057 /// compile error never overwrites a live pipeline with a half-built
1058 /// replacement. Default no-op (returns `Err`): backends without an
1059 /// implementation leave the world-loaded shader reload logged + skipped
1060 /// at the caller.
1061 ///
1062 /// Skinned-mesh variants are out of scope here: their pipelines depend
1063 /// on the world's `SkinnedMesh`-injected library bytes that
1064 /// [`Self::upload_skinned`] consumes and drops.
1065 fn update_world_shader_pipelines(
1066 &mut self,
1067 vert_bytes: Option<&[u8]>,
1068 frag_bytes: Option<&[u8]>,
1069 shadow_bytes: Option<&[u8]>,
1070 vert_instanced_bytes: Option<&[u8]>,
1071 ) -> Result<(), String> {
1072 let _ = (vert_bytes, frag_bytes, shadow_bytes, vert_instanced_bytes);
1073 Err("update_world_shader_pipelines: not implemented on this backend".to_string())
1074 }
1075
1076 /// Build the render pipeline for one shader bucket from its compiled stage
1077 /// bytes, making draws that carry that bucket renderable. Called by the
1078 /// streaming pump when a scene that exclusively owns the bucket's `Shader`
1079 /// pins: init skipped the build, so this is where the cost lands (behind
1080 /// the loading screen, since the bucket counts as scene-resident content).
1081 /// Bucket 0 is the world default program and is never installed this way.
1082 ///
1083 /// Default no-op-with-Ok: a backend that renders every draw with the world
1084 /// default program has no per-bucket pipeline to build, and the bucket is
1085 /// resident as far as scene loading is concerned.
1086 fn install_world_shader(&mut self, bucket: u32, shader: ShaderBytes<'_>) -> RenderResult<()> {
1087 let _ = (bucket, shader);
1088 Ok(())
1089 }
1090
1091 /// Release one shader bucket's render pipeline, undoing
1092 /// [`Self::install_world_shader`]. Called when the owning scene unpins;
1093 /// draws carrying the bucket stop rendering until it is installed again.
1094 /// Default no-op, for the same reason as above.
1095 fn evict_world_shader(&mut self, bucket: u32) {
1096 let _ = bucket;
1097 }
1098
1099 /// The swapchain-level configuration this live backend can hot-swap a world
1100 /// onto, or `None` when the backend cannot reload a world in place (it must
1101 /// be fully rebuilt instead). Read by GraphicsSystem when a transplanted
1102 /// backend is handed a new world (the `cn editor` live SAVE): the swap reuses
1103 /// the backend via [`Self::reload_world`] only when this equals the new
1104 /// world's `BackendInit::swapchain_config`; a `None` or a mismatch routes to a
1105 /// full rebuild (recreating the window). Default `None`: DirectX / Vulkan
1106 /// (and any backend without a real `reload_world`) always rebuild.
1107 fn hot_swap_config(&self) -> Option<SwapchainConfig> {
1108 None
1109 }
1110
1111 /// Re-upload a new world's GPU content onto this already-constructed backend,
1112 /// reusing the live device + window + swapchain instead of building a new one.
1113 /// Driven by the `cn editor` live SAVE: after a structural edit recompiles the
1114 /// blobs, GraphicsSystem transplants the running backend into the rebuilt
1115 /// world and calls this so the edit applies without recreating the OS window
1116 /// or re-initialising the GPU device. The backend waits for the GPU to idle,
1117 /// drops the old world's content resources, and rebuilds them from `init` on
1118 /// the retained hardware. Only ever called when [`Self::hot_swap_config`]
1119 /// reported a config matching `init.swapchain_config()`, so the swapchain
1120 /// (pixel format / frames-in-flight / EDR) is guaranteed unchanged. Default
1121 /// `Err`/unsupported: DirectX / Vulkan fall back to a full rebuild (no
1122 /// regression; a real implementation is Windows-pending like the rest).
1123 fn reload_world(&mut self, init: BackendInit<'_>) -> RenderResult<()> {
1124 let _ = init;
1125 Err(RenderError::Other(
1126 "reload_world: not supported on this backend".to_string(),
1127 ))
1128 }
1129}
1130
1131// A do-nothing backend used to exercise the trait's provided (default) method
1132// bodies without a GPU: the smallest valid bodies for the required methods,
1133// no defaults overridden. Shared by this module's tests and the ops tests.
1134#[cfg(test)]
1135pub(crate) mod test_stub {
1136 use super::*;
1137
1138 pub(crate) struct StubBackend;
1139
1140 impl SceneControl for StubBackend {
1141 fn update_visibility(&mut self, _draw_idx: usize, _visible: bool) {}
1142 fn set_fade(&mut self, _fade: f32) {}
1143 }
1144
1145 impl RenderBackend for StubBackend {
1146 fn window_closed(&mut self) -> bool {
1147 false
1148 }
1149 fn capture_cursor(&mut self) {}
1150 fn take_input(&mut self) -> RenderInput {
1151 RenderInput::default()
1152 }
1153 fn wait_idle(&self) {}
1154 fn draw_frame(&mut self, _params: FrameParams<'_>) -> RenderResult<()> {
1155 Ok(())
1156 }
1157 fn update_view(&mut self, _matrix: [[f32; 4]; 4]) {}
1158 fn update_models(&mut self, _updates: &[(u32, [[f32; 4]; 4])]) {}
1159 fn retire_draw_object(&mut self, _draw_idx: usize) {}
1160 fn upload_skinned(
1161 &mut self,
1162 _vertices: &[SkinnedVertex],
1163 _indices: &[u32],
1164 _draw_objects: Vec<SkinnedDrawObject>,
1165 _vert_bytes: &[u8],
1166 _frag_bytes: &[u8],
1167 _shadow_bytes: &[u8],
1168 ) -> RenderResult<()> {
1169 Ok(())
1170 }
1171 fn update_skinned_pose(&mut self, _skinned_index: usize, _matrices: &[[[f32; 4]; 4]]) {}
1172 fn evict_texture_slot(&mut self, _slot: usize) -> Result<(), String> {
1173 Ok(())
1174 }
1175 fn update_texture_slot(
1176 &mut self,
1177 _slot: usize,
1178 _image: &crate::build::texture::TextureImage,
1179 ) -> RenderResult<()> {
1180 Ok(())
1181 }
1182 fn evict_mesh(&mut self, _draw_idx: usize, _retire_frame: u64) -> Result<(), String> {
1183 Ok(())
1184 }
1185 fn upload_mesh(
1186 &mut self,
1187 _draw_idx: usize,
1188 _verts: &[Vertex],
1189 _idxs: &[u16],
1190 _frame: u64,
1191 ) -> RenderResult<()> {
1192 Ok(())
1193 }
1194 fn setup_chunk_streaming(
1195 &mut self,
1196 _chunk_vtx_bytes: usize,
1197 _chunk_idx_bytes: usize,
1198 _texture_slot: usize,
1199 _normal_map_slot: usize,
1200 ) -> RenderResult<()> {
1201 Ok(())
1202 }
1203 fn add_chunk_mesh(
1204 &mut self,
1205 _mesh: ChunkMesh<'_>,
1206 _dst: crate::render::draw_slot::SlotAlloc,
1207 ) -> RenderResult<()> {
1208 Ok(())
1209 }
1210 fn remove_chunk_mesh(
1211 &mut self,
1212 _draw_idx: usize,
1213 _retire_frame: u64,
1214 ) -> Result<(), String> {
1215 Ok(())
1216 }
1217 fn set_chunk_model(
1218 &mut self,
1219 _draw_idx: usize,
1220 _model: [[f32; 4]; 4],
1221 ) -> Result<(), String> {
1222 Ok(())
1223 }
1224 }
1225}
1226
1227#[cfg(test)]
1228mod tests {
1229 use super::*;
1230
1231 use alloc::vec;
1232 const GB: u64 = 1 << 30;
1233
1234 fn input(
1235 vendor: GpuVendor,
1236 memory_budget_bytes: u64,
1237 discrete: bool,
1238 apple_family: u8,
1239 ) -> GpuClassInput {
1240 GpuClassInput {
1241 vendor,
1242 memory_budget_bytes,
1243 discrete,
1244 apple_family,
1245 }
1246 }
1247
1248 #[test]
1249 fn unknown_profile_is_the_conservative_default() {
1250 // The opposite default from capabilities: quality auto-config fails safe.
1251 let p = GpuProfile::default();
1252 assert_eq!(p.tier, GpuTier::Unknown);
1253 assert_eq!(p.vendor, GpuVendor::Other);
1254 assert_eq!(p.memory_budget_bytes, 0);
1255 // Unknown sorts below every real tier, so a `>=` resolver treats it as
1256 // the floor.
1257 assert!(GpuTier::Unknown < GpuTier::Integrated);
1258 assert!(GpuTier::Integrated < GpuTier::EntryDiscrete);
1259 assert!(GpuTier::EntryDiscrete < GpuTier::MidDiscrete);
1260 assert!(GpuTier::MidDiscrete < GpuTier::HighDiscrete);
1261 }
1262
1263 #[test]
1264 fn apple_family_reads_the_generation_out_of_the_device_name() {
1265 // The names MoltenVK reports, mapped onto Metal's family ranks.
1266 assert_eq!(apple_family_from_device_name("Apple M1"), 7);
1267 assert_eq!(apple_family_from_device_name("Apple M2 Max"), 8);
1268 assert_eq!(apple_family_from_device_name("Apple M3 Pro"), 9);
1269 assert_eq!(apple_family_from_device_name("Apple M4 Ultra"), 10);
1270 // A generation past what Metal's SDK names yet still ranks above M3, so
1271 // a newer Mac is not demoted.
1272 assert!(apple_family_from_device_name("Apple M9") > 9);
1273 }
1274
1275 #[test]
1276 fn non_apple_device_names_report_no_family() {
1277 for name in [
1278 "NVIDIA GeForce RTX 4090",
1279 "AMD Radeon RX 7900 XTX",
1280 "Intel(R) Arc(tm) A770",
1281 // Apple's own non-M naming, and a truncated / malformed report.
1282 "Apple A17 Pro",
1283 "Apple M",
1284 "Apple MX",
1285 "",
1286 ] {
1287 assert_eq!(apple_family_from_device_name(name), 0, "{name}");
1288 }
1289 }
1290
1291 #[test]
1292 fn apple_family_from_a_name_reaches_the_same_tier_metal_does() {
1293 // The whole point of the name probe: a MoltenVK build must land on the
1294 // tier the Metal backend reports for the same silicon, not on the
1295 // integrated floor a zero family falls through to.
1296 let family = apple_family_from_device_name("Apple M2 Max");
1297 assert_eq!(
1298 classify_tier(&input(GpuVendor::Apple, 32 * GB, false, family)),
1299 GpuTier::MidDiscrete
1300 );
1301 assert_eq!(
1302 classify_tier(&input(GpuVendor::Apple, 32 * GB, false, 0)),
1303 GpuTier::Integrated
1304 );
1305 }
1306
1307 #[test]
1308 fn apple_silicon_classifies_by_generation() {
1309 // Unified memory is large on Apple silicon, but the family generation
1310 // (not the working-set) decides the tier, so the huge shared budget does
1311 // not read as a high-VRAM discrete card.
1312 assert_eq!(
1313 classify_tier(&input(GpuVendor::Apple, 16 * GB, false, 7)),
1314 GpuTier::EntryDiscrete // M1
1315 );
1316 assert_eq!(
1317 classify_tier(&input(GpuVendor::Apple, 24 * GB, false, 8)),
1318 GpuTier::MidDiscrete // M2
1319 );
1320 assert_eq!(
1321 classify_tier(&input(GpuVendor::Apple, 48 * GB, false, 9)),
1322 GpuTier::HighDiscrete // M3
1323 );
1324 assert_eq!(
1325 classify_tier(&input(GpuVendor::Apple, 64 * GB, false, 10)),
1326 GpuTier::HighDiscrete // M4 and newer cap at high
1327 );
1328 }
1329
1330 #[test]
1331 fn discrete_gpu_classifies_by_vram() {
1332 // An Intel-Mac AMD dGPU or a PC discrete card: vendor is not Apple and
1333 // there is no Apple family, so VRAM buckets the tier.
1334 assert_eq!(
1335 classify_tier(&input(GpuVendor::Nvidia, 24 * GB, true, 0)),
1336 GpuTier::HighDiscrete
1337 );
1338 assert_eq!(
1339 classify_tier(&input(GpuVendor::Amd, 8 * GB, true, 0)),
1340 GpuTier::MidDiscrete
1341 );
1342 assert_eq!(
1343 classify_tier(&input(GpuVendor::Nvidia, 4 * GB, true, 0)),
1344 GpuTier::EntryDiscrete
1345 );
1346 // A discrete card that reports no memory budget is left Unknown rather
1347 // than guessed high.
1348 assert_eq!(
1349 classify_tier(&input(GpuVendor::Amd, 0, true, 0)),
1350 GpuTier::Unknown
1351 );
1352 }
1353
1354 #[test]
1355 fn integrated_gpu_is_the_lowest_tier() {
1356 // Non-Apple integrated part: no dedicated memory, not unified, no Apple
1357 // family.
1358 assert_eq!(
1359 classify_tier(&input(GpuVendor::Intel, 0, false, 0)),
1360 GpuTier::Integrated
1361 );
1362 }
1363
1364 #[test]
1365 fn vram_bucket_boundaries() {
1366 // Boundaries are inclusive lower bounds (>= 12 GB high, >= 6 GB mid).
1367 assert_eq!(
1368 classify_tier(&input(GpuVendor::Nvidia, 12 * GB, true, 0)),
1369 GpuTier::HighDiscrete
1370 );
1371 assert_eq!(
1372 classify_tier(&input(GpuVendor::Nvidia, 12 * GB - 1, true, 0)),
1373 GpuTier::MidDiscrete
1374 );
1375 assert_eq!(
1376 classify_tier(&input(GpuVendor::Nvidia, 6 * GB, true, 0)),
1377 GpuTier::MidDiscrete
1378 );
1379 assert_eq!(
1380 classify_tier(&input(GpuVendor::Nvidia, 6 * GB - 1, true, 0)),
1381 GpuTier::EntryDiscrete
1382 );
1383 }
1384
1385 pub(crate) use super::test_stub::StubBackend;
1386
1387 const IDENTITY: [[f32; 4]; 4] = [
1388 [1.0, 0.0, 0.0, 0.0],
1389 [0.0, 1.0, 0.0, 0.0],
1390 [0.0, 0.0, 1.0, 0.0],
1391 [0.0, 0.0, 0.0, 1.0],
1392 ];
1393
1394 // Minimal QualitySettings with every feature off, so no *Settings sub-type
1395 // needs constructing.
1396 fn stub_quality() -> QualitySettings {
1397 QualitySettings {
1398 taa: false,
1399 ssao: None,
1400 ssr: None,
1401 rt_reflections: None,
1402 ssgi: None,
1403 reflection_blur_scale: 1,
1404 auto_exposure: None,
1405 auto_exposure_bias_ev: 0.0,
1406 }
1407 }
1408
1409 #[test]
1410 fn default_query_methods_report_conservative_values() {
1411 let backend = StubBackend;
1412 // Capabilities fail open: a backend that does not report keeps every
1413 // toggle live.
1414 assert!(backend.capabilities().ray_tracing);
1415 // Quality auto-config fails safe: the unknown/conservative profile.
1416 assert_eq!(backend.gpu_profile().tier, GpuTier::Unknown);
1417 assert_eq!(backend.gpu_profile().vendor, GpuVendor::Other);
1418 assert_eq!(backend.gpu_profile().memory_budget_bytes, 0);
1419 // Diagnostics a backend may leave to the default: zeroed here.
1420 assert_eq!(backend.logical_size(), (0.0, 0.0));
1421 assert_eq!(backend.render_stats(), RenderStats::default());
1422 // No window-bounds tracking: the in-engine cursor always draws.
1423 assert!(!backend.cursor_outside_window());
1424 // No display enumeration and no hot-reload flag wired.
1425 assert!(backend.display_modes().is_empty());
1426 assert!(backend.current_display_mode().is_none());
1427 assert!(backend.shader_reload_flag().is_none());
1428 // Not hot-swap-capable: a live world reload routes to a full rebuild.
1429 assert!(backend.hot_swap_config().is_none());
1430 // No geometry-size introspection for the reload size check.
1431 assert!(backend.draw_geometry_size(0).is_none());
1432 assert!(backend.draw_lod_index_counts(0).is_none());
1433 }
1434
1435 #[test]
1436 fn default_mutators_are_noops_and_fallible_hooks_report_defaults() {
1437 let mut backend = StubBackend;
1438
1439 // Runtime skinned-spawn fallbacks: nothing to reveal or hide.
1440 backend.reveal_skinned_instance(0, IDENTITY);
1441 backend.retire_skinned_draw_object(0);
1442 backend.update_skinned_models(&[(0, IDENTITY)]);
1443
1444 // Streaming + cursor + capture no-ops.
1445 backend.seed_mesh_streaming(0, 0, 0, 0);
1446 backend.set_ui_cursor_hidden(true);
1447 backend.set_menu_mode(true);
1448 backend.set_camera_capture(true);
1449 backend.set_reflection_probes(&[]);
1450
1451 // Presentation + window no-ops.
1452 backend.set_vsync(true);
1453 backend.set_window_mode(crate::components::WindowMode::Fullscreen);
1454 backend.set_window_size(1280, 720);
1455 backend.set_display_mode(crate::render::display_mode::DisplayMode {
1456 width: 1920,
1457 height: 1080,
1458 refresh_hz: 60,
1459 });
1460
1461 // Live look + input tunable no-ops.
1462 backend.update_post_process(PostProcessTunables::DEFAULT);
1463 backend.set_ambient_intensity(1.0);
1464 backend.set_keymap(&KeyMap::default());
1465 backend.apply_quality_settings(stub_quality());
1466 backend.update_quality_params(stub_quality());
1467 backend.set_shadow_update(crate::components::ShadowUpdate::EveryFrame);
1468 backend.set_shadow_distance(200);
1469 backend.set_shadow_cascades(3);
1470 backend.update_fog_settings(None);
1471 backend.update_directional_lights(&[]);
1472 backend.set_draw_material(0, MaterialUniforms::DEFAULT, 0, 0);
1473 backend.set_draw_cull_distance(0, 50.0);
1474
1475 // Fallible hot-reload hooks that succeed by default (no-op Ok).
1476 assert!(backend.update_color_lut(2, &[0u8; 32]).is_ok());
1477 assert!(backend.rebuild_static_geometry(vec![]).is_ok());
1478 assert!(backend.update_skinned_mesh_geometry(0, 0, &[], &[]).is_ok());
1479 assert!(backend.rebuild_skinned_geometry(vec![]).unwrap().is_empty());
1480 assert!(backend.update_skinned_skeleton(0, 0).is_ok());
1481 assert!(backend.update_mesh_geometry(0, &[], &[], &[]).is_ok());
1482 assert!(backend.update_environment_map(&[]).is_ok());
1483
1484 // Fallible hooks a bare backend does not implement: they report Err.
1485 assert!(backend.screenshot("unused.png").is_err());
1486 assert!(
1487 backend
1488 .clone_static_draw_object(
1489 0,
1490 IDENTITY,
1491 crate::render::draw_slot::SlotAlloc::Append(0)
1492 )
1493 .is_err()
1494 );
1495 assert!(backend.add_decal(stub_decal()).is_err());
1496 assert!(backend.remove_decal(0).is_err());
1497 assert!(backend.add_emitter(stub_emitter()).is_err());
1498 assert!(backend.remove_emitter(0).is_err());
1499 assert!(
1500 backend
1501 .update_world_shader_pipelines(None, None, None, None)
1502 .is_err()
1503 );
1504 }
1505
1506 // A minimal empty-world BackendInit borrowing `window`, for exercising the
1507 // default `reload_world`. Empty slices are `'static`; the only real borrow
1508 // is the window args.
1509 fn empty_backend_init(window: &crate::components::Window) -> BackendInit<'_> {
1510 BackendInit::minimal(window, alloc::vec::Vec::new())
1511 }
1512
1513 #[test]
1514 fn default_reload_world_is_unsupported() {
1515 // A backend without a real reload path reports the swap unsupported, so
1516 // the caller falls back to a full rebuild.
1517 let mut backend = StubBackend;
1518 let window = crate::components::Window::default();
1519 assert!(backend.reload_world(empty_backend_init(&window)).is_err());
1520 }
1521
1522 fn stub_decal() -> crate::render::decal::DecalRecord {
1523 crate::render::decal::DecalRecord {
1524 model: IDENTITY,
1525 inv_model: IDENTITY,
1526 texture_slot: 0,
1527 tint: [1.0; 4],
1528 }
1529 }
1530
1531 fn stub_emitter() -> crate::render::particles::ParticleEmitterRecord {
1532 crate::render::particles::ParticleEmitterRecord {
1533 texture_slot: 0,
1534 position: [0.0; 3],
1535 direction: [0.0, 1.0, 0.0],
1536 spread_cos: 1.0,
1537 speed_min: 0.0,
1538 speed_max: 1.0,
1539 lifetime_min: 0.0,
1540 lifetime_max: 1.0,
1541 gravity: [0.0, -9.8, 0.0],
1542 spawn_rate: 1.0,
1543 max_particles: 1,
1544 size_start: 1.0,
1545 size_end: 1.0,
1546 color_start: [1.0; 4],
1547 color_end: [1.0; 4],
1548 }
1549 }
1550}