crevice/
glsl.rs

1/*!
2Defines traits and types for generating GLSL code from Rust definitions.
3
4All GLSL primitives, like `int` or `vec3`, implement the [`Glsl`] trait. Structs
5should implement [`GlslStruct`], which can be derived.
6
7## Examples
8Given this struct:
9*/
10#![cfg_attr(
11    feature = "std",
12    doc = r##"
13```rust
14use mint::{ColumnMatrix4, Vector3};
15use crevice::glsl::GlslStruct;
16
17#[derive(GlslStruct)]
18struct SpotLight {
19    transform: ColumnMatrix4<f32>,
20    color: Vector3<f32>,
21    intensity: f32,
22}
23
24println!("{}", SpotLight::glsl_definition());
25```
26"##
27)]
28/*!
29The output will be:
30```glsl
31struct SpotLight {
32    mat4 transform;
33    vec3 color;
34    float intensity;
35};
36```
37*/
38
39pub use crevice_derive::GlslStruct;
40
41/// Trait for types that have a GLSL equivalent. Useful for generating GLSL code
42/// from Rust structs.
43pub unsafe trait Glsl {
44    /// The name of this type in GLSL, like `vec2` or `mat4`.
45    const NAME: &'static str;
46}
47
48/// A field contained within a GLSL struct definition.
49pub struct GlslField {
50    /// The type of the field, like `vec2` or `mat3`.
51    pub ty: &'static str,
52
53    /// The field's name. This must be a valid GLSL identifier.
54    pub name: &'static str,
55}
56
57/// Trait for types that can be represented as a struct in GLSL.
58///
59/// This trait should not generally be implemented by hand, but can be derived.
60#[cfg(feature = "std")]
61pub unsafe trait GlslStruct: Glsl {
62    /// The fields contained in this struct.
63    const FIELDS: &'static [GlslField];
64
65    /// Generates GLSL code that represents this struct and its fields.
66    fn glsl_definition() -> String {
67        let mut output = String::new();
68        output.push_str("struct ");
69        output.push_str(Self::NAME);
70        output.push_str(" {\n");
71
72        for field in Self::FIELDS {
73            output.push('\t');
74            output.push_str(field.ty);
75            output.push(' ');
76            output.push_str(field.name);
77            output.push_str(";\n");
78        }
79
80        output.push_str("};");
81        output
82    }
83}
84
85unsafe impl Glsl for f32 {
86    const NAME: &'static str = "float";
87}
88
89unsafe impl Glsl for f64 {
90    const NAME: &'static str = "double";
91}
92
93unsafe impl Glsl for i32 {
94    const NAME: &'static str = "int";
95}
96
97unsafe impl Glsl for u32 {
98    const NAME: &'static str = "uint";
99}