Skip to main content

euv_core/game/engine3d/texture/
impl.rs

1use super::*;
2
3/// glTF 2.0 WebGL constant mapping helpers for `TextureFilterMode`.
4impl TextureFilterMode {
5    /// Decodes a glTF 2.0 / WebGL numeric filter constant into `TextureFilterMode`.
6    ///
7    /// # Arguments
8    ///
9    /// - `u32` - glTF numeric filter constant (`9728`, `9729`, `9984..=9987`).
10    ///
11    /// # Returns
12    ///
13    /// - `Self` - Matching texture filter mode (defaults to `Linear`).
14    #[must_use]
15    pub const fn from_gltf_code(code: u32) -> Self {
16        match code {
17            9728 => Self::Nearest,
18            9729 => Self::Linear,
19            9984 => Self::NearestMipmapNearest,
20            9985 => Self::LinearMipmapNearest,
21            9986 => Self::NearestMipmapLinear,
22            9987 => Self::LinearMipmapLinear,
23            _ => Self::Linear,
24        }
25    }
26}
27
28/// glTF 2.0 WebGL constant mapping helpers for `TextureWrapMode`.
29impl TextureWrapMode {
30    /// Decodes a glTF 2.0 / WebGL numeric wrap constant into `TextureWrapMode`.
31    ///
32    /// # Arguments
33    ///
34    /// - `u32` - glTF numeric wrap constant (`10497`, `33071`, `33648`).
35    ///
36    /// # Returns
37    ///
38    /// - `Self` - Matching texture wrap mode (defaults to `Repeat`).
39    #[must_use]
40    pub const fn from_gltf_code(code: u32) -> Self {
41        match code {
42            33_071 => Self::ClampToEdge,
43            33_648 => Self::MirroredRepeat,
44            _ => Self::Repeat,
45        }
46    }
47}
48
49/// Construction, mipmap generation, and filtered sampling for `Texture2D3D`.
50impl Texture2D3D {
51    /// Builds a `Texture2D3D` from raw RGBA8 pixels and optionally generates a full mipmap chain.
52    ///
53    /// # Arguments
54    ///
55    /// - `&str` - Texture name.
56    /// - `u32` - Base image width in pixels.
57    /// - `u32` - Base image height in pixels.
58    /// - `Vec<u8>` - Packed RGBA8 base-level pixels.
59    /// - `TextureColorSpace` - Color-space filtering and decode mode.
60    /// - `bool` - Whether to generate mip levels down to `1x1`.
61    ///
62    /// # Returns
63    ///
64    /// - `Result<Self, String>` - Ready mipmapped texture or size error.
65    pub fn from_rgba8(
66        name: &str,
67        width: u32,
68        height: u32,
69        pixels: Vec<u8>,
70        color_space: TextureColorSpace,
71        generate_mips: bool,
72    ) -> Result<Self, String> {
73        let expected: usize = (width as usize)
74            .saturating_mul(height as usize)
75            .saturating_mul(4);
76        if width == 0 || height == 0 || pixels.len() != expected {
77            return Err(ERR_TEXTURE_SIZE_MISMATCH.to_string());
78        }
79        let mut tex: Self = Self {
80            name: name.to_string(),
81            width,
82            height,
83            color_space,
84            sampler: TextureSampler3D::default(),
85            mips: vec![TextureMipLevel3D {
86                width,
87                height,
88                pixels,
89            }],
90        };
91        if generate_mips {
92            tex.generate_mipmaps();
93        }
94        Ok(tex)
95    }
96
97    /// Decodes encoded PNG, JPEG, BMP, HDR, or EXR bytes into a mipmapped `Texture2D3D`.
98    ///
99    /// # Arguments
100    ///
101    /// - `&str` - Texture name.
102    /// - `&[u8]` - Raw encoded image bytes.
103    /// - `TextureColorSpace` - Color-space interpretation.
104    /// - `bool` - Whether to build the full mipmap chain.
105    ///
106    /// # Returns
107    ///
108    /// - `Result<Self, String>` - Decoded texture or codec error.
109    pub fn from_encoded_bytes(
110        name: &str,
111        bytes: &[u8],
112        color_space: TextureColorSpace,
113        generate_mips: bool,
114    ) -> Result<Self, String> {
115        let decoded: DecodedRgbaImage = decode_raster_image_rgba(bytes)?;
116        let width: u32 = decoded.get_width();
117        let height: u32 = decoded.get_height();
118        Self::from_rgba8(
119            name,
120            width,
121            height,
122            decoded.pixels,
123            color_space,
124            generate_mips,
125        )
126    }
127
128    /// Rebuilds the mipmap chain from `mips[0]` down to `1x1`.
129    ///
130    /// # Arguments
131    ///
132    /// - `&Self` - Mutable texture asset.
133    pub fn generate_mipmaps(&mut self) {
134        let color_space: TextureColorSpace = self.get_color_space();
135        let mips: &mut Vec<TextureMipLevel3D> = self.get_mut_mips();
136        if mips.is_empty() {
137            return;
138        }
139        mips.truncate(1);
140        while mips.len() < TEXTURE_MAX_MIP_LEVELS {
141            let Some(last) = mips.last() else {
142                break;
143            };
144            if last.get_width() <= 1 && last.get_height() <= 1 {
145                break;
146            }
147            let next: TextureMipLevel3D = downsample_mip_level(last, color_space);
148            mips.push(next);
149        }
150    }
151
152    /// Samples a single mip level bilinearly or nearest-neighbor in linear color space.
153    ///
154    /// # Arguments
155    ///
156    /// - `&Self` - Texture reference.
157    /// - `usize` - Clamped mip level index.
158    /// - `f32` - Normalized U coordinate.
159    /// - `f32` - Normalized V coordinate.
160    ///
161    /// # Returns
162    ///
163    /// - `[f32; 4]` - Linear RGBA sample in `[0.0, 1.0]`.
164    #[must_use]
165    pub fn sample_mip(&self, mip_index: usize, u_coord: f32, v_coord: f32) -> [f32; 4] {
166        let mips: &[TextureMipLevel3D] = self.get_mips().as_slice();
167        if mips.is_empty() {
168            return [1.0, 1.0, 1.0, 1.0];
169        }
170        let mip: &TextureMipLevel3D = &mips[mip_index.min(mips.len() - 1)];
171        let w: usize = mip.get_width().max(1) as usize;
172        let h: usize = mip.get_height().max(1) as usize;
173        let sampler: TextureSampler3D = self.get_sampler();
174        let u: f32 = wrap_texture_coord(u_coord, sampler.get_wrap_s());
175        let v: f32 = wrap_texture_coord(v_coord, sampler.get_wrap_t());
176        let fx: f32 = (u * (w as f32) - 0.5).clamp(0.0, (w - 1) as f32);
177        let fy: f32 = (v * (h as f32) - 0.5).clamp(0.0, (h - 1) as f32);
178        let x0: usize = fx.floor() as usize;
179        let y0: usize = fy.floor() as usize;
180        let x1: usize = (x0 + 1).min(w - 1);
181        let y1: usize = (y0 + 1).min(h - 1);
182        let tx: f32 = if matches!(
183            sampler.get_mag_filter(),
184            TextureFilterMode::Nearest | TextureFilterMode::NearestMipmapNearest
185        ) {
186            0.0
187        } else {
188            fx - (x0 as f32)
189        };
190        let ty: f32 = if matches!(
191            sampler.get_mag_filter(),
192            TextureFilterMode::Nearest | TextureFilterMode::NearestMipmapNearest
193        ) {
194            0.0
195        } else {
196            fy - (y0 as f32)
197        };
198        let pixels: &[u8] = mip.get_pixels().as_slice();
199        let is_srgb: bool = self.get_color_space() == TextureColorSpace::Srgb;
200        let read_texel: fn(&[u8], usize, usize, usize, bool) -> [f32; 4] =
201            |buf: &[u8], stride: usize, cx: usize, cy: usize, srgb: bool| -> [f32; 4] {
202                let off: usize = (cy * stride + cx) * 4;
203                if srgb {
204                    [
205                        srgb_u8_to_linear(buf[off]),
206                        srgb_u8_to_linear(buf[off + 1]),
207                        srgb_u8_to_linear(buf[off + 2]),
208                        f32::from(buf[off + 3]) / 255.0,
209                    ]
210                } else {
211                    [
212                        f32::from(buf[off]) / 255.0,
213                        f32::from(buf[off + 1]) / 255.0,
214                        f32::from(buf[off + 2]) / 255.0,
215                        f32::from(buf[off + 3]) / 255.0,
216                    ]
217                }
218            };
219        let c00: [f32; 4] = read_texel(pixels, w, x0, y0, is_srgb);
220        let c10: [f32; 4] = read_texel(pixels, w, x1, y0, is_srgb);
221        let c01: [f32; 4] = read_texel(pixels, w, x0, y1, is_srgb);
222        let c11: [f32; 4] = read_texel(pixels, w, x1, y1, is_srgb);
223        let mut out: [f32; 4] = [0.0; 4];
224        for ch in 0..4usize {
225            let top: f32 = c00[ch] + (c10[ch] - c00[ch]) * tx;
226            let bot: f32 = c01[ch] + (c11[ch] - c01[ch]) * tx;
227            out[ch] = top + (bot - top) * ty;
228        }
229        out
230    }
231
232    /// Performs trilinear-filtered linear-space texture sampling at `(u, v, lod)`.
233    ///
234    /// # Arguments
235    ///
236    /// - `&Self` - Texture reference.
237    /// - `f32` - Normalized U coordinate.
238    /// - `f32` - Normalized V coordinate.
239    /// - `f32` - Continuous mip level-of-detail (`0.0` = full resolution).
240    ///
241    /// # Returns
242    ///
243    /// - `[f32; 4]` - Trilinearly filtered linear RGBA sample.
244    #[must_use]
245    pub fn sample_trilinear(&self, u_coord: f32, v_coord: f32, lod: f32) -> [f32; 4] {
246        let mip_count: usize = self.get_mips().len();
247        if mip_count <= 1 || lod <= 0.0 {
248            return self.sample_mip(0, u_coord, v_coord);
249        }
250        let max_lod: f32 = (mip_count - 1) as f32;
251        let clamped: f32 = lod.clamp(0.0, max_lod);
252        let lod0: usize = clamped.floor() as usize;
253        let lod1: usize = (lod0 + 1).min(mip_count - 1);
254        let frac: f32 = clamped - (lod0 as f32);
255        let s0: [f32; 4] = self.sample_mip(lod0, u_coord, v_coord);
256        if lod0 == lod1 || frac <= 1e-4 {
257            return s0;
258        }
259        let s1: [f32; 4] = self.sample_mip(lod1, u_coord, v_coord);
260        [
261            s0[0] + (s1[0] - s0[0]) * frac,
262            s0[1] + (s1[1] - s0[1]) * frac,
263            s0[2] + (s1[2] - s0[2]) * frac,
264            s0[3] + (s1[3] - s0[3]) * frac,
265        ]
266    }
267}