naga-rust-rt 0.2.0

Support library for shaders compiled to Rust via the `naga-rust-back` library.
Documentation
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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
use core::marker::PhantomData;
use core::num::NonZeroU32;

use crate::{Scalar, Vec2, Vec3, Vec4};

// -------------------------------------------------------------------------------------------------

/// Texture sampler (placeholder).
///
/// Use this type to satisfy a sampler binding in a resource struct.
pub struct Sampler;

/// The number 1, as a [`NonZeroU32`].
///
/// Convenience alias because textures heavily use non-zero sizes.
pub const ONE: NonZeroU32 = NonZeroU32::MIN;

// -------------------------------------------------------------------------------------------------

/// 1-dimensional texture object.
///
/// Use this type to satisfy a texture binding in a resource struct,
/// when the binding has WGSL type `texture_1d`.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub struct Texture1d<T: ?Sized> {
    pub dimensions: Scalar<NonZeroU32>,
    pub mip_levels: NonZeroU32,
    pub data: T,
}

/// 2-dimensional texture object.
///
/// Use this type to satisfy a texture binding in a resource struct,
/// when the binding has WGSL type `texture_2d` or `texture_external`.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub struct Texture2d<T: ?Sized> {
    pub dimensions: Vec2<NonZeroU32>,
    pub mip_levels: NonZeroU32,
    pub data: T,
}

/// 2-dimensional array texture object.
///
/// Use this type to satisfy a texture binding in a resource struct,
/// when the binding has WGSL type `texture_2d_array`.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub struct Texture2dArray<T: ?Sized> {
    pub dimensions: Vec2<NonZeroU32>,
    pub array_layers: NonZeroU32,
    pub mip_levels: NonZeroU32,
    pub data: T,
}

/// 3-dimensional texture object.
///
/// Use this type to satisfy a texture binding in a resource struct,
/// when the binding has WGSL type `texture_3d`.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub struct Texture3d<T: ?Sized> {
    pub dimensions: Vec3<NonZeroU32>,
    pub mip_levels: NonZeroU32,
    pub data: T,
}

/// Cubemap texture object.
///
/// Use this type to satisfy a texture binding in a resource struct,
/// when the binding has WGSL type `texture_cube`.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub struct TextureCube<T: ?Sized> {
    pub dimensions: Vec2<NonZeroU32>,
    pub mip_levels: NonZeroU32,
    pub data: T,
}

/// Cubemap array texture object.
///
/// Use this type to satisfy a texture binding in a resource struct,
/// when the binding has WGSL type `texture_cube_array`.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub struct TextureCubeArray<T: ?Sized> {
    pub dimensions: Vec2<NonZeroU32>,
    pub array_layers: NonZeroU32,
    pub mip_levels: NonZeroU32,
    pub data: T,
}

/// Multisampled texture object.
///
/// Use this type to satisfy a texture binding in a resource struct,
/// when the binding has WGSL type `texture_multisampled_2d`.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub struct TextureMultisampled2d<T: ?Sized> {
    pub dimensions: Vec2<NonZeroU32>,
    pub samples: NonZeroU32,
    pub data: T,
}

// -------------------------------------------------------------------------------------------------

// TODO: we want to have these convenient constructors but without a requirement for borrowing.
// We could solve that by using `Box` instead of `&`, but it would be better to work on a general
// mechanism to avoid `dyn`.

impl<'d, C: Component> Texture1d<&'d dyn Read<Coordinates = Scalar<i32>, Component = C>> {
    pub fn one_texel(texel: &'d Constant<Scalar<i32>, C>) -> Self {
        Self {
            dimensions: Scalar::new(ONE),
            mip_levels: ONE,
            data: texel,
        }
    }
}

impl<'d, C: Component> Texture2d<&'d dyn Read<Coordinates = Vec2<i32>, Component = C>> {
    pub fn one_texel(texel: &'d Constant<Vec2<i32>, C>) -> Self {
        Self {
            dimensions: Vec2::splat(ONE),
            mip_levels: ONE,
            data: texel,
        }
    }
}

// -------------------------------------------------------------------------------------------------

/// Reads one texel from a texture.
///
/// Implement this trait and then put the implementation in a [`Texture1d`], [`Texture2d`], etc.
/// to provide a texture to your shader code.
//
// TODO: Usage example.
pub trait Read {
    type Coordinates: Copy + 'static;
    type Component: Component;

