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
501
502
503
//! GLSL shader compilation, program linking, uniform setters, and reflection.

use std::fmt;
use std::rc::Rc;

use crate::context::{GlContext, GlInner};
use crate::error::{checked_sizei, GlError, Result};
use crate::loader::to_cstring;
use crate::sys;
use crate::types::{AttribLocation, ShaderStage, UniformLocation};

/// Compiled GLSL shader stage object with RAII cleanup.
pub struct Shader {
    ctx: Rc<GlInner>,
    id: sys::GLuint,
    stage: ShaderStage,
}

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

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

impl Shader {
    /// Compiles GLSL source code for the specified [`ShaderStage`].
    pub fn compile(ctx: &GlContext, stage: ShaderStage, source: &str) -> Result<Self> {
        if source.is_empty() {
            return Err(GlError::InvalidParameter {
                parameter: "source",
                reason: "shader source must not be empty",
            });
        }
        if source.as_bytes().contains(&0) {
            return Err(GlError::InvalidString {
                parameter: "source",
            });
        }
        let len = checked_sizei(source.len(), "Shader::compile source length")?;

        // SAFETY: `stage` is a valid `GL_*_SHADER` enum.
        let id = unsafe { (ctx.inner.fns.create_shader)(stage as sys::GLenum) };
        if id == 0 {
            return Err(GlError::ObjectCreationFailed { object: "Shader" });
        }

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

        let src_ptr = source.as_ptr().cast::<sys::GLchar>();
        // SAFETY: `src_ptr` points to `len` valid bytes and `id` is a valid shader handle.
        unsafe {
            (shader.ctx.fns.shader_source)(shader.id, 1, &src_ptr, &len);
            (shader.ctx.fns.compile_shader)(shader.id);
        }

        let mut status: sys::GLint = 0;
        // SAFETY: `status` is a valid stack pointer.
        unsafe {
            (shader.ctx.fns.get_shaderiv)(shader.id, sys::GL_COMPILE_STATUS, &mut status);
        }

        if status == 0 {
            let log = shader.read_info_log();
            return Err(GlError::ShaderCompileFailed { stage, log });
        }

        Ok(shader)
    }

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

    /// Returns the shader stage.
    #[inline]
    pub const fn stage(&self) -> ShaderStage {
        self.stage
    }

    fn read_info_log(&self) -> String {
        let mut log_len: sys::GLint = 0;
        // SAFETY: Valid stack pointer for `GL_INFO_LOG_LENGTH`.
        unsafe {
            (self.ctx.fns.get_shaderiv)(self.id, sys::GL_INFO_LOG_LENGTH, &mut log_len);
        }
        if log_len <= 1 {
            return String::new();
        }
        let mut buf = vec![0u8; log_len as usize];
        let mut written: sys::GLsizei = 0;
        // SAFETY: `buf` has capacity `log_len` bytes.
        unsafe {
            (self.ctx.fns.get_shader_info_log)(
                self.id,
                log_len,
                &mut written,
                buf.as_mut_ptr().cast::<sys::GLchar>(),
            );
        }
        let actual = usize::try_from(written).unwrap_or(0).min(buf.len());
        buf.truncate(actual);
        String::from_utf8_lossy(&buf).into_owned()
    }
}

/// Introspected active uniform metadata from a linked [`Program`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ActiveUniform {
    /// Uniform variable name.
    pub name: String,
    /// Array length (`1` for non-arrays).
    pub size: i32,
    /// Raw OpenGL type enum (e.g. `GL_FLOAT_VEC4`, `GL_FLOAT_MAT4`).
    pub gl_type: u32,
}

/// Introspected active vertex attribute metadata from a linked [`Program`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ActiveAttribute {
    /// Attribute variable name.
    pub name: String,
    /// Array length (`1` for non-arrays).
    pub size: i32,
    /// Raw OpenGL type enum.
    pub gl_type: u32,
}

/// Linked OpenGL shader program with typed uniform setters and RAII cleanup.
pub struct Program {
    ctx: Rc<GlInner>,
    id: sys::GLuint,
}

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

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

