Skip to main content

strata_render/
texture3d.rs

1//! Texture resources, sampler state, and per-triangle sampling for the 3D path.
2//!
3//! The 3D rasterizer previously had no way to represent an image on a mesh, so
4//! tile imagery could not be drawn at all. This module provides the minimum a
5//! renderer needs: an RGBA texture store with stable handles, sampler state
6//! (filter and address mode), and a UV transform that maps a tile's sub-rect of
7//! a loaded ancestor texture onto a unit quad.
8//!
9//! Sampling is perspective correct: callers interpolate `u/w` and `v/w`
10//! alongside `1/w`, then divide. See `crate::rasterizer3d`.
11
12use std::collections::HashMap;
13use std::sync::Arc;
14
15/// Opaque handle to a texture in a [`TextureStore`].
16#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
17pub struct TextureId(pub u32);
18
19/// Pixel layout of a texture.
20#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
21pub enum TextureFormat {
22    /// 8-bit per channel RGBA, rows top to bottom, no padding.
23    #[default]
24    Rgba8,
25}
26
27impl TextureFormat {
28    /// Bytes occupied by one pixel.
29    #[inline(always)]
30    pub const fn bytes_per_pixel(self) -> usize {
31        4
32    }
33}
34
35/// Minification and magnification filtering.
36#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
37pub enum FilterMode {
38    /// Nearest neighbour: exact texel, no blending.
39    Nearest,
40    /// Bilinear: four-tap blend of neighbouring texels.
41    #[default]
42    Bilinear,
43}
44
45/// Out-of-range behaviour for texture coordinates.
46#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
47pub enum AddressMode {
48    /// Coordinates are clamped to the border texels.
49    #[default]
50    ClampToEdge,
51    /// Coordinates wrap to `frac(u)`.
52    Repeat,
53    /// Coordinates mirror on each integer boundary.
54    MirrorRepeat,
55}
56
57impl AddressMode {
58    /// Resolves a normalized coordinate into a wrapped or clamped value.
59    #[inline(always)]
60    pub fn wrap(self, t: f32) -> f32 {
61        match self {
62            Self::ClampToEdge => t.clamp(0.0, 1.0),
63            Self::Repeat => t - t.floor(),
64            Self::MirrorRepeat => {
65                // Period is 2: `0..=1` mirrors, `1..=2` reflects back.
66                let period = 2.0;
67                let mut m = t - (t / period).floor() * period;
68                if m > 1.0 {
69                    m = period - m;
70                }
71                m
72            }
73        }
74    }
75}
76
77/// An affine transform applied to texture coordinates before sampling.
78///
79/// The reference resolves a tile to the closest loaded ancestor image plus the
80/// exact sub-rectangle of that image the tile occupies. That rectangle is
81/// `uv * scale + offset`, where `scale` is the sub-rect extent and `offset` is
82/// its origin.
83#[derive(Debug, Clone, Copy, PartialEq)]
84pub struct UvTransform {
85    pub scale: [f32; 2],
86    pub offset: [f32; 2],
87}
88
89impl Default for UvTransform {
90    fn default() -> Self {
91        Self::IDENTITY
92    }
93}
94
95impl UvTransform {
96    /// Samples the whole texture.
97    pub const IDENTITY: Self = Self {
98        scale: [1.0, 1.0],
99        offset: [0.0, 0.0],
100    };
101
102    /// Builds a transform from the sub-rect `[u_min, v_min] ..= [u_max, v_max]`.
103    pub fn from_sub_rect(u_min: f32, v_min: f32, u_max: f32, v_max: f32) -> Self {
104        Self {
105            scale: [u_max - u_min, v_max - v_min],
106            offset: [u_min, v_min],
107        }
108    }
109
110    /// Applies the transform to a normalized coordinate.
111    #[inline(always)]
112    pub fn apply(self, uv: (f32, f32)) -> (f32, f32) {
113        (
114            uv.0 * self.scale[0] + self.offset[0],
115            uv.1 * self.scale[1] + self.offset[1],
116        )
117    }
118}
119
120/// Sampler state for one texture.
121#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
122pub struct SamplerDesc {
123    pub filter: FilterMode,
124    pub address_u: AddressMode,
125    pub address_v: AddressMode,
126}
127
128/// Immutable texture description.
129#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
130pub struct TextureDesc {
131    pub width: u32,
132    pub height: u32,
133    pub format: TextureFormat,
134}
135
136impl TextureDesc {
137    /// Number of bytes a correctly sized pixel buffer occupies.
138    #[inline(always)]
139    pub const fn byte_len(&self) -> usize {
140        self.width as usize * self.height as usize * self.format.bytes_per_pixel()
141    }
142}
143
144/// A described texture payload.
145#[derive(Debug, Clone, PartialEq)]
146pub struct TextureData {
147    pub desc: TextureDesc,
148    /// Tightly packed pixels; length must equal `desc.byte_len()`.
149    pub pixels: Arc<[u8]>,
150}
151
152/// A stored texture: payload plus sampler state.
153#[derive(Debug, Clone, PartialEq)]
154pub struct Texture {
155    pub data: TextureData,
156    pub sampler: SamplerDesc,
157}
158
159/// Registry of textures addressable by [`TextureId`].
160///
161/// Ids are stable for the lifetime of the store and are never reused, so a
162/// handle held by a mesh cannot accidentally resolve to a different image
163/// after an eviction.
164#[derive(Debug, Clone, Default, PartialEq)]
165pub struct TextureStore {
166    textures: HashMap<TextureId, Texture>,
167    next_id: u32,
168    generation: u64,
169}
170
171impl TextureStore {
172    pub fn new() -> Self {
173        Self {
174            textures: HashMap::new(),
175            next_id: 1,
176            generation: 0,
177        }
178    }
179
180    /// Inserts a texture and returns its handle.
181    ///
182    /// Returns `None` when the pixel buffer does not match the description.
183    pub fn insert(&mut self, data: TextureData, sampler: SamplerDesc) -> Option<TextureId> {
184        if data.pixels.len() != data.desc.byte_len()
185            || data.desc.width == 0
186            || data.desc.height == 0
187        {
188            return None;
189        }
190        let id = TextureId(self.next_id);
191        self.next_id += 1;
192        self.textures.insert(id, Texture { data, sampler });
193        self.generation += 1;
194        Some(id)
195    }
196
197    /// Inserts a texture with the default sampler.
198    pub fn insert_rgba8(
199        &mut self,
200        width: u32,
201        height: u32,
202        pixels: impl Into<Arc<[u8]>>,
203    ) -> Option<TextureId> {
204        self.insert(
205            TextureData {
206                desc: TextureDesc {
207                    width,
208                    height,
209                    format: TextureFormat::Rgba8,
210                },
211                pixels: pixels.into(),
212            },
213            SamplerDesc::default(),
214        )
215    }
216
217    pub fn get(&self, id: TextureId) -> Option<&Texture> {
218        self.textures.get(&id)
219    }
220
221    pub fn remove(&mut self, id: TextureId) -> Option<Texture> {
222        let removed = self.textures.remove(&id);
223        if removed.is_some() {
224            self.generation += 1;
225        }
226        removed
227    }
228
229    pub fn len(&self) -> usize {
230        self.textures.len()
231    }
232
233    pub fn is_empty(&self) -> bool {
234        self.textures.is_empty()
235    }
236
237    /// Number of mutations since creation. GPU upload caches compare this to
238    /// decide whether a bind group must be rebuilt.
239    pub fn generation(&self) -> u64 {
240        self.generation
241    }
242
243    /// Samples a texture with perspective-correct inputs already divided out.
244    ///
245    /// `uv` is the interpolated `(u/w, v/w)` divided by the interpolated
246    /// `1/w` by the caller. Returns straight RGBA8.
247    pub fn sample(&self, id: TextureId, uv: (f32, f32)) -> Option<[u8; 4]> {
248        let texture = self.get(id)?;
249        Some(sample_texture(texture, uv))
250    }
251}
252
253/// Samples one texture. Pure function so the rasterizer can call it per pixel
254/// without touching the store's hash map.
255#[inline]
256pub fn sample_texture(texture: &Texture, uv: (f32, f32)) -> [u8; 4] {
257    let width = texture.data.desc.width as usize;
258    let height = texture.data.desc.height as usize;
259    let pixels = &texture.data.pixels;
260
261    let u = texture.sampler.address_u.wrap(uv.0);
262    let v = texture.sampler.address_v.wrap(uv.1);
263
264    match texture.sampler.filter {
265        FilterMode::Nearest => {
266            let x = ((u * width as f32) as isize).clamp(0, width as isize - 1) as usize;
267            let y = ((v * height as f32) as isize).clamp(0, height as isize - 1) as usize;
268            texel(pixels, width, x, y)
269        }
270        FilterMode::Bilinear => {
271            // Texel centres sit at (i + 0.5) / size.
272            let fx = u * width as f32 - 0.5;
273            let fy = v * height as f32 - 0.5;
274            let x0 = fx.floor();
275            let y0 = fy.floor();
276            let tx = fx - x0;
277            let ty = fy - y0;
278
279            let xi = |raw: f32| -> usize { raw.clamp(0.0, width as f32 - 1.0) as usize };
280            let yi = |raw: f32| -> usize { raw.clamp(0.0, height as f32 - 1.0) as usize };
281
282            let x0u = xi(x0);
283            let x1u = xi(x0 + 1.0);
284            let y0u = yi(y0);
285            let y1u = yi(y0 + 1.0);
286
287            let c00 = texel(pixels, width, x0u, y0u);
288            let c10 = texel(pixels, width, x1u, y0u);
289            let c01 = texel(pixels, width, x0u, y1u);
290            let c11 = texel(pixels, width, x1u, y1u);
291
292            let mut out = [0u8; 4];
293            for ch in 0..4 {
294                let top = c00[ch] as f32 * (1.0 - tx) + c10[ch] as f32 * tx;
295                let bottom = c01[ch] as f32 * (1.0 - tx) + c11[ch] as f32 * tx;
296                let value = top * (1.0 - ty) + bottom * ty;
297                out[ch] = value.round().clamp(0.0, 255.0) as u8;
298            }
299            out
300        }
301    }
302}
303
304/// Bilinear sample with clamped addressing, the tile path.
305///
306/// This is the specialized form of [`sample_texture`] for the sampler every
307/// tile uses. Hoisting the filter and address-mode branches out of the
308/// reference function matters when terrain fills a 1440x900 viewport.
309#[inline(always)]
310pub fn sample_bilinear_clamped(texture: &Texture, u: f32, v: f32) -> [u8; 4] {
311    let width = texture.data.desc.width as usize;
312    let height = texture.data.desc.height as usize;
313    let pixels = &texture.data.pixels;
314    let u = u.clamp(0.0, 1.0);
315    let v = v.clamp(0.0, 1.0);
316
317    let fx = u * width as f32 - 0.5;
318    let fy = v * height as f32 - 0.5;
319    let x0 = fx.floor();
320    let y0 = fy.floor();
321    let tx = fx - x0;
322    let ty = fy - y0;
323
324    let x0u = x0.clamp(0.0, width as f32 - 1.0) as usize;
325    let x1u = (x0 + 1.0).clamp(0.0, width as f32 - 1.0) as usize;
326    let y0u = y0.clamp(0.0, height as f32 - 1.0) as usize;
327    let y1u = (y0 + 1.0).clamp(0.0, height as f32 - 1.0) as usize;
328
329    let c00 = texel(pixels, width, x0u, y0u);
330    let c10 = texel(pixels, width, x1u, y0u);
331    let c01 = texel(pixels, width, x0u, y1u);
332    let c11 = texel(pixels, width, x1u, y1u);
333
334    let w00 = (1.0 - tx) * (1.0 - ty);
335    let w10 = tx * (1.0 - ty);
336    let w01 = (1.0 - tx) * ty;
337    let w11 = tx * ty;
338    let mix = |c00: u8, c10: u8, c01: u8, c11: u8| -> u8 {
339        let value = c00 as f32 * w00 + c10 as f32 * w10 + c01 as f32 * w01 + c11 as f32 * w11;
340        value.round().clamp(0.0, 255.0) as u8
341    };
342    [
343        mix(c00[0], c10[0], c01[0], c11[0]),
344        mix(c00[1], c10[1], c01[1], c11[1]),
345        mix(c00[2], c10[2], c01[2], c11[2]),
346        mix(c00[3], c10[3], c01[3], c11[3]),
347    ]
348}
349
350#[inline(always)]
351fn texel(pixels: &[u8], width: usize, x: usize, y: usize) -> [u8; 4] {
352    let idx = (y * width + x) * 4;
353    [
354        pixels[idx],
355        pixels[idx + 1],
356        pixels[idx + 2],
357        pixels[idx + 3],
358    ]
359}