euv-core 0.53.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::*;

/// glTF 2.0 WebGL constant mapping helpers for `TextureFilterMode`.
impl TextureFilterMode {
    /// Decodes a glTF 2.0 / WebGL numeric filter constant into `TextureFilterMode`.
    ///
    /// # Arguments
    ///
    /// - `u32` - glTF numeric filter constant (`9728`, `9729`, `9984..=9987`).
    ///
    /// # Returns
    ///
    /// - `Self` - Matching texture filter mode (defaults to `Linear`).
    #[must_use]
    pub const fn from_gltf_code(code: u32) -> Self {
        match code {
            9728 => Self::Nearest,
            9729 => Self::Linear,
            9984 => Self::NearestMipmapNearest,
            9985 => Self::LinearMipmapNearest,
            9986 => Self::NearestMipmapLinear,
            9987 => Self::LinearMipmapLinear,
            _ => Self::Linear,
        }
    }
}

/// glTF 2.0 WebGL constant mapping helpers for `TextureWrapMode`.
impl TextureWrapMode {
    /// Decodes a glTF 2.0 / WebGL numeric wrap constant into `TextureWrapMode`.
    ///
    /// # Arguments
    ///
    /// - `u32` - glTF numeric wrap constant (`10497`, `33071`, `33648`).
    ///
    /// # Returns
    ///
    /// - `Self` - Matching texture wrap mode (defaults to `Repeat`).
    #[must_use]
    pub const fn from_gltf_code(code: u32) -> Self {
        match code {
            33_071 => Self::ClampToEdge,
            33_648 => Self::MirroredRepeat,
            _ => Self::Repeat,
        }
    }
}

/// Construction, mipmap generation, and filtered sampling for `Texture2D3D`.
impl Texture2D3D {
    /// Builds a `Texture2D3D` from raw RGBA8 pixels and optionally generates a full mipmap chain.
    ///
    /// # Arguments
    ///
    /// - `&str` - Texture name.
    /// - `u32` - Base image width in pixels.
    /// - `u32` - Base image height in pixels.
    /// - `Vec<u8>` - Packed RGBA8 base-level pixels.
    /// - `TextureColorSpace` - Color-space filtering and decode mode.
    /// - `bool` - Whether to generate mip levels down to `1x1`.
    ///
    /// # Returns
    ///
    /// - `Result<Self, String>` - Ready mipmapped texture or size error.
    pub fn from_rgba8(
        name: &str,
        width: u32,
        height: u32,
        pixels: Vec<u8>,
        color_space: TextureColorSpace,
        generate_mips: bool,
    ) -> Result<Self, String> {
        let expected: usize = (width as usize)
            .saturating_mul(height as usize)
            .saturating_mul(4);
        if width == 0 || height == 0 || pixels.len() != expected {
            return Err(ERR_TEXTURE_SIZE_MISMATCH.to_string());
        }
        let mut tex: Self = Self {
            name: name.to_string(),
            width,
            height,
            color_space,
            sampler: TextureSampler3D::default(),
            mips: vec![TextureMipLevel3D {
                width,
                height,
                pixels,
            }],
        };
        if generate_mips {
            tex.generate_mipmaps();
        }
        Ok(tex)
    }

    /// Decodes encoded PNG, JPEG, BMP, HDR, or EXR bytes into a mipmapped `Texture2D3D`.
    ///
    /// # Arguments
    ///
    /// - `&str` - Texture name.
    /// - `&[u8]` - Raw encoded image bytes.
    /// - `TextureColorSpace` - Color-space interpretation.
    /// - `bool` - Whether to build the full mipmap chain.
    ///
    /// # Returns
    ///
    /// - `Result<Self, String>` - Decoded texture or codec error.
    pub fn from_encoded_bytes(
        name: &str,
        bytes: &[u8],
        color_space: TextureColorSpace,
        generate_mips: bool,
    ) -> Result<Self, String> {
        let decoded: DecodedRgbaImage = decode_raster_image_rgba(bytes)?;
        let width: u32 = decoded.get_width();
        let height: u32 = decoded.get_height();
        Self::from_rgba8(
            name,
            width,
            height,
            decoded.pixels,
            color_space,
            generate_mips,
        )
    }

    /// Rebuilds the mipmap chain from `mips[0]` down to `1x1`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable texture asset.
    pub fn generate_mipmaps(&mut self) {
        let color_space: TextureColorSpace = self.get_color_space();
        let mips: &mut Vec<TextureMipLevel3D> = self.get_mut_mips();
        if mips.is_empty() {
            return;
        }
        mips.truncate(1);
        while mips.len() < TEXTURE_MAX_MIP_LEVELS {
            let Some(last) = mips.last() else {
                break;
            };
            if last.get_width() <= 1 && last.get_height() <= 1 {
                break;
            }
            let next: TextureMipLevel3D = downsample_mip_level(last, color_space);
            mips.push(next);
        }
    }

