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
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
use crate::buffer::*;
use crate::commands::*;
use crate::crevice::std140::{AsStd140, Std140};
use crate::limits::Limits;
use crate::pipeline::*;
use crate::render_texture::*;
use crate::renderer::Renderer;
use crate::shader::*;
use crate::texture::*;
use parking_lot::RwLock;
use std::sync::Arc;

/// Device resource ID, used to know which resource was dropped
#[derive(Debug)]
pub enum ResourceId {
    Buffer(u64),
    Texture(u64),
    Pipeline(u64),
    RenderTexture(u64),
}

/// Represents what the GPU did in the last frame
#[derive(Clone, Copy, Default, Debug)]
pub struct GpuStats {
    /// Number of draw calls
    pub draw_calls: usize,
    /// Number of read_pixels callas
    pub read_pixels: usize,
    /// Number of textures updated
    pub texture_updates: usize,
    /// Number of textures created
    pub texture_creation: usize,
    /// Number of buffers updated
    pub buffer_updates: usize,
    /// Number of buffers created
    pub buffer_creation: usize,
    /// Any other interaction with the GPU
    pub misc: usize,
}

impl GpuStats {
    pub fn total(&self) -> usize {
        self.draw_calls + self.read_pixels + self.misc
    }
}

/// Represents a the implementation graphics backend like glow, wgpu or another
pub trait DeviceBackend {
    /// Returns the name of the api used (like webgl, wgpu, etc...)
    fn api_name(&self) -> &str;

    /// Return the device limits
    fn limits(&self) -> Limits {
        Default::default()
    }

    /// Return the GPU stats
    fn stats(&self) -> GpuStats;

    /// Reset the GPU stats
    fn reset_stats(&mut self);

    /// Create a new pipeline and returns the id
    fn create_pipeline(
        &mut self,
        vertex_source: &[u8],
        fragment_source: &[u8],
        vertex_attrs: &[VertexAttr],
        texture_locations: &[(u32, String)],
        options: PipelineOptions,
    ) -> Result<u64, String>;

    /// Create a new vertex buffer object and returns the id
    fn create_vertex_buffer(
        &mut self,
        attrs: &[VertexAttr],
        step_mode: VertexStepMode,
    ) -> Result<u64, String>;

    /// Create a new index buffer object and returns the id
    fn create_index_buffer(&mut self, format: IndexFormat) -> Result<u64, String>;

    /// Create a new uniform buffer and returns the id
    fn create_uniform_buffer(&mut self, slot: u32, name: &str) -> Result<u64, String>;

    /// Upload to the GPU the buffer data slice
    fn set_buffer_data(&mut self, buffer: u64, data: &[u8]);

    /// Create a new renderer using the size of the graphics
    fn render(&mut self, commands: &[Commands], target: Option<u64>);

    /// Clean all the dropped resources
    fn clean(&mut self, to_clean: &[ResourceId]);

    /// Sets the render size
    fn set_size(&mut self, width: u32, height: u32);

    /// Sets the screen dpi
    fn set_dpi(&mut self, scale_factor: f64);

    /// Create a new texture and returns the id
    fn create_texture(
        &mut self,
        source: TextureSourceKind,
        info: TextureInfo,
    ) -> Result<(u64, TextureInfo), String>;

    /// Create a new render target and returns the id
    fn create_render_texture(&mut self, texture_id: u64, info: &TextureInfo)
        -> Result<u64, String>;

    /// Update texture data
    fn update_texture(
        &mut self,
        texture: u64,
        source: TextureUpdaterSourceKind,
        opts: TextureUpdate,
    ) -> Result<(), String>;

    /// Read texture pixels
    fn read_pixels(
        &mut self,
        texture: u64,
        bytes: &mut [u8],
        opts: &TextureRead,
    ) -> Result<(), String>;

    fn as_any_mut(&mut self) -> &mut dyn std::any::Any;
}

/// Helper to drop resources on the backend
/// Like pipelines, textures, buffers
#[derive(Debug, Default)]
pub(crate) struct DropManager {
    dropped: RwLock<Vec<ResourceId>>,
}

