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
extern crate fnv;
extern crate miniquad;
pub extern crate rgb;

use std::time::{Duration, Instant};

use fnv::FnvHashSet;

use miniquad::conf::Conf;
use miniquad::*;
pub use miniquad::conf::Icon;
pub use miniquad::{KeyCode, KeyMods, MouseButton, FilterMode};

use rgb::{ComponentBytes, RGBA8};

#[derive(Debug)]
pub struct Config {
    pub window_title: String,
    pub window_width: u32,
    pub window_height: u32,
    pub fullscreen: bool,
    pub icon: Option<Icon>,
}

#[repr(C)]
struct Vec2 {
    x: f32,
    y: f32,
}

#[repr(C)]
struct Vertex {
    pos: Vec2,
    uv: Vec2,
}

const SHADER_VERT: &str = r#"#version 100
attribute vec2 pos;
attribute vec2 uv;

varying lowp vec2 texcoord;

void main() {
    gl_Position = vec4(pos.x, pos.y, 0.0, 1.0);
    texcoord = uv;
}"#;

const SHADER_FRAG: &str = r#"#version 100
varying lowp vec2 texcoord;

uniform sampler2D tex;

void main() {
    gl_FragColor = texture2D(tex, texcoord);
}"#;

#[derive(Debug)]
struct Window {
    width: u32,
    height: u32,

    pipeline: Pipeline,
    bindings: Bindings,

    instant: Instant,
    delta_time: Duration,

    clear_color: RGBA8,
    buffer: Vec<RGBA8>,

    key_codes: FnvHashSet<KeyCode>,
    key_mods: KeyMods,
    key_repeated: bool,

    mouse_pos: (f32, f32),
    mouse_buttons: FnvHashSet<MouseButton>,
}

impl Window {
    fn init(ctx: &mut GraphicsContext, width: u32, height: u32) -> Self {
        let vertices: [Vertex; 4] = [
            Vertex { pos: Vec2 { x: -1., y: -1. }, uv: Vec2 { x: 0., y: 1. } },
            Vertex { pos: Vec2 { x:  1., y: -1. }, uv: Vec2 { x: 1., y: 1. } },
            Vertex { pos: Vec2 { x:  1., y:  1. }, uv: Vec2 { x: 1., y: 0. } },
            Vertex { pos: Vec2 { x: -1., y:  1. }, uv: Vec2 { x: 0., y: 0. } },
        ];
        let vertex_buffer = Buffer::immutable(ctx, BufferType::VertexBuffer, &vertices);

        let indices: [u16; 6] = [0, 1, 2, 0, 2, 3];
        let index_buffer = Buffer::immutable(ctx, BufferType::IndexBuffer, &indices);

        let texture = Texture::new_render_texture(ctx, TextureParams {
            format: TextureFormat::RGBA8,
            wrap: TextureWrap::Clamp,
            filter: FilterMode::Nearest,
            width,
            height,
        });

        let bindings = Bindings {
            vertex_buffers: vec![vertex_buffer],
            index_buffer,
            images: vec![texture],
        };

        let shader_meta = ShaderMeta {
            images: vec!["tex".to_string()],
            uniforms: UniformBlockLayout {
                uniforms: vec![],
            },
        };

        let shader = Shader::new(ctx, SHADER_VERT, SHADER_FRAG, shader_meta).unwrap_or_else(|err| panic!("{}", err));

        let pipeline = Pipeline::new(
            ctx,
            &[BufferLayout::default()],
            &[
                VertexAttribute::new("pos", VertexFormat::Float2),
                VertexAttribute::new("uv", VertexFormat::Float2),
            ],
            shader
        );

        let black = RGBA8 { r: 0, g: 0, b: 0, a: 255 };

        Self {
            width,
            height,

            pipeline,
            bindings,

            instant: Instant::now(),
            delta_time: Duration::ZERO,

            clear_color: black,
            buffer: vec![black; (width * height) as usize],

            key_codes: FnvHashSet::default(),
            key_mods: KeyMods {
                shift: false,
                ctrl: false,
                alt: false,
                logo: false
            },
            key_repeated: false,

            mouse_pos: (0., 0.),
            mouse_buttons: FnvHashSet::default(),
        }
    }
}

pub struct Context<'a> {
    win: &'a mut Window,
    ctx: &'a mut GraphicsContext,
}

impl<'a> Context<'a> {
    #[inline]
    pub fn width(&self) -> u32 {
        self.win.width
    }

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

    #[inline]
    pub fn delta_time(&self) -> Duration {
        self.win.delta_time
    }

    #[inline]
    pub fn clear_color(&mut self, color: RGBA8) {
        self.win.clear_color = color;
    }

    #[inline]
    pub fn is_key_down(&self, key: KeyCode) -> bool {
        self.win.key_codes.contains(&key)
    }

    #[inline]
    pub fn get_key_mods(&self) -> KeyMods {
        self.win.key_mods
    }

    #[inline]
    pub fn is_key_repeated(&self) -> bool {
        self.win.key_repeated
    }

    #[inline]
    pub fn get_mouse_pos(&self) -> (f32, f32) {
        self.win.mouse_pos
    }

    #[inline]
    pub fn get_mouse_pos_int(&self) -> (i32, i32) {
        let (x, y) = self.win.mouse_pos;
        
        (x.round() as i32, y.round() as i32)
    }

