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