Skip to main content

oa/render/
renderer.rs

1//! Headless render-to-texture session with an explicit bounded target ring.
2//!
3//! One `Renderer` admits four frame sources:
4//! - `begin_frame(texture)` — deep-copies a packed Texture (always available).
5//! - `begin_frame_mesh(mesh, camera)` — vertex-color lit draw call.
6//! - `begin_frame_flat_color(mesh, camera, material)` — solid-color draw call.
7//! - `begin_frame_unlit(mesh, camera, material)` — textured unlit draw call.
8//! - `begin_frame_scene(scene, camera)` — material-dispatched scene draw
9//!   (Surface PBR; requires graphics path and non-empty scene).
10//!
11//! `submit_frame` returns a [`RenderFrame`] carrying the color `Texture` and
12//! exact producer `Event` for every path.
13//!
14//! Donor: `oa::Renderer` (`oacpp/source/cpp/include/oa/render/renderer.h`).
15
16use std::{
17	cell::RefCell,
18	collections::HashMap,
19	rc::{Rc, Weak},
20};
21
22use crate::{
23	Color, Engine, Error, Event, Result,
24	render::material::{FlatColorMaterial, SurfaceMaterial, TextureHandle, UnlitMaterial},
25	runtime::{
26		CanvasGridPipeline, FlatColorPipeline, GraphicsPipeline, MeshBuffer, NativeRgbaImage,
27		RenderTarget, SceneDrawCmd, SurfaceBlendPipeline, SurfaceDescriptorArena,
28		SurfaceDescriptorLayouts, SurfacePipeline, UnlitDescriptorArena, UnlitDescriptorLayouts,
29		UnlitPipeline,
30	},
31};
32
33use super::{
34	Camera, MeshData, Scene, Texture, blit,
35	scene::compile_scene_packets,
36	texture::{RenderTargetLease, texture_from_render_target, texture_from_rgba8_on},
37};
38
39// ── Configuration ─────────────────────────────────────────────────────────────
40
41/// Configuration for one headless [`Renderer`] target ring.
42#[derive(Clone, Debug, PartialEq)]
43pub struct RendererConfig {
44	/// Target width in pixels. Must be non-zero.
45	pub width: u32,
46	/// Target height in pixels. Must be non-zero.
47	pub height: u32,
48	/// Number of simultaneously retained target slots (1–4).
49	pub target_slot_count: u32,
50	/// Maximum vertex count per mesh frame. Zero disables the graphics path.
51	pub max_vertex_count: u32,
52	/// Maximum index count per mesh frame. Zero disables the graphics path.
53	pub max_index_count: u32,
54	/// Background clear color (linear RGBA, each component 0.0–1.0).
55	pub clear_color: Color,
56	/// Normalized light direction (XYZ) pointing from the surface toward the
57	/// light; used by the vertex-color-lit and surface paths.
58	pub light_direction: [f32; 3],
59	/// Ambient light intensity (0.0–1.0) for the vertex-color-lit path.
60	pub ambient: f32,
61	/// Maximum number of distinct materials per `begin_frame_scene` call.
62	///
63	/// Must be in `[1, 64]`. Each material slot allocates one UBO and one
64	/// descriptor set per render target slot. Default is `8`.
65	pub max_materials_per_scene: u32,
66}
67
68impl Default for RendererConfig {
69	fn default() -> Self {
70		Self {
71			width: 256,
72			height: 192,
73			target_slot_count: 3,
74			max_vertex_count: 4096,
75			max_index_count: 12288,
76			clear_color: Color::new(0.02, 0.03, 0.05, 1.0),
77			light_direction: [0.35, 0.82, 0.45],
78			ambient: 0.24,
79			max_materials_per_scene: 8,
80		}
81	}
82}
83
84// ── Public types ──────────────────────────────────────────────────────────────
85
86/// Engine-borrowing headless render-to-texture session.
87///
88/// Admits multiple frame sources through the same slot-ring lifecycle.
89/// `submit_frame` returns a [`RenderFrame`] carrying the color `Texture` and
90/// exact producer `Event`.
91pub struct Renderer<'engine> {
92	engine: &'engine Engine,
93	config: RendererConfig,
94	state: Rc<RefCell<RendererState>>,
95}
96
97/// Generation-safe lease for one submitted headless target.
98#[must_use]
99pub struct RenderFrame {
100	slot: usize,
101	generation: u64,
102	texture: Texture,
103	producer: Event,
104	/// True when the slot has a graphics render target (not a buffer blit).
105	is_graphics: bool,
106	state: Weak<RefCell<RendererState>>,
107	released: bool,
108}
109
110// ── Internal state ────────────────────────────────────────────────────────────
111
112pub(super) struct RendererState {
113	/// Vertex-color lit pipeline (original mesh path).
114	pipeline: Option<GraphicsPipeline>,
115	/// Flat-color material pipeline.
116	flat_color_pipeline: Option<FlatColorPipeline>,
117	/// Unlit textured material pipeline.
118	unlit_pipeline: Option<UnlitPipeline>,
119	/// One sampled-image descriptor set per target-ring slot.
120	unlit_descriptors: Option<UnlitDescriptorArena>,
121	/// Owned descriptor set layouts for the unlit pipeline (set 1).
122	/// Must be declared after `unlit_pipeline` so it drops after the pipeline.
123	_unlit_layouts: Option<UnlitDescriptorLayouts>,
124	/// Surface PBR material pipeline (opaque pass).
125	surface_pipeline: Option<SurfacePipeline>,
126	/// Surface alpha-blend pipeline (transparent pass).
127	/// Must be declared before `_surface_layouts` so it drops before
128	/// the layout — but after `surface_pipeline` so destroy order is
129	/// opaque then blend then layouts.
130	surface_blend_pipeline: Option<SurfaceBlendPipeline>,
131	/// Procedural canvas-grid pipeline (vertexless fullscreen triangle).
132	canvas_grid_pipeline: Option<CanvasGridPipeline>,
133	surface_descriptors: Option<SurfaceDescriptorArena>,
134	/// Owned descriptor set layouts for the Surface pipeline (sets 0+1).
135	/// Must be declared after `surface_pipeline` so it drops after.
136	_surface_layouts: Option<SurfaceDescriptorLayouts>,
137	textures: HashMap<TextureHandle, Texture>,
138	white_texture: Option<Texture>,
139	slots: Vec<Slot>,
140	building: Option<Building>,
141	closed: bool,
142}
143
144struct Slot {
145	generation: u64,
146	state: SlotState,
147	/// Present when the graphics path is enabled.
148	graphics: Option<GraphicsSlot>,
149	sampled_image: Option<Rc<NativeRgbaImage>>,
150	texture_lease: Option<Weak<crate::render::texture::TextureSemantic>>,
151}
152
153struct GraphicsSlot {
154	target: RenderTarget,
155	vertex_buf: MeshBuffer,
156	index_buf: MeshBuffer,
157	scene_uniform: MeshBuffer,
158	/// One UBO slot per material-descriptor index (`max_materials_per_scene`).
159	material_uniforms: Vec<MeshBuffer>,
160}
161
162struct Building {
163	slot: usize,
164	generation: u64,
165	source: BuildingSource,
166}
167
168/// Per-draw packet carried in `BuildingSource::Surface`.
169struct PendingDraw {
170	index_start: u32,
171	index_count: u32,
172	/// 128-byte push block (MVP + model matrix).
173	push_data: [u8; 128],
174	/// Index into `material_uniforms` / descriptor arena for this draw.
175	mat_index: usize,
176	/// Serialized material params to upload before submit.
177	material_data: Box<[u8; MATERIAL_PARAMS_SIZE]>,
178	/// Optional registered texture handles for the three sampler bindings.
179	base_texture: Option<TextureHandle>,
180	orm_texture: Option<TextureHandle>,
181	normal_texture: Option<TextureHandle>,
182	/// True when this draw belongs to the transparent/blend pass.
183	is_blend: bool,
184}
185
186enum BuildingSource {
187	Texture(Texture),
188	/// Vertex-color lit (original mesh path) — 80-byte push.
189	Mesh {
190		index_count: u32,
191		push_data: [u8; 80],
192	},
193	/// Flat-color material — 96-byte push; VERT+FRAG stages.
194	FlatColor {
195		index_count: u32,
196		push_data: [u8; 96],
197	},
198	/// Unlit textured material — 96-byte push; VERT+FRAG stages.
199	Unlit {
200		index_count: u32,
201		push_data: [u8; 96],
202		texture: Rc<NativeRgbaImage>,
203	},
204	/// Surface PBR — per-draw packets sharing one scene UBO.
205	Surface {
206		scene_data: Box<[u8; SCENE_LIGHTS_SIZE]>,
207		draws: Vec<PendingDraw>,
208	},
209	/// Procedural canvas grid — 100-byte push, vertexless 3-vertex draw.
210	CanvasGrid {
211		push_data: [u8; 100],
212	},
213}
214
215enum SlotState {
216	Free,
217	Building,
218	Submitted(Event),
219}
220
221impl RendererState {
222	pub(super) fn mark_texture_consumed(
223		&mut self,
224		slot_index: usize,
225		generation: u64,
226		event: &Event,
227	) -> Result<()> {
228		let slot = self
229			.slots
230			.get_mut(slot_index)
231			.ok_or_else(|| Error::failed_precondition("render target slot is no longer available"))?;
232		if slot.generation != generation {
233			return Err(Error::failed_precondition(
234				"render target slot belongs to a later frame",
235			));
236		}
237		let SlotState::Submitted(current) = &mut slot.state else {
238			return Err(Error::failed_precondition(
239				"render target has no submitted producer",
240			));
241		};
242		if !event.follows_or_equals(current) {
243			return Err(Error::invalid_argument(
244				"render target consumer event precedes its producer or another consumer",
245			));
246		}
247		*current = event.clone();
248		Ok(())
249	}
250}
251
252impl Drop for RendererState {
253	fn drop(&mut self) {
254		let has_unretired_submission = self.slots.iter().any(|slot| match &slot.state {
255			SlotState::Submitted(event) => !matches!(event.is_complete(), Ok(true)),
256			SlotState::Free | SlotState::Building => false,
257		});
258		if !has_unretired_submission {
259			return;
260		}
261
262		// Renderer Drop is not a completion boundary. If the caller omits `close`,
263		// retain every Vulkan object reachable by a pending graphics command rather
264		// than destroying live targets, buffers, descriptors, layouts, or pipelines.
265		std::mem::forget(std::mem::take(&mut self.slots));
266		std::mem::forget(std::mem::take(&mut self.textures));
267		std::mem::forget(self.white_texture.take());
268		std::mem::forget(self.pipeline.take());
269		std::mem::forget(self.flat_color_pipeline.take());
270		std::mem::forget(self.unlit_pipeline.take());
271		std::mem::forget(self.unlit_descriptors.take());
272		std::mem::forget(self._unlit_layouts.take());
273		std::mem::forget(self.surface_pipeline.take());
274		std::mem::forget(self.surface_blend_pipeline.take());
275		std::mem::forget(self.canvas_grid_pipeline.take());
276		std::mem::forget(self.surface_descriptors.take());
277		std::mem::forget(self._surface_layouts.take());
278	}
279}
280
281// ── Return-type aliases ───────────────────────────────────────────────────────
282
283/// Resolved draw parameters from [`Renderer::resolve_graphics_source`].
284type DrawParams = (
285	u32,
286	Vec<u8>,
287	vk::ShaderStageFlags,
288	vk::Pipeline,
289	vk::PipelineLayout,
290	Vec<vk::DescriptorSet>,
291);
292
293// ── Push-constant helpers ─────────────────────────────────────────────────────
294
295const VERTEX_STRIDE: usize = 48;
296const SCENE_LIGHTS_SIZE: usize = 416;
297const MATERIAL_PARAMS_SIZE: usize = 80;
298
299/// Parameters for one procedural canvas-grid frame.
300///
301/// Fields map 1:1 onto the 100-byte fragment push block consumed by
302/// `src/slang/ui/canvas_grid.frag.slang`; colors are packed `0xRRGGBBAA`.
303#[derive(Clone, Copy, Debug, PartialEq)]
304pub struct CanvasGridFrame {
305	/// Destination rect inside the render target, in pixels.
306	pub dst_x: i32,
307	pub dst_y: i32,
308	pub dst_w: u32,
309	pub dst_h: u32,
310	/// Grid-line origin in target pixels (lines pass through this point).
311	pub origin: [f32; 2],
312	/// Minor-tier spacing in pixels on each axis. Must be finite and `>= 1`.
313	pub minor_spacing: [f32; 2],
314	/// Lines every `major_every` minors promote to the major tier (>= 1).
315	pub major_every: u32,
316	/// Lines every `super_major_every` majors promote further (>= 1).
317	pub super_major_every: u32,
318	/// Coverage thickness in pixels: minor, major, super-major, axis.
319	pub thickness: [f32; 4],
320	pub background_top_rgba: u32,
321	pub background_bottom_rgba: u32,
322	pub minor_rgba: u32,
323	pub major_rgba: u32,
324	pub super_major_rgba: u32,
325	pub axis_rgba: u32,
326	/// Radial-fade center in target pixels.
327	pub fade_center: [f32; 2],
328	/// Inner (full opacity) and outer (zero opacity) fade radii.
329	pub fade_radii: [f32; 2],
330	/// Layer enable bits, matching the fragment shader: bit 0 gradient
331	/// background, bit 1 axes, bit 2 grid tiers, bit 3 radial fade,
332	/// bit 4 background dither.
333	pub flags: u32,
334}
335
336impl CanvasGridFrame {
337	/// Flag mask enabling every layer (background, axes, grid, fade, dither).
338	pub const ALL_FLAGS: u32 = 1 | 2 | 4 | 8 | 16;
339
340	pub(crate) fn validate(&self) -> Result<()> {
341		if self.dst_w == 0 || self.dst_h == 0 {
342			return Err(Error::invalid_argument(
343				"canvas-grid destination size must be non-zero",
344			));
345		}
346		if self
347			.thickness
348			.iter()
349			.chain(self.minor_spacing.iter())
350			.chain(self.origin.iter())
351			.chain(self.fade_center.iter())
352			.chain(self.fade_radii.iter())
353			.any(|v| !v.is_finite())
354		{
355			return Err(Error::invalid_argument(
356				"canvas-grid parameters must be finite",
357			));
358		}
359		if self.minor_spacing.iter().any(|v| *v <= 0.0) {
360			return Err(Error::invalid_argument(
361				"canvas-grid minor spacing must be positive",
362			));
363		}
364		if self.major_every == 0 || self.super_major_every == 0 {
365			return Err(Error::invalid_argument(
366				"canvas-grid tier multipliers must be non-zero",
367			));
368		}
369		if self.flags & !Self::ALL_FLAGS != 0 {
370			return Err(Error::invalid_argument(
371				"canvas-grid flags contain an unknown layer bit",
372			));
373		}
374		Ok(())
375	}
376
377	pub(crate) fn pack_push(&self) -> [u8; 100] {
378		let mut data = [0u8; 100];
379		let ints = [self.dst_x as u32, self.dst_y as u32, self.dst_w, self.dst_h];
380		let floats = [
381			self.origin[0],
382			self.origin[1],
383			self.minor_spacing[0],
384			self.minor_spacing[1],
385		];
386		let tier = [self.major_every, self.super_major_every];
387		let colors = [
388			self.background_top_rgba,
389			self.background_bottom_rgba,
390			self.minor_rgba,
391			self.major_rgba,
392			self.super_major_rgba,
393			self.axis_rgba,
394		];
395		let fade = [
396			self.fade_center[0],
397			self.fade_center[1],
398			self.fade_radii[0],
399			self.fade_radii[1],
400		];
401		let mut off = 0;
402		let mut put_u32 = |v: u32| {
403			data[off..off + 4].copy_from_slice(&v.to_le_bytes());
404			off += 4;
405		};
406		for v in ints {
407			put_u32(v);
408		}
409		for v in floats {
410			put_u32(v.to_bits());
411		}
412		for v in tier {
413			put_u32(v);
414		}
415		for v in self.thickness {
416			put_u32(v.to_bits());
417		}
418		for v in colors {
419			put_u32(v);
420		}
421		for v in fade {
422			put_u32(v.to_bits());
423		}
424		put_u32(self.flags);
425		debug_assert_eq!(off, 100);
426		data
427	}
428}
429
430/// Build the 80-byte vertex-color-lit push block (MVP + light/ambient).
431fn build_vcl_push(vp: &crate::vlm::Mat4, light: [f32; 3], ambient: f32) -> [u8; 80] {
432	let mut data = [0u8; 80];
433	for (i, row) in vp.m.iter().enumerate() {
434		for (j, val) in row.iter().enumerate() {
435			let off = (i * 4 + j) * 4;
436			data[off..off + 4].copy_from_slice(&val.to_le_bytes());
437		}
438	}
439	data[64..68].copy_from_slice(&light[0].to_le_bytes());
440	data[68..72].copy_from_slice(&light[1].to_le_bytes());
441	data[72..76].copy_from_slice(&light[2].to_le_bytes());
442	data[76..80].copy_from_slice(&ambient.to_le_bytes());
443	data
444}
445
446/// Build the 96-byte flat-color push block (MVP + material_color + opacity + pad).
447fn build_flat_color_push(mvp: &crate::vlm::Mat4, mat: &FlatColorMaterial) -> [u8; 96] {
448	let mut data = [0u8; 96];
449	for (i, row) in mvp.m.iter().enumerate() {
450		for (j, val) in row.iter().enumerate() {
451			let off = (i * 4 + j) * 4;
452			data[off..off + 4].copy_from_slice(&val.to_le_bytes());
453		}
454	}
455	// offset 64: material_color (float4)
456	for (k, c) in mat.color.to_array().iter().enumerate() {
457		data[64 + k * 4..64 + k * 4 + 4].copy_from_slice(&c.to_le_bytes());
458	}
459	// offset 80: opacity (float) + 12 bytes padding
460	data[80..84].copy_from_slice(&mat.opacity.to_le_bytes());
461	data
462}
463
464/// Build the 96-byte unlit push block (MVP + tint + uv_scale + uv_offset).
465fn build_unlit_push(mvp: &crate::vlm::Mat4, mat: &UnlitMaterial) -> [u8; 96] {
466	let mut data = [0u8; 96];
467	for (i, row) in mvp.m.iter().enumerate() {
468		for (j, val) in row.iter().enumerate() {
469			let off = (i * 4 + j) * 4;
470			data[off..off + 4].copy_from_slice(&val.to_le_bytes());
471		}
472	}
473	// offset 64: tint (float4)
474	for (k, c) in mat.tint.to_array().iter().enumerate() {
475		data[64 + k * 4..64 + k * 4 + 4].copy_from_slice(&c.to_le_bytes());
476	}
477	// offset 80: uv_scale (float2)
478	data[80..84].copy_from_slice(&mat.uv_scale[0].to_le_bytes());
479	data[84..88].copy_from_slice(&mat.uv_scale[1].to_le_bytes());
480	// offset 88: uv_offset (float2)
481	data[88..92].copy_from_slice(&mat.uv_offset[0].to_le_bytes());
482	data[92..96].copy_from_slice(&mat.uv_offset[1].to_le_bytes());
483	data
484}
485
486/// Build the 128-byte surface push block (MVP + model matrix).
487fn build_surface_push(mvp: &crate::vlm::Mat4, model: &crate::vlm::Mat4) -> [u8; 128] {
488	let mut data = [0u8; 128];
489	for (i, row) in mvp.m.iter().enumerate() {
490		for (j, val) in row.iter().enumerate() {
491			let off = (i * 4 + j) * 4;
492			data[off..off + 4].copy_from_slice(&val.to_le_bytes());
493		}
494	}
495	for (i, row) in model.m.iter().enumerate() {
496		for (j, val) in row.iter().enumerate() {
497			let off = 64 + (i * 4 + j) * 4;
498			data[off..off + 4].copy_from_slice(&val.to_le_bytes());
499		}
500	}
501	data
502}
503
504fn build_scene_lights(config: &RendererConfig) -> [u8; SCENE_LIGHTS_SIZE] {
505	let mut data = [0_u8; SCENE_LIGHTS_SIZE];
506	for (index, value) in config.light_direction.iter().enumerate() {
507		data[index * 4..index * 4 + 4].copy_from_slice(&value.to_le_bytes());
508	}
509	data[12..16].copy_from_slice(&1.0_f32.to_le_bytes());
510	for offset in [16, 20, 24] {
511		data[offset..offset + 4].copy_from_slice(&1.0_f32.to_le_bytes());
512	}
513	data[384..388].copy_from_slice(&1_i32.to_le_bytes());
514	data[388..392].copy_from_slice(&0_i32.to_le_bytes());
515	data[392..396].copy_from_slice(&1.0_f32.to_le_bytes());
516	data[396..400].copy_from_slice(&config.ambient.to_le_bytes());
517	for offset in [400, 404, 408] {
518		data[offset..offset + 4].copy_from_slice(&1.0_f32.to_le_bytes());
519	}
520	data[412..416].copy_from_slice(&0_i32.to_le_bytes());
521	data
522}
523
524fn build_material_params(material: &SurfaceMaterial) -> [u8; MATERIAL_PARAMS_SIZE] {
525	let mut data = [0_u8; MATERIAL_PARAMS_SIZE];
526	let mut write = |offset: usize, value: f32| {
527		data[offset..offset + 4].copy_from_slice(&value.to_le_bytes());
528	};
529	for (index, value) in material.base_color.iter().enumerate() {
530		write(index * 4, *value);
531	}
532	write(12, material.metalness);
533	write(16, material.roughness);
534	write(20, material.normal_scale);
535	write(24, material.specular_ior);
536	write(28, material.emission_scale);
537	for (index, value) in material.specular_tint.iter().enumerate() {
538		write(32 + index * 4, *value);
539	}
540	write(44, material.opacity);
541	for (index, value) in material.emission_color.iter().enumerate() {
542		write(48 + index * 4, *value);
543	}
544	write(64, material.uv_scale[0]);
545	write(68, material.uv_scale[1]);
546	write(72, material.uv_offset[0]);
547	write(76, material.uv_offset[1]);
548	data
549}
550
551fn mesh_vertex_bytes(mesh: &MeshData) -> Vec<u8> {
552	let mut out = Vec::with_capacity(mesh.vertices.len() * VERTEX_STRIDE);
553	for v in &mesh.vertices {
554		out.extend_from_slice(&v.position.x.to_le_bytes());
555		out.extend_from_slice(&v.position.y.to_le_bytes());
556		out.extend_from_slice(&v.position.z.to_le_bytes());
557		out.extend_from_slice(&v.normal.x.to_le_bytes());
558		out.extend_from_slice(&v.normal.y.to_le_bytes());
559		out.extend_from_slice(&v.normal.z.to_le_bytes());
560		out.extend_from_slice(&v.uv.x.to_le_bytes());
561		out.extend_from_slice(&v.uv.y.to_le_bytes());
562		out.extend_from_slice(&v.color.x.to_le_bytes());
563		out.extend_from_slice(&v.color.y.to_le_bytes());
564		out.extend_from_slice(&v.color.z.to_le_bytes());
565		out.extend_from_slice(&v.color.w.to_le_bytes());
566	}
567	out
568}
569
570// ── impl Renderer ─────────────────────────────────────────────────────────────
571
572impl<'engine> Renderer<'engine> {
573	pub(crate) fn owns_frame(&self, frame: &RenderFrame) -> bool {
574		frame
575			.state
576			.upgrade()
577			.is_some_and(|state| Rc::ptr_eq(&state, &self.state))
578			&& frame.texture.engine_handle().same_as(&self.engine.handle())
579	}
580
581	/// Create a bounded headless target ring borrowing `engine`.
582	///
583	/// When `max_vertex_count` / `max_index_count` are non-zero and the Engine
584	/// has a graphics queue, all graphics pipelines are created and per-slot
585	/// render targets and mesh buffers are allocated.
586	///
587	/// # Errors
588	///
589	/// Returns an error for zero extent, zero or >4 target slots, invalid
590	/// light/color config, a missing graphics queue when mesh capacity is
591	/// requested, or device allocation failure.
592	pub fn new(engine: &'engine Engine, config: RendererConfig) -> Result<Self> {
593		validate_config(&config)?;
594		let mesh_enabled =
595			config.max_vertex_count > 0 && config.max_index_count > 0 && engine.has_graphics();
596		let handle = engine.handle();
597
598		let (
599			pipeline,
600			flat_color_pipeline,
601			unlit_pipeline,
602			unlit_descriptors,
603			unlit_layouts,
604			surface_pipeline,
605			surface_blend_pipeline,
606			canvas_grid_pipeline,
607			surface_descriptors,
608			surface_layouts,
609		) = if mesh_enabled {
610			let vcl = handle.create_graphics_pipeline()?;
611			let fc = handle.create_flat_color_pipeline()?;
612			let unlit_layouts = handle.create_unlit_descriptor_layouts()?;
613			let unlit_descriptors = handle
614				.create_unlit_descriptor_arena(unlit_layouts.sampler_layout, config.target_slot_count)?;
615			let unlit = handle.create_unlit_pipeline(unlit_layouts.sampler_layout)?;
616			let surface_layouts = handle.create_surface_descriptor_layouts()?;
617			let surface_descriptors = handle.create_surface_descriptor_arena(
618				surface_layouts.scene_layout,
619				surface_layouts.material_layout,
620				config.target_slot_count,
621				config.max_materials_per_scene,
622			)?;
623			let surface = handle.create_surface_pipeline(
624				surface_layouts.scene_layout,
625				surface_layouts.material_layout,
626			)?;
627			// The blend pipeline reuses the opaque pipeline's layout.
628			let surface_blend = handle.create_surface_blend_pipeline(surface.layout())?;
629			let canvas_grid = handle.create_canvas_grid_pipeline()?;
630			(
631				Some(vcl),
632				Some(fc),
633				Some(unlit),
634				Some(unlit_descriptors),
635				Some(unlit_layouts),
636				Some(surface),
637				Some(surface_blend),
638				Some(canvas_grid),
639				Some(surface_descriptors),
640				Some(surface_layouts),
641			)
642		} else {
643			(None, None, None, None, None, None, None, None, None, None)
644		};
645		let white_texture = mesh_enabled
646			.then(|| texture_from_rgba8_on(engine, &[255, 255, 255, 255], 1, 1))
647			.transpose()?;
648
649		let vertex_cap = config.max_vertex_count as usize * VERTEX_STRIDE;
650		let index_cap = config.max_index_count as usize * size_of::<u32>();
651		let mut slots = Vec::with_capacity(config.target_slot_count as usize);
652		for _ in 0..config.target_slot_count {
653			let graphics = if mesh_enabled {
654				let target = handle.allocate_render_target(config.width, config.height)?;
655				let vertex_buf =
656					handle.allocate_mesh_buffer(vertex_cap, vk::BufferUsageFlagBits::VERTEX_BUFFER_BIT)?;
657				let index_buf =
658					handle.allocate_mesh_buffer(index_cap, vk::BufferUsageFlagBits::INDEX_BUFFER_BIT)?;
659				let scene_uniform = handle.allocate_mesh_buffer(
660					SCENE_LIGHTS_SIZE,
661					vk::BufferUsageFlagBits::UNIFORM_BUFFER_BIT,
662				)?;
663				let mut material_uniforms = Vec::with_capacity(config.max_materials_per_scene as usize);
664				for _ in 0..config.max_materials_per_scene {
665					material_uniforms.push(handle.allocate_mesh_buffer(
666						MATERIAL_PARAMS_SIZE,
667						vk::BufferUsageFlagBits::UNIFORM_BUFFER_BIT,
668					)?);
669				}
670				Some(GraphicsSlot {
671					target,
672					vertex_buf,
673					index_buf,
674					scene_uniform,
675					material_uniforms,
676				})
677			} else {
678				None
679			};
680			slots.push(Slot {
681				generation: 0,
682				state: SlotState::Free,
683				graphics,
684				sampled_image: None,
685				texture_lease: None,
686			});
687		}
688		Ok(Self {
689			engine,
690			config,
691			state: Rc::new(RefCell::new(RendererState {
692				pipeline,
693				flat_color_pipeline,
694				unlit_pipeline,
695				unlit_descriptors,
696				_unlit_layouts: unlit_layouts,
697				surface_pipeline,
698				surface_blend_pipeline,
699				canvas_grid_pipeline,
700				surface_descriptors,
701				_surface_layouts: surface_layouts,
702				textures: HashMap::new(),
703				white_texture,
704				slots,
705				building: None,
706				closed: false,
707			})),
708		})
709	}
710
711	/// Return this session's fixed configuration.
712	pub fn config(&self) -> &RendererConfig {
713		&self.config
714	}
715
716	/// Return whether the graphics draw paths are available.
717	pub fn has_mesh_path(&self) -> bool {
718		self.state.borrow().pipeline.is_some()
719	}
720
721	/// Associate a semantic material texture handle with one native Texture.
722	///
723	/// Replacing an existing handle affects future frames only. Submitted frames
724	/// retain the exact native image they referenced until their producer event
725	/// completes.
726	pub fn register_texture(&self, handle: TextureHandle, texture: &Texture) -> Result<()> {
727		if handle.0 == 0 {
728			return Err(Error::invalid_argument(
729				"render::Renderer texture handles must be non-zero",
730			));
731		}
732		if !texture.engine_handle().same_as(&self.engine.handle()) {
733			return Err(Error::invalid_argument(
734				"render::Renderer registered Texture belongs to a different Engine",
735			));
736		}
737		if texture.native().is_none() {
738			return Err(Error::failed_precondition(
739				"render::Renderer sampled textures require native image backing",
740			));
741		}
742		let mut state = self.state.borrow_mut();
743		if state.closed {
744			return Err(Error::failed_precondition("render::Renderer is closed"));
745		}
746		state.textures.insert(handle, texture.clone());
747		Ok(())
748	}
749
750	// ── Frame sources ─────────────────────────────────────────────────────────
751
752	/// Begin one frame from a completed packed source `Texture` (blit path).
753	pub fn begin_frame(&self, source: &Texture) -> Result<()> {
754		if !source.engine_handle().same_as(&self.engine.handle()) {
755			return Err(Error::invalid_argument(
756				"render::Renderer source Texture belongs to a different Engine",
757			));
758		}
759		if source.width() != self.config.width as usize
760			|| source.height() != self.config.height as usize
761		{
762			return Err(Error::invalid_argument(format!(
763				"render::Renderer source extent {}x{} does not match configured {}x{}",
764				source.width(),
765				source.height(),
766				self.config.width,
767				self.config.height,
768			)));
769		}
770		let (slot, generation) = self.acquire_free_slot()?;
771		match blit(source) {
772			Ok(texture) => {
773				self.state.borrow_mut().building = Some(Building {
774					slot,
775					generation,
776					source: BuildingSource::Texture(texture),
777				});
778				Ok(())
779			}
780			Err(error) => {
781				self.release_slot(slot, generation);
782				Err(error)
783			}
784		}
785	}
786
787	/// Begin one frame using the vertex-color-lit pipeline.
788	///
789	/// Requires `has_mesh_path()`.
790	pub fn begin_frame_mesh(&self, mesh: &MeshData, camera: &Camera) -> Result<()> {
791		self.require_graphics("mesh")?;
792		camera.validate()?;
793		self.validate_mesh_capacity(mesh)?;
794		let (slot_idx, generation) = self.acquire_free_slot()?;
795		let vp = camera.get_view_projection_matrix();
796		let push_data = build_vcl_push(&vp, self.config.light_direction, self.config.ambient);
797		let index_count = u32::try_from(mesh.indices.len())
798			.map_err(|_| Error::out_of_range("mesh index count overflows u32"))?;
799		if let Err(e) = self.write_mesh_to_slot(slot_idx, mesh) {
800			self.release_slot(slot_idx, generation);
801			return Err(e);
802		}
803		self.state.borrow_mut().building = Some(Building {
804			slot: slot_idx,
805			generation,
806			source: BuildingSource::Mesh {
807				index_count,
808				push_data,
809			},
810		});
811		Ok(())
812	}
813
814	/// Begin one frame using the flat-color material pipeline.
815	///
816	/// Requires `has_mesh_path()`. `material` parameters are baked into the
817	/// push constant block at record time — no GPU buffer is retained.
818	pub fn begin_frame_flat_color(
819		&self,
820		mesh: &MeshData,
821		camera: &Camera,
822		material: &FlatColorMaterial,
823	) -> Result<()> {
824		self.require_graphics("flat_color")?;
825		material.validate()?;
826		camera.validate()?;
827		self.validate_mesh_capacity(mesh)?;
828		let (slot_idx, generation) = self.acquire_free_slot()?;
829		let mvp = camera.get_view_projection_matrix();
830		let push_data = build_flat_color_push(&mvp, material);
831		let index_count = u32::try_from(mesh.indices.len())
832			.map_err(|_| Error::out_of_range("mesh index count overflows u32"))?;
833		if let Err(e) = self.write_mesh_to_slot(slot_idx, mesh) {
834			self.release_slot(slot_idx, generation);
835			return Err(e);
836		}
837		self.state.borrow_mut().building = Some(Building {
838			slot: slot_idx,
839			generation,
840			source: BuildingSource::FlatColor {
841				index_count,
842				push_data,
843			},
844		});
845		Ok(())
846	}
847
848	/// Begin one frame drawing the procedural canvas grid.
849	///
850	/// Requires `has_mesh_path()`. The draw is a vertexless fullscreen
851	/// triangle; `frame` is baked into the 100-byte fragment push block and
852	/// the scissor limits coverage to `frame`'s destination rect.
853	pub fn begin_frame_canvas_grid(&self, frame: &CanvasGridFrame) -> Result<()> {
854		self.require_graphics("canvas_grid")?;
855		frame.validate()?;
856		if frame.dst_x < 0
857			|| frame.dst_y < 0
858			|| frame.dst_x as u64 + u64::from(frame.dst_w) > u64::from(self.config.width)
859			|| frame.dst_y as u64 + u64::from(frame.dst_h) > u64::from(self.config.height)
860		{
861			return Err(Error::out_of_range(
862				"canvas-grid destination rect must lie inside the render target",
863			));
864		}
865		let (slot_idx, generation) = self.acquire_free_slot()?;
866		self.state.borrow_mut().building = Some(Building {
867			slot: slot_idx,
868			generation,
869			source: BuildingSource::CanvasGrid {
870				push_data: frame.pack_push(),
871			},
872		});
873		Ok(())
874	}
875
876	/// Begin one frame using the unlit textured material pipeline.
877	///
878	/// Requires `has_mesh_path()`. Material tint and UV transform are baked
879	/// into the push block. `base_color_texture` resolves through
880	/// [`Renderer::register_texture`]; `None` uses the renderer's retained white
881	/// texture so tint-only unlit materials remain a valid draw path.
882	pub fn begin_frame_unlit(
883		&self,
884		mesh: &MeshData,
885		camera: &Camera,
886		material: &UnlitMaterial,
887	) -> Result<()> {
888		self.require_graphics("unlit")?;
889		material.validate()?;
890		camera.validate()?;
891		self.validate_mesh_capacity(mesh)?;
892		let texture = {
893			let state = self.state.borrow();
894			let texture = if let Some(handle) = material.base_color_texture {
895				state.textures.get(&handle).ok_or_else(|| {
896					Error::invalid_argument(format!(
897						"render::Renderer has no Texture registered for handle {}",
898						handle.0
899					))
900				})?
901			} else {
902				state
903					.white_texture
904					.as_ref()
905					.ok_or_else(|| Error::failed_precondition("unlit default texture unavailable"))?
906			};
907			texture
908				.native()
909				.ok_or_else(|| Error::failed_precondition("unlit Texture is not image-backed"))?
910		};
911		let (slot_idx, generation) = self.acquire_free_slot()?;
912		let mvp = camera.get_view_projection_matrix();
913		let push_data = build_unlit_push(&mvp, material);
914		let index_count = u32::try_from(mesh.indices.len())
915			.map_err(|_| Error::out_of_range("mesh index count overflows u32"))?;
916		if let Err(e) = self.write_mesh_to_slot(slot_idx, mesh) {
917			self.release_slot(slot_idx, generation);
918			return Err(e);
919		}
920		self.state.borrow_mut().building = Some(Building {
921			slot: slot_idx,
922			generation,
923			source: BuildingSource::Unlit {
924				index_count,
925				push_data,
926				texture,
927			},
928		});
929		Ok(())
930	}
931
932	/// Begin one frame by compiling and drawing a semantic `Scene`.
933	///
934	/// Requires `has_mesh_path()`. The scene is validated and compiled into a
935	/// merged world-space mesh. Each visible mesh node with geometry produces
936	/// one draw call; nodes with different materials bind different material
937	/// UBOs and descriptor sets within the same render pass.
938	///
939	/// Material dispatch:
940	/// - `Material::Surface` → Surface PBR pipeline.
941	/// - `None` (no assignment) → `SurfaceMaterial::default()`.
942	/// - Non-Surface materials and scenes exceeding `max_materials_per_scene`
943	///   are rejected.
944	///
945	/// # Errors
946	///
947	/// Returns an error when the graphics path is unavailable, the scene fails
948	/// validation or produces an empty mesh, the compiled vertex/index count
949	/// exceeds configured capacity, more than `max_materials_per_scene`
950	/// distinct materials are referenced, any assigned material is not
951	/// `Material::Surface`, or buffer write fails.
952	pub fn begin_frame_scene(&self, scene: &Scene, camera: &Camera) -> Result<()> {
953		self.require_graphics("scene")?;
954		camera.validate()?;
955		let (compiled, packets) = compile_scene_packets(scene)?;
956		if compiled.vertices.is_empty() || compiled.indices.is_empty() {
957			return Err(Error::invalid_argument(
958				"render::Renderer begin_frame_scene: compiled scene contains no visible geometry",
959			));
960		}
961		self.validate_mesh_capacity(&compiled)?;
962
963		// ── Build material UBO map ─────────────────────────────────────────
964		// Map MaterialId (or None) → material UBO slot index (0-based).
965		let max_mat = self.config.max_materials_per_scene as usize;
966		let mut mat_slot_map: std::collections::HashMap<Option<crate::render::MaterialId>, usize> =
967			std::collections::HashMap::new();
968		for packet in &packets {
969			let key = packet.material_id;
970			if !mat_slot_map.contains_key(&key) {
971				let next = mat_slot_map.len();
972				if next >= max_mat {
973					return Err(Error::resource_exhausted(
974						"render::Renderer scene exceeds max_materials_per_scene; increase \
975						 RendererConfig::max_materials_per_scene",
976					));
977				}
978				mat_slot_map.insert(key, next);
979			}
980		}
981
982		// ── Validate all materials are Surface ────────────────────────────
983		let mvp = camera.get_view_projection_matrix();
984		let model = crate::vlm::Mat4::identity();
985		let push_data = build_surface_push(&mvp, &model);
986		let scene_data = Box::new(build_scene_lights(&self.config));
987
988		let mut draws: Vec<PendingDraw> = Vec::with_capacity(packets.len());
989		for packet in &packets {
990			let mat_index = mat_slot_map[&packet.material_id];
991			let material = packet
992				.material_id
993				.and_then(|id| scene.materials.iter().find(|m| m.id == id))
994				.map(|entry| &entry.data);
995			let surface = match material {
996				Some(super::Material::Surface(m)) => m.clone(),
997				Some(_) => {
998					return Err(Error::invalid_argument(
999						"render::Renderer scene path requires Surface materials; \
1000						 FlatColor and Unlit are not supported in begin_frame_scene",
1001					));
1002				}
1003				None => SurfaceMaterial::default(),
1004			};
1005			draws.push(PendingDraw {
1006				index_start: packet.index_start,
1007				index_count: packet.index_count,
1008				push_data,
1009				mat_index,
1010				material_data: Box::new(build_material_params(&surface)),
1011				base_texture: surface.base_color_texture,
1012				orm_texture: surface.orm_texture,
1013				normal_texture: surface.normal_texture,
1014				is_blend: surface.alpha_mode == crate::render::material::AlphaMode::Blend,
1015			});
1016		}
1017
1018		let (slot_idx, generation) = self.acquire_free_slot()?;
1019		if let Err(e) = self.write_mesh_to_slot(slot_idx, &compiled) {
1020			self.release_slot(slot_idx, generation);
1021			return Err(e);
1022		}
1023		self.state.borrow_mut().building = Some(Building {
1024			slot: slot_idx,
1025			generation,
1026			source: BuildingSource::Surface { scene_data, draws },
1027		});
1028		Ok(())
1029	}
1030
1031	/// Submit the in-progress frame and return its target lease and producer.
1032	pub fn submit_frame(&self) -> Result<RenderFrame> {
1033		let building = self
1034			.state
1035			.borrow_mut()
1036			.building
1037			.take()
1038			.ok_or_else(|| Error::failed_precondition("render::Renderer has no frame in progress"))?;
1039
1040		match building.source {
1041			BuildingSource::Texture(texture) => {
1042				let producer = match self.engine.checkpoint() {
1043					Ok(event) => event,
1044					Err(error) => {
1045						self.release_slot(building.slot, building.generation);
1046						return Err(error);
1047					}
1048				};
1049				let mut state = self.state.borrow_mut();
1050				let slot = &mut state.slots[building.slot];
1051				if slot.generation != building.generation || !matches!(slot.state, SlotState::Building) {
1052					return Err(Error::failed_precondition(
1053						"render::Renderer frame lease was invalidated",
1054					));
1055				}
1056				slot.state = SlotState::Submitted(producer.clone());
1057				Ok(RenderFrame {
1058					slot: building.slot,
1059					generation: building.generation,
1060					texture,
1061					producer,
1062					is_graphics: false,
1063					state: Rc::downgrade(&self.state),
1064					released: false,
1065				})
1066			}
1067
1068			// ── Surface — multi-draw scene path ─────────────────────
1069			BuildingSource::Surface { scene_data, draws } => {
1070				let handle = self.engine.handle();
1071				let producer = {
1072					let mut state = self.state.borrow_mut();
1073					// Resolve pipeline and arena handles.
1074					let p = state
1075						.surface_pipeline
1076						.as_ref()
1077						.ok_or_else(|| Error::failed_precondition("surface pipeline unavailable"))?
1078						.raw();
1079					let pl = state.surface_pipeline.as_ref().unwrap().layout();
1080					// Write scene UBO and build per-draw SceneDrawCmds.
1081					let slot_ref = &mut state.slots[building.slot];
1082					let gfx = slot_ref
1083						.graphics
1084						.as_mut()
1085						.ok_or_else(|| Error::failed_precondition("surface graphics slot missing"))?;
1086					gfx.scene_uniform.write_and_flush(scene_data.as_ref())?;
1087					let scene_raw = gfx.scene_uniform.raw();
1088					// Resolve the white-texture view for sampler fallback.
1089					let white_view = state
1090						.white_texture
1091						.as_ref()
1092						.and_then(|t| t.native())
1093						.map(|n| n.view())
1094						.ok_or_else(|| {
1095							Error::failed_precondition("surface white fallback texture unavailable")
1096						})?;
1097					// Write scene descriptor set.
1098					let scene_set = state
1099						.surface_descriptors
1100						.as_ref()
1101						.ok_or_else(|| Error::failed_precondition("surface descriptor arena unavailable"))?
1102						.write_scene_slot(building.slot, scene_raw, SCENE_LIGHTS_SIZE as u64)?;
1103					// Per-draw: write material UBO + descriptor set.
1104					let mut draw_cmds: Vec<SceneDrawCmd> = Vec::with_capacity(draws.len());
1105					for draw in &draws {
1106						let mat_uniform = state.slots[building.slot]
1107							.graphics
1108							.as_mut()
1109							.ok_or_else(|| {
1110								Error::failed_precondition("surface graphics slot missing (material)")
1111							})?
1112							.material_uniforms
1113							.get(draw.mat_index)
1114							.ok_or_else(|| {
1115								Error::internal("surface material UBO index exceeds allocated count")
1116							})?;
1117						mat_uniform.write_and_flush(draw.material_data.as_ref())?;
1118						let mat_raw = mat_uniform.raw();
1119						let base_view = draw
1120							.base_texture
1121							.and_then(|h| state.textures.get(&h))
1122							.and_then(|t| t.native())
1123							.map(|n| n.view());
1124						let orm_view = draw
1125							.orm_texture
1126							.and_then(|h| state.textures.get(&h))
1127							.and_then(|t| t.native())
1128							.map(|n| n.view());
1129						let normal_view = draw
1130							.normal_texture
1131							.and_then(|h| state.textures.get(&h))
1132							.and_then(|t| t.native())
1133							.map(|n| n.view());
1134						let mat_set = state
1135							.surface_descriptors
1136							.as_ref()
1137							.unwrap()
1138							.write_material_slot(
1139								building.slot,
1140								draw.mat_index,
1141								mat_raw,
1142								MATERIAL_PARAMS_SIZE as u64,
1143								base_view,
1144								orm_view,
1145								normal_view,
1146								white_view,
1147							)?;
1148						draw_cmds.push(SceneDrawCmd {
1149							index_start: draw.index_start,
1150							index_count: draw.index_count,
1151							push_data: draw.push_data.to_vec(),
1152							material_set: mat_set,
1153							is_blend: draw.is_blend,
1154						});
1155					}
1156					// Depth-sort blend draws back-to-front by index_start (proxy for
1157					// submission order; a full depth sort requires world-space centroids
1158					// which are not available here without transform data).
1159					// Opaque draws come first in the slice; blend draws follow in reverse
1160					// index order (back = higher index_start).
1161					draw_cmds.sort_by(|a, b| match (a.is_blend, b.is_blend) {
1162						(false, true) => std::cmp::Ordering::Less,
1163						(true, false) => std::cmp::Ordering::Greater,
1164						(true, true) => b.index_start.cmp(&a.index_start),
1165						(false, false) => std::cmp::Ordering::Equal,
1166					});
1167					// Record and submit.
1168					let blend_p = state
1169						.surface_blend_pipeline
1170						.as_ref()
1171						.ok_or_else(|| Error::failed_precondition("surface blend pipeline unavailable"))?
1172						.raw();
1173					let slot_mut = &mut state.slots[building.slot];
1174					let gfx_mut = slot_mut.graphics.as_mut().expect("graphics slot populated");
1175					let result = handle.record_and_submit_scene_frame(
1176						&mut gfx_mut.target,
1177						&gfx_mut.vertex_buf,
1178						&gfx_mut.index_buf,
1179						self.config.clear_color.to_array(),
1180						vk::ShaderStageFlagBits::VERTEX_BIT,
1181						p,
1182						blend_p,
1183						pl,
1184						scene_set,
1185						&draw_cmds,
1186					);
1187					match result {
1188						Ok(event) => event,
1189						Err(e) => {
1190							slot_mut.state = SlotState::Free;
1191							slot_mut.sampled_image = None;
1192							return Err(e);
1193						}
1194					}
1195				};
1196				let texture = {
1197					let state = self.state.borrow();
1198					let gfx = state.slots[building.slot]
1199						.graphics
1200						.as_ref()
1201						.expect("graphics slot populated");
1202					texture_from_render_target(
1203						handle,
1204						self.state.clone(),
1205						RenderTargetLease {
1206							slot: building.slot,
1207							generation: building.generation,
1208						},
1209						gfx.target.color_image,
1210						gfx.target.color_view,
1211						gfx.target.width,
1212						gfx.target.height,
1213					)
1214				};
1215				{
1216					let mut state = self.state.borrow_mut();
1217					state.slots[building.slot].state = SlotState::Submitted(producer.clone());
1218					state.slots[building.slot].sampled_image = None;
1219					state.slots[building.slot].texture_lease = Some(texture.lease_weak());
1220				}
1221				Ok(RenderFrame {
1222					slot: building.slot,
1223					generation: building.generation,
1224					texture,
1225					producer,
1226					is_graphics: true,
1227					state: Rc::downgrade(&self.state),
1228					released: false,
1229				})
1230			}
1231
1232			// ── Single-draw graphics sources ──────────────────────────────────
1233			source => {
1234				let (index_count, push_bytes, push_stages, pipeline_vk, pipeline_layout, descriptor_sets) =
1235					{
1236						let state = self.state.borrow();
1237						self.resolve_graphics_source(&state, building.slot, &source)
1238					}?;
1239				let vertexless = matches!(source, BuildingSource::CanvasGrid { .. });
1240				let sampled_image = match &source {
1241					BuildingSource::Unlit { texture, .. } => Some(texture.clone()),
1242					_ => None,
1243				};
1244				let handle = self.engine.handle();
1245				let producer = {
1246					let mut state = self.state.borrow_mut();
1247					let slot = &mut state.slots[building.slot];
1248					let gfx = slot.graphics.as_mut().expect("graphics slot populated");
1249					let result = if vertexless {
1250						handle.record_and_submit_vertexless_frame(
1251							&mut gfx.target,
1252							index_count,
1253							self.config.clear_color.to_array(),
1254							&push_bytes,
1255							push_stages,
1256							pipeline_vk,
1257							pipeline_layout,
1258							&descriptor_sets,
1259						)
1260					} else {
1261						handle.record_and_submit_mesh_frame(
1262							&mut gfx.target,
1263							&gfx.vertex_buf,
1264							&gfx.index_buf,
1265							index_count,
1266							self.config.clear_color.to_array(),
1267							&push_bytes,
1268							push_stages,
1269							pipeline_vk,
1270							pipeline_layout,
1271							&descriptor_sets,
1272						)
1273					};
1274					match result {
1275						Ok(event) => event,
1276						Err(e) => {
1277							slot.state = SlotState::Free;
1278							slot.sampled_image = None;
1279							return Err(e);
1280						}
1281					}
1282				};
1283				let texture = {
1284					let state = self.state.borrow();
1285					let gfx = state.slots[building.slot]
1286						.graphics
1287						.as_ref()
1288						.expect("graphics slot populated");
1289					texture_from_render_target(
1290						handle,
1291						self.state.clone(),
1292						RenderTargetLease {
1293							slot: building.slot,
1294							generation: building.generation,
1295						},
1296						gfx.target.color_image,
1297						gfx.target.color_view,
1298						gfx.target.width,
1299						gfx.target.height,
1300					)
1301				};
1302				{
1303					let mut state = self.state.borrow_mut();
1304					state.slots[building.slot].state = SlotState::Submitted(producer.clone());
1305					state.slots[building.slot].sampled_image = sampled_image;
1306					state.slots[building.slot].texture_lease = Some(texture.lease_weak());
1307				}
1308				Ok(RenderFrame {
1309					slot: building.slot,
1310					generation: building.generation,
1311					texture,
1312					producer,
1313					is_graphics: true,
1314					state: Rc::downgrade(&self.state),
1315					released: false,
1316				})
1317			}
1318		}
1319	}
1320
1321	/// Cancel the in-progress frame without submitting or waiting.
1322	pub fn cancel_frame(&self) -> Result<()> {
1323		let building = self
1324			.state
1325			.borrow_mut()
1326			.building
1327			.take()
1328			.ok_or_else(|| Error::failed_precondition("render::Renderer has no frame in progress"))?;
1329		self.release_slot(building.slot, building.generation);
1330		Ok(())
1331	}
1332
1333	/// Recycle submitted slots whose exact producer event has completed.
1334	pub fn collect(&self) -> Result<usize> {
1335		let mut state = self.state.borrow_mut();
1336		let mut released = 0;
1337		for slot in &mut state.slots {
1338			if let SlotState::Submitted(event) = &slot.state
1339				&& event.is_complete()?
1340				&& slot
1341					.texture_lease
1342					.as_ref()
1343					.is_none_or(|lease| lease.strong_count() == 0)
1344			{
1345				slot.state = SlotState::Free;
1346				slot.sampled_image = None;
1347				slot.texture_lease = None;
1348				released += 1;
1349			}
1350		}
1351		Ok(released)
1352	}
1353
1354	/// Wait for outstanding submitted frames and permanently close the session.
1355	pub fn close(&self) -> Result<()> {
1356		let events = {
1357			let mut state = self.state.borrow_mut();
1358			if state.closed {
1359				return Ok(());
1360			}
1361			if state.building.is_some() {
1362				return Err(Error::failed_precondition(
1363					"render::Renderer cannot close with a frame in progress; submit or cancel it",
1364				));
1365			}
1366			state.closed = true;
1367			state
1368				.slots
1369				.iter()
1370				.filter_map(|slot| match &slot.state {
1371					SlotState::Submitted(event) => Some(event.clone()),
1372					_ => None,
1373				})
1374				.collect::<Vec<_>>()
1375		};
1376		for event in events {
1377			event.wait()?;
1378		}
1379		self.collect()?;
1380		Ok(())
1381	}
1382
1383	// ── Private helpers ───────────────────────────────────────────────────────
1384
1385	fn require_graphics(&self, path: &str) -> Result<()> {
1386		if self.state.borrow().pipeline.is_none() {
1387			Err(Error::failed_precondition(format!(
1388				"render::Renderer {path} path requires a graphics-capable Engine and non-zero \
1389				 max_vertex_count/max_index_count in RendererConfig",
1390			)))
1391		} else {
1392			Ok(())
1393		}
1394	}
1395
1396	fn validate_mesh_capacity(&self, mesh: &MeshData) -> Result<()> {
1397		if mesh.vertices.is_empty() || mesh.indices.is_empty() || !mesh.indices.len().is_multiple_of(3)
1398		{
1399			return Err(Error::invalid_argument(
1400				"render::Renderer requires a non-empty indexed triangle-list mesh",
1401			));
1402		}
1403		if mesh.vertices.len() > self.config.max_vertex_count as usize {
1404			return Err(Error::resource_exhausted(
1405				"render::Renderer mesh vertex count exceeds max_vertex_count",
1406			));
1407		}
1408		if mesh.indices.len() > self.config.max_index_count as usize {
1409			return Err(Error::resource_exhausted(
1410				"render::Renderer mesh index count exceeds max_index_count",
1411			));
1412		}
1413		Ok(())
1414	}
1415
1416	fn write_mesh_to_slot(&self, slot_idx: usize, mesh: &MeshData) -> Result<()> {
1417		let state = self.state.borrow();
1418		let gfx = state.slots[slot_idx]
1419			.graphics
1420			.as_ref()
1421			.expect("mesh slot has graphics");
1422		let vbytes = mesh_vertex_bytes(mesh);
1423		let ibytes: Vec<u8> = mesh.indices.iter().flat_map(|i| i.to_le_bytes()).collect();
1424		gfx
1425			.vertex_buf
1426			.write_and_flush(&vbytes)
1427			.and_then(|()| gfx.index_buf.write_and_flush(&ibytes))
1428	}
1429
1430	/// Resolve a graphics `BuildingSource` to the raw Vulkan handles and push
1431	/// bytes needed by `record_and_submit_mesh_frame`.
1432	///
1433	/// Returns owned push bytes so the `RendererState` borrow can be released
1434	/// before the bytes are passed to `record_and_submit_mesh_frame`.
1435	fn resolve_graphics_source(
1436		&self,
1437		state: &RendererState,
1438		slot: usize,
1439		source: &BuildingSource,
1440	) -> Result<DrawParams> {
1441		match source {
1442			BuildingSource::Mesh {
1443				index_count,
1444				push_data,
1445			} => {
1446				let p = state.pipeline.as_ref().expect("vcl pipeline live");
1447				Ok((
1448					*index_count,
1449					push_data.to_vec(),
1450					vk::ShaderStageFlagBits::VERTEX_BIT,
1451					p.raw(),
1452					p.layout(),
1453					Vec::new(),
1454				))
1455			}
1456			BuildingSource::FlatColor {
1457				index_count,
1458				push_data,
1459			} => {
1460				let p = state
1461					.flat_color_pipeline
1462					.as_ref()
1463					.ok_or_else(|| Error::failed_precondition("flat-color pipeline unavailable"))?;
1464				Ok((
1465					*index_count,
1466					push_data.to_vec(),
1467					vk::ShaderStageFlagBits::VERTEX_BIT | vk::ShaderStageFlagBits::FRAGMENT_BIT,
1468					p.raw(),
1469					p.layout(),
1470					Vec::new(),
1471				))
1472			}
1473			BuildingSource::Unlit {
1474				index_count,
1475				push_data,
1476				texture,
1477			} => {
1478				let p = state
1479					.unlit_pipeline
1480					.as_ref()
1481					.ok_or_else(|| Error::failed_precondition("unlit pipeline unavailable"))?;
1482				let descriptors = state
1483					.unlit_descriptors
1484					.as_ref()
1485					.ok_or_else(|| Error::failed_precondition("unlit descriptor arena unavailable"))?;
1486				let set = descriptors.write_sampled_image(slot, texture.view())?;
1487				Ok((
1488					*index_count,
1489					push_data.to_vec(),
1490					vk::ShaderStageFlagBits::VERTEX_BIT | vk::ShaderStageFlagBits::FRAGMENT_BIT,
1491					p.raw(),
1492					p.layout(),
1493					vec![set],
1494				))
1495			}
1496			BuildingSource::CanvasGrid { push_data } => {
1497				let p = state
1498					.canvas_grid_pipeline
1499					.as_ref()
1500					.ok_or_else(|| Error::failed_precondition("canvas-grid pipeline unavailable"))?;
1501				Ok((
1502					3,
1503					push_data.to_vec(),
1504					vk::ShaderStageFlagBits::FRAGMENT_BIT,
1505					p.raw(),
1506					p.layout(),
1507					Vec::new(),
1508				))
1509			}
1510			BuildingSource::Surface { .. } => {
1511				unreachable!("Surface source handled in the Surface match arm")
1512			}
1513			BuildingSource::Texture(_) => {
1514				unreachable!("Texture source handled before resolve_graphics_source")
1515			}
1516		}
1517	}
1518
1519	fn acquire_free_slot(&self) -> Result<(usize, u64)> {
1520		let mut state = self.state.borrow_mut();
1521		if state.closed {
1522			return Err(Error::failed_precondition("render::Renderer is closed"));
1523		}
1524		if state.building.is_some() {
1525			return Err(Error::failed_precondition(
1526				"render::Renderer already has a frame in progress",
1527			));
1528		}
1529		let Some((idx, entry)) = state
1530			.slots
1531			.iter_mut()
1532			.enumerate()
1533			.find(|(_, s)| matches!(s.state, SlotState::Free))
1534		else {
1535			return Err(Error::resource_exhausted(
1536				"render::Renderer target ring has no reusable slot; consume or collect a frame",
1537			));
1538		};
1539		entry.generation = entry.generation.checked_add(1).ok_or_else(|| {
1540			Error::resource_exhausted("render::Renderer target generation space is exhausted")
1541		})?;
1542		entry.sampled_image = None;
1543		entry.texture_lease = None;
1544		entry.state = SlotState::Building;
1545		Ok((idx, entry.generation))
1546	}
1547
1548	fn release_slot(&self, slot: usize, generation: u64) {
1549		let mut state = self.state.borrow_mut();
1550		if let Some(entry) = state.slots.get_mut(slot)
1551			&& entry.generation == generation
1552		{
1553			entry.state = SlotState::Free;
1554			entry.sampled_image = None;
1555			entry.texture_lease = None;
1556		}
1557	}
1558}
1559
1560// ── impl RenderFrame ──────────────────────────────────────────────────────────
1561
1562impl RenderFrame {
1563	/// Borrow the color target texture for this frame.
1564	pub const fn color(&self) -> &Texture {
1565		&self.texture
1566	}
1567
1568	/// Return the exact producer completion event for this target.
1569	pub const fn producer(&self) -> &Event {
1570		&self.producer
1571	}
1572
1573	/// Return the target width in pixels.
1574	pub fn width(&self) -> usize {
1575		self.texture.width()
1576	}
1577
1578	/// Return the target height in pixels.
1579	pub fn height(&self) -> usize {
1580		self.texture.height()
1581	}
1582
1583	/// Explicitly wait and read back RGBA8 pixels, releasing the ring slot.
1584	pub fn consume_readback(mut self) -> Result<Vec<u8>> {
1585		let result = if self.is_graphics {
1586			self.producer.wait()?;
1587			if let Some(state) = self.state.upgrade() {
1588				let state = state.borrow();
1589				state.slots[self.slot]
1590					.graphics
1591					.as_ref()
1592					.ok_or_else(|| Error::failed_precondition("render::RenderFrame graphics slot missing"))?
1593					.target
1594					.read_color_rgba8()
1595			} else {
1596				Err(Error::failed_precondition(
1597					"render::RenderFrame renderer has been dropped",
1598				))
1599			}
1600		} else {
1601			self.producer.wait()?;
1602			self.texture.read_rgba8()
1603		};
1604		if result.is_ok() {
1605			self.release_completed();
1606		} else {
1607			self.do_release();
1608		}
1609		self.released = true;
1610		result
1611	}
1612
1613	/// Explicitly abandon this target without waiting.
1614	pub fn abandon(mut self) {
1615		self.do_release();
1616		self.released = true;
1617	}
1618
1619	fn do_release(&self) {
1620		if let Some(state) = self.state.upgrade() {
1621			let mut state = state.borrow_mut();
1622			if let Some(slot) = state.slots.get_mut(self.slot)
1623				&& slot.generation == self.generation
1624				&& !matches!(&slot.state, SlotState::Submitted(event) if event.follows_or_equals(&self.producer))
1625			{
1626				slot.state = SlotState::Submitted(self.producer.clone());
1627			}
1628		}
1629	}
1630
1631	fn release_completed(&self) {
1632		if let Some(state) = self.state.upgrade() {
1633			let mut state = state.borrow_mut();
1634			// The strong-count gate only applies to render-target frames: their
1635			// `texture` is a slot alias, so an extra clone means a live external
1636			// retainer must keep the slot. Texture-source frames carry the
1637			// caller's own buffer-backed texture — the caller's binding is not
1638			// a slot retainer and always keeps the count above one.
1639			if let Some(slot) = state.slots.get_mut(self.slot)
1640				&& slot.generation == self.generation
1641				&& (!self.is_graphics || self.texture.lease_strong_count() == 1)
1642				&& matches!(&slot.state, SlotState::Submitted(event) if matches!(event.is_complete(), Ok(true)))
1643			{
1644				slot.state = SlotState::Free;
1645				slot.sampled_image = None;
1646				slot.texture_lease = None;
1647			}
1648		}
1649	}
1650}
1651
1652impl Drop for RenderFrame {
1653	fn drop(&mut self) {
1654		if !self.released {
1655			self.do_release();
1656		}
1657	}
1658}
1659
1660// ── Config validation ─────────────────────────────────────────────────────────
1661
1662fn validate_config(config: &RendererConfig) -> Result<()> {
1663	if config.width == 0
1664		|| config.height == 0
1665		|| config.target_slot_count == 0
1666		|| config.target_slot_count > 4
1667	{
1668		return Err(Error::invalid_argument(
1669			"render::RendererConfig requires non-zero extent and 1–4 target slots",
1670		));
1671	}
1672	if !config
1673		.clear_color
1674		.to_array()
1675		.iter()
1676		.all(|v| v.is_finite() && (0.0..=1.0).contains(v))
1677	{
1678		return Err(Error::invalid_argument(
1679			"render::RendererConfig clear_color must be finite values in [0, 1]",
1680		));
1681	}
1682	if !config.light_direction.iter().all(|v| v.is_finite())
1683		|| !config.ambient.is_finite()
1684		|| !(0.0..=1.0).contains(&config.ambient)
1685	{
1686		return Err(Error::invalid_argument(
1687			"render::RendererConfig light_direction must be finite; ambient must be in [0, 1]",
1688		));
1689	}
1690	if config.max_materials_per_scene == 0 || config.max_materials_per_scene > 64 {
1691		return Err(Error::invalid_argument(
1692			"render::RendererConfig max_materials_per_scene must be in [1, 64]",
1693		));
1694	}
1695	Ok(())
1696}