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
use crate::buffer::{VertexAttr, VertexInfo};
use crate::color::Color;
use crate::device::{DropManager, ResourceId};
use crate::{Device, ShaderSource};
use std::sync::Arc;

#[derive(Debug)]
struct PipelineIdRef {
    id: u64,
    drop_manager: Arc<DropManager>,
}

impl Drop for PipelineIdRef {
    fn drop(&mut self) {
        self.drop_manager.push(ResourceId::Pipeline(self.id));
    }
}

#[derive(Debug, Clone)]
pub struct Pipeline {
    id: u64,
    _id_ref: Arc<PipelineIdRef>,
    stride: usize,
    pub options: PipelineOptions,
}

impl std::cmp::PartialEq for Pipeline {
    fn eq(&self, other: &Self) -> bool {
        self.id() == other.id() && self.options == other.options
    }
}

impl Pipeline {
    pub(crate) fn new(
        id: u64,
        stride: usize,
        options: PipelineOptions,
        drop_manager: Arc<DropManager>,
    ) -> Self {
        let id_ref = Arc::new(PipelineIdRef { id, drop_manager });

        Self {
            id,
            _id_ref: id_ref,
            stride,
            options,
        }
    }

    #[inline(always)]
    pub fn id(&self) -> u64 {
        self.id
    }

    #[inline(always)]
    pub fn stride(&self) -> usize {
        self.stride
    }

    #[inline(always)]
    pub fn offset(&self) -> usize {
        self.stride / 4
    }
}

enum ShaderKind<'b> {
    Raw {
        vertex: &'b [u8],
        fragment: &'b [u8],
    },

    Source {
        vertex: &'b ShaderSource<'b>,
        fragment: &'b ShaderSource<'b>,
    },
}

/// Pipeline builder pattern
pub struct PipelineBuilder<'a, 'b> {
    device: &'a mut Device,
    attrs: Vec<VertexAttr>,
    options: PipelineOptions,
    shaders: Option<ShaderKind<'b>>,
    texture_locations: Vec<(u32, String)>,
}

impl<'a, 'b> PipelineBuilder<'a, 'b> {
    pub fn new(device: &'a mut Device) -> Self {
        Self {
            device,
            attrs: vec![],
            options: Default::default(),
            shaders: None,
            texture_locations: vec![],
        }
    }

    /// Set the shaders from a ShaderSource object
    pub fn from(mut self, vertex: &'b ShaderSource, fragment: &'b ShaderSource) -> Self {
        self.shaders = Some(ShaderKind::Source { vertex, fragment });
        self
    }

    /// Set the shaders from a bytes slice
    #[allow(clippy::wrong_self_convention)]
    pub fn from_raw(mut self, vertex: &'b [u8], fragment: &'b [u8]) -> Self {
        self.shaders = Some(ShaderKind::Raw { vertex, fragment });
        self
    }

    /// Set the vertex structure info for a vertex buffer
    pub fn with_vertex_info(mut self, info: &VertexInfo) -> Self {
        self.attrs.extend(&info.attrs);
        self
    }

    /// Map uniform location to a texture id
    pub fn with_texture_location(mut self, location: u32, id: &str) -> Self {
        self.texture_locations.push((location, id.to_string()));
        self
    }

    /// Set the Color blending mode
    pub fn with_color_blend(mut self, color_blend: BlendMode) -> Self {
        self.options.color_blend = Some(color_blend);
        self
    }

    /// Set the alpha blending mode
    pub fn with_alpha_blend(mut self, alpha_blend: BlendMode) -> Self {
        self.options.alpha_blend = Some(alpha_blend);
        self
    }

    /// Set the Culling mode
    pub fn with_cull_mode(mut self, cull_mode: CullMode) -> Self {
        self.options.cull_mode = cull_mode;
        self
    }

    /// Set the Depth Stencil options
    pub fn with_depth_stencil(mut self, depth_stencil: DepthStencil) -> Self {
        self.options.depth_stencil = depth_stencil;
        self
    }

    /// Set the Color Mask options
    pub fn with_color_mask(mut self, color_mask: ColorMask) -> Self {
        self.options.color_mask = color_mask;
        self
    }

    /// Set the Stencil options
    pub fn with_stencil(mut self, stencil: StencilOptions) -> Self {
        self.options.stencil = Some(stencil);
        self
    }

    /// Enable the SRGB Color Space
    pub fn with_srgb_space(mut self, srgb: bool) -> Self {
        self.options.srgb_space = srgb;
        self
    }

    /// Build the pipeline with the data set on the builder
    pub fn build(self) -> Result<Pipeline, String> {
        match self.shaders {
            Some(ShaderKind::Source { vertex, fragment }) => self.device.inner_create_pipeline(
                vertex,
                fragment,
                &self.attrs,
                &self.texture_locations,
                self.options,
            ),
            Some(ShaderKind::Raw { vertex, fragment }) => {
                self.device.inner_create_pipeline_from_raw(
                    vertex,
                    fragment,
                    &self.attrs,
                    &self.texture_locations,
                    self.options,
                )
            }
            _ => Err("Vertex and Fragment shaders should be present".to_string()),
        }
    }
}

/// Blending factor computed
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum BlendFactor {
    Zero,
    One,
    SourceColor,
    InverseSourceColor,
    DestinationColor,
    InverseDestinationColor,
    SourceAlpha,
    InverseSourceAlpha,
    DestinationAlpha,
    InverseDestinationAlpha,
}

