euv-core 0.51.0

Core cross-platform runtime for euv featuring arena-based fine-grained reactivity, deterministic layout, flat scene graph, multi-mode rendering, and direct OS platform adapters.
Documentation
use super::*;

/// Default identity `TextureTransform3D`.
impl Default for TextureTransform3D {
    /// Returns the identity UV transform with zero offset, zero rotation, and unit scale.
    ///
    /// # Returns
    ///
    /// - `Self` - Identity `TextureTransform3D`.
    fn default() -> Self {
        Self::from_trs(Vec2::zero(), 0.0, Vec2::splat(1.0))
    }
}

/// UV matrix baking and coordinate transformation for `TextureTransform3D`.
impl TextureTransform3D {
    /// Constructs a `TextureTransform3D` and pre-bakes its 2x3 glTF `KHR_texture_transform` matrix.
    ///
    /// # Arguments
    ///
    /// - `Vec2` - UV translation offset `(u, v)`.
    /// - `f32` - Rotation in radians.
    /// - `Vec2` - UV scale `(su, sv)`.
    ///
    /// # Returns
    ///
    /// - `Self` - Ready UV transform.
    #[must_use]
    pub fn from_trs(offset: Vec2, rotation: f32, scale: Vec2) -> Self {
        let cos_r: f32 = rotation.cos();
        let sin_r: f32 = rotation.sin();
        let sx: f32 = scale.get_x();
        let sy: f32 = scale.get_y();
        let uv_matrix: [f32; 6] = [
            cos_r * sx,
            sin_r * sy,
            offset.get_x(),
            -sin_r * sx,
            cos_r * sy,
            offset.get_y(),
        ];
        Self {
            offset,
            rotation,
            scale,
            uv_matrix,
        }
    }

    /// Evaluates the transformed UV coordinate using the pre-baked 2x3 matrix.
    ///
    /// # Arguments
    ///
    /// - `&Self` - UV transform reference.
    /// - `Vec2` - Input mesh UV coordinate.
    ///
    /// # Returns
    ///
    /// - `Vec2` - Transformed texture sampling coordinate.
    #[cfg_attr(not(target_arch = "wasm32"), inline)]
    #[must_use]
    pub fn apply_uv(&self, uv: Vec2) -> Vec2 {
        let m: [f32; 6] = self.get_uv_matrix();
        let u: f32 = uv.get_x();
        let v: f32 = uv.get_y();
        Vec2::new(m[0] * u + m[1] * v + m[2], m[3] * u + m[4] * v + m[5])
    }
}

/// Constructors for `TextureSlot3D`.
impl TextureSlot3D {
    /// Creates a texture slot referencing `texture_index` on UV channel `tex_coord` with identity UV transform.
    ///
    /// # Arguments
    ///
    /// - `u32` - Index inside the scene texture list.
    /// - `u8` - UV attribute channel (`0` or `1`).
    ///
    /// # Returns
    ///
    /// - `Self` - Constructed texture slot.
    #[must_use]
    pub fn from_index(texture_index: u32, tex_coord: u8) -> Self {
        Self {
            texture_index,
            tex_coord,
            transform: TextureTransform3D::default(),
        }
    }
}

/// Default Blender Principled BSDF dielectric preset for `PrincipledMaterial3D`.
impl Default for PrincipledMaterial3D {
    /// Returns the canonical glTF 2.0 / Blender Principled BSDF default material.
    ///
    /// # Returns
    ///
    /// - `Self` - Default `PrincipledMaterial3D`.
    fn default() -> Self {
        Self {
            name: PRINCIPLED_DEFAULT_NAME.to_string(),
            base_color_factor: [1.0, 1.0, 1.0, 1.0],
            base_color_texture: None,
            metallic_factor: 0.0,
            roughness_factor: 0.5,
            metallic_roughness_texture: None,
            normal_texture: None,
            normal_scale: 1.0,
            occlusion_texture: None,
            occlusion_strength: 1.0,
            emissive_factor: [0.0, 0.0, 0.0],
            emissive_texture: None,
            emissive_strength: 1.0,
            alpha_mode: AlphaMode3D::Opaque,
            alpha_cutoff: PRINCIPLED_DEFAULT_ALPHA_CUTOFF,
            double_sided: false,
            unlit: false,
            ior: PRINCIPLED_DEFAULT_IOR,
            specular_factor: 1.0,
            specular_color_factor: [1.0, 1.0, 1.0],
            specular_texture: None,
            specular_color_texture: None,
            clearcoat_factor: 0.0,
            clearcoat_roughness_factor: 0.0,
            clearcoat_texture: None,
            clearcoat_roughness_texture: None,
            clearcoat_normal_texture: None,
            transmission_factor: 0.0,
            transmission_texture: None,
            thickness_factor: 0.0,
            attenuation_distance: f32::INFINITY,
            attenuation_color: [1.0, 1.0, 1.0],
            sheen_color_factor: [0.0, 0.0, 0.0],
            sheen_roughness_factor: 0.0,
            sheen_color_texture: None,
            sheen_roughness_texture: None,
        }
    }
}

/// Conversion and GPU packing helpers for `PrincipledMaterial3D`.
impl PrincipledMaterial3D {
    /// Computes the dielectric `F0` derived from `self.ior`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Principled material reference.
    ///
    /// # Returns
    ///
    /// - `f32` - Dielectric Fresnel `F0` scalar.
    #[must_use]
    pub fn dielectric_f0(&self) -> f32 {
        dielectric_f0_from_ior(self.get_ior())
    }