impl Program {
    /// Links one or more compiled [`Shader`] objects into an executable GPU [`Program`].
    ///
    /// Shaders are automatically detached after linking so they can be dropped immediately.
    pub fn link(ctx: &GlContext, shaders: &[&Shader]) -> Result<Self> {
        if shaders.is_empty() {
            return Err(GlError::InvalidParameter {
                parameter: "shaders",
                reason: "at least one shader must be provided to link a program",
            });
        }

        // SAFETY: Creates a new OpenGL program handle.
        let id = unsafe { (ctx.inner.fns.create_program)() };
        if id == 0 {
            return Err(GlError::ObjectCreationFailed { object: "Program" });
        }

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

        for shader in shaders {
            // SAFETY: Both `program.id` and `shader.id` are valid GL objects on this context.
            unsafe { (program.ctx.fns.attach_shader)(program.id, shader.id) };
        }

        // SAFETY: `program.id` is valid and has shaders attached.
        unsafe { (program.ctx.fns.link_program)(program.id) };

        for shader in shaders {
            // SAFETY: Detach shaders cleanly after linking.
            unsafe { (program.ctx.fns.detach_shader)(program.id, shader.id) };
        }

        let mut status: sys::GLint = 0;
        // SAFETY: Valid stack pointer for `GL_LINK_STATUS`.
        unsafe {
            (program.ctx.fns.get_programiv)(program.id, sys::GL_LINK_STATUS, &mut status);
        }

        if status == 0 {
            let log = program.read_info_log();
            return Err(GlError::ProgramLinkFailed { log });
        }

        Ok(program)
    }

    /// Convenience helper that compiles vertex + fragment GLSL sources and links a [`Program`].
    pub fn from_vertex_fragment(
        ctx: &GlContext,
        vertex_src: &str,
        fragment_src: &str,
    ) -> Result<Self> {
        let vs = Shader::compile(ctx, ShaderStage::Vertex, vertex_src)?;
        let fs = Shader::compile(ctx, ShaderStage::Fragment, fragment_src)?;
        Self::link(ctx, &[&vs, &fs])
    }

    /// Convenience helper that compiles a compute GLSL source and links a [`Program`].
    pub fn from_compute(ctx: &GlContext, compute_src: &str) -> Result<Self> {
        let cs = Shader::compile(ctx, ShaderStage::Compute, compute_src)?;
        Self::link(ctx, &[&cs])
    }

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

    /// Activates this program in the current OpenGL context (`glUseProgram`).
    #[inline]
    pub fn bind(&self) {
        // SAFETY: `self.id` is a linked OpenGL program.
        unsafe { (self.ctx.fns.use_program)(self.id) };
    }

    /// Unbinds any active program (`glUseProgram(0)`).
    #[inline]
    pub fn unbind(ctx: &GlContext) {
        // SAFETY: `0` unbinds the active program.
        unsafe { (ctx.inner.fns.use_program)(0) };
    }

    /// Validates the program against the current OpenGL state (`glValidateProgram`).
    pub fn validate(&self) -> Result<()> {
        // SAFETY: `self.id` is a valid program handle.
        unsafe { (self.ctx.fns.validate_program)(self.id) };
        let mut status: sys::GLint = 0;
        // SAFETY: Valid stack pointer for `GL_VALIDATE_STATUS`.
        unsafe {
            (self.ctx.fns.get_programiv)(self.id, sys::GL_VALIDATE_STATUS, &mut status);
        }
        if status == 0 {
            return Err(GlError::ProgramValidateFailed {
                log: self.read_info_log(),
            });
        }
        Ok(())
    }

    /// Looks up the location of an active uniform variable (`glGetUniformLocation`).
    /// Returns `Ok(None)` if the uniform does not exist or was optimized out by the compiler.
    pub fn uniform_location(&self, name: &str) -> Result<Option<UniformLocation>> {
        let cname = to_cstring(name, "name")?;
        // SAFETY: `self.id` is valid and `cname` is NUL-terminated.
        let loc = unsafe { (self.ctx.fns.get_uniform_location)(self.id, cname.as_ptr()) };
        if loc < 0 {
            Ok(None)
        } else {
            Ok(Some(UniformLocation(loc)))
        }
    }

    /// Looks up the location of an active vertex attribute (`glGetAttribLocation`).
    pub fn attrib_location(&self, name: &str) -> Result<Option<AttribLocation>> {
        let cname = to_cstring(name, "name")?;
        // SAFETY: `self.id` is valid and `cname` is NUL-terminated.
        let loc = unsafe { (self.ctx.fns.get_attrib_location)(self.id, cname.as_ptr()) };
        if loc < 0 {
            Ok(None)
        } else {
            Ok(Some(AttribLocation(loc as u32)))
        }
    }

