concinnity_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::auto_exposure::AutoExposureSettings;
21use crate::backend_init::{BackendInit, ShaderBytes, SwapchainConfig};
22use crate::error::{RenderError, RenderResult};
23use crate::input::RenderInput;
24use crate::keymap::KeyMap;
25use crate::mesh_payload::{SkinnedVertex, Vertex};
26use crate::profile::RenderStats;
27use crate::render_types::{
28 LineVertex, MaterialUniforms, PostProcessTunables, SkinnedDrawObject, TextDrawCall,
29};
30use crate::rt_reflections::RtReflectionSettings;
31use crate::scene_flow::SceneControl;
32use crate::ssao::SsaoSettings;
33use crate::ssgi::SsgiSettings;
34use crate::ssr::SsrSettings;
35use crate::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: concinnity_core::gfx::view_modes::ViewMode,
68 /// Feature passes to run this frame.
69 pub show: concinnity_core::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::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::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(&mut self, probes: &[crate::reflection_probe::ProbePlacement]) {
614 let _ = probes;
615 }
616
617 /// Turn display sync (vsync) on or off at runtime, applied to presentation.
618 /// Edge-triggered by the backend, so calling it with the unchanged value is
619 /// cheap. Default no-op: a backend that only honors vsync at init ignores
620 /// runtime changes.
621 fn set_vsync(&mut self, on: bool) {
622 let _ = on;
623 }
624
625 /// Switch the window between windowed / borderless / fullscreen at runtime.
626 /// The change flows through the backend's normal resize path (no GPU rebuild
627 /// beyond the resize it triggers). Default no-op for backends without a
628 /// window (embedded / preview) or that don't yet implement it.
629 fn set_window_mode(&mut self, mode: crate::components::WindowMode) {
630 let _ = mode;
631 }
632
633 /// Resize the window's content area at runtime (meaningful in windowed mode).
634 /// Drives the same resize path as a user-dragged resize. Default no-op for
635 /// backends without a window or that don't yet implement it.
636 fn set_window_size(&mut self, width: u32, height: u32) {
637 let _ = (width, height);
638 }
639
640 /// The display modes (pixel resolution + refresh rate) the display this
641 /// backend renders to supports, unshaped (the caller dedups + sorts).
642 /// Default empty: a backend that cannot enumerate (or has no window) makes
643 /// the Resolution row fall back to the static preset list.
644 fn display_modes(&self) -> Vec<crate::display_mode::DisplayMode> {
645 Vec::new()
646 }
647
648 /// The mode the display is currently running, if the backend can read it.
649 /// Shown by the Resolution row when the user has never chosen a mode (the
650 /// display keeps its desktop mode until one is chosen). Default `None`.
651 fn current_display_mode(&self) -> Option<crate::display_mode::DisplayMode> {
652 None
653 }
654
655 /// Select the display mode to hold while the window is in fullscreen. The
656 /// backend applies it whenever the window is (or becomes) fullscreen and
657 /// restores the display's original mode when the window leaves fullscreen
658 /// or shuts down; outside fullscreen the choice is only remembered. Default
659 /// no-op: a backend without mode switching leaves the display alone.
660 fn set_display_mode(&mut self, mode: crate::display_mode::DisplayMode) {
661 let _ = mode;
662 }
663
664 /// Replace the live post-process tunables (bloom / exposure / vignette /
665 /// LUT blend / FXAA). These are pushed to the bloom + composite shaders each
666 /// frame, so a change takes effect on the next draw with no allocation or
667 /// pipeline rebuild. Only the authored half travels here: the composite's
668 /// display-output flags belong to the display the backend negotiated with
669 /// at init, so a push cannot disturb them. Default no-op: a backend that
670 /// only reads the tunables at init ignores runtime changes.
671 fn update_post_process(&mut self, tunables: PostProcessTunables) {
672 let _ = tunables;
673 }
674
675 /// Set the live ambient (IBL) light scale. Unlike the post-process params
676 /// above, `ambient_intensity` lives in the shared `LightUniforms` (uploaded
677 /// each frame by the main lighting pass), so it takes its own setter rather
678 /// than `update_post_process`. Default no-op: only Metal mutates it live
679 /// today; DirectX / Vulkan keep the init-time value (they read it at init).
680 fn set_ambient_intensity(&mut self, value: f32) {
681 let _ = value;
682 }
683
684 /// Replace the live directional-light set (the sun). Unlike the local
685 /// lights, which ride a per-scene storage buffer sized once at init, the
686 /// directional slots are a fixed-size array in the shared `LightUniforms`,
687 /// so a new set is written in place: the backend re-packs the array and
688 /// re-caches whatever it derived from the first light at init (the cascade
689 /// shadow direction, the fog sun). Default no-op: a backend that only reads
690 /// the lights at init keeps the init-time sun.
691 fn update_directional_lights(&mut self, lights: &[crate::components::DirectionalLight]) {
692 let _ = lights;
693 }
694
695 /// Push the gameplay movement key map. The backend resolves each canonical
696 /// `InputKey` to its native key code and decodes physical key events through the
697 /// map (instead of hardcoded keys), so a settings-menu rebind takes effect on
698 /// the next key event. Pushed once after the backend is built and again on
699 /// each rebind. Default no-op: a backend without keymap decode keeps its
700 /// built-in defaults.
701 fn set_keymap(&mut self, keymap: &KeyMap) {
702 let _ = keymap;
703 }
704
705 /// Apply a change to the quality-feature toggles (TAA / SSAO / SSR / RT
706 /// reflections / SSGI / auto-exposure) live. Unlike the post-process params,
707 /// these gate render passes whose GPU resources (pipelines, render targets,
708 /// ray-tracing acceleration structures) are built once at init, so applying a
709 /// change rebuilds the affected resources in place rather than flipping a
710 /// uniform. Default no-op: a backend that only reads these at init ignores
711 /// runtime changes (DirectX / Vulkan today), so the choice persists and takes
712 /// effect at the next launch there.
713 fn apply_quality_settings(&mut self, settings: QualitySettings) {
714 let _ = settings;
715 }
716
717 /// Set the shadow cascade re-render cadence live. The cascade scheduler reads
718 /// the policy at the start of each shadow pass, so a change takes effect on the
719 /// next draw with no pipeline rebuild or allocation (unlike the shadow map
720 /// resolution, which is sized once at init). Default no-op: a backend that only
721 /// reads the cadence at init keeps the init-time value (DirectX / Vulkan
722 /// today), so the choice persists and takes effect at the next launch there.
723 fn set_shadow_update(&mut self, update: crate::components::ShadowUpdate) {
724 let _ = update;
725 }
726
727 /// Set the shadow distance (world units the cascades cover, capped at the
728 /// camera far plane) live. The per-frame cascade-split computation reads it
729 /// each draw, so a change takes effect on the next frame with no allocation or
730 /// rebuild (it sizes no GPU resource, unlike the shadow map resolution).
731 /// Default no-op: a backend that only reads the distance at init keeps the
732 /// init-time value (DirectX / Vulkan today), so the choice persists and takes
733 /// effect at the next launch there.
734 fn set_shadow_distance(&mut self, distance: u32) {
735 let _ = distance;
736 }
737
738 /// Set the live shadow cascade count (1..=4). The cascade-split math + the
739 /// re-render schedule read it each frame and only the first `count` cascades
740 /// are projected, rendered, and sampled (the array capacity stays 4), so a
741 /// change takes effect on the next frame with no resize or rebuild. Default
742 /// no-op: a backend that only reads the count at init keeps the init-time
743 /// value (DirectX / Vulkan today), so the choice persists and takes effect at
744 /// the next launch there.
745 fn set_shadow_cascades(&mut self, count: u32) {
746 let _ = count;
747 }
748
749 /// Update the live scalar sub-tunables of the SSAO / SSR / SSGI / auto-exposure
750 /// passes (radius, intensity, distance, EV bounds, adaptation speed). Unlike
751 /// `apply_quality_settings`, this rebuilds nothing: each backend re-reads these
752 /// values from its stored `*Settings` structs into a per-frame uniform every
753 /// draw, so mutating them takes effect on the next frame with no pipeline /
754 /// target rebuild and no TAA-history reset. Only the fields of a feature that is
755 /// currently on are honoured (its settings are present); a value for an off
756 /// feature is ignored here and applies when the feature next turns on. The
757 /// structural sub-knobs (gather resolution, ray / step counts) are NOT live and
758 /// still ride `apply_quality_settings`. Default no-op: a backend that reads
759 /// these only at init keeps the init-time values (DirectX / Vulkan today), so
760 /// the choice persists and takes effect at the next launch there.
761 fn update_quality_params(&mut self, settings: QualitySettings) {
762 let _ = settings;
763 }
764
765 /// Shared atomic flag the backend polls at frame start to trigger a
766 /// shader rebuild. `Some` only under `cn debug` on backends that ship
767 /// hot-reload (Metal today); `None` on production runs and on backends
768 /// that have not implemented hot-reload yet. The debug server reads this
769 /// to forward `reload-shaders` commands; the filesystem watcher writes
770 /// it directly. Default: `None`.
771 fn shader_reload_flag(&self) -> Option<alloc::sync::Arc<core::sync::atomic::AtomicBool>> {
772 None
773 }
774
775 /// Replace the live colour-grading LUT with a fresh `size³` RGBA8 payload.
776 /// Driven by asset hot-reload (`cn debug` only). Default no-op: backends
777 /// that have not implemented the swap leave the LUT bound at whatever
778 /// payload was uploaded at init.
779 fn update_color_lut(&mut self, size: u32, data: &[u8]) -> Result<(), String> {
780 let _ = (size, data);
781 Ok(())
782 }
783
784 /// `(vertex_count, index_count)` for the static draw at `draw_idx`, or
785 /// `None` when the index is out of range / the backend does not expose
786 /// the field. Used by asset hot-reload to detect size-changing
787 /// reloads before attempting [`Self::update_mesh_geometry`], which
788 /// rejects size mismatches. Default returns `None`; backends that
789 /// implement the rebuild path also override this.
790 fn draw_geometry_size(&self, draw_idx: usize) -> Option<(usize, usize)> {
791 let _ = draw_idx;
792 None
793 }
794
795 /// Per-LOD-alternate index counts for the static draw at `draw_idx`,
796 /// ordered from LOD1 upward (LOD0 is reported by
797 /// [`Self::draw_geometry_size`]). Returns `None` when the index is out of
798 /// range or the backend does not expose its LOD layout. Used by asset
799 /// hot-reload alongside [`Self::draw_geometry_size`] to detect
800 /// size-changing reloads: a `.glb` that re-exports with a different LOD
801 /// breakdown queues the entry for [`Self::rebuild_static_geometry`]
802 /// instead of [`Self::update_mesh_geometry`]'s in-place write.
803 fn draw_lod_index_counts(&self, draw_idx: usize) -> Option<Vec<usize>> {
804 let _ = draw_idx;
805 None
806 }
807
808 /// Rebuild the shared static-mesh vertex + index buffers, replacing the
809 /// geometry of each `DrawGeometryUpdate.draw_idx` with the new
810 /// vertices / indices / LOD alternates. Draws not named in `changes`
811 /// keep their current geometry, copied byte-for-byte from the live
812 /// buffers. The slot's `vertex_count`, `index_count`, and
813 /// `lod_alternates` index offsets are rewritten as the new buffers are
814 /// laid out. Driven by asset hot-reload (`cn debug` only) when a
815 /// size-changing `.glb` re-export means the existing
816 /// [`Self::update_mesh_geometry`] in-place write no longer fits.
817 /// `wait_idle` first; the rebuild swaps the GPU buffers wholesale.
818 /// Default no-op: backends that have not implemented the rebuild
819 /// return `Ok(())` and the size-changing reload is logged + skipped at
820 /// the caller (the existing in-place path already errored on size
821 /// mismatch).
822 fn rebuild_static_geometry(&mut self, changes: Vec<DrawGeometryUpdate>) -> RenderResult<()> {
823 let _ = changes;
824 Ok(())
825 }
826
827 /// Replace a `SkinnedMesh` draw slot's vertex + index data in place.
828 /// Driven by asset hot-reload (`cn debug` only). Reuses the slot's
829 /// existing vertex region + index region in the shared skinned vertex /
830 /// index buffers (created once by [`Self::upload_skinned`]), so the new
831 /// geometry must match the slot's init-time vertex count + index count
832 /// and the new skeleton must keep the same joint count; pipelines stay
833 /// untouched, only the bytes change. `vertex_base` is the init-time
834 /// vertex offset (in vertex units) into the shared buffer; indices are
835 /// rebased onto it before writing. Default no-op.
836 fn update_skinned_mesh_geometry(
837 &mut self,
838 skinned_index: usize,
839 vertex_base: u32,
840 verts: &[SkinnedVertex],
841 idxs: &[u16],
842 ) -> Result<(), String> {
843 let _ = (skinned_index, vertex_base, verts, idxs);
844 Ok(())
845 }
846
847 /// Rebuild the shared skinned-mesh vertex + index buffers, replacing the
848 /// geometry of each `SkinnedDrawGeometryUpdate.skinned_index` with the
849 /// new vertices / indices. Slots not named in `changes` keep their
850 /// current geometry, copied byte-for-byte from the live buffers and
851 /// re-based onto the new vertex region they land in. Returns the
852 /// post-rebuild layout (one [`SkinnedSlotLayout`] per slot, in
853 /// `skinned_index` order) so the caller can refresh its source-map
854 /// `vertex_base` / `vertex_count` / `index_count` to point at the new
855 /// regions. Driven by asset hot-reload (`cn debug` only) when a
856 /// size-changing `.glb` re-export means the existing
857 /// [`Self::update_skinned_mesh_geometry`] in-place write no longer fits.
858 /// The backend `wait_idle`s first; the rebuild swaps the GPU buffers
859 /// wholesale. The skinned pipelines, shadow + velocity + SSAO + SSR
860 /// variants, and `skinned_draw_objects` slot metadata
861 /// (`texture_slot` / `normal_map_slot` / `material` / `joint_count`)
862 /// all stay untouched; only the `index_offset` / `index_count` on each
863 /// `SkinnedDrawObject` (and the buffers themselves) move. Default no-op
864 /// (returns an empty layout vec): backends that have not implemented
865 /// the rebuild leave the size-changing reload as logged + skipped at
866 /// the caller, the same behaviour as before, since the in-place path
867 /// already errored on size mismatch.
868 fn rebuild_skinned_geometry(
869 &mut self,
870 changes: Vec<SkinnedDrawGeometryUpdate>,
871 ) -> Result<Vec<SkinnedSlotLayout>, String> {
872 let _ = changes;
873 Ok(Vec::new())
874 }
875
876 /// Update a skinned slot's joint count and resize the backend's per-slot
877 /// joint-matrix buffers to match. Driven by asset hot-reload (`cn debug`
878 /// only) when a re-imported `.glb`'s skeleton has a different joint
879 /// count than the slot was initialised with. Shrinking truncates the
880 /// per-slot Vec; growing seeds the new entries to identity so the slot
881 /// renders undeformed on the next `update_skinned_pose`. The skinned
882 /// shaders consume the joints buffer through a pointer (not a fixed-
883 /// size array) and use vertex-attribute-encoded joint indices, so no
884 /// pipeline or shader rebuild is required for a joint-count change;
885 /// only the CPU-side per-slot buffer and `SkinnedDrawObject.joint_count`
886 /// change. Default no-op: backends that have not implemented the resize
887 /// leave the skeleton-shape change logged + skipped at the caller.
888 fn update_skinned_skeleton(
889 &mut self,
890 skinned_index: usize,
891 new_joint_count: usize,
892 ) -> Result<(), String> {
893 let _ = (skinned_index, new_joint_count);
894 Ok(())
895 }
896
897 /// Replace a `Mesh` draw slot's vertex + index data in place. Driven by
898 /// asset hot-reload (`cn debug` only). Reuses the slot's existing offset
899 /// in the shared vertex / index buffers, so the new geometry must match
900 /// the slot's init-time vertex count + index count; a size-changing
901 /// reload returns an error so the caller can queue
902 /// [`Self::rebuild_static_geometry`] instead, which repacks the shared
903 /// buffers. Each entry in
904 /// `lod_alternates` (`(switch_distance, mesh-relative indices)`) is
905 /// written to the matching slot's pre-allocated LOD index region; the
906 /// number of LODs and each LOD's index count must match the slot's
907 /// init-time layout, otherwise the call returns an error so the caller
908 /// can queue [`Self::rebuild_static_geometry`]. `switch_distance` is
909 /// re-stored per LOD so a JSON-side tweak to `lod_distances` propagates
910 /// without a process restart. Default no-op.
911 fn update_mesh_geometry(
912 &mut self,
913 draw_idx: usize,
914 verts: &[Vertex],
915 idxs: &[u16],
916 lod_alternates: &[(f32, Vec<u16>)],
917 ) -> Result<(), String> {
918 let _ = (draw_idx, verts, idxs, lod_alternates);
919 Ok(())
920 }
921
922 /// Replace the live IBL environment map with a freshly precomputed payload.
923 /// `payload` is the serialised byte format emitted by
924 /// `concinnity_core::build::environment_map::compile_environment_map_payload`
925 /// (header + irradiance cube + prefilter mip chain), so init and hot-reload
926 /// share a single byte format. Driven by asset hot-reload (`cn debug`
927 /// only). Default no-op: backends that have not implemented the swap leave
928 /// the IBL cubes bound at whatever payload was uploaded at init.
929 fn update_environment_map(&mut self, payload: &[u8]) -> RenderResult<()> {
930 let _ = payload;
931 Ok(())
932 }
933
934 /// Replace the live volumetric-fog settings, or disable the fog pass when
935 /// `None`. Driven by world.jsonl hot-reload (`cn debug` only). Default
936 /// no-op: backends that have not implemented the swap leave the fog pass
937 /// at whatever settings were resolved at init.
938 ///
939 /// A backend that built its fog pipeline lazily based on the world's
940 /// init-time `VolumetricFog` cannot enable the pass via this call when
941 /// the world started with no fog declared; re-enabling fog on a world
942 /// that did not declare it at startup requires a relaunch.
943 fn update_fog_settings(&mut self, settings: Option<FogSettings>) {
944 let _ = settings;
945 }
946
947 /// Capture the last presented frame to a PNG at `path` and return the saved
948 /// path. Driven by the `cn debug` WS `screenshot` command for headless
949 /// on-GPU render verification. Default `Err`: a backend without a capture
950 /// path reports it unsupported (all current backends override this).
951 fn screenshot(&mut self, path: &str) -> Result<String, String> {
952 let _ = path;
953 Err("screenshot capture not supported on this backend".to_string())
954 }
955
956 /// Instantiate a runtime copy of an existing draw object at a new transform:
957 /// re-use the source slot's geometry region (`vertex_offset` / `vertex_count`
958 /// / `index_offset` / `index_count` / `base_vertex` / `lod_alternates`) and
959 /// copy its texture slots, material, and cull distance, swapping only the
960 /// model matrix. The new slot reuses one freed by `retire_draw_object` before
961 /// growing the draw-object vec. The destination slot comes from the
962 /// engine's draw-slot allocator: `Reuse` overwrites a vacated entry,
963 /// `Append` grows the vec (the index always equals the current length,
964 /// which implementations debug-assert). Driven by runtime entity spawn
965 /// (`SpawnRequest`). The copy is non-cullable (sentinel AABB) and drawn
966 /// every frame, since the init-time BVH cannot refit to admit a slot added
967 /// at runtime; moving copies (the common case) opt out of the static BVH
968 /// exactly like streamed chunks and held items. Default no-op (returns
969 /// `Err`): backends without an implementation leave the spawn path
970 /// logged + skipped at the caller.
971 fn clone_static_draw_object(
972 &mut self,
973 src_draw_idx: usize,
974 model: [[f32; 4]; 4],
975 dst: crate::draw_slot::SlotAlloc,
976 ) -> Result<(), String> {
977 let _ = (src_draw_idx, model, dst);
978 Err("clone_static_draw_object: not implemented on this backend".to_string())
979 }
980
981 /// Rewrite a draw slot's material parameters + texture/normal-map pool
982 /// indices in place. Driven by the editor's live draw seam when a Prop edits
983 /// its `material` arg. Default no-op; a backend that implements it reports
984 /// [`DeviceCapabilities::rewrites_draws`], which is what the caller gates on
985 /// rather than pushing an edit that would not land.
986 fn set_draw_material(
987 &mut self,
988 draw_idx: usize,
989 material: MaterialUniforms,
990 texture_slot: usize,
991 normal_map_slot: usize,
992 ) {
993 let _ = (draw_idx, material, texture_slot, normal_map_slot);
994 }
995
996 /// Rewrite a draw slot's `cull_distance` in place. Driven by the editor's
997 /// live draw seam when a Prop edits its `cull_distance` arg. Default no-op,
998 /// gated by the same [`DeviceCapabilities::rewrites_draws`] flag.
999 fn set_draw_cull_distance(&mut self, draw_idx: usize, cull_distance: f32) {
1000 let _ = (draw_idx, cull_distance);
1001 }
1002
1003 /// Append a projected-decal record at runtime, returning a stable slot
1004 /// index the caller hands to [`Self::remove_decal`] later. Lets a
1005 /// gameplay system stamp bullet holes, footprints, or other ad-hoc
1006 /// decals after the world has built. Backends that have not implemented
1007 /// the runtime path return `Err`; the caller logs and drops the request.
1008 fn add_decal(&mut self, record: crate::decal::DecalRecord) -> Result<usize, String> {
1009 let _ = record;
1010 Err("add_decal: not implemented on this backend".to_string())
1011 }
1012
1013 /// Tombstone a runtime decal slot. The id returned by
1014 /// [`Self::add_decal`] becomes invalid; the next add may reuse it.
1015 /// Default no-op-with-Err: backends without a runtime path leave the
1016 /// remove logged + skipped at the caller.
1017 fn remove_decal(&mut self, decal_id: usize) -> Result<(), String> {
1018 let _ = decal_id;
1019 Err("remove_decal: not implemented on this backend".to_string())
1020 }
1021
1022 /// Append a particle-emitter record at runtime, returning a stable slot
1023 /// index. The backend allocates the per-emitter GPU pool + atomic
1024 /// spawn counter (matching the init-time path) so the compute kernel
1025 /// can begin ticking on the next frame. Default no-op-with-Err.
1026 fn add_emitter(
1027 &mut self,
1028 record: crate::particles::ParticleEmitterRecord,
1029 ) -> Result<usize, String> {
1030 let _ = record;
1031 Err("add_emitter: not implemented on this backend".to_string())
1032 }
1033
1034 /// Tombstone a runtime emitter slot and release its GPU pool +
1035 /// counter buffers (the GPU keeps them alive via its own refcount
1036 /// until any in-flight command buffer that referenced them completes).
1037 /// Default no-op-with-Err.
1038 fn remove_emitter(&mut self, emitter_id: usize) -> Result<(), String> {
1039 let _ = emitter_id;
1040 Err("remove_emitter: not implemented on this backend".to_string())
1041 }
1042
1043 /// Rebuild the live main / instanced / shadow render pipelines from
1044 /// freshly compiled world-loaded shader stage bytes. Driven by asset
1045 /// hot-reload (`cn debug` only) when one of the captured `Shader`
1046 /// source files is saved or a debug-WS `reload-assets` command fires.
1047 /// Each `Some(bytes)` replaces the matching live pipeline (and any
1048 /// dependent state: bindless-texture argument encoder, cull pipeline,
1049 /// instanced variant, shadow variant); `None` leaves the pipeline
1050 /// untouched (e.g. a world without an instanced shader passes `None`
1051 /// for the instanced slot). The backend should build every replacement
1052 /// into a temporary first and only swap when every build succeeds;
1053 /// mirrors the safety pattern in the Metal backend's `hot_reload` so a
1054 /// compile error never overwrites a live pipeline with a half-built
1055 /// replacement. Default no-op (returns `Err`): backends without an
1056 /// implementation leave the world-loaded shader reload logged + skipped
1057 /// at the caller.
1058 ///
1059 /// Skinned-mesh variants are out of scope here: their pipelines depend
1060 /// on the world's `SkinnedMesh`-injected library bytes that
1061 /// [`Self::upload_skinned`] consumes and drops.
1062 fn update_world_shader_pipelines(
1063 &mut self,
1064 vert_bytes: Option<&[u8]>,
1065 frag_bytes: Option<&[u8]>,
1066 shadow_bytes: Option<&[u8]>,
1067 vert_instanced_bytes: Option<&[u8]>,
1068 ) -> Result<(), String> {
1069 let _ = (vert_bytes, frag_bytes, shadow_bytes, vert_instanced_bytes);
1070 Err("update_world_shader_pipelines: not implemented on this backend".to_string())
1071 }
1072
1073 /// Build the render pipeline for one shader bucket from its compiled stage
1074 /// bytes, making draws that carry that bucket renderable. Called by the
1075 /// streaming pump when a scene that exclusively owns the bucket's `Shader`
1076 /// pins: init skipped the build, so this is where the cost lands (behind
1077 /// the loading screen, since the bucket counts as scene-resident content).
1078 /// Bucket 0 is the world default program and is never installed this way.
1079 ///
1080 /// Default no-op-with-Ok: a backend that renders every draw with the world
1081 /// default program has no per-bucket pipeline to build, and the bucket is
1082 /// resident as far as scene loading is concerned.
1083 fn install_world_shader(&mut self, bucket: u32, shader: ShaderBytes<'_>) -> RenderResult<()> {
1084 let _ = (bucket, shader);
1085 Ok(())
1086 }
1087
1088 /// Release one shader bucket's render pipeline, undoing
1089 /// [`Self::install_world_shader`]. Called when the owning scene unpins;
1090 /// draws carrying the bucket stop rendering until it is installed again.
1091 /// Default no-op, for the same reason as above.
1092 fn evict_world_shader(&mut self, bucket: u32) {
1093 let _ = bucket;
1094 }
1095
1096 /// The swapchain-level configuration this live backend can hot-swap a world
1097 /// onto, or `None` when the backend cannot reload a world in place (it must
1098 /// be fully rebuilt instead). Read by GraphicsSystem when a transplanted
1099 /// backend is handed a new world (the `cn editor` live SAVE): the swap reuses
1100 /// the backend via [`Self::reload_world`] only when this equals the new
1101 /// world's `BackendInit::swapchain_config`; a `None` or a mismatch routes to a
1102 /// full rebuild (recreating the window). Default `None`: DirectX / Vulkan
1103 /// (and any backend without a real `reload_world`) always rebuild.
1104 fn hot_swap_config(&self) -> Option<SwapchainConfig> {
1105 None
1106 }
1107
1108 /// Re-upload a new world's GPU content onto this already-constructed backend,
1109 /// reusing the live device + window + swapchain instead of building a new one.
1110 /// Driven by the `cn editor` live SAVE: after a structural edit recompiles the
1111 /// blobs, GraphicsSystem transplants the running backend into the rebuilt
1112 /// world and calls this so the edit applies without recreating the OS window
1113 /// or re-initialising the GPU device. The backend waits for the GPU to idle,
1114 /// drops the old world's content resources, and rebuilds them from `init` on
1115 /// the retained hardware. Only ever called when [`Self::hot_swap_config`]
1116 /// reported a config matching `init.swapchain_config()`, so the swapchain
1117 /// (pixel format / frames-in-flight / EDR) is guaranteed unchanged. Default
1118 /// `Err`/unsupported: DirectX / Vulkan fall back to a full rebuild (no
1119 /// regression; a real implementation is Windows-pending like the rest).
1120 fn reload_world(&mut self, init: BackendInit<'_>) -> RenderResult<()> {
1121 let _ = init;
1122 Err(RenderError::Other(
1123 "reload_world: not supported on this backend".to_string(),
1124 ))
1125 }
1126}
1127
1128// A do-nothing backend used to exercise the trait's provided (default) method
1129// bodies without a GPU: the smallest valid bodies for the required methods,
1130// no defaults overridden. Shared by this module's tests and the ops tests.
1131#[cfg(test)]
1132pub(crate) mod test_stub {
1133 use super::*;
1134
1135 pub(crate) struct StubBackend;
1136
1137 impl SceneControl for StubBackend {
1138 fn update_visibility(&mut self, _draw_idx: usize, _visible: bool) {}
1139 fn set_fade(&mut self, _fade: f32) {}
1140 }
1141
1142 impl RenderBackend for StubBackend {
1143 fn window_closed(&mut self) -> bool {
1144 false
1145 }
1146 fn capture_cursor(&mut self) {}
1147 fn take_input(&mut self) -> RenderInput {
1148 RenderInput::default()
1149 }
1150 fn wait_idle(&self) {}
1151 fn draw_frame(&mut self, _params: FrameParams<'_>) -> RenderResult<()> {
1152 Ok(())
1153 }
1154 fn update_view(&mut self, _matrix: [[f32; 4]; 4]) {}
1155 fn update_models(&mut self, _updates: &[(u32, [[f32; 4]; 4])]) {}
1156 fn retire_draw_object(&mut self, _draw_idx: usize) {}
1157 fn upload_skinned(
1158 &mut self,
1159 _vertices: &[SkinnedVertex],
1160 _indices: &[u32],
1161 _draw_objects: Vec<SkinnedDrawObject>,
1162 _vert_bytes: &[u8],
1163 _frag_bytes: &[u8],
1164 _shadow_bytes: &[u8],
1165 ) -> RenderResult<()> {
1166 Ok(())
1167 }
1168 fn update_skinned_pose(&mut self, _skinned_index: usize, _matrices: &[[[f32; 4]; 4]]) {}
1169 fn evict_texture_slot(&mut self, _slot: usize) -> Result<(), String> {
1170 Ok(())
1171 }
1172 fn update_texture_slot(
1173 &mut self,
1174 _slot: usize,
1175 _image: &crate::build::texture::TextureImage,
1176 ) -> RenderResult<()> {
1177 Ok(())
1178 }
1179 fn evict_mesh(&mut self, _draw_idx: usize, _retire_frame: u64) -> Result<(), String> {
1180 Ok(())
1181 }
1182 fn upload_mesh(
1183 &mut self,
1184 _draw_idx: usize,
1185 _verts: &[Vertex],
1186 _idxs: &[u16],
1187 _frame: u64,
1188 ) -> RenderResult<()> {
1189 Ok(())
1190 }
1191 fn setup_chunk_streaming(
1192 &mut self,
1193 _chunk_vtx_bytes: usize,
1194 _chunk_idx_bytes: usize,
1195 _texture_slot: usize,
1196 _normal_map_slot: usize,
1197 ) -> RenderResult<()> {
1198 Ok(())
1199 }
1200 fn add_chunk_mesh(
1201 &mut self,
1202 _mesh: ChunkMesh<'_>,
1203 _dst: crate::draw_slot::SlotAlloc,
1204 ) -> RenderResult<()> {
1205 Ok(())
1206 }
1207 fn remove_chunk_mesh(
1208 &mut self,
1209 _draw_idx: usize,
1210 _retire_frame: u64,
1211 ) -> Result<(), String> {
1212 Ok(())
1213 }
1214 fn set_chunk_model(
1215 &mut self,
1216 _draw_idx: usize,
1217 _model: [[f32; 4]; 4],
1218 ) -> Result<(), String> {
1219 Ok(())
1220 }
1221 }
1222}
1223
1224#[cfg(test)]
1225mod tests {
1226 use super::*;
1227
1228 use alloc::vec;
1229 const GB: u64 = 1 << 30;
1230
1231 fn input(
1232 vendor: GpuVendor,
1233 memory_budget_bytes: u64,
1234 discrete: bool,
1235 apple_family: u8,
1236 ) -> GpuClassInput {
1237 GpuClassInput {
1238 vendor,
1239 memory_budget_bytes,
1240 discrete,
1241 apple_family,
1242 }
1243 }
1244
1245 #[test]
1246 fn unknown_profile_is_the_conservative_default() {
1247 // The opposite default from capabilities: quality auto-config fails safe.
1248 let p = GpuProfile::default();
1249 assert_eq!(p.tier, GpuTier::Unknown);
1250 assert_eq!(p.vendor, GpuVendor::Other);
1251 assert_eq!(p.memory_budget_bytes, 0);
1252 // Unknown sorts below every real tier, so a `>=` resolver treats it as
1253 // the floor.
1254 assert!(GpuTier::Unknown < GpuTier::Integrated);
1255 assert!(GpuTier::Integrated < GpuTier::EntryDiscrete);
1256 assert!(GpuTier::EntryDiscrete < GpuTier::MidDiscrete);
1257 assert!(GpuTier::MidDiscrete < GpuTier::HighDiscrete);
1258 }
1259
1260 #[test]
1261 fn apple_family_reads_the_generation_out_of_the_device_name() {
1262 // The names MoltenVK reports, mapped onto Metal's family ranks.
1263 assert_eq!(apple_family_from_device_name("Apple M1"), 7);
1264 assert_eq!(apple_family_from_device_name("Apple M2 Max"), 8);
1265 assert_eq!(apple_family_from_device_name("Apple M3 Pro"), 9);
1266 assert_eq!(apple_family_from_device_name("Apple M4 Ultra"), 10);
1267 // A generation past what Metal's SDK names yet still ranks above M3, so
1268 // a newer Mac is not demoted.
1269 assert!(apple_family_from_device_name("Apple M9") > 9);
1270 }
1271
1272 #[test]
1273 fn non_apple_device_names_report_no_family() {
1274 for name in [
1275 "NVIDIA GeForce RTX 4090",
1276 "AMD Radeon RX 7900 XTX",
1277 "Intel(R) Arc(tm) A770",
1278 // Apple's own non-M naming, and a truncated / malformed report.
1279 "Apple A17 Pro",
1280 "Apple M",
1281 "Apple MX",
1282 "",
1283 ] {
1284 assert_eq!(apple_family_from_device_name(name), 0, "{name}");
1285 }
1286 }
1287
1288 #[test]
1289 fn apple_family_from_a_name_reaches_the_same_tier_metal_does() {
1290 // The whole point of the name probe: a MoltenVK build must land on the
1291 // tier the Metal backend reports for the same silicon, not on the
1292 // integrated floor a zero family falls through to.
1293 let family = apple_family_from_device_name("Apple M2 Max");
1294 assert_eq!(
1295 classify_tier(&input(GpuVendor::Apple, 32 * GB, false, family)),
1296 GpuTier::MidDiscrete
1297 );
1298 assert_eq!(
1299 classify_tier(&input(GpuVendor::Apple, 32 * GB, false, 0)),
1300 GpuTier::Integrated
1301 );
1302 }
1303
1304 #[test]
1305 fn apple_silicon_classifies_by_generation() {
1306 // Unified memory is large on Apple silicon, but the family generation
1307 // (not the working-set) decides the tier, so the huge shared budget does
1308 // not read as a high-VRAM discrete card.
1309 assert_eq!(
1310 classify_tier(&input(GpuVendor::Apple, 16 * GB, false, 7)),
1311 GpuTier::EntryDiscrete // M1
1312 );
1313 assert_eq!(
1314 classify_tier(&input(GpuVendor::Apple, 24 * GB, false, 8)),
1315 GpuTier::MidDiscrete // M2
1316 );
1317 assert_eq!(
1318 classify_tier(&input(GpuVendor::Apple, 48 * GB, false, 9)),
1319 GpuTier::HighDiscrete // M3
1320 );
1321 assert_eq!(
1322 classify_tier(&input(GpuVendor::Apple, 64 * GB, false, 10)),
1323 GpuTier::HighDiscrete // M4 and newer cap at high
1324 );
1325 }
1326
1327 #[test]
1328 fn discrete_gpu_classifies_by_vram() {
1329 // An Intel-Mac AMD dGPU or a PC discrete card: vendor is not Apple and
1330 // there is no Apple family, so VRAM buckets the tier.
1331 assert_eq!(
1332 classify_tier(&input(GpuVendor::Nvidia, 24 * GB, true, 0)),
1333 GpuTier::HighDiscrete
1334 );
1335 assert_eq!(
1336 classify_tier(&input(GpuVendor::Amd, 8 * GB, true, 0)),
1337 GpuTier::MidDiscrete
1338 );
1339 assert_eq!(
1340 classify_tier(&input(GpuVendor::Nvidia, 4 * GB, true, 0)),
1341 GpuTier::EntryDiscrete
1342 );
1343 // A discrete card that reports no memory budget is left Unknown rather
1344 // than guessed high.
1345 assert_eq!(
1346 classify_tier(&input(GpuVendor::Amd, 0, true, 0)),
1347 GpuTier::Unknown
1348 );
1349 }
1350
1351 #[test]
1352 fn integrated_gpu_is_the_lowest_tier() {
1353 // Non-Apple integrated part: no dedicated memory, not unified, no Apple
1354 // family.
1355 assert_eq!(
1356 classify_tier(&input(GpuVendor::Intel, 0, false, 0)),
1357 GpuTier::Integrated
1358 );
1359 }
1360
1361 #[test]
1362 fn vram_bucket_boundaries() {
1363 // Boundaries are inclusive lower bounds (>= 12 GB high, >= 6 GB mid).
1364 assert_eq!(
1365 classify_tier(&input(GpuVendor::Nvidia, 12 * GB, true, 0)),
1366 GpuTier::HighDiscrete
1367 );
1368 assert_eq!(
1369 classify_tier(&input(GpuVendor::Nvidia, 12 * GB - 1, true, 0)),
1370 GpuTier::MidDiscrete
1371 );
1372 assert_eq!(
1373 classify_tier(&input(GpuVendor::Nvidia, 6 * GB, true, 0)),
1374 GpuTier::MidDiscrete
1375 );
1376 assert_eq!(
1377 classify_tier(&input(GpuVendor::Nvidia, 6 * GB - 1, true, 0)),
1378 GpuTier::EntryDiscrete
1379 );
1380 }
1381
1382 pub(crate) use super::test_stub::StubBackend;
1383
1384 const IDENTITY: [[f32; 4]; 4] = [
1385 [1.0, 0.0, 0.0, 0.0],
1386 [0.0, 1.0, 0.0, 0.0],
1387 [0.0, 0.0, 1.0, 0.0],
1388 [0.0, 0.0, 0.0, 1.0],
1389 ];
1390
1391 // Minimal QualitySettings with every feature off, so no *Settings sub-type
1392 // needs constructing.
1393 fn stub_quality() -> QualitySettings {
1394 QualitySettings {
1395 taa: false,
1396 ssao: None,
1397 ssr: None,
1398 rt_reflections: None,
1399 ssgi: None,
1400 reflection_blur_scale: 1,
1401 auto_exposure: None,
1402 auto_exposure_bias_ev: 0.0,
1403 }
1404 }
1405
1406 #[test]
1407 fn default_query_methods_report_conservative_values() {
1408 let backend = StubBackend;
1409 // Capabilities fail open: a backend that does not report keeps every
1410 // toggle live.
1411 assert!(backend.capabilities().ray_tracing);
1412 // Quality auto-config fails safe: the unknown/conservative profile.
1413 assert_eq!(backend.gpu_profile().tier, GpuTier::Unknown);
1414 assert_eq!(backend.gpu_profile().vendor, GpuVendor::Other);
1415 assert_eq!(backend.gpu_profile().memory_budget_bytes, 0);
1416 // Diagnostics a backend may leave to the default: zeroed here.
1417 assert_eq!(backend.logical_size(), (0.0, 0.0));
1418 assert_eq!(backend.render_stats(), RenderStats::default());
1419 // No window-bounds tracking: the in-engine cursor always draws.
1420 assert!(!backend.cursor_outside_window());
1421 // No display enumeration and no hot-reload flag wired.
1422 assert!(backend.display_modes().is_empty());
1423 assert!(backend.current_display_mode().is_none());
1424 assert!(backend.shader_reload_flag().is_none());
1425 // Not hot-swap-capable: a live world reload routes to a full rebuild.
1426 assert!(backend.hot_swap_config().is_none());
1427 // No geometry-size introspection for the reload size check.
1428 assert!(backend.draw_geometry_size(0).is_none());
1429 assert!(backend.draw_lod_index_counts(0).is_none());
1430 }
1431
1432 #[test]
1433 fn default_mutators_are_noops_and_fallible_hooks_report_defaults() {
1434 let mut backend = StubBackend;
1435
1436 // Runtime skinned-spawn fallbacks: nothing to reveal or hide.
1437 backend.reveal_skinned_instance(0, IDENTITY);
1438 backend.retire_skinned_draw_object(0);
1439 backend.update_skinned_models(&[(0, IDENTITY)]);
1440
1441 // Streaming + cursor + capture no-ops.
1442 backend.seed_mesh_streaming(0, 0, 0, 0);
1443 backend.set_ui_cursor_hidden(true);
1444 backend.set_menu_mode(true);
1445 backend.set_camera_capture(true);
1446 backend.set_reflection_probes(&[]);
1447
1448 // Presentation + window no-ops.
1449 backend.set_vsync(true);
1450 backend.set_window_mode(crate::components::WindowMode::Fullscreen);
1451 backend.set_window_size(1280, 720);
1452 backend.set_display_mode(crate::display_mode::DisplayMode {
1453 width: 1920,
1454 height: 1080,
1455 refresh_hz: 60,
1456 });
1457
1458 // Live look + input tunable no-ops.
1459 backend.update_post_process(PostProcessTunables::DEFAULT);
1460 backend.set_ambient_intensity(1.0);
1461 backend.set_keymap(&KeyMap::default());
1462 backend.apply_quality_settings(stub_quality());
1463 backend.update_quality_params(stub_quality());
1464 backend.set_shadow_update(crate::components::ShadowUpdate::EveryFrame);
1465 backend.set_shadow_distance(200);
1466 backend.set_shadow_cascades(3);
1467 backend.update_fog_settings(None);
1468 backend.update_directional_lights(&[]);
1469 backend.set_draw_material(0, MaterialUniforms::DEFAULT, 0, 0);
1470 backend.set_draw_cull_distance(0, 50.0);
1471
1472 // Fallible hot-reload hooks that succeed by default (no-op Ok).
1473 assert!(backend.update_color_lut(2, &[0u8; 32]).is_ok());
1474 assert!(backend.rebuild_static_geometry(vec![]).is_ok());
1475 assert!(backend.update_skinned_mesh_geometry(0, 0, &[], &[]).is_ok());
1476 assert!(backend.rebuild_skinned_geometry(vec![]).unwrap().is_empty());
1477 assert!(backend.update_skinned_skeleton(0, 0).is_ok());
1478 assert!(backend.update_mesh_geometry(0, &[], &[], &[]).is_ok());
1479 assert!(backend.update_environment_map(&[]).is_ok());
1480
1481 // Fallible hooks a bare backend does not implement: they report Err.
1482 assert!(backend.screenshot("unused.png").is_err());
1483 assert!(
1484 backend
1485 .clone_static_draw_object(0, IDENTITY, crate::draw_slot::SlotAlloc::Append(0))
1486 .is_err()
1487 );
1488 assert!(backend.add_decal(stub_decal()).is_err());
1489 assert!(backend.remove_decal(0).is_err());
1490 assert!(backend.add_emitter(stub_emitter()).is_err());
1491 assert!(backend.remove_emitter(0).is_err());
1492 assert!(
1493 backend
1494 .update_world_shader_pipelines(None, None, None, None)
1495 .is_err()
1496 );
1497 }
1498
1499 // A minimal empty-world BackendInit borrowing `window`, for exercising the
1500 // default `reload_world`. Empty slices are `'static`; the only real borrow
1501 // is the window args.
1502 fn empty_backend_init(window: &crate::components::Window) -> BackendInit<'_> {
1503 BackendInit::minimal(window, alloc::vec::Vec::new())
1504 }
1505
1506 #[test]
1507 fn default_reload_world_is_unsupported() {
1508 // A backend without a real reload path reports the swap unsupported, so
1509 // the caller falls back to a full rebuild.
1510 let mut backend = StubBackend;
1511 let window = crate::components::Window::default();
1512 assert!(backend.reload_world(empty_backend_init(&window)).is_err());
1513 }
1514
1515 fn stub_decal() -> crate::decal::DecalRecord {
1516 crate::decal::DecalRecord {
1517 model: IDENTITY,
1518 inv_model: IDENTITY,
1519 texture_slot: 0,
1520 tint: [1.0; 4],
1521 }
1522 }
1523
1524 fn stub_emitter() -> crate::particles::ParticleEmitterRecord {
1525 crate::particles::ParticleEmitterRecord {
1526 texture_slot: 0,
1527 position: [0.0; 3],
1528 direction: [0.0, 1.0, 0.0],
1529 spread_cos: 1.0,
1530 speed_min: 0.0,
1531 speed_max: 1.0,
1532 lifetime_min: 0.0,
1533 lifetime_max: 1.0,
1534 gravity: [0.0, -9.8, 0.0],
1535 spawn_rate: 1.0,
1536 max_particles: 1,
1537 size_start: 1.0,
1538 size_end: 1.0,
1539 color_start: [1.0; 4],
1540 color_end: [1.0; 4],
1541 }
1542 }
1543}