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
use self::{
    batches::{Batch, DrawCall},
    camera::Camera,
    mesh::{Mesh, MeshBuilder, Vertex},
    shaders::Program,
    shaders::{Shader, ShaderType},
    sprites::Sprite,
    text::{Font, FontError, TextSettings},
    textures::Texture,
};
use gl;
use maths::{Vector2f, Vector2u, Vector3f};
use sdl2;
use std::{error, fmt, ptr};
use transform::Transform;

mod batches;
pub mod camera;
pub mod mesh;
pub mod shaders;
pub mod sprites;
pub mod text;
pub mod textures;

/// Error related to OpenGL drawing.
#[derive(Debug)]
pub enum DrawingError {
    /// Error related to SDL.
    SdlError(String),
    /// Error related to OpenGL.
    GlError(String),
    /// Tried drawing a mesh that had no EBO set.
    MeshEBONotInitialized,
    /// Tried drawing a mesh that had no VAO set.
    MeshVAONotInitialized,
    /// Error related to OpenGL shaders.
    ShaderError(shaders::ShaderError),
    /// Error related to window building.
    WindowBuildError(sdl2::video::WindowBuildError),
}

impl fmt::Display for DrawingError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            DrawingError::SdlError(string) => write!(f, "{}", string),
            DrawingError::GlError(string) => write!(f, "{}", string),
            DrawingError::ShaderError(error) => write!(f, "{}", error),
            DrawingError::WindowBuildError(error) => write!(f, "{}", error),
            DrawingError::MeshEBONotInitialized => write!(f, "Mesh EBO not initialized"),
            DrawingError::MeshVAONotInitialized => write!(f, "Mesh VAO not initialized"),
        }
    }
}

impl error::Error for DrawingError {
    fn cause(&self) -> Option<&error::Error> {
        match self {
            DrawingError::ShaderError(error) => Some(error),
            DrawingError::WindowBuildError(error) => Some(error),

            _ => None,
        }
    }
}

#[derive(Debug, Copy, Clone)]
pub struct WindowSettings<'a> {
    pub title: &'a str,
    pub width: u32,
    pub height: u32,
    pub vsync: bool,
}

/// Manages everything related to graphics and rendering.
pub struct GraphicsManager {
    window: sdl2::video::Window,

    #[allow(dead_code)]
    gl_context: sdl2::video::GLContext,

    /// Base shader program.
    program: Program,
    /// Base mesh used to draw sprites.
    quad: Mesh,

    /// All draw calls to be rendered this frame.
    batches: Vec<Batch>,
}

impl GraphicsManager {
    /// Initializes graphics from SDL object, resource loader, default shader paths and window settings
    pub fn new(sdl: &sdl2::Sdl, window_settings: WindowSettings) -> Result<Self, DrawingError> {
        //Initialize VideoSubsystem
        let video = sdl.video().map_err(DrawingError::SdlError)?;

        //Set OpenGL parameters
        {
            let gl_attr = video.gl_attr();
            gl_attr.set_context_profile(sdl2::video::GLProfile::Core);
            gl_attr.set_context_version(3, 3);
        }

        //Create Window
        let window = video
            .window(
                window_settings.title,
                window_settings.width,
                window_settings.height,
            ).opengl()
            .resizable()
            .build()
            .map_err(DrawingError::WindowBuildError)?;

        //Initialize OpenGL
        let gl_context = window.gl_create_context().map_err(DrawingError::GlError)?;
        gl::load_with(|s| video.gl_get_proc_address(s) as *const gl::types::GLvoid);

        //Enable/disable vsync
        video.gl_set_swap_interval(if window_settings.vsync {
            sdl2::video::SwapInterval::VSync
        } else {
            sdl2::video::SwapInterval::Immediate
        });

        unsafe {
            //Depth testing
            gl::Enable(gl::DEPTH_TEST);
            gl::DepthFunc(gl::LEQUAL);

            //Blending
            gl::Enable(gl::BLEND);
            gl::BlendFunc(gl::SRC_ALPHA, gl::ONE_MINUS_SRC_ALPHA);

            //Clear color
            gl::ClearColor(0.3, 0.3, 0.5, 1.0);
        }

        //Load shaders
        let vertex_shader =
            Shader::from_source(include_str!("shaders/standard.vert"), ShaderType::Vertex)
                .map_err(DrawingError::ShaderError)?;
        let fragment_shader =
            Shader::from_source(include_str!("shaders/standard.frag"), ShaderType::Fragment)
                .map_err(DrawingError::ShaderError)?;
        let program = Program::from_shaders(vertex_shader, fragment_shader)
            .map_err(DrawingError::ShaderError)?;

        //Build quad mesh
        let quad = MeshBuilder {
            vertices: vec![
                Vertex {
                    position: Vector3f::new(0.5, 0.5, 0.0),
                    uv: Vector2f::new(1.0, 0.0),
                },
                Vertex {
                    position: Vector3f::new(0.5, -0.5, 0.0),
                    uv: Vector2f::new(1.0, 1.0),
                },
                Vertex {
                    position: Vector3f::new(-0.5, -0.5, 0.0),
                    uv: Vector2f::new(0.0, 1.0),
                },
                Vertex {
                    position: Vector3f::new(-0.5, 0.5, 0.0),
                    uv: Vector2f::new(0.0, 0.0),
                },
            ],
            indices: vec![0, 1, 2, 0, 2, 3],
        }.build();

        //Build and return graphics manager
        Ok(Self {
            window,
            gl_context,
            program,
            quad,
            batches: Vec::new(),
        })
    }