    /// Looks up a uniform block index (`glGetUniformBlockIndex`).
    pub fn uniform_block_index(&self, name: &str) -> Result<Option<u32>> {
        let cname = to_cstring(name, "name")?;
        // SAFETY: `self.id` is valid and `cname` is NUL-terminated.
        let idx = unsafe { (self.ctx.fns.get_uniform_block_index)(self.id, cname.as_ptr()) };
        if idx == sys::GL_INVALID_INDEX {
            Ok(None)
        } else {
            Ok(Some(idx))
        }
    }

    /// Assigns a uniform block to a binding point (`glUniformBlockBinding`).
    pub fn set_uniform_block_binding(&self, block_index: u32, binding_point: u32) -> Result<()> {
        // SAFETY: `self.id` is valid.
        unsafe { (self.ctx.fns.uniform_block_binding)(self.id, block_index, binding_point) };
        self.ctx.check_gl_error("glUniformBlockBinding")
    }

    // -----------------------------------------------------------------------
    // Typed Uniform Setters (bind program automatically for safety)
    // -----------------------------------------------------------------------

    /// Sets an `int` / sampler uniform (`glUniform1i`).
    pub fn set_i32(&self, loc: UniformLocation, value: i32) {
        self.bind();
        // SAFETY: `self` is bound and `loc` came from `uniform_location`.
        unsafe { (self.ctx.fns.uniform1i)(loc.0, value) };
    }

    /// Sets an `uint` uniform (`glUniform1ui`).
    pub fn set_u32(&self, loc: UniformLocation, value: u32) {
        self.bind();
        // SAFETY: `self` is bound and `loc` came from `uniform_location`.
        unsafe { (self.ctx.fns.uniform1ui)(loc.0, value) };
    }

    /// Sets a `float` uniform (`glUniform1f`).
    pub fn set_f32(&self, loc: UniformLocation, value: f32) {
        self.bind();
        // SAFETY: `self` is bound and `loc` came from `uniform_location`.
        unsafe { (self.ctx.fns.uniform1f)(loc.0, value) };
    }

    /// Sets a `vec2` uniform (`glUniform2f`).
    pub fn set_vec2(&self, loc: UniformLocation, value: [f32; 2]) {
        self.bind();
        // SAFETY: `self` is bound and `loc` came from `uniform_location`.
        unsafe { (self.ctx.fns.uniform2f)(loc.0, value[0], value[1]) };
    }

    /// Sets a `vec3` uniform (`glUniform3f`).
    pub fn set_vec3(&self, loc: UniformLocation, value: [f32; 3]) {
        self.bind();
        // SAFETY: `self` is bound and `loc` came from `uniform_location`.
        unsafe { (self.ctx.fns.uniform3f)(loc.0, value[0], value[1], value[2]) };
    }

    /// Sets a `vec4` uniform (`glUniform4f`).
    pub fn set_vec4(&self, loc: UniformLocation, value: [f32; 4]) {
        self.bind();
        // SAFETY: `self` is bound and `loc` came from `uniform_location`.
        unsafe { (self.ctx.fns.uniform4f)(loc.0, value[0], value[1], value[2], value[3]) };
    }

    /// Sets a column-major `mat3` uniform (`glUniformMatrix3fv`).
    pub fn set_mat3(&self, loc: UniformLocation, matrix: &[f32; 9], transpose: bool) {
        self.bind();
        let t = if transpose {
            sys::GL_TRUE
        } else {
            sys::GL_FALSE
        };
        // SAFETY: `matrix` points to 9 contiguous `f32` values.
        unsafe { (self.ctx.fns.uniform_matrix3fv)(loc.0, 1, t, matrix.as_ptr()) };
    }

    /// Sets a column-major `mat4` uniform (`glUniformMatrix4fv`).
    pub fn set_mat4(&self, loc: UniformLocation, matrix: &[f32; 16], transpose: bool) {
        self.bind();
        let t = if transpose {
            sys::GL_TRUE
        } else {
            sys::GL_FALSE
        };
        // SAFETY: `matrix` points to 16 contiguous `f32` values.
        unsafe { (self.ctx.fns.uniform_matrix4fv)(loc.0, 1, t, matrix.as_ptr()) };
    }

