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
use crate::{
    ha_renderer::{RenderStageResources, RenderStats},
    material::{
        common::{MaterialSignature, MaterialValue},
        MaterialDrawOptions, MaterialError, MaterialId,
    },
    math::*,
    mesh::{MeshDrawRange, MeshError, MeshId},
};
use glow::*;
use serde::{Deserialize, Serialize};
use std::{borrow::Cow, collections::HashMap};

#[derive(Debug, Clone)]
pub enum RenderQueueError {
    QueueLimitReached(usize),
    MaterialDoesNotExist(MaterialId),
    MeshDoesNotExist(MeshId),
    Mesh(MeshId, Box<MeshError>),
    Material(MaterialId, Box<MaterialError>),
    NoMeshActive,
    NoMaterialActive,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum RenderCommand {
    SortingBarrier,
    Viewport(usize, usize, usize, usize),
    ActivateMaterial(MaterialId, MaterialSignature),
    OverrideUniform(Cow<'static, str>, MaterialValue),
    ResetUniform(Cow<'static, str>),
    ResetUniforms,
    ApplyDrawOptions(MaterialDrawOptions),
    ActivateMesh(MeshId),
    DrawMesh(MeshDrawRange),
    /// (x, y, width, height, clipped)
    PushScissor(usize, usize, usize, usize, bool),
    PopScissor,
}

#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct GroupOrder(usize, usize);

#[derive(Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum RenderQueueSize {
    Limited(usize),
    Growable(usize),
}

impl Default for RenderQueueSize {
    fn default() -> Self {
        Self::Growable(1024)
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RenderQueue {
    size: RenderQueueSize,
    commands: Vec<(GroupOrder, RenderCommand)>,
    pub persistent: bool,
}

impl Default for RenderQueue {
    fn default() -> Self {
        Self::new(Default::default(), false)
    }
}

impl RenderQueue {
    pub fn new(size: RenderQueueSize, persistent: bool) -> Self {
        Self {
            size,
            commands: Vec::with_capacity(match size {
                RenderQueueSize::Limited(size) => size,
                RenderQueueSize::Growable(size) => size,
            }),
            persistent,
        }
    }

    pub fn size(&self) -> RenderQueueSize {
        self.size
    }

    pub fn auto_recorder(&mut self, initial_group: Option<usize>) -> RenderQueueAutoRecorder {
        RenderQueueAutoRecorder::new(self, initial_group.unwrap_or_default())
    }

    pub fn record(
        &mut self,
        group: usize,
        order: usize,
        command: RenderCommand,
    ) -> Result<(), RenderQueueError> {
        match self.size {
            RenderQueueSize::Limited(size) => {
                if self.commands.len() >= size {
                    return Err(RenderQueueError::QueueLimitReached(size));
                }
            }
            RenderQueueSize::Growable(resize) => {
                if self.commands.len() % resize == 0 {
                    self.commands.reserve(resize);
                }
            }
        }
        self.commands.push((GroupOrder(group, order), command));
        Ok(())
    }

    pub fn is_empty(&self) -> bool {
        self.commands.is_empty()
    }

    pub fn len(&self) -> usize {
        self.commands.len()
    }

    pub fn commands(&self) -> &[(GroupOrder, RenderCommand)] {
        &self.commands
    }

    pub fn iter(&self) -> impl Iterator<Item = &RenderCommand> {
        self.commands.iter().map(|(_, command)| command)
    }

    pub fn move_into(&mut self, other: &mut Self) -> Result<(), RenderQueueError> {
        for (GroupOrder(group, order), command) in self.commands.drain(..) {
            other.record(group, order, command)?;
        }
        Ok(())
    }

    pub fn clone_into(&self, other: &mut Self) -> Result<(), RenderQueueError> {
        for (GroupOrder(group, order), command) in &self.commands {
            other.record(*group, *order, command.to_owned())?;
        }
        Ok(())
    }

    pub fn remap_groups<F>(&mut self, mut f: F)
    where
        F: FnMut(usize) -> usize,
    {
        for (GroupOrder(group, _), _) in &mut self.commands {
            *group = f(*group);
        }
    }

    pub fn sort_by_group_order(&mut self, stable: bool) {
        let mut start = 0;
        for index in 0..self.commands.len() {
            if matches!(&self.commands[index].1, RenderCommand::SortingBarrier)
                || index == self.commands.len() - 1
            {
                if index - start > 1 {
                    if stable {
                        self.commands[start..index].sort_by(|a, b| a.0.cmp(&b.0));
                    } else {
                        self.commands[start..index].sort_unstable_by(|a, b| a.0.cmp(&b.0));
                    }
                }
                start = index + 1;
            }
        }
    }

    pub fn clear(&mut self) {
        self.commands.clear();
    }

    pub fn execute(
        &mut self,
        context: &Context,
        resources: &RenderStageResources<'_>,
        stats: &mut RenderStats,
        height: usize,
    ) -> Result<(), RenderQueueError> {
        let result = self.execute_inner(context, resources, stats, height);
        if !self.persistent {
            self.commands.clear();
        }
        result
    }

    fn execute_inner(
        &mut self,
        context: &Context,
        resources: &RenderStageResources<'_>,
        stats: &mut RenderStats,
        height: usize,
    ) -> Result<(), RenderQueueError> {
        let mut current_material = None;
        let mut current_mesh = None;
        let mut current_uniforms = HashMap::<&str, &MaterialValue>::with_capacity(32);
        let mut last_uniforms = HashMap::<&str, &MaterialValue>::with_capacity(32);
        let mut scissor_stack = Vec::<(usize, usize, usize, usize)>::with_capacity(32);
        for (_, command) in &self.commands {
            match command {
                RenderCommand::SortingBarrier => {}
                RenderCommand::Viewport(x, y, w, h) => unsafe {
                    context.viewport(*x as _, *y as _, *w as _, *h as _);
                },
                RenderCommand::ActivateMaterial(id, signature) => {
                    if current_material
                        .map(|(cid, _, _)| cid == id)
                        .unwrap_or_default()
                    {
                        continue;
                    }
                    match resources.materials.get(*id) {
                        Some(material) => {
                            match material.activate(signature, context, resources, stats) {
                                Ok(_) => {
                                    current_uniforms.clear();
                                    last_uniforms.clear();
                                    current_material = Some((id, signature, material));
                                }
                                Err(error) => {
                                    return Err(RenderQueueError::Material(*id, Box::new(error)))
                                }
                            }
                        }
                        None => return Err(RenderQueueError::MaterialDoesNotExist(*id)),
                    }
                }
                RenderCommand::OverrideUniform(name, value) => {
                    current_uniforms.insert(name.as_ref(), value);
                }
                RenderCommand::ResetUniform(name) => {
                    current_uniforms.remove(name.as_ref());
                }
                RenderCommand::ResetUniforms => {
                    current_uniforms.clear();
                }
                RenderCommand::ApplyDrawOptions(draw_options) => {
                    draw_options.apply(context, stats);
                }
                RenderCommand::ActivateMesh(id) => {
                    if current_mesh.map(|(cid, _)| cid == id).unwrap_or_default() {
                        continue;
                    }
                    match resources.meshes.get(*id) {
                        Some(mesh) => match mesh.activate(context, stats) {
                            Ok(_) => current_mesh = Some((id, mesh)),
                            Err(error) => return Err(RenderQueueError::Mesh(*id, Box::new(error))),
                        },
                        None => return Err(RenderQueueError::MeshDoesNotExist(*id)),
                    }
                }
                RenderCommand::DrawMesh(draw_range) => {
                    let (mesh_id, mesh) = match current_mesh {
                        Some((id, mesh)) => (id, mesh),
                        None => return Err(RenderQueueError::NoMeshActive),
                    };
                    let (material_id, signature, material) = match current_material {
                        Some((id, signature, material)) => (id, signature, material),
                        None => return Err(RenderQueueError::NoMaterialActive),
                    };
                    for (name, current_value) in &current_uniforms {
                        if last_uniforms
                            .get(name)
                            .map(|last_value| current_value != last_value)
                            .unwrap_or(true)
                        {
                            if let Err(error) = material.submit_uniform(
                                signature,
                                name,
                                current_value,
                                context,
                                resources,
                                stats,
                            ) {
                                return Err(RenderQueueError::Material(
                                    *material_id,
                                    Box::new(error),
                                ));
                            }
                        }
                    }
                    for name in last_uniforms.keys() {
                        let name: &str = name;
                        if !current_uniforms.contains_key(name) {
                            if let Some(default_value) = material.default_values.get(name) {
                                if let Err(error) = material.submit_uniform(
                                    signature,
                                    name,
                                    default_value,
                                    context,
                                    resources,
                                    stats,
                                ) {
                                    return Err(RenderQueueError::Material(
                                        *material_id,
                                        Box::new(error),
                                    ));
                                }
                            }
                        }
                    }
                    if let Err(error) = mesh.draw(draw_range.clone(), context, stats) {
                        return Err(RenderQueueError::Mesh(*mesh_id, Box::new(error)));
                    }
                    last_uniforms.clear();
                    last_uniforms.reserve(current_uniforms.len());
                    for (key, value) in &current_uniforms {
                        last_uniforms.insert(key, value);
                    }
                }
                RenderCommand::PushScissor(mut x, mut y, mut w, mut h, clipped) => unsafe {
                    if scissor_stack.is_empty() {
                        context.enable(SCISSOR_TEST);
                    }
                    if *clipped {
                        if let Some((sx, sy, sw, sh)) = scissor_stack.last() {
                            w = w.saturating_sub(sx.saturating_sub(x)).min(*sw);
                            x = x.max(*sx);
                            h = h.saturating_sub(sy.saturating_sub(y)).min(*sh);
                            y = y.max(*sy);
                        }
                    }
                    context.scissor(
                        x as _,
                        height.saturating_sub(h).saturating_sub(y) as _,
                        w as _,
                        h as _,
                    );
                    scissor_stack.push((x, y, w, h));
                },
                RenderCommand::PopScissor => unsafe {
                    if let Some((x, y, w, h)) = scissor_stack.pop() {
                        context.scissor(
                            x as _,
                            height.saturating_sub(h).saturating_sub(y) as _,
                            w as _,
                            h as _,
                        );
                    } else {
                        context.disable(SCISSOR_TEST);
                    }
                },
            }
        }
        Ok(())
    }
}

pub struct RenderQueueAutoRecorder<'a> {
    group: usize,
    order: usize,
    queue: &'a mut RenderQueue,
}

impl<'a> RenderQueueAutoRecorder<'a> {
    fn new(queue: &'a mut RenderQueue, initial_group: usize) -> Self {
        Self {
            group: initial_group,
            order: 0,
            queue,
        }
    }

    pub fn group_order(&self) -> (usize, usize) {
        (self.group, self.order)
    }

    pub fn next_group(&mut self) -> usize {
        self.order = 0;
        self.group += 1;
        self.group
    }

    pub fn record(&mut self, command: RenderCommand) -> Result<usize, RenderQueueError> {
        self.order += 1;
        self.queue.record(self.group, self.order, command)?;
        Ok(self.order)
    }
}