    #[inline]
    pub fn is_mouse_button_down(&self, button: MouseButton) -> bool {
        self.win.mouse_buttons.contains(&button)
    }

    #[inline]
    pub fn quit(&mut self) {
        self.ctx.quit();
    }
    
    #[inline]
    pub fn show_mouse(&mut self, shown: bool) {
        self.ctx.show_mouse(shown);
    }
    
    #[inline]
    pub fn set_fullscreen(&mut self, fullscreen: bool) {
        self.ctx.set_fullscreen(fullscreen);
    }
    
    #[inline]
    pub fn get_clipboard(&mut self) -> Option<String> {
        self.ctx.clipboard_get()
    }
    
    #[inline]
    pub fn set_clipboard(&mut self, data: &str) {
        self.ctx.clipboard_set(data);
    }

    pub fn clear(&mut self) {
        for pix in self.win.buffer.iter_mut() {
            *pix = self.win.clear_color;
        }
    }

    #[inline]
    pub fn draw_pixel(&mut self, x: i32, y: i32, color: RGBA8) {
        self.win.buffer[y as usize * self.win.width as usize + x as usize] = color;
    }

    pub fn draw_rect(&mut self, x: i32, y: i32, width: u32, height: u32, color: RGBA8) {
        for y in (y as usize)..(y as usize + height as usize) {
            for x in (x as usize)..(x as usize + width as usize) {
                self.win.buffer[y * self.win.width as usize + x] = color;
            }
        }
    }
    
    pub fn draw_pixels(&mut self, x: i32, y: i32, width: u32, height: u32, pixels: &[RGBA8]) {
        for iy in 0..(height as usize) {
            for ix in 0..(width as usize) {
                self.win.buffer[(iy + y as usize) * self.win.width as usize + ix + x as usize] = pixels[iy * width as usize + ix];
            }
        }
    }

    #[inline]
    pub fn draw_screen(&mut self, pixels: &[RGBA8]) {
        self.win.buffer.copy_from_slice(pixels);
    }

    #[inline]
    pub fn get_draw_buffer(&self) -> &[RGBA8] {
        &self.win.buffer
    }

    #[inline]
    pub fn get_mut_draw_buffer(&mut self) -> &mut [RGBA8] {
        &mut self.win.buffer
    }

    pub fn set_filter_mode(&mut self, filter: FilterMode) {
        let texture = &self.win.bindings.images[0];
        texture.set_filter(self.ctx, filter);
    }
}

pub trait State: 'static {
    fn update(&mut self, ctx: &mut Context);
    fn draw(&mut self, ctx: &mut Context);
}

struct Handler {
    win: Window,
    state: Box<dyn State>,
}

impl EventHandler for Handler {
    fn update(&mut self, ctx: &mut GraphicsContext) {
        self.win.delta_time = self.win.instant.elapsed();
        self.win.instant = Instant::now();

        let mut context = Context {
            win: &mut self.win,
            ctx,
        };

        self.state.update(&mut context);
    }

    fn draw(&mut self, ctx: &mut GraphicsContext) {
        let mut context = Context {
            win: &mut self.win,
            ctx,
        };

        self.state.draw(&mut context);
        
        let texture = &self.win.bindings.images[0];
        texture.update(ctx, self.win.buffer.as_bytes());

        ctx.begin_default_pass(PassAction::Nothing);

        ctx.apply_pipeline(&self.win.pipeline);
        ctx.apply_bindings(&self.win.bindings);

        ctx.draw(0, 6, 1);

        ctx.end_render_pass();
        ctx.commit_frame();
    }

    fn key_down_event(
        &mut self,
        _ctx: &mut GraphicsContext,
        key_code: KeyCode,
        key_mods: KeyMods,
        repeat: bool,
    ) {
        self.win.key_codes.insert(key_code);
        self.win.key_mods = key_mods;
        self.win.key_repeated = repeat;
    }

    fn key_up_event(
        &mut self,
        _ctx: &mut GraphicsContext,
        key_code: KeyCode,
        key_mods: KeyMods,
    ) {
        self.win.key_codes.remove(&key_code);
        self.win.key_mods = key_mods;
    }

    fn mouse_motion_event(&mut self, _ctx: &mut GraphicsContext, x: f32, y: f32) {
        self.win.mouse_pos = (x, y);
    }

    fn mouse_button_down_event(
        &mut self,
        _ctx: &mut GraphicsContext,
        button: MouseButton,
        _x: f32,
        _y: f32,
    ) {
        self.win.mouse_buttons.insert(button);
    }

    fn mouse_button_up_event(
        &mut self,
        _ctx: &mut GraphicsContext,
        button: MouseButton,
        _x: f32,
        _y: f32,
    ) {
        self.win.mouse_buttons.remove(&button);
    }
}

pub fn start(config: Config, state: impl State) {
    let conf = Conf {
        window_title: config.window_title,
        window_width: config.window_width as i32,
        window_height: config.window_height as i32,
        fullscreen: config.fullscreen,
        window_resizable: false,
        icon: config.icon,
        ..Default::default()
    };

    miniquad::start(conf, move |ctx| Box::new(
        Handler {
            win: Window::init(ctx, config.window_width, config.window_height),
            state: Box::new(state),
        }
    ));
}