spitfire_glow/
renderer.rs

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
use bytemuck::{checked::cast_slice, Pod};
use glow::{
    Buffer, Context, HasContext, Program, Texture, VertexArray, ARRAY_BUFFER, BLEND, DST_COLOR,
    ELEMENT_ARRAY_BUFFER, FLOAT, INT, LINEAR, NEAREST, ONE, ONE_MINUS_SRC_ALPHA, RGB, RGBA,
    RGBA16F, RGBA32F, SCISSOR_TEST, SRC_ALPHA, STREAM_DRAW, TEXTURE0, TEXTURE_2D_ARRAY,
    TEXTURE_MAG_FILTER, TEXTURE_MIN_FILTER, TRIANGLES, UNSIGNED_INT, ZERO,
};
use spitfire_core::{Triangle, VertexStream, VertexStreamRenderer};
use std::{borrow::Cow, collections::HashMap, marker::PhantomData, ops::Range};

#[derive(Clone, Copy)]
pub enum GlowVertexAttrib {
    Float { channels: u8, normalized: bool },
    Integer { channels: u8 },
}

impl GlowVertexAttrib {
    pub fn channels(&self) -> u8 {
        match self {
            Self::Float { channels, .. } => *channels,
            Self::Integer { channels } => *channels,
        }
    }
}

pub trait GlowVertexAttribs: Pod {
    const ATTRIBS: &'static [(&'static str, GlowVertexAttrib)];
}

#[derive(Debug, Copy, Clone, PartialEq)]
pub enum GlowUniformValue {
    F1(f32),
    F2([f32; 2]),
    F3([f32; 3]),
    F4([f32; 4]),
    M2([f32; 4]),
    M3([f32; 9]),
    M4([f32; 16]),
    I1(i32),
    I2([i32; 2]),
    I3([i32; 3]),
    I4([i32; 4]),
}

#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub enum GlowBlending {
    #[default]
    None,
    Alpha,
    Multiply,
    Additive,
}

impl GlowBlending {
    pub fn into_gl(self) -> Option<(u32, u32)> {
        match self {
            Self::None => None,
            Self::Alpha => Some((SRC_ALPHA, ONE_MINUS_SRC_ALPHA)),
            Self::Multiply => Some((DST_COLOR, ZERO)),
            Self::Additive => Some((ONE, ONE)),
        }
    }
}

#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub enum GlowTextureFiltering {
    #[default]
    Nearest,
    Linear,
}

impl GlowTextureFiltering {
    pub fn into_gl(self) -> (i32, i32) {
        match self {
            Self::Nearest => (NEAREST as _, NEAREST as _),
            Self::Linear => (LINEAR as _, LINEAR as _),
        }
    }
}

#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub enum GlowTextureFormat {
    #[default]
    Rgba,
    Rgb,
    Monochromatic,
    Data16,
    Data32,
}

impl GlowTextureFormat {
    pub fn into_gl(self) -> u32 {
        match self {
            Self::Rgba => RGBA,
            Self::Rgb => RGB,
            #[cfg(not(target_arch = "wasm32"))]
            Self::Monochromatic => glow::RED,
            #[cfg(target_arch = "wasm32")]
            Self::Monochromatic => glow::LUMINANCE,
            Self::Data16 => RGBA16F,
            Self::Data32 => RGBA32F,
        }
    }
}

#[derive(Debug, Default, Clone, PartialEq)]
pub struct GlowBatch {
    pub shader_program: Option<Program>,
    pub uniforms: HashMap<Cow<'static, str>, GlowUniformValue>,
    /// [(texture object, texture target, min filter, mag filter)?]
    pub textures: Vec<(Texture, u32, i32, i32)>,
    /// (source, destination)?
    pub blending: Option<(u32, u32)>,
    /// [x, y, width, height]?
    pub scissor: Option<[i32; 4]>,
}

impl GlowBatch {
    pub fn draw<V: GlowVertexAttribs>(&self, context: &Context, range: Range<usize>, prev: &Self) {
        unsafe {
            if let Some(program) = self.shader_program {
                let changed = prev
                    .shader_program
                    .map(|program_prev| program != program_prev)
                    .unwrap_or(true);
                context.use_program(Some(program));
                for (name, value) in &self.uniforms {
                    if changed
                        || prev
                            .uniforms
                            .get(name)
                            .map(|v| value != v)
                            .unwrap_or_default()
                    {
                        let location = context.get_uniform_location(program, name.as_ref());
                        if let Some(location) = location {
                            match value {
                                GlowUniformValue::F1(value) => {
                                    context.uniform_1_f32(Some(&location), *value);
                                }
                                GlowUniformValue::F2(value) => {
                                    context.uniform_2_f32_slice(Some(&location), value);
                                }
                                GlowUniformValue::F3(value) => {
                                    context.uniform_3_f32_slice(Some(&location), value);
                                }
                                GlowUniformValue::F4(value) => {
                                    context.uniform_4_f32_slice(Some(&location), value);
                                }
                                GlowUniformValue::M2(value) => {
                                    context.uniform_matrix_2_f32_slice(
                                        Some(&location),
                                        false,
                                        value,
                                    );
                                }
                                GlowUniformValue::M3(value) => {
                                    context.uniform_matrix_3_f32_slice(
                                        Some(&location),
                                        false,
                                        value,
                                    );
                                }
                                GlowUniformValue::M4(value) => {
                                    context.uniform_matrix_4_f32_slice(
                                        Some(&location),
                                        false,
                                        value,
                                    );
                                }
                                GlowUniformValue::I1(value) => {
                                    context.uniform_1_i32(Some(&location), *value);
                                }
                                GlowUniformValue::I2(value) => {
                                    context.uniform_2_i32_slice(Some(&location), value);
                                }
                                GlowUniformValue::I3(value) => {
                                    context.uniform_3_i32_slice(Some(&location), value);
                                }
                                GlowUniformValue::I4(value) => {
                                    context.uniform_4_i32_slice(Some(&location), value);
                                }
                            }
                        }
                    }
                }
            }
            for (index, data) in self.textures.iter().enumerate() {
                context.active_texture(TEXTURE0 + index as u32);
                let data_prev = prev.textures.get(index);
                if data_prev.map(|prev| prev != data).unwrap_or(true) {
                    let (texture, target, min_filter, mag_filter) = data;
                    context.bind_texture(*target, Some(*texture));
                    context.tex_parameter_i32(TEXTURE_2D_ARRAY, TEXTURE_MIN_FILTER, *min_filter);
                    context.tex_parameter_i32(TEXTURE_2D_ARRAY, TEXTURE_MAG_FILTER, *mag_filter);
                }
            }
            if self.blending != prev.blending {
                if let Some((source, destination)) = self.blending {
                    context.enable(BLEND);
                    context.blend_func(source, destination);
                } else {
                    context.disable(BLEND);
                }
            }
            if self.scissor != prev.scissor {
                if let Some([x, y, w, h]) = self.scissor {
                    context.enable(SCISSOR_TEST);
                    context.scissor(x, y, w, h);
                } else {
                    context.disable(SCISSOR_TEST);
                }
            }
            context.draw_elements(
                TRIANGLES,
                range.len() as i32 * 3,
                UNSIGNED_INT,
                (range.start * std::mem::size_of::<u32>() * 3) as i32,
            );
        }
    }
}