impl DropManager {
    pub fn push(&self, id: ResourceId) {
        self.dropped.write().push(id);
    }

    pub fn clean(&self) {
        self.dropped.write().clear();
    }
}

pub struct Device {
    size: (u32, u32),
    dpi: f64,
    backend: Box<dyn DeviceBackend>, //TODO generic?
    drop_manager: Arc<DropManager>,
}

impl Device {
    pub fn new(backend: Box<dyn DeviceBackend>) -> Result<Self, String> {
        Ok(Self {
            backend,
            size: (1, 1),
            dpi: 1.0,
            drop_manager: Arc::new(Default::default()),
        })
    }

    #[inline]
    pub fn limits(&self) -> Limits {
        self.backend.limits()
    }

    #[inline]
    pub fn stats(&self) -> GpuStats {
        self.backend.stats()
    }

    #[inline]
    pub fn size(&self) -> (u32, u32) {
        self.size
    }

    #[inline]
    pub fn set_size(&mut self, width: u32, height: u32) {
        self.size = (width, height);
        self.backend.set_size(width, height);
    }

    #[inline]
    pub fn dpi(&self) -> f64 {
        self.dpi
    }

    #[inline]
    pub fn set_dpi(&mut self, scale_factor: f64) {
        self.dpi = scale_factor;
        self.backend.set_dpi(scale_factor);
    }

    #[inline]
    pub fn api_name(&self) -> &str {
        self.backend.api_name()
    }

    #[inline]
    pub fn create_renderer(&self) -> Renderer {
        Renderer::new(self.size.0, self.size.1)
    }

    /// Creates a Pipeline builder
    #[inline]
    pub fn create_pipeline(&mut self) -> PipelineBuilder {
        PipelineBuilder::new(self)
    }

    /// Creates a texture builder
    #[inline]
    pub fn create_texture(&mut self) -> TextureBuilder {
        TextureBuilder::new(self)
    }

    /// Creates a render texture builder
    #[inline]
    pub fn create_render_texture(&mut self, width: u32, height: u32) -> RenderTextureBuilder {
        RenderTextureBuilder::new(self, width, height)
    }

    /// Creates a vertex buffer builder
    #[inline]
    pub fn create_vertex_buffer(&mut self) -> VertexBufferBuilder {
        VertexBufferBuilder::new(self)
    }

    /// Creates a index buffer builder
    #[inline]
    pub fn create_index_buffer(&mut self) -> IndexBufferBuilder {
        IndexBufferBuilder::new(self)
    }

    /// Creates a uniform buffer builder
    #[inline]
    pub fn create_uniform_buffer(&mut self, slot: u32, name: &str) -> UniformBufferBuilder {
        UniformBufferBuilder::new(self, slot, name)
    }

