siftgl 0.1.0

Memory-safe, ergonomic, zero-dependency, security-hardened OpenGL 3.3-4.6 Core frontend for Rust
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
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
//! Bounds-checked OpenGL textures and sampler objects.

use std::ffi::c_void;
use std::fmt;
use std::ptr;
use std::rc::Rc;

use crate::context::{GlContext, GlInner};
use crate::error::{checked_sizei, GlError, Result};
use crate::sys;
use crate::types::{
    CompareFunc, InternalFormat, PixelFormat, PixelType, TextureFilter, TextureTarget, TextureWrap,
};

/// Descriptor for creating a 2D [`Texture`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Texture2DDesc {
    /// Width in texels (must be non-zero).
    pub width: u32,
    /// Height in texels (must be non-zero).
    pub height: u32,
    /// GPU internal storage format.
    pub internal_format: InternalFormat,
    /// Client pixel channel layout (used when uploading initial data).
    pub pixel_format: PixelFormat,
    /// Client pixel scalar type (used when uploading initial data).
    pub pixel_type: PixelType,
    /// Minification filter.
    pub min_filter: TextureFilter,
    /// Magnification filter (must be `Nearest` or `Linear`).
    pub mag_filter: TextureFilter,
    /// Horizontal wrap mode (`S`).
    pub wrap_s: TextureWrap,
    /// Vertical wrap mode (`T`).
    pub wrap_t: TextureWrap,
}

impl Texture2DDesc {
    /// Creates a standard `RGBA8` 2D texture descriptor with linear filtering and edge clamping.
    #[inline]
    pub const fn rgba8(width: u32, height: u32) -> Self {
        Self {
            width,
            height,
            internal_format: InternalFormat::Rgba8,
            pixel_format: PixelFormat::Rgba,
            pixel_type: PixelType::U8,
            min_filter: TextureFilter::Linear,
            mag_filter: TextureFilter::Linear,
            wrap_s: TextureWrap::ClampToEdge,
            wrap_t: TextureWrap::ClampToEdge,
        }
    }
}

/// RAII wrapper around an OpenGL texture object.
pub struct Texture {
    ctx: Rc<GlInner>,
    id: sys::GLuint,
    target: TextureTarget,
    width: u32,
    height: u32,
    internal_format: InternalFormat,
}

impl fmt::Debug for Texture {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Texture")
            .field("id", &self.id)
            .field("target", &self.target)
            .field("width", &self.width)
            .field("height", &self.height)
            .field("internal_format", &self.internal_format)
            .finish()
    }
}

impl Drop for Texture {
    fn drop(&mut self) {
        if self.id != 0 {
            // SAFETY: `self.id` is exclusively owned by this `Texture`.
            unsafe { (self.ctx.fns.delete_textures)(1, &self.id) };
        }
    }
}