    /// Projects this Principled BSDF material down to a compact legacy `PbrMaterial` for existing CPU fast paths.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Principled material reference.
    ///
    /// # Returns
    ///
    /// - `PbrMaterial` - Legacy scalar PBR summary.
    #[must_use]
    pub fn to_legacy_pbr(&self) -> PbrMaterial {
        let base: [f32; 4] = self.get_base_color_factor();
        let em: [f32; 3] = self.get_emissive_factor();
        let em_str: f32 = self.get_emissive_strength().max(0.0);
        let rough: f32 = self.get_roughness_factor().clamp(0.04, 1.0);
        let refl: f32 = ((1.0 - rough) + self.get_clearcoat_factor() * 0.25).clamp(0.05, 0.98);
        let mut out: PbrMaterial = PbrMaterial::default()
            .with_metallic(self.get_metallic_factor().clamp(0.0, 1.0))
            .with_roughness(rough)
            .with_reflectivity(refl)
            .with_emissive(Vec3::new(em[0] * em_str, em[1] * em_str, em[2] * em_str));
        out.set_base_color(Vec3::new(base[0], base[1], base[2]));
        out
    }

    /// Lifts a legacy scalar `PbrMaterial` into a `PrincipledMaterial3D`.
    ///
    /// # Arguments
    ///
    /// - `&str` - Assigned material name.
    /// - `PbrMaterial` - Source legacy PBR material.
    ///
    /// # Returns
    ///
    /// - `Self` - Equivalent `PrincipledMaterial3D`.
    #[must_use]
    pub fn from_legacy_pbr(name: &str, legacy: PbrMaterial) -> Self {
        let bc: Vec3 = legacy.get_base_color();
        let em: Vec3 = legacy.get_emissive();
        let mut mat: Self = Self::default();
        mat.set_name(name.to_string());
        mat.set_base_color_factor([bc.get_x(), bc.get_y(), bc.get_z(), 1.0]);
        mat.set_metallic_factor(legacy.get_metallic());
        mat.set_roughness_factor(legacy.get_roughness());
        mat.set_emissive_factor([em.get_x(), em.get_y(), em.get_z()]);
        mat
    }

    /// Packs this material into a 160-byte std140 `GpuMaterialData3D` ready for GPU storage buffer upload.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Principled material reference.
    ///
    /// # Returns
    ///
    /// - `GpuMaterialData3D` - GPU-aligned 160-byte material block.
    #[must_use]
    pub fn to_gpu_data(&self) -> GpuMaterialData3D {
        let em: [f32; 3] = self.get_emissive_factor();
        let em_str: f32 = self.get_emissive_strength().max(0.0);
        let spec_col: [f32; 3] = self.get_specular_color_factor();
        let atten_col: [f32; 3] = self.get_attenuation_color();
        let sheen_col: [f32; 3] = self.get_sheen_color_factor();
        let slot_id: fn(Option<TextureSlot3D>) -> u32 = |slot: Option<TextureSlot3D>| -> u32 {
            match slot {
                Some(entry) => entry.get_texture_index(),
                None => GPU_MATERIAL_NO_TEXTURE,
            }
        };
        let mut flags: u32 = match self.get_alpha_mode() {
            AlphaMode3D::Opaque => 0,
            AlphaMode3D::Mask => GPU_MATERIAL_FLAG_ALPHA_MASK,
            AlphaMode3D::Blend => GPU_MATERIAL_FLAG_ALPHA_BLEND,
        };
        if self.get_double_sided() {
            flags |= GPU_MATERIAL_FLAG_DOUBLE_SIDED;
        }
        if self.get_unlit() {
            flags |= GPU_MATERIAL_FLAG_UNLIT;
        }
        let atten_dist_finite: f32 = if self.get_attenuation_distance().is_finite() {
            self.get_attenuation_distance().max(1e-4)
        } else {
            1.0e9
        };
        GpuMaterialData3D {
            base_color_factor: self.get_base_color_factor(),
            emissive_alpha_cutoff: [
                em[0] * em_str,
                em[1] * em_str,
                em[2] * em_str,
                self.get_alpha_cutoff(),
            ],
            pbr_ior_specular: [
                self.get_metallic_factor().clamp(0.0, 1.0),
                self.get_roughness_factor().clamp(0.04, 1.0),
                self.get_ior().max(1.0),
                self.get_specular_factor().clamp(0.0, 1.0),
            ],
            specular_color_clearcoat: [
                spec_col[0],
                spec_col[1],
                spec_col[2],
                self.get_clearcoat_factor().clamp(0.0, 1.0),
            ],
            clearcoat_normal_occ_trans: [
                self.get_clearcoat_roughness_factor().clamp(0.0, 1.0),
                self.get_normal_scale(),
                self.get_occlusion_strength().clamp(0.0, 1.0),
                self.get_transmission_factor().clamp(0.0, 1.0),
            ],
            volume_attenuation: [
                atten_col[0],
                atten_col[1],
                atten_col[2],
                self.get_thickness_factor().max(0.0),
            ],
            sheen_color_roughness: [
                sheen_col[0],
                sheen_col[1],
                sheen_col[2],
                self.get_sheen_roughness_factor().clamp(0.0, 1.0),
            ],
            tex_indices_a: [
                slot_id(self.try_get_base_color_texture()),
                slot_id(self.try_get_metallic_roughness_texture()),
                slot_id(self.try_get_normal_texture()),
                slot_id(self.try_get_occlusion_texture()),
            ],
            tex_indices_b: [
                slot_id(self.try_get_emissive_texture()),
                slot_id(self.try_get_clearcoat_texture()),
                slot_id(self.try_get_sheen_color_texture()),
                slot_id(self.try_get_transmission_texture()),
            ],
            flags_volume: [
                flags,
                atten_dist_finite.to_bits(),
                slot_id(self.try_get_clearcoat_normal_texture()),
                slot_id(self.try_get_specular_texture()),
            ],
        }
    }
}