    /// Update the texture data
    #[inline]
    pub fn update_texture<'a>(&'a mut self, texture: &'a mut Texture) -> TextureUpdater {
        TextureUpdater::new(self, texture)
    }

    /// Read pixels from a texture
    #[inline]
    pub fn read_pixels<'a>(&'a mut self, texture: &'a Texture) -> TextureReader {
        TextureReader::new(self, texture)
    }

    #[inline]
    pub(crate) fn inner_create_pipeline_from_raw(
        &mut self,
        vertex_source: &[u8],
        fragment_source: &[u8],
        vertex_attrs: &[VertexAttr],
        texture_locations: &[(u32, String)],
        options: PipelineOptions,
    ) -> Result<Pipeline, String> {
        let stride = vertex_attrs
            .iter()
            .fold(0, |acc, data| acc + data.format.bytes()) as usize;

        let id = self.backend.create_pipeline(
            vertex_source,
            fragment_source,
            vertex_attrs,
            texture_locations,
            options,
        )?;

        Ok(Pipeline::new(
            id,
            stride,
            options,
            self.drop_manager.clone(),
        ))
    }

    #[inline]
    pub(crate) fn inner_create_pipeline(
        &mut self,
        vertex_source: &ShaderSource,
        fragment_source: &ShaderSource,
        vertex_attrs: &[VertexAttr],
        texture_locations: &[(u32, String)],
        options: PipelineOptions,
    ) -> Result<Pipeline, String> {
        let api = self.backend.api_name();
        let vertex = match vertex_source.get_source(api) {
            Some(v) => v,
            None => {
                log::warn!("Vertex shader for api '{api}' not available.");
                &[]
            }
        };
        let fragment = match fragment_source.get_source(api) {
            Some(f) => f,
            None => {
                log::warn!("Fragment shader for api '{api}' not available.");
                &[]
            }
        };
        self.inner_create_pipeline_from_raw(
            vertex,
            fragment,
            vertex_attrs,
            texture_locations,
            options,
        )
    }

    #[inline(always)]
    pub(crate) fn inner_create_vertex_buffer(
        &mut self,
        data: Option<&[f32]>,
        attrs: &[VertexAttr],
        step_mode: VertexStepMode,
    ) -> Result<Buffer, String> {
        let id = self.backend.create_vertex_buffer(attrs, step_mode)?;

        let buffer = Buffer::new(id, BufferUsage::Vertex, None, self.drop_manager.clone());

        if let Some(d) = data {
            self.set_buffer_data(&buffer, d);
        }

        Ok(buffer)
    }

    #[inline]
    pub(crate) fn inner_create_index_buffer(
        &mut self,
        data: Option<IndexBufferWrapper>,
        format: IndexFormat,
    ) -> Result<Buffer, String> {
        let id = self.backend.create_index_buffer(format)?;
        let buffer = Buffer::new(id, BufferUsage::Index, None, self.drop_manager.clone());
        if let Some(d) = data {
            match d {
                IndexBufferWrapper::Uint16(s) => self.set_buffer_data(&buffer, s),
                IndexBufferWrapper::Uint32(s) => self.set_buffer_data(&buffer, s),
            }
        }
        Ok(buffer)
    }

    #[inline]
    pub(crate) fn inner_create_uniform_buffer(
        &mut self,
        slot: u32,
        name: &str,
        data: Option<Vec<u8>>,
    ) -> Result<Buffer, String> {
        //debug_assert!(current_pipeline.is_some()) //pipeline should be already binded
        let id = self.backend.create_uniform_buffer(slot, name)?;
        let buffer = Buffer::new(
            id,
            BufferUsage::Uniform(slot),
            None,
            self.drop_manager.clone(),
        );

        if let Some(d) = data {
            self.set_buffer_data(&buffer, &d);
        }

        Ok(buffer)
    }

    #[inline]
    pub(crate) fn inner_create_texture(
        &mut self,
        source: TextureSourceKind,
        info: TextureInfo,
    ) -> Result<Texture, String> {
        let (id, info) = self.backend.create_texture(source, info)?;
        Ok(Texture::new(id, info, self.drop_manager.clone()))
    }

    #[inline]
    pub(crate) fn inner_create_render_texture(
        &mut self,
        info: TextureInfo,
    ) -> Result<RenderTexture, String> {
        let (tex_id, info) = self
            .backend
            .create_texture(TextureSourceKind::Empty, info)?;

        let id = self.backend.create_render_texture(tex_id, &info)?;
        let mut texture = Texture::new(tex_id, info, self.drop_manager.clone());
        texture.is_render_texture = true;
        Ok(RenderTexture::new(id, texture, self.drop_manager.clone()))
    }

    #[inline]
    pub fn render(&mut self, commands: &[Commands]) {
        self.backend.render(commands, None);
    }

    #[inline]
    pub fn render_to(&mut self, target: &RenderTexture, commands: &[Commands]) {
        self.backend.render(commands, Some(target.id()));
    }

    #[inline]
    pub(crate) fn inner_update_texture(
        &mut self,
        texture: &mut Texture,
        source: TextureUpdaterSourceKind,
        opts: TextureUpdate,
    ) -> Result<(), String> {
        self.backend.update_texture(texture.id(), source, opts)
    }

    #[inline]
    pub(crate) fn inner_read_pixels(
        &mut self,
        texture: &Texture,
        bytes: &mut [u8],
        opts: &TextureRead,
    ) -> Result<(), String> {
        // Check if the buffer size is enough to read the pixels
        if cfg!(debug_assertions) {
            let size = (opts.width * opts.height) as usize;
            let bpp = opts.format.bytes_per_pixel() as usize;
            let len = size * bpp;
            debug_assert!(
                bytes.len() >= len,
                "The provided buffer len of {} is less than the required {} when reading pixels from texture {}",
                bytes.len(),
                len,
                texture.id()
            );
        }

        self.backend.read_pixels(texture.id(), bytes, opts)
    }

    #[inline]
    pub fn clean(&mut self) {
        self.backend.reset_stats();

        if self.drop_manager.dropped.read().is_empty() {
            return;
        }

        self.backend.clean(&self.drop_manager.dropped.read());
        self.drop_manager.clean();
    }

    #[inline]
    pub fn set_buffer_data<T: BufferData>(&mut self, buffer: &Buffer, data: T) {
        data.upload(self, buffer.id());
    }

    pub fn downcast_backend<B: DeviceBackend + 'static>(&mut self) -> Result<&mut B, String> {
        self.backend
            .as_any_mut()
            .downcast_mut()
            .ok_or_else(|| "Invalid backend type".to_string())
    }
}