impl Texture {
    /// Creates a 2D texture, optionally uploading initial tightly-packed pixel data.
    pub fn new_2d(
        ctx: &GlContext,
        desc: &Texture2DDesc,
        initial_data: Option<&[u8]>,
    ) -> Result<Self> {
        if desc.width == 0 || desc.height == 0 {
            return Err(GlError::InvalidParameter {
                parameter: "dimensions",
                reason: "texture width and height must be non-zero",
            });
        }
        if !desc.mag_filter.is_valid_mag_filter() {
            return Err(GlError::InvalidParameter {
                parameter: "mag_filter",
                reason: "magnification filter must be Nearest or Linear",
            });
        }

        let w = checked_sizei(desc.width as usize, "Texture::new_2d width")?;
        let h = checked_sizei(desc.height as usize, "Texture::new_2d height")?;

        if let Some(bytes) = initial_data {
            let expected = expected_pixel_bytes(
                desc.width,
                desc.height,
                desc.pixel_format,
                desc.pixel_type,
            )?;
            if bytes.len() < expected {
                return Err(GlError::BufferSizeMismatch {
                    expected,
                    actual: bytes.len(),
                });
            }
        }

        let mut id: sys::GLuint = 0;
        // SAFETY: Generates one texture name in valid stack storage.
        unsafe { (ctx.inner.fns.gen_textures)(1, &mut id) };
        if id == 0 {
            return Err(GlError::ObjectCreationFailed { object: "Texture" });
        }

        let tex = Self {
            ctx: Rc::clone(&ctx.inner),
            id,
            target: TextureTarget::Texture2D,
            width: desc.width,
            height: desc.height,
            internal_format: desc.internal_format,
        };

        let ptr = initial_data.map_or(ptr::null(), |b| b.as_ptr().cast::<c_void>());
        // SAFETY: `GL_UNPACK_ALIGNMENT = 1` matches tightly packed `initial_data`
        // whose length was validated against `expected_pixel_bytes`.
        unsafe {
            (tex.ctx.fns.bind_texture)(sys::GL_TEXTURE_2D, tex.id);
            (tex.ctx.fns.pixel_storei)(sys::GL_UNPACK_ALIGNMENT, 1);
            (tex.ctx.fns.tex_image_2d)(
                sys::GL_TEXTURE_2D,
                0,
                desc.internal_format as sys::GLint,
                w,
                h,
                0,
                desc.pixel_format as sys::GLenum,
                desc.pixel_type as sys::GLenum,
                ptr,
            );
            (tex.ctx.fns.tex_parameteri)(
                sys::GL_TEXTURE_2D,
                sys::GL_TEXTURE_MIN_FILTER,
                desc.min_filter as sys::GLint,
            );
            (tex.ctx.fns.tex_parameteri)(
                sys::GL_TEXTURE_2D,
                sys::GL_TEXTURE_MAG_FILTER,
                desc.mag_filter as sys::GLint,
            );
            (tex.ctx.fns.tex_parameteri)(
                sys::GL_TEXTURE_2D,
                sys::GL_TEXTURE_WRAP_S,
                desc.wrap_s as sys::GLint,
            );
            (tex.ctx.fns.tex_parameteri)(
                sys::GL_TEXTURE_2D,
                sys::GL_TEXTURE_WRAP_T,
                desc.wrap_t as sys::GLint,
            );
        }
        tex.ctx.check_gl_error("glTexImage2D")?;
        Ok(tex)
    }

    /// Returns the raw OpenGL texture ID.
    #[inline]
    pub const fn raw_id(&self) -> u32 {
        self.id
    }

    /// Returns the texture target.
    #[inline]
    pub const fn target(&self) -> TextureTarget {
        self.target
    }

    /// Returns the base-level width in texels.
    #[inline]
    pub const fn width(&self) -> u32 {
        self.width
    }

    /// Returns the base-level height in texels.
    #[inline]
    pub const fn height(&self) -> u32 {
        self.height
    }

    /// Returns the internal storage format.
    #[inline]
    pub const fn internal_format(&self) -> InternalFormat {
        self.internal_format
    }

    /// Binds this texture to texture unit `unit` (`0..31`).
    pub fn bind_unit(&self, unit: u32) -> Result<()> {
        if unit >= 32 {
            return Err(GlError::OutOfBounds {
                context: "Texture::bind_unit",
                requested: unit as usize,
                available: 32,
            });
        }
        // SAFETY: `GL_TEXTURE0 + unit` is within valid texture unit range.
        unsafe {
            (self.ctx.fns.active_texture)(sys::GL_TEXTURE0 + unit);
            (self.ctx.fns.bind_texture)(self.target as sys::GLenum, self.id);
        }
        Ok(())
    }

