1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
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,
]
}
}