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
use hashbrown::HashMap;
pub use notan_graphics::prelude::*;
pub use notan_graphics::*;
use std::any::{Any, TypeId};
use std::cell::{Ref, RefCell, RefMut};

/// Graphic interface to interact with the GPU
/// It's a wrapper for the Device interface and
/// the graphics extensions
pub struct Graphics {
    /// Graphic raw implementation
    pub device: Device,

    pub extensions: ExtContainer,
}

impl Graphics {
    pub fn new(backend: Box<dyn DeviceBackend>) -> Result<Self, String> {
        let device = Device::new(backend)?;
        let plugins = ExtContainer::default();

        Ok(Self {
            device,
            extensions: plugins,
        })
    }

    /// Adds a new graphic extensions
    #[inline]
    pub fn add_extension<R, T>(&mut self, extension: T)
    where
        R: GfxRenderer,
        T: GfxExtension<R> + 'static,
    {
        self.extensions.add(extension);
    }

    /// Remove a graphic extensions
    #[inline]
    pub fn remove_extension<R, T>(&mut self)
    where
        R: GfxRenderer,
        T: GfxExtension<R> + 'static,
    {
        self.extensions.remove::<R, T>();
    }

    /// Returns the extension as mutable reference
    #[inline]
    pub fn extension_mut<R, T>(&self) -> Option<RefMut<T>>
    where
        R: GfxRenderer,
        T: GfxExtension<R> + 'static,
    {
        self.extensions.get_mut()
    }

    /// Returns the extension as reference
    #[inline]
    pub fn extension<R, T>(&self) -> Option<Ref<T>>
    where
        R: GfxRenderer,
        T: GfxExtension<R> + 'static,
    {
        self.extensions.get()
    }

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

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

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

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

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

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

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

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

    /// Render to the screen
    #[inline]
    pub fn render<G: GfxRenderer>(&mut self, renderer: &G) {
        if let Err(err) = renderer.render(&mut self.device, &mut self.extensions, None) {
            log::error!("{}", err);
            panic!("{}", err);
        }
    }

    /// Render to a custom target
    #[inline]
    pub fn render_to<G: GfxRenderer>(&mut self, target: &RenderTexture, renderer: &G) {
        if let Err(err) = renderer.render(&mut self.device, &mut self.extensions, Some(target)) {
            log::error!("{}", err);
            panic!("{}", err);
        }
    }

    /// Upload the buffer data to the GPU
    #[inline]
    pub fn set_buffer_data<T: BufferData>(&mut self, buffer: &Buffer, data: T) {
        self.device.set_buffer_data(buffer, data);
    }

    /// Creates a render pass
    #[inline]
    pub fn create_renderer(&self) -> Renderer {
        self.device.create_renderer()
    }

    /// Returns the Graphics API limits
    #[inline]
    pub fn limits(&self) -> Limits {
        self.device.limits()
    }

    /// Returns the drawable size
    #[inline]
    pub fn size(&self) -> (u32, u32) {
        self.device.size()
    }

    /// Sets the drawable size
    #[inline]
    pub fn set_size(&mut self, width: u32, height: u32) {
        self.device.set_size(width, height);
    }

    /// Returns the screen dpi
    #[inline]
    pub fn dpi(&self) -> f64 {
        self.device.dpi()
    }

    /// Sets the screens dpi
    #[inline]
    pub fn set_dpi(&mut self, scale_factor: f64) {
        self.device.set_dpi(scale_factor);
    }

    /// Return the GPU stats
    #[inline]
    pub fn stats(&self) -> GpuStats {
        self.device.stats()
    }
}

impl std::ops::Deref for Graphics {
    type Target = Device;

    fn deref(&self) -> &Self::Target {
        &self.device
    }
}

impl std::ops::DerefMut for Graphics {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.device
    }
}

/// Graphic extensions container
#[derive(Default)]
pub struct ExtContainer {
    map: HashMap<TypeId, Box<dyn Any>>,
}

impl ExtContainer {
    /// Adds a graphics extension
    #[inline]
    pub fn add<R, T>(&mut self, value: T)
    where
        R: GfxRenderer,
        T: GfxExtension<R> + 'static,
    {
        self.map
            .insert(TypeId::of::<T>(), Box::new(RefCell::new(value)));
    }

    /// Returns the extension as mutable reference
    #[inline]
    pub fn get_mut<R, T>(&self) -> Option<RefMut<'_, T>>
    where
        R: GfxRenderer,
        T: GfxExtension<R> + 'static,
    {
        self.map
            .get(&TypeId::of::<T>())?
            .downcast_ref::<RefCell<T>>()
            .map(|value| value.borrow_mut())
    }

    /// Returns the extension
    #[inline]
    pub fn get<R, T>(&self) -> Option<Ref<'_, T>>
    where
        R: GfxRenderer,
        T: GfxExtension<R> + 'static,
    {
        self.map
            .get(&TypeId::of::<T>())?
            .downcast_ref::<RefCell<T>>()
            .map(|value| value.borrow())
    }

    /// Remove the extension
    #[inline]
    pub fn remove<R, T>(&mut self)
    where
        R: GfxRenderer,
        T: GfxExtension<R> + 'static,
    {
        self.map.remove(&TypeId::of::<T>());
    }
}

/// Represents an object that contains render commands
pub trait GfxRenderer {
    /// Send the commands to the gpu to be rendered
    fn render(
        &self,
        device: &mut Device,
        extensions: &mut ExtContainer,
        target: Option<&RenderTexture>,
    ) -> Result<(), String>;
}

pub trait GfxExtension<T: ?Sized> {}

impl GfxRenderer for Renderer {
    fn render(
        &self,
        device: &mut Device,
        _extensions: &mut ExtContainer,
        target: Option<&RenderTexture>,
    ) -> Result<(), String> {
        match target {
            None => device.render(self.commands()),
            Some(rt) => device.render_to(rt, self.commands()),
        }

        Ok(())
    }
}