    /// Uploads a sub-rectangle of tightly-packed pixels to mip level `0` (`glTexSubImage2D`).
    #[allow(clippy::too_many_arguments)]
    pub fn upload_sub_2d(
        &self,
        x: u32,
        y: u32,
        width: u32,
        height: u32,
        pixel_format: PixelFormat,
        pixel_type: PixelType,
        data: &[u8],
    ) -> Result<()> {
        let x_end = x.checked_add(width).ok_or(GlError::IntegerOverflow {
            context: "Texture::upload_sub_2d x_end",
        })?;
        let y_end = y.checked_add(height).ok_or(GlError::IntegerOverflow {
            context: "Texture::upload_sub_2d y_end",
        })?;
        if x_end > self.width {
            return Err(GlError::OutOfBounds {
                context: "Texture::upload_sub_2d x",
                requested: x_end as usize,
                available: self.width as usize,
            });
        }
        if y_end > self.height {
            return Err(GlError::OutOfBounds {
                context: "Texture::upload_sub_2d y",
                requested: y_end as usize,
                available: self.height as usize,
            });
        }

        let expected = expected_pixel_bytes(width, height, pixel_format, pixel_type)?;
        if data.len() < expected {
            return Err(GlError::BufferSizeMismatch {
                expected,
                actual: data.len(),
            });
        }

        let gx = checked_sizei(x as usize, "Texture::upload_sub_2d x")?;
        let gy = checked_sizei(y as usize, "Texture::upload_sub_2d y")?;
        let gw = checked_sizei(width as usize, "Texture::upload_sub_2d width")?;
        let gh = checked_sizei(height as usize, "Texture::upload_sub_2d height")?;

        // SAFETY: Sub-region and `data.len()` are strictly bounds-checked.
        unsafe {
            (self.ctx.fns.bind_texture)(sys::GL_TEXTURE_2D, self.id);
            (self.ctx.fns.pixel_storei)(sys::GL_UNPACK_ALIGNMENT, 1);
            (self.ctx.fns.tex_sub_image_2d)(
                sys::GL_TEXTURE_2D,
                0,
                gx,
                gy,
                gw,
                gh,
                pixel_format as sys::GLenum,
                pixel_type as sys::GLenum,
                data.as_ptr().cast(),
            );
        }
        self.ctx.check_gl_error("glTexSubImage2D")
    }

    /// Generates mipmaps for this texture (`glGenerateMipmap`).
    pub fn generate_mipmaps(&self) -> Result<()> {
        // SAFETY: `self.id` is a valid texture bound to `self.target`.
        unsafe {
            (self.ctx.fns.bind_texture)(self.target as sys::GLenum, self.id);
            (self.ctx.fns.generate_mipmap)(self.target as sys::GLenum);
        }
        self.ctx.check_gl_error("glGenerateMipmap")
    }
}

/// Descriptor for creating an OpenGL 3.3+ [`Sampler`] object.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct SamplerDesc {
    /// Minification filter.
    pub min_filter: TextureFilter,
    /// Magnification filter (must be `Nearest` or `Linear`).
    pub mag_filter: TextureFilter,
    /// Horizontal wrap mode (`S`).
    pub wrap_s: TextureWrap,
    /// Vertical wrap mode (`T`).
    pub wrap_t: TextureWrap,
    /// Depth wrap mode (`R`).
    pub wrap_r: TextureWrap,
    /// Optional shadow-map comparison function.
    pub compare_func: Option<CompareFunc>,
    /// Minimum LOD clamp.
    pub min_lod: f32,
    /// Maximum LOD clamp.
    pub max_lod: f32,
}

impl Default for SamplerDesc {
    fn default() -> Self {
        Self {
            min_filter: TextureFilter::LinearMipmapLinear,
            mag_filter: TextureFilter::Linear,
            wrap_s: TextureWrap::Repeat,
            wrap_t: TextureWrap::Repeat,
            wrap_r: TextureWrap::Repeat,
            compare_func: None,
            min_lod: -1000.0,
            max_lod: 1000.0,
        }
    }
}

/// RAII wrapper around an OpenGL 3.3+ sampler object.
pub struct Sampler {
    ctx: Rc<GlInner>,
    id: sys::GLuint,
}

impl fmt::Debug for Sampler {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Sampler").field("id", &self.id).finish()
    }
}

impl Drop for Sampler {
    fn drop(&mut self) {
        if self.id != 0 {
            // SAFETY: `self.id` is exclusively owned by this `Sampler`.
            unsafe { (self.ctx.fns.delete_samplers)(1, &self.id) };
        }
    }
}

