good-web-game 0.6.1

An alternative implementation of the ggez game engine, based on miniquad
Documentation
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
mod canvas;
mod context;
mod drawparam;
mod image;
#[cfg(feature = "mesh")]
mod mesh;
mod shader;
mod text;
mod types;

pub mod spritebatch;

use crate::error::GameResult;
use crate::Context;

pub use self::{
    canvas::*, context::GraphicsContext, drawparam::*, image::*, shader::*, text::*, types::*,
};

#[cfg(feature = "mesh")]
pub use self::mesh::*;

use miniquad::PassAction;

/// Holds the bindings of objects that were dropped this frame.
/// They (and the buffers inside of them) are kept alive until the beginning of the next frame
/// to ensure that they're not deleted before being used in the frame in which they were dropped.
static mut DROPPED_BINDINGS: Vec<(miniquad::Bindings, i32, bool)> = Vec::new();

/// Adds some bindings to a vec where they'll be kept alive until the beginning of the next but one frame.
pub(crate) fn add_dropped_bindings(bindings: miniquad::Bindings, delete_texture: bool) {
    unsafe { DROPPED_BINDINGS.push((bindings, 1, delete_texture)) };
}

/// Deletes all buffers that were dropped two frames before and kept alive for the duration of their
/// own frame and the next one.
pub(crate) fn release_dropped_bindings() {
    unsafe {
        for (bindings, counter, delete_texture) in DROPPED_BINDINGS.iter_mut() {
            if *counter == 0 {
                for v_buffer in bindings.vertex_buffers.iter_mut() {
                    v_buffer.delete();
                }
                bindings.index_buffer.delete();
                if *delete_texture {
                    bindings.images[0].delete();
                }
            }
            *counter -= 1;
        }
        DROPPED_BINDINGS.retain(|(_bindings, counter, _delete_texture)| *counter >= 0);
    }
}

/// Clear the screen to the background color.
pub fn clear(ctx: &mut Context, quad_ctx: &mut miniquad::graphics::GraphicsContext, color: Color) {
    let action = PassAction::Clear {
        color: Some((color.r, color.g, color.b, color.a)),
        depth: None,
        stencil: None,
    };

    let pass = ctx.framebuffer();
    quad_ctx.begin_pass(pass, action);
    quad_ctx.clear(Some((color.r, color.g, color.b, color.a)), None, None);
}

/// Draws the given `Drawable` object to the screen by calling its
/// [`draw()`](trait.Drawable.html#tymethod.draw) method.
pub fn draw<D, T>(
    ctx: &mut Context,
    quad_ctx: &mut miniquad::graphics::GraphicsContext,
    drawable: &D,
    params: T,
) -> GameResult
where
    D: Drawable,
    T: Into<DrawParam>,
{
    let params = params.into();
    drawable.draw(ctx, quad_ctx, params)
}

pub fn set_projection<M>(context: &mut Context, proj: M)
where
    M: Into<mint::ColumnMatrix4<f32>>,
{
    let proj = cgmath::Matrix4::from(proj.into());
    let gfx = &mut context.gfx_context;
    gfx.set_projection(proj);
}

pub fn mul_projection<M>(context: &mut Context, proj: M)
where
    M: Into<mint::ColumnMatrix4<f32>>,
{
    let proj = cgmath::Matrix4::from(proj.into());
    let gfx = &mut context.gfx_context;
    let curr = gfx.projection();
    gfx.set_projection(proj * curr);
}

/*
/// Returns the size of the window in pixels as (width, height),
/// including borders, titlebar, etc.
/// Returns zeros if the window doesn't exist.
pub fn size(_ctx: &Context) -> (f32, f32) {
    unimplemented!("use `drawable_size()` for getting the size of the underlying window's drawable")
}
*/

/// Returns the size of the window's underlying drawable in pixels as (width, height).
/// This may return a different value than `get_size()` when run on a platform with high-DPI support
pub fn drawable_size(quad_ctx: &miniquad::graphics::GraphicsContext) -> (f32, f32) {
    quad_ctx.screen_size()
}

/// Sets the bounds of the screen viewport.
///
/// The default coordinate system has (0,0) at the top-left corner
/// with X increasing to the right and Y increasing down, with the
/// viewport scaled such that one coordinate unit is one pixel on the
/// screen.  This function lets you change this coordinate system to
/// be whatever you prefer.
///
/// The `Rect`'s x and y will define the top-left corner of the screen,
/// and that plus its w and h will define the bottom-right corner.
pub fn set_screen_coordinates(context: &mut Context, rect: Rect) -> GameResult {
    context.gfx_context.set_screen_coordinates(rect);
    Ok(())
}

/// Returns a rectangle defining the coordinate system of the screen.
/// It will be `Rect { x: left, y: top, w: width, h: height }`
///
/// If the Y axis increases downwards, the `height` of the `Rect`
/// will be negative.
pub fn screen_coordinates(ctx: &Context) -> Rect {
    ctx.gfx_context.screen_rect
}