/// Blending equation used to combine source and destiny
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum BlendOperation {
    Add,
    Subtract,
    ReverseSubtract,
    Min,
    Max,
}

/// Blending mode used to draw
#[derive(Debug, Clone, Eq, PartialEq, Copy)]
pub struct BlendMode {
    pub src: BlendFactor,
    pub dst: BlendFactor,
    pub op: BlendOperation,
}

impl BlendMode {
    pub const NONE: BlendMode = BlendMode {
        src: BlendFactor::One,
        dst: BlendFactor::Zero,
        op: BlendOperation::Add,
    };
    pub const NORMAL: BlendMode = BlendMode {
        src: BlendFactor::SourceAlpha,
        dst: BlendFactor::InverseSourceAlpha,
        op: BlendOperation::Add,
    };
    pub const ADD: BlendMode = BlendMode {
        src: BlendFactor::One,
        dst: BlendFactor::One,
        op: BlendOperation::Add,
    };
    pub const MULTIPLY: BlendMode = BlendMode {
        src: BlendFactor::DestinationColor,
        dst: BlendFactor::InverseSourceAlpha,
        op: BlendOperation::Add,
    };
    pub const SCREEN: BlendMode = BlendMode {
        src: BlendFactor::One,
        dst: BlendFactor::InverseSourceColor,
        op: BlendOperation::Add,
    };
    pub const ERASE: BlendMode = BlendMode {
        src: BlendFactor::Zero,
        dst: BlendFactor::InverseSourceColor,
        op: BlendOperation::Add,
    };
    pub const OVER: BlendMode = BlendMode {
        src: BlendFactor::One,
        dst: BlendFactor::InverseSourceAlpha,
        op: BlendOperation::Add,
    };

    /// Creates a new blend mode using the ADD operation
    pub fn new(source: BlendFactor, destination: BlendFactor) -> Self {
        Self::with_operation(source, destination, BlendOperation::Add)
    }

    /// Creates a new blend mode
    pub fn with_operation(
        source: BlendFactor,
        destination: BlendFactor,
        operation: BlendOperation,
    ) -> Self {
        Self {
            src: source,
            dst: destination,
            op: operation,
        }
    }
}

/// Represents stencil and depth comparison
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum CompareMode {
    None,
    Less,
    Equal,
    LEqual,
    Greater,
    NotEqual,
    GEqual,
    Always,
}

/// Represents face culling modes
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum CullMode {
    None,
    Front,
    Back,
}

/// Represents the color mask
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub struct ColorMask {
    pub r: bool,
    pub g: bool,
    pub b: bool,
    pub a: bool,
}

impl Default for ColorMask {
    fn default() -> Self {
        Self {
            r: true,
            g: true,
            b: true,
            a: true,
        }
    }
}

impl ColorMask {
    pub const ALL: ColorMask = ColorMask {
        r: true,
        g: true,
        b: true,
        a: true,
    };

    pub const NONE: ColorMask = ColorMask {
        r: false,
        g: false,
        b: false,
        a: false,
    };
}

/// Represents the color mask
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub struct DepthStencil {
    pub write: bool,
    pub compare: CompareMode,
}

impl Default for DepthStencil {
    fn default() -> Self {
        Self {
            write: true,
            compare: CompareMode::None, //Less?
        }
    }
}

/// Options to use with the render pipeline
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub struct PipelineOptions {
    pub color_blend: Option<BlendMode>,
    pub alpha_blend: Option<BlendMode>,
    pub cull_mode: CullMode,
    pub depth_stencil: DepthStencil,
    pub color_mask: ColorMask,
    pub stencil: Option<StencilOptions>,
    pub srgb_space: bool,
}

impl Default for PipelineOptions {
    fn default() -> Self {
        Self {
            depth_stencil: Default::default(),
            cull_mode: CullMode::None,
            color_blend: None,
            alpha_blend: None,
            color_mask: Default::default(),
            stencil: None,
            srgb_space: false,
        }
    }
}

/// Clear options to use at the beginning of the frame
#[derive(Default, Debug, Clone, Copy, PartialEq)]
pub struct ClearOptions {
    pub color: Option<Color>,
    pub depth: Option<f32>,
    pub stencil: Option<i32>,
}

impl ClearOptions {
    /// Create a new struct just with color
    pub fn color(color: Color) -> Self {
        Self {
            color: Some(color),
            ..Default::default()
        }
    }

    pub fn none() -> Self {
        Self::default()
    }
}

/// Represents the draw usage
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum DrawType {
    Static,
    Dynamic,
}

/// Represent's the stencil action
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum StencilAction {
    Keep,
    Zero,
    Replace,
    Increment,
    IncrementWrap,
    Decrement,
    DecrementWrap,
    Invert,
}

/// Represents the stencil's option
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub struct StencilOptions {
    pub stencil_fail: StencilAction,
    pub depth_fail: StencilAction,
    pub pass: StencilAction,
    pub compare: CompareMode,
    pub read_mask: u32,
    pub write_mask: u32,
    pub reference: u32,
}

impl Default for StencilOptions {
    fn default() -> Self {
        Self {
            stencil_fail: StencilAction::Keep,
            depth_fail: StencilAction::Keep,
            pass: StencilAction::Keep,
            compare: CompareMode::Always,
            read_mask: 0xff,
            write_mask: 0,
            reference: 0,
        }
    }
}

#[derive(Default, Debug, Copy, Clone, Eq, PartialEq)]
pub enum DrawPrimitive {
    Lines,
    LineStrip,
    #[default]
    Triangles,
    TriangleStrip,
}