    // -----------------------------------------------------------------------
    // Program Introspection
    // -----------------------------------------------------------------------

    /// Enumerates all active uniforms declared in this linked program.
    pub fn active_uniforms(&self) -> Vec<ActiveUniform> {
        let mut count: sys::GLint = 0;
        let mut max_len: sys::GLint = 0;
        // SAFETY: Valid stack pointers for program queries.
        unsafe {
            (self.ctx.fns.get_programiv)(self.id, sys::GL_ACTIVE_UNIFORMS, &mut count);
            (self.ctx.fns.get_programiv)(
                self.id,
                sys::GL_ACTIVE_UNIFORM_MAX_LENGTH,
                &mut max_len,
            );
        }
        if count <= 0 || max_len <= 0 {
            return Vec::new();
        }
        let mut buf = vec![0u8; max_len as usize];
        let mut result = Vec::with_capacity(count as usize);
        for i in 0..(count as sys::GLuint) {
            let mut written: sys::GLsizei = 0;
            let mut size: sys::GLint = 0;
            let mut gl_type: sys::GLenum = 0;
            // SAFETY: `buf` has capacity `max_len` bytes and `i < count`.
            unsafe {
                (self.ctx.fns.get_active_uniform)(
                    self.id,
                    i,
                    max_len,
                    &mut written,
                    &mut size,
                    &mut gl_type,
                    buf.as_mut_ptr().cast::<sys::GLchar>(),
                );
            }
            let actual = usize::try_from(written).unwrap_or(0).min(buf.len());
            let name = String::from_utf8_lossy(&buf[..actual]).into_owned();
            result.push(ActiveUniform {
                name,
                size,
                gl_type,
            });
        }
        result
    }

    /// Enumerates all active vertex attributes declared in this linked program.
    pub fn active_attributes(&self) -> Vec<ActiveAttribute> {
        let mut count: sys::GLint = 0;
        let mut max_len: sys::GLint = 0;
        // SAFETY: Valid stack pointers for program queries.
        unsafe {
            (self.ctx.fns.get_programiv)(self.id, sys::GL_ACTIVE_ATTRIBUTES, &mut count);
            (self.ctx.fns.get_programiv)(
                self.id,
                sys::GL_ACTIVE_ATTRIBUTE_MAX_LENGTH,
                &mut max_len,
            );
        }
        if count <= 0 || max_len <= 0 {
            return Vec::new();
        }
        let mut buf = vec![0u8; max_len as usize];
        let mut result = Vec::with_capacity(count as usize);
        for i in 0..(count as sys::GLuint) {
            let mut written: sys::GLsizei = 0;
            let mut size: sys::GLint = 0;
            let mut gl_type: sys::GLenum = 0;
            // SAFETY: `buf` has capacity `max_len` bytes and `i < count`.
            unsafe {
                (self.ctx.fns.get_active_attrib)(
                    self.id,
                    i,
                    max_len,
                    &mut written,
                    &mut size,
                    &mut gl_type,
                    buf.as_mut_ptr().cast::<sys::GLchar>(),
                );
            }
            let actual = usize::try_from(written).unwrap_or(0).min(buf.len());
            let name = String::from_utf8_lossy(&buf[..actual]).into_owned();
            result.push(ActiveAttribute {
                name,
                size,
                gl_type,
            });
        }
        result
    }

    fn read_info_log(&self) -> String {
        let mut log_len: sys::GLint = 0;
        // SAFETY: Valid stack pointer for `GL_INFO_LOG_LENGTH`.
        unsafe {
            (self.ctx.fns.get_programiv)(self.id, sys::GL_INFO_LOG_LENGTH, &mut log_len);
        }
        if log_len <= 1 {
            return String::new();
        }
        let mut buf = vec![0u8; log_len as usize];
        let mut written: sys::GLsizei = 0;
        // SAFETY: `buf` has capacity `log_len` bytes.
        unsafe {
            (self.ctx.fns.get_program_info_log)(
                self.id,
                log_len,
                &mut written,
                buf.as_mut_ptr().cast::<sys::GLchar>(),
            );
        }
        let actual = usize::try_from(written).unwrap_or(0).min(buf.len());
        buf.truncate(actual);
        String::from_utf8_lossy(&buf).into_owned()
    }
}