Skip to main content

oa/render/
material.rs

1//! Semantic material values — CPU-side only, no GPU handles.
2//!
3//! Three tiers cover the full fidelity range without shared
4//! over-parameterization:
5//!
6//! - [`FlatColorMaterial`] — solid-color UI and debug geometry; zero textures,
7//!   no lighting.
8//! - [`UnlitMaterial`] — textured image/video display; one texture, no
9//!   lighting.
10//! - [`SurfaceMaterial`] — OA's metallic/roughness PBR parameter value, with
11//!   GGX specular, Lambertian diffuse, direct light, ambient, and emission.
12//!   Additional layer parameters are reserved for future renderer support.
13//!
14//! All color and intensity values are **linear** at this API boundary. sRGB
15//! conversion is handled by the Vulkan image-view format, not in shaders.
16//!
17//! Shading follows the OA material and lighting contracts.
18
19use crate::{Color, Error, Result};
20
21// ── Ids and handles ───────────────────────────────────────────────────────────
22
23/// Opaque index into the owning [`Scene`]'s texture registry.
24///
25/// A handle is valid only within the `Scene` that issued it. Zero is reserved
26/// and will be rejected by `validate_scene`.
27///
28/// [`Scene`]: super::scene::Scene
29#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
30pub struct TextureHandle(pub u64);
31
32/// Stable identity of one material in a [`Scene`]. Zero is invalid.
33///
34/// [`Scene`]: super::scene::Scene
35#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
36pub struct MaterialId(pub u64);
37
38// ── AlphaMode ─────────────────────────────────────────────────────────────────
39
40/// Alpha blending mode for [`UnlitMaterial`] and [`SurfaceMaterial`].
41#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
42pub enum AlphaMode {
43	/// Alpha is ignored; surface is drawn in the opaque pass with depth write.
44	#[default]
45	Opaque,
46	/// Fragment is discarded when `alpha < alpha_cutoff`; drawn in the opaque
47	/// pass (avoids blending cost).
48	AlphaTest,
49	/// Premultiplied alpha blend over the existing color buffer; drawn in a
50	/// back-to-front transparent pass with depth write disabled.
51	Blend,
52}
53
54// ── FlatColorMaterial ─────────────────────────────────────────────────────────
55
56/// Solid-color material for UI elements and debug geometry.
57///
58/// Zero texture bindings; lighting is disabled. Matches the `flat_color`
59/// Slang shader variant.
60#[derive(Clone, Debug, PartialEq)]
61pub struct FlatColorMaterial {
62	/// Linear RGBA color, each component in `[0, 1]`.
63	pub color: Color,
64	/// Final alpha multiplier applied after `color.a`, in `[0, 1]`.
65	pub opacity: f32,
66}
67
68impl Default for FlatColorMaterial {
69	/// Opaque white.
70	fn default() -> Self {
71		Self {
72			color: Color::new(1.0, 1.0, 1.0, 1.0),
73			opacity: 1.0,
74		}
75	}
76}
77
78impl FlatColorMaterial {
79	/// Validate that all components are finite and in `[0, 1]`.
80	pub fn validate(&self) -> Result<()> {
81		if self
82			.color
83			.to_array()
84			.iter()
85			.any(|c| !c.is_finite() || *c < 0.0 || *c > 1.0)
86			|| !self.opacity.is_finite()
87			|| self.opacity < 0.0
88			|| self.opacity > 1.0
89		{
90			return Err(Error::invalid_argument(
91				"render::FlatColorMaterial color and opacity must be finite and in [0, 1]",
92			));
93		}
94		Ok(())
95	}
96}
97
98// ── UnlitMaterial ─────────────────────────────────────────────────────────────
99
100/// Textured unlit material for image and video display.
101///
102/// One optional base-color texture; no lighting computation. Matches the
103/// `unlit` Slang shader variant.
104#[derive(Clone, Debug, PartialEq)]
105pub struct UnlitMaterial {
106	/// Optional base-color texture (sRGB RGBA8). When `None`, `tint` is used
107	/// as the solid color.
108	pub base_color_texture: Option<TextureHandle>,
109	/// Linear RGBA tint multiplied with the texture sample (or used directly
110	/// when no texture is bound). Default `[1, 1, 1, 1]`.
111	pub tint: Color,
112	/// UV scale applied before sampling. Default `[1, 1]`.
113	pub uv_scale: [f32; 2],
114	/// UV offset applied after scaling. Default `[0, 0]`.
115	pub uv_offset: [f32; 2],
116	/// Alpha mode for this surface.
117	pub alpha_mode: AlphaMode,
118}
119
120impl Default for UnlitMaterial {
121	/// Opaque white, no texture, identity UV transform.
122	fn default() -> Self {
123		Self {
124			base_color_texture: None,
125			tint: Color::new(1.0, 1.0, 1.0, 1.0),
126			uv_scale: [1.0, 1.0],
127			uv_offset: [0.0, 0.0],
128			alpha_mode: AlphaMode::Opaque,
129		}
130	}
131}
132
133impl UnlitMaterial {
134	/// Validate that all scalar components are finite.
135	pub fn validate(&self) -> Result<()> {
136		if self.base_color_texture.is_some_and(|handle| handle.0 == 0)
137			|| self.tint.to_array().iter().any(|c| !c.is_finite())
138			|| self.uv_scale.iter().any(|c| !c.is_finite())
139			|| self.uv_offset.iter().any(|c| !c.is_finite())
140		{
141			return Err(Error::invalid_argument(
142				"render::UnlitMaterial tint, uv_scale, and uv_offset must be finite",
143			));
144		}
145		Ok(())
146	}
147}
148
149// ── SurfaceMaterial ───────────────────────────────────────────────────
150
151/// Metallic/roughness PBR material for scene geometry.
152///
153/// OA evaluates GGX specular and Lambertian diffuse using base color,
154/// metalness, perceptual roughness, and dielectric index of refraction.
155/// Direct light, flat ambient, and emission form the current renderer subset.
156/// Base/ORM/normal descriptors are connected, but their sampling variants
157/// are not enabled by the current shader build. Texture sampling, coat,
158/// sheen, subsurface, separate emission/opacity maps, and interchange
159/// adapters remain Planned.
160///
161/// **Texture channel packing (ORM convention):**
162/// - `orm_texture` R = ambient occlusion, G = roughness, B = metalness.
163/// - `normal_texture` stores tangent-space XY as BC5 SNORM; Z is reconstructed
164///   as `sqrt(saturate(1 - dot(n.xy, n.xy)))`.
165///
166/// All color values are **linear** at this API boundary.
167#[derive(Clone, Debug, PartialEq)]
168pub struct SurfaceMaterial {
169	// ── Base lobe ─────────────────────────────────────────────────────────────
170	/// Linear RGB base color. Default `[0.8, 0.8, 0.8]`.
171	pub base_color: [f32; 3],
172	/// Optional base-color texture. Format admission belongs to the renderer.
173	pub base_color_texture: Option<TextureHandle>,
174
175	/// Metalness in `[0, 1]`. Default `0.0` (dielectric).
176	pub metalness: f32,
177	/// Perceptual roughness in `[0, 1]`. Default `0.5`. Squared to α in the
178	/// shader for the GGX distribution.
179	pub roughness: f32,
180	/// Optional ORM texture (R=occlusion, G=roughness, B=metalness).
181	pub orm_texture: Option<TextureHandle>,
182
183	// ── Normal ────────────────────────────────────────────────────────────────
184	/// Optional tangent-space normal texture (BC5 SNORM XY).
185	pub normal_texture: Option<TextureHandle>,
186	/// Normal map strength multiplier. Default `1.0`.
187	pub normal_scale: f32,
188
189	// ── Specular ──────────────────────────────────────────────────────────────
190	/// Index of refraction for dielectric F0 derivation. Default `1.5`
191	/// (glass/plastic → F0 ≈ 0.04).
192	pub specular_ior: f32,
193	/// Linear RGB tint applied to the specular F0. Default `[1, 1, 1]`.
194	pub specular_tint: [f32; 3],
195
196	// ── Emission ──────────────────────────────────────────────────────────────
197	/// Linear RGB emissive color. Default `[0, 0, 0]`.
198	pub emission_color: [f32; 3],
199	/// HDR intensity multiplier for emission. Default `0.0`.
200	pub emission_scale: f32,
201	/// Optional emissive texture (BC6H UFLOAT or RGBA16F).
202	pub emission_texture: Option<TextureHandle>,
203
204	// ── Clear coat ────────────────────────────────────────────────────────────
205	/// Clear coat weight in `[0, 1]`. Default `0.0`. Rendering is Planned.
206	pub coat_weight: f32,
207	/// Clear coat perceptual roughness in `[0, 1]`. Default `0.03`.
208	pub coat_roughness: f32,
209	/// Clear coat IOR. Default `1.5`.
210	pub coat_ior: f32,
211	/// Optional separate tangent-space normal for the coat layer.
212	pub coat_normal_texture: Option<TextureHandle>,
213
214	// ── Sheen (fabric/cloth) ──────────────────────────────────────────────────
215	/// Sheen weight in `[0, 1]`. Default `0.0`. Rendering is Planned.
216	pub sheen_weight: f32,
217	/// Linear RGB sheen color. Default `[1, 1, 1]`.
218	pub sheen_color: [f32; 3],
219	/// Sheen perceptual roughness in `[0, 1]`. Default `0.3`.
220	pub sheen_roughness: f32,
221
222	// ── Subsurface scattering ─────────────────────────────────────────────────
223	/// Subsurface weight in `[0, 1]`. Default `0.0`. Rendering is Planned.
224	pub subsurface_weight: f32,
225	/// Linear RGB subsurface color. Default `[1, 1, 1]`.
226	pub subsurface_color: [f32; 3],
227	/// Per-channel scattering distance in world units (RGB). Default `[1, 1, 1]`.
228	pub subsurface_radius: [f32; 3],
229
230	// ── Alpha ─────────────────────────────────────────────────────────────────
231	/// Global opacity multiplier in `[0, 1]`. Default `1.0`.
232	pub opacity: f32,
233	/// Optional single-channel (R) opacity texture.
234	pub opacity_texture: Option<TextureHandle>,
235	/// Alpha mode for this surface.
236	pub alpha_mode: AlphaMode,
237	/// Alpha cutoff threshold for `AlphaMode::AlphaTest`. Default `0.5`.
238	pub alpha_cutoff: f32,
239
240	// ── UV transform (shared across all maps) ─────────────────────────────────
241	/// UV scale applied before sampling all maps. Default `[1, 1]`.
242	pub uv_scale: [f32; 2],
243	/// UV offset applied after scaling. Default `[0, 0]`.
244	pub uv_offset: [f32; 2],
245}
246
247impl Default for SurfaceMaterial {
248	/// Neutral gray dielectric: `base_color = [0.8, 0.8, 0.8]`, `roughness = 0.5`,
249	/// `metalness = 0.0`, all optional textures `None`, all optional lobes at
250	/// weight `0.0`.
251	fn default() -> Self {
252		Self {
253			base_color: [0.8, 0.8, 0.8],
254			base_color_texture: None,
255			metalness: 0.0,
256			roughness: 0.5,
257			orm_texture: None,
258			normal_texture: None,
259			normal_scale: 1.0,
260			specular_ior: 1.5,
261			specular_tint: [1.0, 1.0, 1.0],
262			emission_color: [0.0, 0.0, 0.0],
263			emission_scale: 0.0,
264			emission_texture: None,
265			coat_weight: 0.0,
266			coat_roughness: 0.03,
267			coat_ior: 1.5,
268			coat_normal_texture: None,
269			sheen_weight: 0.0,
270			sheen_color: [1.0, 1.0, 1.0],
271			sheen_roughness: 0.3,
272			subsurface_weight: 0.0,
273			subsurface_color: [1.0, 1.0, 1.0],
274			subsurface_radius: [1.0, 1.0, 1.0],
275			opacity: 1.0,
276			opacity_texture: None,
277			alpha_mode: AlphaMode::Opaque,
278			alpha_cutoff: 0.5,
279			uv_scale: [1.0, 1.0],
280			uv_offset: [0.0, 0.0],
281		}
282	}
283}
284
285impl SurfaceMaterial {
286	/// Validate that all scalar parameters are finite and in-range.
287	pub fn validate(&self) -> Result<()> {
288		let in_unit = |v: f32| v.is_finite() && (0.0..=1.0).contains(&v);
289		let finite3 = |c: [f32; 3]| c.iter().all(|v| v.is_finite());
290		let finite2 = |c: [f32; 2]| c.iter().all(|v| v.is_finite());
291		let texture_handles = [
292			self.base_color_texture,
293			self.orm_texture,
294			self.normal_texture,
295			self.emission_texture,
296			self.coat_normal_texture,
297			self.opacity_texture,
298		];
299		if texture_handles
300			.into_iter()
301			.flatten()
302			.any(|handle| handle.0 == 0)
303			|| !finite3(self.base_color)
304			|| !in_unit(self.metalness)
305			|| !in_unit(self.roughness)
306			|| !self.normal_scale.is_finite()
307			|| !self.specular_ior.is_finite()
308			|| self.specular_ior <= 0.0
309			|| !finite3(self.specular_tint)
310			|| !finite3(self.emission_color)
311			|| !self.emission_scale.is_finite()
312			|| self.emission_scale < 0.0
313			|| !in_unit(self.coat_weight)
314			|| !in_unit(self.coat_roughness)
315			|| !self.coat_ior.is_finite()
316			|| self.coat_ior <= 0.0
317			|| !in_unit(self.sheen_weight)
318			|| !finite3(self.sheen_color)
319			|| !in_unit(self.sheen_roughness)
320			|| !in_unit(self.subsurface_weight)
321			|| !finite3(self.subsurface_color)
322			|| !finite3(self.subsurface_radius)
323			|| self.subsurface_radius.iter().any(|v| *v < 0.0)
324			|| !in_unit(self.opacity)
325			|| !in_unit(self.alpha_cutoff)
326			|| !finite2(self.uv_scale)
327			|| !finite2(self.uv_offset)
328		{
329			return Err(Error::invalid_argument(
330				"render::SurfaceMaterial parameters must be finite and in-range",
331			));
332		}
333		Ok(())
334	}
335}
336
337// ── Material ──────────────────────────────────────────────────────────────────
338
339/// Semantic material value — CPU-side only, no GPU handles.
340///
341/// Three tiers correspond to distinct shader pipelines:
342/// - [`Material::FlatColor`] — `flat_color` shader, UI and debug.
343/// - [`Material::Unlit`] — `unlit` shader, image/video display.
344/// - [`Material::Surface`] — `surface` shader, metallic/roughness PBR.
345#[derive(Clone, Debug, PartialEq)]
346pub enum Material {
347	FlatColor(FlatColorMaterial),
348	Unlit(UnlitMaterial),
349	Surface(SurfaceMaterial),
350}
351
352impl Default for Material {
353	/// Neutral gray opaque `Surface` material.
354	fn default() -> Self {
355		Self::Surface(SurfaceMaterial::default())
356	}
357}
358
359impl Material {
360	/// Validate the enclosed material's scalar parameters.
361	pub fn validate(&self) -> Result<()> {
362		match self {
363			Self::FlatColor(m) => m.validate(),
364			Self::Unlit(m) => m.validate(),
365			Self::Surface(m) => m.validate(),
366		}
367	}
368}