    /// Loads a single texel from the texture.
    ///
    /// If the coordinates are out of bounds, the implementation should not panic,
    /// but perform one of the behaviors specified in <https://www.w3.org/TR/WGSL/#textureload>.
    fn read_texel(
        &self,
        coordinates: Self::Coordinates,
        array_layer: i32,
        sample: i32,
        mip_level: i32,
    ) -> Vec4<Self::Component>;
}

/// Information about a texture.
///
/// This trait is implemented by all the texture types like [`Texture1d`], [`Texture2d`], etc.
pub trait Query {
    /// Type of the dimensions of the texture.
    /// Should be a [`Scalar`], [`Vec2`], or [`Vec3`] of [`NonZeroU32`].
    type Dimensions: Dimensions;

    /// Numeric type exposed to the shader.
    ///
    /// Should be one of [`u32`], [`i32`], or [`f32`], and must match the parameter of the
    /// texture type in the shader.
    type Component: Component;

    /// Returns the dimensions of mip level 0 of the texture.
    fn base_dimensions(&self) -> Self::Dimensions;

    /// Returns the count of array layers of the texture.
    ///
    /// For non-array textures, returns 1.
    fn array_layers(&self) -> NonZeroU32 {
        ONE
    }

    /// Returns the count of mip levels of the texture.
    fn mip_levels(&self) -> NonZeroU32 {
        ONE
    }

    /// Returns the count of samples of the texture.
    ///
    /// For non-multisampled textures, returns 1.
    fn samples(&self) -> NonZeroU32 {
        ONE
    }
}

/// Types which can be components of texels.
pub trait Component: Copy + 'static {}
impl Component for u32 {}
impl Component for i32 {}
impl Component for f32 {}

// -------------------------------------------------------------------------------------------------

macro_rules! impl_read_forwarder_struct {
    ($texture_type:ident) => {
        impl<T: ?Sized + Read> Read for $texture_type<T> {
            type Coordinates = T::Coordinates;
            type Component = T::Component;

            fn read_texel(
                &self,
                coordinates: Self::Coordinates,
                array_layer: i32,
                sample: i32,
                mip_level: i32,
            ) -> Vec4<Self::Component> {
                self.data
                    .read_texel(coordinates, array_layer, sample, mip_level)
            }
        }
    };
}

impl_read_forwarder_struct!(Texture1d);
impl_read_forwarder_struct!(Texture2d);
impl_read_forwarder_struct!(Texture2dArray);
impl_read_forwarder_struct!(Texture3d);
impl_read_forwarder_struct!(TextureCube);
impl_read_forwarder_struct!(TextureCubeArray);
impl_read_forwarder_struct!(TextureMultisampled2d);

macro_rules! impl_read_forwarder_deref {
    ($($ty:tt)*) => {
        impl<T: ?Sized + Read> Read for $($ty)* {
            type Coordinates = T::Coordinates;
            type Component = T::Component;

            fn read_texel(
                &self,
                coordinates: Self::Coordinates,
                array_layer: i32,
                sample: i32,
                mip_level: i32,
            ) -> Vec4<Self::Component> {
                T::read_texel(&**self, coordinates, array_layer, sample, mip_level)
            }
        }
    };
}

impl_read_forwarder_deref!(&T);
impl_read_forwarder_deref!(&mut T);
#[cfg(feature = "alloc")]
impl_read_forwarder_deref!(alloc::boxed::Box<T>);
#[cfg(feature = "alloc")]
impl_read_forwarder_deref!(alloc::rc::Rc<T>);
#[cfg(feature = "alloc")]
impl_read_forwarder_deref!(alloc::sync::Arc<T>);

// -------------------------------------------------------------------------------------------------

macro_rules! query_common {
    () => {
        type Component = T::Component;
        fn base_dimensions(&self) -> Self::Dimensions {
            self.dimensions
        }
    };
}

macro_rules! query_mip {
    () => {
        fn mip_levels(&self) -> NonZeroU32 {
            self.mip_levels
        }
    };
}

impl<T: ?Sized + Read> Query for Texture1d<T> {
    type Dimensions = Scalar<NonZeroU32>;
    query_common!();
    query_mip!();
}

impl<T: ?Sized + Read> Query for Texture2d<T> {
    type Dimensions = Vec2<NonZeroU32>;
    query_common!();
    query_mip!();
}

impl<T: ?Sized + Read> Query for Texture2dArray<T> {
    type Dimensions = Vec2<NonZeroU32>;
    query_common!();
    query_mip!();
    fn array_layers(&self) -> NonZeroU32 {
        self.array_layers
    }
}

