Skip to main content

euv_core/game/engine3d/material/
impl.rs

1use super::*;
2
3/// Default identity `TextureTransform3D`.
4impl Default for TextureTransform3D {
5    /// Returns the identity UV transform with zero offset, zero rotation, and unit scale.
6    ///
7    /// # Returns
8    ///
9    /// - `Self` - Identity `TextureTransform3D`.
10    fn default() -> Self {
11        Self::from_trs(Vec2::zero(), 0.0, Vec2::splat(1.0))
12    }
13}
14
15/// UV matrix baking and coordinate transformation for `TextureTransform3D`.
16impl TextureTransform3D {
17    /// Constructs a `TextureTransform3D` and pre-bakes its 2x3 glTF `KHR_texture_transform` matrix.
18    ///
19    /// # Arguments
20    ///
21    /// - `Vec2` - UV translation offset `(u, v)`.
22    /// - `f32` - Rotation in radians.
23    /// - `Vec2` - UV scale `(su, sv)`.
24    ///
25    /// # Returns
26    ///
27    /// - `Self` - Ready UV transform.
28    #[must_use]
29    pub fn from_trs(offset: Vec2, rotation: f32, scale: Vec2) -> Self {
30        let cos_r: f32 = rotation.cos();
31        let sin_r: f32 = rotation.sin();
32        let sx: f32 = scale.get_x();
33        let sy: f32 = scale.get_y();
34        let uv_matrix: [f32; 6] = [
35            cos_r * sx,
36            sin_r * sy,
37            offset.get_x(),
38            -sin_r * sx,
39            cos_r * sy,
40            offset.get_y(),
41        ];
42        Self {
43            offset,
44            rotation,
45            scale,
46            uv_matrix,
47        }
48    }
49
50    /// Evaluates the transformed UV coordinate using the pre-baked 2x3 matrix.
51    ///
52    /// # Arguments
53    ///
54    /// - `&Self` - UV transform reference.
55    /// - `Vec2` - Input mesh UV coordinate.
56    ///
57    /// # Returns
58    ///
59    /// - `Vec2` - Transformed texture sampling coordinate.
60    #[cfg_attr(not(target_arch = "wasm32"), inline)]
61    #[must_use]
62    pub fn apply_uv(&self, uv: Vec2) -> Vec2 {
63        let m: [f32; 6] = self.get_uv_matrix();
64        let u: f32 = uv.get_x();
65        let v: f32 = uv.get_y();
66        Vec2::new(m[0] * u + m[1] * v + m[2], m[3] * u + m[4] * v + m[5])
67    }
68}
69
70/// Constructors for `TextureSlot3D`.
71impl TextureSlot3D {
72    /// Creates a texture slot referencing `texture_index` on UV channel `tex_coord` with identity UV transform.
73    ///
74    /// # Arguments
75    ///
76    /// - `u32` - Index inside the scene texture list.
77    /// - `u8` - UV attribute channel (`0` or `1`).
78    ///
79    /// # Returns
80    ///
81    /// - `Self` - Constructed texture slot.
82    #[must_use]
83    pub fn from_index(texture_index: u32, tex_coord: u8) -> Self {
84        Self {
85            texture_index,
86            tex_coord,
87            transform: TextureTransform3D::default(),
88        }
89    }
90}
91
92/// Default Blender Principled BSDF dielectric preset for `PrincipledMaterial3D`.
93impl Default for PrincipledMaterial3D {
94    /// Returns the canonical glTF 2.0 / Blender Principled BSDF default material.
95    ///
96    /// # Returns
97    ///
98    /// - `Self` - Default `PrincipledMaterial3D`.
99    fn default() -> Self {
100        Self {
101            name: PRINCIPLED_DEFAULT_NAME.to_string(),
102            base_color_factor: [1.0, 1.0, 1.0, 1.0],
103            base_color_texture: None,
104            metallic_factor: 0.0,
105            roughness_factor: 0.5,
106            metallic_roughness_texture: None,
107            normal_texture: None,
108            normal_scale: 1.0,
109            occlusion_texture: None,
110            occlusion_strength: 1.0,
111            emissive_factor: [0.0, 0.0, 0.0],
112            emissive_texture: None,
113            emissive_strength: 1.0,
114            alpha_mode: AlphaMode3D::Opaque,
115            alpha_cutoff: PRINCIPLED_DEFAULT_ALPHA_CUTOFF,
116            double_sided: false,
117            unlit: false,
118            ior: PRINCIPLED_DEFAULT_IOR,
119            specular_factor: 1.0,
120            specular_color_factor: [1.0, 1.0, 1.0],
121            specular_texture: None,
122            specular_color_texture: None,
123            clearcoat_factor: 0.0,
124            clearcoat_roughness_factor: 0.0,
125            clearcoat_texture: None,
126            clearcoat_roughness_texture: None,
127            clearcoat_normal_texture: None,
128            transmission_factor: 0.0,
129            transmission_texture: None,
130            thickness_factor: 0.0,
131            attenuation_distance: f32::INFINITY,
132            attenuation_color: [1.0, 1.0, 1.0],
133            sheen_color_factor: [0.0, 0.0, 0.0],
134            sheen_roughness_factor: 0.0,
135            sheen_color_texture: None,
136            sheen_roughness_texture: None,
137        }
138    }
139}
140
141/// Conversion and GPU packing helpers for `PrincipledMaterial3D`.
142impl PrincipledMaterial3D {
143    /// Computes the dielectric `F0` derived from `self.ior`.
144    ///
145    /// # Arguments
146    ///
147    /// - `&Self` - Principled material reference.
148    ///
149    /// # Returns
150    ///
151    /// - `f32` - Dielectric Fresnel `F0` scalar.
152    #[must_use]
153    pub fn dielectric_f0(&self) -> f32 {
154        dielectric_f0_from_ior(self.get_ior())
155    }
156
157    /// Projects this Principled BSDF material down to a compact legacy `PbrMaterial` for existing CPU fast paths.
158    ///
159    /// # Arguments
160    ///
161    /// - `&Self` - Principled material reference.
162    ///
163    /// # Returns
164    ///
165    /// - `PbrMaterial` - Legacy scalar PBR summary.
166    #[must_use]
167    pub fn to_legacy_pbr(&self) -> PbrMaterial {
168        let base: [f32; 4] = self.get_base_color_factor();
169        let em: [f32; 3] = self.get_emissive_factor();
170        let em_str: f32 = self.get_emissive_strength().max(0.0);
171        let rough: f32 = self.get_roughness_factor().clamp(0.04, 1.0);
172        let refl: f32 = ((1.0 - rough) + self.get_clearcoat_factor() * 0.25).clamp(0.05, 0.98);
173        let mut out: PbrMaterial = PbrMaterial::default()
174            .with_metallic(self.get_metallic_factor().clamp(0.0, 1.0))
175            .with_roughness(rough)
176            .with_reflectivity(refl)
177            .with_emissive(Vec3::new(em[0] * em_str, em[1] * em_str, em[2] * em_str));
178        out.set_base_color(Vec3::new(base[0], base[1], base[2]));
179        out
180    }
181
182    /// Lifts a legacy scalar `PbrMaterial` into a `PrincipledMaterial3D`.
183    ///
184    /// # Arguments
185    ///
186    /// - `&str` - Assigned material name.
187    /// - `PbrMaterial` - Source legacy PBR material.
188    ///
189    /// # Returns
190    ///
191    /// - `Self` - Equivalent `PrincipledMaterial3D`.
192    #[must_use]
193    pub fn from_legacy_pbr(name: &str, legacy: PbrMaterial) -> Self {
194        let bc: Vec3 = legacy.get_base_color();
195        let em: Vec3 = legacy.get_emissive();
196        let mut mat: Self = Self::default();
197        mat.set_name(name.to_string());
198        mat.set_base_color_factor([bc.get_x(), bc.get_y(), bc.get_z(), 1.0]);
199        mat.set_metallic_factor(legacy.get_metallic());
200        mat.set_roughness_factor(legacy.get_roughness());
201        mat.set_emissive_factor([em.get_x(), em.get_y(), em.get_z()]);
202        mat
203    }
204
205    /// Packs this material into a 160-byte std140 `GpuMaterialData3D` ready for GPU storage buffer upload.
206    ///
207    /// # Arguments
208    ///
209    /// - `&Self` - Principled material reference.
210    ///
211    /// # Returns
212    ///
213    /// - `GpuMaterialData3D` - GPU-aligned 160-byte material block.
214    #[must_use]
215    pub fn to_gpu_data(&self) -> GpuMaterialData3D {
216        let em: [f32; 3] = self.get_emissive_factor();
217        let em_str: f32 = self.get_emissive_strength().max(0.0);
218        let spec_col: [f32; 3] = self.get_specular_color_factor();
219        let atten_col: [f32; 3] = self.get_attenuation_color();
220        let sheen_col: [f32; 3] = self.get_sheen_color_factor();
221        let slot_id: fn(Option<TextureSlot3D>) -> u32 = |slot: Option<TextureSlot3D>| -> u32 {
222            match slot {
223                Some(entry) => entry.get_texture_index(),
224                None => GPU_MATERIAL_NO_TEXTURE,
225            }
226        };
227        let mut flags: u32 = match self.get_alpha_mode() {
228            AlphaMode3D::Opaque => 0,
229            AlphaMode3D::Mask => GPU_MATERIAL_FLAG_ALPHA_MASK,
230            AlphaMode3D::Blend => GPU_MATERIAL_FLAG_ALPHA_BLEND,
231        };
232        if self.get_double_sided() {
233            flags |= GPU_MATERIAL_FLAG_DOUBLE_SIDED;
234        }
235        if self.get_unlit() {
236            flags |= GPU_MATERIAL_FLAG_UNLIT;
237        }
238        let atten_dist_finite: f32 = if self.get_attenuation_distance().is_finite() {
239            self.get_attenuation_distance().max(1e-4)
240        } else {
241            1.0e9
242        };
243        GpuMaterialData3D {
244            base_color_factor: self.get_base_color_factor(),
245            emissive_alpha_cutoff: [
246                em[0] * em_str,
247                em[1] * em_str,
248                em[2] * em_str,
249                self.get_alpha_cutoff(),
250            ],
251            pbr_ior_specular: [
252                self.get_metallic_factor().clamp(0.0, 1.0),
253                self.get_roughness_factor().clamp(0.04, 1.0),
254                self.get_ior().max(1.0),
255                self.get_specular_factor().clamp(0.0, 1.0),
256            ],
257            specular_color_clearcoat: [
258                spec_col[0],
259                spec_col[1],
260                spec_col[2],
261                self.get_clearcoat_factor().clamp(0.0, 1.0),
262            ],
263            clearcoat_normal_occ_trans: [
264                self.get_clearcoat_roughness_factor().clamp(0.0, 1.0),
265                self.get_normal_scale(),
266                self.get_occlusion_strength().clamp(0.0, 1.0),
267                self.get_transmission_factor().clamp(0.0, 1.0),
268            ],
269            volume_attenuation: [
270                atten_col[0],
271                atten_col[1],
272                atten_col[2],
273                self.get_thickness_factor().max(0.0),
274            ],
275            sheen_color_roughness: [
276                sheen_col[0],
277                sheen_col[1],
278                sheen_col[2],
279                self.get_sheen_roughness_factor().clamp(0.0, 1.0),
280            ],
281            tex_indices_a: [
282                slot_id(self.try_get_base_color_texture()),
283                slot_id(self.try_get_metallic_roughness_texture()),
284                slot_id(self.try_get_normal_texture()),
285                slot_id(self.try_get_occlusion_texture()),
286            ],
287            tex_indices_b: [
288                slot_id(self.try_get_emissive_texture()),
289                slot_id(self.try_get_clearcoat_texture()),
290                slot_id(self.try_get_sheen_color_texture()),
291                slot_id(self.try_get_transmission_texture()),
292            ],
293            flags_volume: [
294                flags,
295                atten_dist_finite.to_bits(),
296                slot_id(self.try_get_clearcoat_normal_texture()),
297                slot_id(self.try_get_specular_texture()),
298            ],
299        }
300    }
301}