    /// Samples a single mip level bilinearly or nearest-neighbor in linear color space.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Texture reference.
    /// - `usize` - Clamped mip level index.
    /// - `f32` - Normalized U coordinate.
    /// - `f32` - Normalized V coordinate.
    ///
    /// # Returns
    ///
    /// - `[f32; 4]` - Linear RGBA sample in `[0.0, 1.0]`.
    #[must_use]
    pub fn sample_mip(&self, mip_index: usize, u_coord: f32, v_coord: f32) -> [f32; 4] {
        let mips: &[TextureMipLevel3D] = self.get_mips().as_slice();
        if mips.is_empty() {
            return [1.0, 1.0, 1.0, 1.0];
        }
        let mip: &TextureMipLevel3D = &mips[mip_index.min(mips.len() - 1)];
        let w: usize = mip.get_width().max(1) as usize;
        let h: usize = mip.get_height().max(1) as usize;
        let sampler: TextureSampler3D = self.get_sampler();
        let u: f32 = wrap_texture_coord(u_coord, sampler.get_wrap_s());
        let v: f32 = wrap_texture_coord(v_coord, sampler.get_wrap_t());
        let fx: f32 = (u * (w as f32) - 0.5).clamp(0.0, (w - 1) as f32);
        let fy: f32 = (v * (h as f32) - 0.5).clamp(0.0, (h - 1) as f32);
        let x0: usize = fx.floor() as usize;
        let y0: usize = fy.floor() as usize;
        let x1: usize = (x0 + 1).min(w - 1);
        let y1: usize = (y0 + 1).min(h - 1);
        let tx: f32 = if matches!(
            sampler.get_mag_filter(),
            TextureFilterMode::Nearest | TextureFilterMode::NearestMipmapNearest
        ) {
            0.0
        } else {
            fx - (x0 as f32)
        };
        let ty: f32 = if matches!(
            sampler.get_mag_filter(),
            TextureFilterMode::Nearest | TextureFilterMode::NearestMipmapNearest
        ) {
            0.0
        } else {
            fy - (y0 as f32)
        };
        let pixels: &[u8] = mip.get_pixels().as_slice();
        let is_srgb: bool = self.get_color_space() == TextureColorSpace::Srgb;
        let read_texel: fn(&[u8], usize, usize, usize, bool) -> [f32; 4] =
            |buf: &[u8], stride: usize, cx: usize, cy: usize, srgb: bool| -> [f32; 4] {
                let off: usize = (cy * stride + cx) * 4;
                if srgb {
                    [
                        srgb_u8_to_linear(buf[off]),
                        srgb_u8_to_linear(buf[off + 1]),
                        srgb_u8_to_linear(buf[off + 2]),
                        f32::from(buf[off + 3]) / 255.0,
                    ]
                } else {
                    [
                        f32::from(buf[off]) / 255.0,
                        f32::from(buf[off + 1]) / 255.0,
                        f32::from(buf[off + 2]) / 255.0,
                        f32::from(buf[off + 3]) / 255.0,
                    ]
                }
            };
        let c00: [f32; 4] = read_texel(pixels, w, x0, y0, is_srgb);
        let c10: [f32; 4] = read_texel(pixels, w, x1, y0, is_srgb);
        let c01: [f32; 4] = read_texel(pixels, w, x0, y1, is_srgb);
        let c11: [f32; 4] = read_texel(pixels, w, x1, y1, is_srgb);
        let mut out: [f32; 4] = [0.0; 4];
        for ch in 0..4usize {
            let top: f32 = c00[ch] + (c10[ch] - c00[ch]) * tx;
            let bot: f32 = c01[ch] + (c11[ch] - c01[ch]) * tx;
            out[ch] = top + (bot - top) * ty;
        }
        out
    }

    /// Performs trilinear-filtered linear-space texture sampling at `(u, v, lod)`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Texture reference.
    /// - `f32` - Normalized U coordinate.
    /// - `f32` - Normalized V coordinate.
    /// - `f32` - Continuous mip level-of-detail (`0.0` = full resolution).
    ///
    /// # Returns
    ///
    /// - `[f32; 4]` - Trilinearly filtered linear RGBA sample.
    #[must_use]
    pub fn sample_trilinear(&self, u_coord: f32, v_coord: f32, lod: f32) -> [f32; 4] {
        let mip_count: usize = self.get_mips().len();
        if mip_count <= 1 || lod <= 0.0 {
            return self.sample_mip(0, u_coord, v_coord);
        }
        let max_lod: f32 = (mip_count - 1) as f32;
        let clamped: f32 = lod.clamp(0.0, max_lod);
        let lod0: usize = clamped.floor() as usize;
        let lod1: usize = (lod0 + 1).min(mip_count - 1);
        let frac: f32 = clamped - (lod0 as f32);
        let s0: [f32; 4] = self.sample_mip(lod0, u_coord, v_coord);
        if lod0 == lod1 || frac <= 1e-4 {
            return s0;
        }
        let s1: [f32; 4] = self.sample_mip(lod1, u_coord, v_coord);
        [
            s0[0] + (s1[0] - s0[0]) * frac,
            s0[1] + (s1[1] - s0[1]) * frac,
            s0[2] + (s1[2] - s0[2]) * frac,
            s0[3] + (s1[3] - s0[3]) * frac,
        ]
    }
}