impl<T: ?Sized + Read> Query for Texture3d<T> {
    type Dimensions = Vec3<NonZeroU32>;
    query_common!();
    query_mip!();
}

impl<T: ?Sized + Read> Query for TextureCube<T> {
    type Dimensions = Vec2<NonZeroU32>;
    query_common!();
    query_mip!();
}

impl<T: ?Sized + Read> Query for TextureCubeArray<T> {
    type Dimensions = Vec2<NonZeroU32>;
    query_common!();
    query_mip!();
    fn array_layers(&self) -> NonZeroU32 {
        self.array_layers
    }
}

impl<T: ?Sized + Read> Query for TextureMultisampled2d<T> {
    type Dimensions = Vec2<NonZeroU32>;
    query_common!();
    fn samples(&self) -> NonZeroU32 {
        self.samples
    }
}

// -------------------------------------------------------------------------------------------------

/// Generic texture data container for textures whose texels are all identical.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] // TODO: derives have bounds on C
pub struct Constant<C, T> {
    pub texel: Vec4<T>,
    _phantom: PhantomData<fn(C)>,
}

impl<C: Copy + 'static, T: Component> Constant<C, T> {
    pub const fn new(texel: Vec4<T>) -> Self {
        Self {
            texel,
            _phantom: PhantomData,
        }
    }
}

impl<C: Copy + 'static, T: Component> Read for Constant<C, T> {
    type Coordinates = C;
    type Component = T;

    fn read_texel(
        &self,
        _coordinates: Self::Coordinates,
        _array_layer: i32,
        _sample: i32,
        _mip_level: i32,
    ) -> Vec4<Self::Component> {
        self.texel
    }
}

// -------------------------------------------------------------------------------------------------

/// Computes the dimensions of a specific mip level of a texture.
///
/// The result is meaningless if the mip level is out of bounds.
///
/// As per WGSL [`textureDimensions`](https://www.w3.org/TR/2026/CRD-WGSL-20260507/#texturedimensions).
//
// Design note: The result is `u32`, not `NonZeroU32`, for the sake of the shader code which does
// not have `NonZero` types.
pub fn dimensions<Q>(texture: &Q, mip_level: i32) -> <Q::Dimensions as Dimensions>::Plain
where
    Q: ?Sized + Query,
{
    Dimensions::at_mip_level(texture.base_dimensions(), mip_level as u32)
}

/// Adapter for calling texture query functions.
///
/// TODO: This should probably be something more general, but it’s hard to say what.
#[doc(hidden)]
pub fn non_zero_to_scalar(input: NonZeroU32) -> Scalar<u32> {
    Scalar(input.get())
}

use dim::Dimensions;
mod dim {
    use super::*;

    /// Semi-private trait implemented for vectors that can describe texture dimensions.
    /// Helper for [`dimensions()`].
    pub trait Dimensions: Copy + 'static {
        /// The vector with `u32` components instead of `NonZeroU32`.
        type Plain;

        fn at_mip_level(self, mip_level: u32) -> Self::Plain;
    }

    impl Dimensions for Scalar<NonZeroU32> {
        type Plain = Scalar<u32>;
        fn at_mip_level(self, mip_level: u32) -> Self::Plain {
            Scalar::new(mip_divide_size(self.0, mip_level))
        }
    }
    impl Dimensions for Vec2<NonZeroU32> {
        type Plain = Vec2<u32>;
        fn at_mip_level(self, mip_level: u32) -> Self::Plain {
            Vec2::new(
                mip_divide_size(self.x, mip_level),
                mip_divide_size(self.y, mip_level),
            )
        }
    }
    impl Dimensions for Vec3<NonZeroU32> {
        type Plain = Vec3<u32>;
        fn at_mip_level(self, mip_level: u32) -> Self::Plain {
            Vec3::new(
                mip_divide_size(self.x, mip_level),
                mip_divide_size(self.y, mip_level),
                mip_divide_size(self.z, mip_level),
            )
        }
    }

    /// Computes one component of the size of a given mip level of a texture,
    /// given the size at level 0.
    fn mip_divide_size(size: NonZeroU32, mip_level: u32) -> u32 {
        // Per <https://www.w3.org/TR/2026/CRD-webgpu-20260507/#abstract-opdef-logical-miplevel-specific-texture-extent>
        (size.get() >> mip_level).max(1)
    }
}