#[derive(Copy, Clone)]
struct GlowMesh {
    vertex_array: VertexArray,
    vertex_buffer: Buffer,
    index_buffer: Buffer,
}

impl GlowMesh {
    fn new(context: &Context) -> Result<Self, String> {
        unsafe {
            Ok(GlowMesh {
                vertex_array: context.create_vertex_array()?,
                vertex_buffer: context.create_buffer()?,
                index_buffer: context.create_buffer()?,
            })
        }
    }

    fn dispose(self, context: &Context) {
        unsafe {
            context.delete_vertex_array(self.vertex_array);
            context.delete_buffer(self.vertex_buffer);
            context.delete_buffer(self.index_buffer);
        }
    }

    fn upload<V: GlowVertexAttribs>(
        &self,
        context: &Context,
        vertices: &[V],
        triangles: &[Triangle],
    ) {
        unsafe {
            context.bind_vertex_array(Some(self.vertex_array));
            context.bind_buffer(ARRAY_BUFFER, Some(self.vertex_buffer));
            context.buffer_data_u8_slice(ARRAY_BUFFER, cast_slice(vertices), STREAM_DRAW);
            context.bind_buffer(ELEMENT_ARRAY_BUFFER, Some(self.index_buffer));
            context.buffer_data_u8_slice(ELEMENT_ARRAY_BUFFER, cast_slice(triangles), STREAM_DRAW);
            let mut offset = 0;
            let stride = V::ATTRIBS
                .iter()
                .map(|(_, info)| info.channels() * 4)
                .sum::<u8>();
            for (location, (_, info)) in V::ATTRIBS.iter().enumerate() {
                match info {
                    GlowVertexAttrib::Float {
                        channels,
                        normalized,
                    } => {
                        context.vertex_attrib_pointer_f32(
                            location as _,
                            *channels as _,
                            FLOAT,
                            *normalized,
                            stride as _,
                            offset as _,
                        );
                    }
                    GlowVertexAttrib::Integer { channels } => {
                        context.vertex_attrib_pointer_i32(
                            location as _,
                            *channels as _,
                            INT,
                            stride as _,
                            offset as _,
                        );
                    }
                }
                context.enable_vertex_attrib_array(location as _);
                offset += info.channels() * 4;
            }
        }
    }
}

#[derive(Default)]
pub struct GlowState {
    mesh: Option<GlowMesh>,
}

impl Drop for GlowState {
    fn drop(&mut self) {
        if self.mesh.is_some() {
            panic!("Mesh was not disposed!");
        }
    }
}

impl GlowState {
    pub fn dispose(&mut self, context: &Context) {
        if let Some(mesh) = self.mesh.take() {
            mesh.dispose(context)
        }
    }

    fn mesh(&mut self, context: &Context) -> Result<GlowMesh, String> {
        if let Some(mesh) = self.mesh.as_ref().copied() {
            Ok(mesh)
        } else {
            self.mesh = Some(GlowMesh::new(context)?);
            Ok(self.mesh.unwrap())
        }
    }
}

pub struct GlowRenderer<'a, B: Into<GlowBatch>> {
    context: &'a Context,
    state: &'a mut GlowState,
    _phantom: PhantomData<fn() -> B>,
}

impl<'a, B> GlowRenderer<'a, B>
where
    B: Into<GlowBatch>,
{
    pub fn new(context: &'a Context, state: &'a mut GlowState) -> Self {
        Self {
            context,
            state,
            _phantom: Default::default(),
        }
    }
}

impl<'a, V, B> VertexStreamRenderer<V, B> for GlowRenderer<'a, B>
where
    V: GlowVertexAttribs,
    B: Into<GlowBatch> + Default + Clone,
{
    type Error = String;

    fn render(&mut self, stream: &mut VertexStream<V, B>) -> Result<(), Self::Error> {
        let mesh = self.state.mesh(self.context)?;
        mesh.upload(self.context, stream.vertices(), stream.triangles());
        let mut prev = GlowBatch::default();
        for (batch, range) in stream.batches().iter().cloned() {
            let batch = batch.into();
            batch.draw::<V>(self.context, range, &prev);
            prev = batch;
        }
        Ok(())
    }
}