    /// Get the current window's size.
    pub fn window_size(&self) -> Vector2u {
        self.window.size().into()
    }

    /// Sets the OpenGL viewport. Call when the window is resized.
    pub fn resize(&mut self, width: i32, height: i32) {
        unsafe {
            gl::Viewport(0, 0, width as gl::types::GLint, height as gl::types::GLint);
        }
    }

    /// Draws a `Sprite` on a textured quad mesh.
    ///
    /// `transform` specifies the position, scale, and rotation
    /// of the drawn `Sprite`.
    ///
    /// `Camera` is the camera the `Sprite` is viewed from.
    ///
    /// Note: by default all sprites are square. For non-square sprites,
    /// you must use `transform.scale` to scale the quad appropriately.
    pub fn draw_sprite(&mut self, sprite: &Sprite, transform: &Transform, camera: &Camera) {
        let drawcall = DrawCall {
            program: self.program,
            mesh: self.quad,
            texture: sprite.texture(),
            tex_position: sprite.gl_position(),
            matrix: camera.matrix(self.window.size().into()) * transform.matrix(),
        };

        self.queue_drawcall(&drawcall);
    }

    /// Draws a string.
    pub fn draw_text(
        &mut self,
        text: &str,
        font: &mut Font,
        settings: TextSettings,
        transform: &Transform,
        camera: &Camera,
    ) -> Result<(), FontError> {
        for char_position in font.get_glyphs(text, settings)? {
            let texture = font.texture();

            let char_transform = Transform {
                position: transform.position + Vector3f::new(
                    char_position.world_position.x,
                    char_position.world_position.y,
                    0.0,
                ),
                scale: Vector3f::new(
                    transform.scale.x * char_position.world_position.z,
                    transform.scale.y * char_position.world_position.w,
                    transform.scale.z,
                ),
                rotation: transform.rotation,
            };

            let drawcall = DrawCall {
                program: self.program,
                mesh: self.quad,
                texture,
                tex_position: char_position.texture_position,
                matrix: camera.matrix(self.window.size().into()) * char_transform.matrix(),
            };

            self.queue_drawcall(&drawcall);
        }

        Ok(())
    }

    /// Adds a drawcall to the render queue.
    ///
    /// If no suitable batch is found, a new one is created.
    pub fn queue_drawcall(&mut self, drawcall: &DrawCall) {
        for batch in &mut self.batches {
            //Attempts to add drawcall to batch
            if batch.add(drawcall) {
                return;
            }
        }

        //Could not find suitable batch, create a new one
        self.batches.push(Batch::new(drawcall));
    }

    /// Renders the current queued batches.
    pub fn render(&mut self) -> Result<(), DrawingError> {
        //Clear render target
        unsafe {
            gl::Clear(gl::COLOR_BUFFER_BIT | gl::DEPTH_BUFFER_BIT);
        }

        //println!("Rendering {} batches", self.batches.len());

        //Render batches
        for batch in &self.batches {
            self.draw(batch)?
        }

        //Clear queue
        self.batches.clear();

        //Swap buffers
        self.window.gl_swap_window();

        Ok(())
    }

    /// Draw a batch.
    fn draw(&self, batch: &Batch) -> Result<(), DrawingError> {
        //Check that mesh is valid
        batch.mesh().check()?;

        //Use program
        batch.program().set_used();

        unsafe {
            //Bind texture
            gl::BindTexture(gl::TEXTURE_2D, batch.texture());

            //Bind mesh
            gl::BindVertexArray(batch.mesh().vao());
            gl::BindBuffer(gl::ELEMENT_ARRAY_BUFFER, batch.mesh().ebo());
        }

        //Bind objects data
        batch.buffer_data();

        //Draw batch
        unsafe {
            gl::DrawElementsInstanced(
                gl::TRIANGLES,                         //Draw mode
                batch.mesh().indices_count() as i32,   //Number of indices
                gl::UNSIGNED_INT,                      //Type of indices
                ptr::null(),                           //Starting index
                batch.obj_count() as gl::types::GLint, //Number of objects in batch
            );
        }

        Ok(())
    }
}