impl Sampler {
    /// Creates a new OpenGL sampler object with the given descriptor.
    pub fn new(ctx: &GlContext, desc: &SamplerDesc) -> Result<Self> {
        if !desc.mag_filter.is_valid_mag_filter() {
            return Err(GlError::InvalidParameter {
                parameter: "mag_filter",
                reason: "magnification filter must be Nearest or Linear",
            });
        }
        if !desc.min_lod.is_finite() || !desc.max_lod.is_finite() {
            return Err(GlError::InvalidParameter {
                parameter: "lod",
                reason: "min_lod and max_lod must be finite",
            });
        }

        let mut id: sys::GLuint = 0;
        // SAFETY: Generates one sampler name in valid stack storage.
        unsafe { (ctx.inner.fns.gen_samplers)(1, &mut id) };
        if id == 0 {
            return Err(GlError::ObjectCreationFailed { object: "Sampler" });
        }

        let sampler = Self {
            ctx: Rc::clone(&ctx.inner),
            id,
        };

        // SAFETY: `sampler.id` is valid and all parameter enums are validated.
        unsafe {
            (sampler.ctx.fns.sampler_parameteri)(
                sampler.id,
                sys::GL_TEXTURE_MIN_FILTER,
                desc.min_filter as sys::GLint,
            );
            (sampler.ctx.fns.sampler_parameteri)(
                sampler.id,
                sys::GL_TEXTURE_MAG_FILTER,
                desc.mag_filter as sys::GLint,
            );
            (sampler.ctx.fns.sampler_parameteri)(
                sampler.id,
                sys::GL_TEXTURE_WRAP_S,
                desc.wrap_s as sys::GLint,
            );
            (sampler.ctx.fns.sampler_parameteri)(
                sampler.id,
                sys::GL_TEXTURE_WRAP_T,
                desc.wrap_t as sys::GLint,
            );
            (sampler.ctx.fns.sampler_parameteri)(
                sampler.id,
                sys::GL_TEXTURE_WRAP_R,
                desc.wrap_r as sys::GLint,
            );
            (sampler.ctx.fns.sampler_parameterf)(
                sampler.id,
                sys::GL_TEXTURE_MIN_LOD,
                desc.min_lod,
            );
            (sampler.ctx.fns.sampler_parameterf)(
                sampler.id,
                sys::GL_TEXTURE_MAX_LOD,
                desc.max_lod,
            );
            if let Some(cmp) = desc.compare_func {
                (sampler.ctx.fns.sampler_parameteri)(
                    sampler.id,
                    sys::GL_TEXTURE_COMPARE_MODE,
                    sys::GL_COMPARE_REF_TO_TEXTURE as sys::GLint,
                );
                (sampler.ctx.fns.sampler_parameteri)(
                    sampler.id,
                    sys::GL_TEXTURE_COMPARE_FUNC,
                    cmp as sys::GLint,
                );
            } else {
                (sampler.ctx.fns.sampler_parameteri)(
                    sampler.id,
                    sys::GL_TEXTURE_COMPARE_MODE,
                    sys::GL_NONE as sys::GLint,
                );
            }
        }
        sampler.ctx.check_gl_error("Sampler::new")?;
        Ok(sampler)
    }

    /// Returns the raw OpenGL sampler ID.
    #[inline]
    pub const fn raw_id(&self) -> u32 {
        self.id
    }

    /// Binds this sampler to texture unit `unit` (`0..31`).
    pub fn bind_unit(&self, unit: u32) -> Result<()> {
        if unit >= 32 {
            return Err(GlError::OutOfBounds {
                context: "Sampler::bind_unit",
                requested: unit as usize,
                available: 32,
            });
        }
        // SAFETY: `self.id` is valid and `unit < 32`.
        unsafe { (self.ctx.fns.bind_sampler)(unit, self.id) };
        Ok(())
    }

    /// Unbinds any sampler from texture unit `unit` (`0..31`).
    pub fn unbind_unit(ctx: &GlContext, unit: u32) -> Result<()> {
        if unit >= 32 {
            return Err(GlError::OutOfBounds {
                context: "Sampler::unbind_unit",
                requested: unit as usize,
                available: 32,
            });
        }
        // SAFETY: `0` unbinds the sampler from `unit`.
        unsafe { (ctx.inner.fns.bind_sampler)(unit, 0) };
        Ok(())
    }
}

/// Computes the exact minimum byte size for a tightly-packed 2D pixel buffer.
pub(crate) fn expected_pixel_bytes(
    width: u32,
    height: u32,
    format: PixelFormat,
    pixel_type: PixelType,
) -> Result<usize> {
    (width as usize)
        .checked_mul(height as usize)
        .and_then(|px| px.checked_mul(format.channel_count()))
        .and_then(|ch| ch.checked_mul(pixel_type.component_bytes()))
        .ok_or(GlError::IntegerOverflow {
            context: "pixel buffer byte size",
        })
}