/// Sets the global blend mode. Note that whenever a `Drawable` has its own blend mode it will
/// prioritize it over the global one.
pub fn set_blend_mode(
    ctx: &mut Context,
    quad_ctx: &mut miniquad::graphics::GraphicsContext,
    mode: BlendMode,
) -> GameResult {
    let (color_blend, alpha_blend) = mode.into();
    quad_ctx.set_blend(Some(color_blend), Some(alpha_blend));
    ctx.gfx_context.set_blend_mode(mode);
    Ok(())
}

/// Gets the current global blend mode
pub fn blend_mode(ctx: &Context) -> &BlendMode {
    ctx.gfx_context.blend_mode()
}

/// Sets the default filter mode used to scale images.
///
/// This does not apply retroactively to already created images.
pub fn set_default_filter(ctx: &mut Context, mode: FilterMode) {
    ctx.gfx_context.default_filter = mode;
}

/// Get the default filter mode for new images.
pub fn default_filter(ctx: &Context) -> FilterMode {
    ctx.gfx_context.default_filter
}

/// makes this blend mode current
pub(crate) fn set_current_blend_mode(
    quad_ctx: &mut miniquad::graphics::GraphicsContext,
    blend_mode: BlendMode,
) {
    let (color_blend, alpha_blend) = blend_mode.into();
    quad_ctx.set_blend(Some(color_blend), Some(alpha_blend));
}

/// makes the global blend mode the current one
pub(crate) fn restore_blend_mode(
    ctx: &Context,
    quad_ctx: &mut miniquad::graphics::GraphicsContext,
) {
    set_current_blend_mode(quad_ctx, ctx.gfx_context.blend_mode)
}

/// Tells the graphics system to actually put everything on the screen.
/// Call this at the end of your [`EventHandler`](../event/trait.EventHandler.html)'s
/// [`draw()`](../event/trait.EventHandler.html#tymethod.draw) method.
///
/// Unsets any active canvas.
pub fn present(
    ctx: &mut Context,
    quad_ctx: &mut miniquad::graphics::GraphicsContext,
) -> GameResult<()> {
    crate::graphics::set_canvas(ctx, None);
    quad_ctx.commit_frame();
    Ok(())
}

/// Sets the window to fullscreen or back.
pub fn set_fullscreen(quad_ctx: &mut miniquad::graphics::GraphicsContext, fullscreen: bool) {
    quad_ctx.set_fullscreen(fullscreen);
}

/// Sets the window size (in physical pixels) / resolution to the specified width and height.
///
/// Note: Currently only available on Windows and currently buggy as well (sets window to a slightly wrong size).
pub fn set_drawable_size(
    quad_ctx: &mut miniquad::graphics::GraphicsContext,
    width: u32,
    height: u32,
) {
    quad_ctx.set_window_size(width, height);
}

/// Deletes all cached font data.
///
/// Suggest this only gets used if you're sure you actually need it.
pub fn clear_font_cache(ctx: &mut Context, quad_ctx: &mut miniquad::graphics::GraphicsContext) {
    use glyph_brush::GlyphBrushBuilder;
    use std::cell::RefCell;
    use std::rc::Rc;
    let font_vec =
        glyph_brush::ab_glyph::FontArc::try_from_slice(Font::default_font_bytes()).unwrap();
    let glyph_brush = GlyphBrushBuilder::using_font(font_vec).build();
    let (glyph_cache_width, glyph_cache_height) = glyph_brush.texture_dimensions();
    let initial_contents = vec![255; 4 * glyph_cache_width as usize * glyph_cache_height as usize];
    let glyph_cache = Image::from_rgba8(
        ctx,
        quad_ctx,
        glyph_cache_width.try_into().unwrap(),
        glyph_cache_height.try_into().unwrap(),
        &initial_contents,
    )
    .unwrap();
    let glyph_state = Rc::new(RefCell::new(spritebatch::SpriteBatch::new(
        glyph_cache.clone(),
    )));
    ctx.gfx_context.glyph_brush = Rc::new(RefCell::new(glyph_brush));
    ctx.gfx_context.glyph_cache = glyph_cache;
    ctx.gfx_context.glyph_state = glyph_state;
}

/// All types that can be drawn on the screen implement the `Drawable` trait.
pub trait Drawable {
    /// Draws the drawable onto the rendering target.
    ///
    /// ALSO TODO: Expand docs
    fn draw(
        &self,
        ctx: &mut Context,
        quad_ctx: &mut miniquad::graphics::GraphicsContext,
        param: DrawParam,
    ) -> GameResult;

    /// Sets the blend mode to be used when drawing this drawable.
    /// This overrides the general [`graphics::set_blend_mode()`](fn.set_blend_mode.html).
    /// If `None` is set, defers to the blend mode set by
    /// `graphics::set_blend_mode()`.
    fn set_blend_mode(&mut self, mode: Option<BlendMode>);