pub trait Uniform: AsStd140 {}
pub trait BufferData {
    fn upload(&self, device: &mut Device, id: u64);
    fn save_as_bytes(&self, _data: &mut Vec<u8>) {}
}

impl<T> BufferData for &[T]
where
    T: bytemuck::Pod,
{
    #[inline]
    fn upload(&self, device: &mut Device, id: u64) {
        device
            .backend
            .set_buffer_data(id, bytemuck::cast_slice(self));
    }

    fn save_as_bytes(&self, data: &mut Vec<u8>) {
        data.extend_from_slice(bytemuck::cast_slice(self));
    }
}

impl<const N: usize, T> BufferData for &[T; N]
where
    T: bytemuck::Pod,
{
    #[inline]
    fn upload(&self, device: &mut Device, id: u64) {
        device
            .backend
            .set_buffer_data(id, bytemuck::cast_slice(self.as_slice()));
    }

    fn save_as_bytes(&self, data: &mut Vec<u8>) {
        data.extend_from_slice(bytemuck::cast_slice(self.as_slice()));
    }
}

impl<T> BufferData for &Vec<T>
where
    T: bytemuck::Pod,
{
    #[inline]
    fn upload(&self, device: &mut Device, id: u64) {
        device
            .backend
            .set_buffer_data(id, bytemuck::cast_slice(self.as_slice()));
    }

    fn save_as_bytes(&self, data: &mut Vec<u8>) {
        data.extend_from_slice(bytemuck::cast_slice(self.as_slice()));
    }
}

impl<T> BufferData for &T
where
    T: Uniform,
{
    #[inline]
    fn upload(&self, device: &mut Device, id: u64) {
        // TODO check opengl version or driver if it uses std140 to layout or not
        device
            .backend
            .set_buffer_data(id, self.as_std140().as_bytes());
    }

    fn save_as_bytes(&self, data: &mut Vec<u8>) {
        data.extend_from_slice(self.as_std140().as_bytes());
    }
}

macro_rules! uniform_impl {
    ( $( $typ:ty, )* ) => {
        $(
            impl Uniform for $typ {}
        )*
    }
}

uniform_impl! {
    notan_math::Vec2,
    notan_math::Vec3,
    notan_math::Vec4,

    notan_math::IVec2,
    notan_math::IVec3,
    notan_math::IVec4,

    notan_math::UVec2,
    notan_math::UVec3,
    notan_math::UVec4,

    notan_math::DVec2,
    notan_math::DVec3,
    notan_math::DVec4,

    notan_math::Mat2,
    notan_math::Mat3,
    notan_math::Mat4,

    notan_math::DMat2,
    notan_math::DMat3,
    notan_math::DMat4,
}