    /// Gets the blend mode to be used when drawing this drawable.
    fn blend_mode(&self) -> Option<BlendMode>;

    fn dimensions(&self, _: &mut Context) -> Option<Rect> {
        None
    }
}

/// Applies `DrawParam` to `Rect`.
pub fn transform_rect(rect: Rect, param: DrawParam) -> Rect {
    match param.trans {
        Transform::Values {
            scale,
            offset,
            dest,
            rotation,
        } => {
            // first apply the offset
            let mut r = Rect {
                w: rect.w,
                h: rect.h,
                x: rect.x - offset.x * rect.w,
                y: rect.y - offset.y * rect.h,
            };
            // apply the scale
            let real_scale = (param.src.w * scale.x, param.src.h * scale.y);
            r.w = real_scale.0 * rect.w;
            r.h = real_scale.1 * rect.h;
            r.x *= real_scale.0;
            r.y *= real_scale.1;
            // apply the rotation
            r.rotate(rotation);
            // apply the destination translation
            r.x += dest.x;
            r.y += dest.y;

            r
        }
        Transform::Matrix(_m) => todo!("Fix me"),
    }
}

#[cfg(test)]
mod tests {
    use crate::graphics::{transform_rect, DrawParam, Rect};
    use approx::assert_relative_eq;
    use std::f32::consts::PI;

    #[test]
    fn headless_test_transform_rect() {
        {
            let r = Rect {
                x: 0.0,
                y: 0.0,
                w: 1.0,
                h: 1.0,
            };
            let param = DrawParam::default();
            let real = transform_rect(r, param);
            let expected = r;
            assert_relative_eq!(real, expected);
        }
        {
            let r = Rect {
                x: -1.0,
                y: -1.0,
                w: 2.0,
                h: 1.0,
            };
            let param = DrawParam::new().scale([0.5, 0.5]);
            let real = transform_rect(r, param);
            let expected = Rect {
                x: -0.5,
                y: -0.5,
                w: 1.0,
                h: 0.5,
            };
            assert_relative_eq!(real, expected);
        }
        {
            let r = Rect {
                x: -1.0,
                y: -1.0,
                w: 1.0,
                h: 1.0,
            };
            let param = DrawParam::new().offset([0.5, 0.5]);
            let real = transform_rect(r, param);
            let expected = Rect {
                x: -1.5,
                y: -1.5,
                w: 1.0,
                h: 1.0,
            };
            assert_relative_eq!(real, expected);
        }
        {
            let r = Rect {
                x: 1.0,
                y: 0.0,
                w: 2.0,
                h: 1.0,
            };
            let param = DrawParam::new().rotation(PI * 0.5);
            let real = transform_rect(r, param);
            let expected = Rect {
                x: -1.0,
                y: 1.0,
                w: 1.0,
                h: 2.0,
            };
            assert_relative_eq!(real, expected);
        }
        {
            let r = Rect {
                x: -1.0,
                y: -1.0,
                w: 2.0,
                h: 1.0,
            };
            let param = DrawParam::new()
                .scale([0.5, 0.5])
                .offset([0.0, 1.0])
                .rotation(PI * 0.5);
            let real = transform_rect(r, param);
            let expected = Rect {
                x: 0.5,
                y: -0.5,
                w: 0.5,
                h: 1.0,
            };
            assert_relative_eq!(real, expected);
        }
        {
            let r = Rect {
                x: -1.0,
                y: -1.0,
                w: 2.0,
                h: 1.0,
            };
            let param = DrawParam::new()
                .scale([0.5, 0.5])
                .offset([0.0, 1.0])
                .rotation(PI * 0.5)
                .dest([1.0, 0.0]);
            let real = transform_rect(r, param);
            let expected = Rect {
                x: 1.5,
                y: -0.5,
                w: 0.5,
                h: 1.0,
            };
            assert_relative_eq!(real, expected);
        }
        {
            let r = Rect {
                x: 0.0,
                y: 0.0,
                w: 1.0,
                h: 1.0,
            };
            let param = DrawParam::new()
                .offset([0.5, 0.5])
                .rotation(PI * 1.5)
                .dest([1.0, 0.5]);
            let real = transform_rect(r, param);
            let expected = Rect {
                x: 0.5,
                y: 0.0,
                w: 1.0,
                h: 1.0,
            };
            assert_relative_eq!(real, expected);
        }
        {
            let r = Rect {
                x: 0.0,
                y: 0.0,
                w: 1.0,
                h: 1.0,
            };
            let param = DrawParam::new()
                .offset([0.5, 0.5])
                .rotation(PI * 0.25)
                .scale([2.0, 1.0])
                .dest([1.0, 2.0]);
            let real = transform_rect(r, param);
            let sqrt = (2f32).sqrt() / 2.;
            let unit = sqrt + sqrt / 2.;
            let expected = Rect {
                x: -unit + 1.,
                y: -unit + 2.,
                w: 2. * unit,
                h: 2. * unit,
            };
            assert_relative_eq!(real, expected);
        }
    }
}