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
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
use std::collections::{HashMap, VecDeque};
use std::rc::Rc;
use std::cell::{RefCell, RefMut};

use glutin;
use vecmath;
use glium;
use poison_pool;
use super::constants as lux_constants;

use super::interactive::keycodes::VirtualKeyCode;
use super::accessors::{
    HasDrawCache,
    HasPrograms,
    HasDisplay,
    HasFontCache,
    HasSurface,
    DrawParamMod,
    Fetch,
};

use super::interactive::{EventIterator, AbstractKey, Event, Interactive};
use super::font::{FontCache, TextLoad};
use ::font::read_atlas;
use super::gfx_integration::{ColorVertex, TexVertex};
use super::canvas::Canvas;
use super::color::Color;
use super::raw::{Colored, Transform};
use super::error::{LuxResult, LuxError};
use super::shaders::{gen_texture_shader, gen_color_shader};
use super::primitive_canvas::{
    PrimitiveCanvas,
    CachedColorDraw,
    CachedTexDraw,
    DrawParamModifier
};
use super::types::{Float, Idx};

use glutin::WindowBuilder;

type Mat4f = [[f32; 4]; 4];
type BaseColor = [f32; 4];

/// A 1 to 1 correlation with a window shown on your desktop.
///
/// Lux uses Glutin for the window implementation.
pub struct Window {
    // CANVAS
    display: glium::Display,
    color_program: Rc<glium::Program>,
    tex_program: Rc<glium::Program>,
    closed: bool,

    // WINDOW
    title: String,

    // CACHES
    idx_cache: poison_pool::PoisonPool<Vec<Idx>>,
    tex_vtx_cache: poison_pool::PoisonPool<Vec<TexVertex>>,
    color_vtx_cache: poison_pool::PoisonPool<Vec<ColorVertex>>,

    // EVENT
    event_store: VecDeque<Event>,
    mouse_pos: (i32, i32),
    window_pos: (i32, i32),
    window_size: (u32, u32),
    focused: bool,
    mouse_down_count: u8,
    events_since_last_render: bool,

    // KEY EVENTS
    codes_pressed: HashMap<u8, bool>,
    chars_pressed: HashMap<char, bool>,
    virtual_keys_pressed: HashMap<VirtualKeyCode, bool>,
    code_to_char: HashMap<usize, char>,

    // FONT
    font_cache: Rc<RefCell<FontCache>>,
}

/// A frame is a render target that can be drawn on.
///
/// Because frame rendering will wait on vsync, you should - as the name
/// implies - use one Frame instance per frame.
pub struct Frame {
    display: glium::Display,
    f: glium::Frame,
    color_program: Rc<glium::Program>,
    tex_program: Rc<glium::Program>,

    // Primitive Canvas
    color_draw_cache: Option<CachedColorDraw>,
    tex_draw_cache: Option<CachedTexDraw>,

    // CACHES
    idx_cache: poison_pool::PoisonPool<Vec<Idx>>,
    tex_vtx_cache: poison_pool::PoisonPool<Vec<TexVertex>>,
    color_vtx_cache: poison_pool::PoisonPool<Vec<ColorVertex>>,

    // Raw
    basis_matrix: Mat4f,
    color: [f32; 4],

    // Misc
    font_cache: Rc<RefCell<FontCache>>,
    draw_mod: DrawParamModifier,
}


impl Frame {
    fn new(display: &glium::Display,
           color_program: Rc<glium::Program>,
           tex_program: Rc<glium::Program>,
           idx_cache: poison_pool::PoisonPool<Vec<Idx>>,
           tex_vtx_cache: poison_pool::PoisonPool<Vec<TexVertex>>,
           color_vtx_cache: poison_pool::PoisonPool<Vec<ColorVertex>>,
           clear_color: Option<[f32; 4]>,
           font_cache: Rc<RefCell<FontCache>>) -> Frame {
        use glium::Surface;

        let mut frm = display.draw();
        if let Some(c) = clear_color {
            frm.clear_color(c[0],c[1],c[2],c[3]);
        }
        frm.clear_stencil(0);

        let size = frm.get_dimensions();
        let (w, h) = (size.0 as f32, size.1 as f32);
        let (sx, sy) = (2.0 / w, -2.0 / h);

        let mut basis = vecmath::mat4_id();
        basis[1][1] = -1.0;
        basis[3][0] = -1.0;
        basis[3][1] = 1.0;
        basis[0][0] = sx;
        basis[1][1] = sy;

        Frame {
            display: display.clone(),
            color_program: color_program,
            tex_program: tex_program,
            idx_cache: idx_cache,
            tex_vtx_cache: tex_vtx_cache,
            color_vtx_cache: color_vtx_cache,
            f: frm,
            color_draw_cache: None,
            tex_draw_cache: None,
            basis_matrix: basis,
            color: [0.0, 0.0, 0.0, 1.0],
            font_cache: font_cache,
            draw_mod: DrawParamModifier::new()
        }
    }
}

impl Drop for Frame {
    fn drop(&mut self) {
        self.flush_draw().unwrap();
        self.f.set_finish().unwrap();
    }
}

impl Window {
    /// Panics if an OpenGL error has occurred.
    pub fn assert_no_error(&self)  {
        self.display.assert_no_error(None);
    }

    /// Constructs a new window with the default settings.
    pub fn new() -> LuxResult<Window> {
        use glium::DisplayBuild;
        use std::io::Cursor;

        let window_builder =
            WindowBuilder::new()
            .with_title("Lux".to_string())
            .with_dimensions(600, 500)
            .with_vsync()
            .with_gl_debug_flag(false)
            .with_multisampling(8)
            .with_visibility(true);


        let display = try!(window_builder.build_glium().map_err(|e| {
            match e {
                glium::GliumCreationError::BackendCreationError(
                    glutin::CreationError::OsError(s)) =>
                        LuxError::WindowError(s),
                glium::GliumCreationError::BackendCreationError(
                    glutin::CreationError::NotSupported)  =>
                        LuxError::WindowError("Window creation is not supported.".to_string()),
                glium::GliumCreationError::IncompatibleOpenGl(m) =>
                    LuxError::OpenGlError(m)
            }
        }));

        let color_program = try!(gen_color_shader(&display));
        let tex_program = try!(gen_texture_shader(&display));

        let (width, height): (u32, u32) = display.get_framebuffer_dimensions();

        let font_cache = try!(FontCache::new());

        let mut window = Window {
            display: display,
            color_program: Rc::new(color_program),
            tex_program: Rc::new(tex_program),
            closed: false,
            title: "Lux".to_string(),
            idx_cache: poison_pool::PoisonPool::new(4, || vec![]),
            tex_vtx_cache: poison_pool::PoisonPool::new(4, || vec![]),
            color_vtx_cache: poison_pool::PoisonPool::new(4, || vec![]),
            event_store: VecDeque::new(),
            mouse_pos: (0, 0),
            window_pos: (0, 0),
            window_size: (width, height),
            focused: true,
            mouse_down_count: 0,
            events_since_last_render: false,
            codes_pressed: HashMap::new(),
            chars_pressed: HashMap::new(),
            virtual_keys_pressed: HashMap::new(),
            code_to_char: HashMap::new(),
            font_cache: Rc::new(RefCell::new(font_cache))
        };

        let loaded_12 = try!(read_atlas(&mut Cursor::new(lux_constants::SCP_12_PNG),
                                        &mut Cursor::new(lux_constants::SCP_12_BINCODE)));
        let loaded_20 = try!(read_atlas(&mut Cursor::new(lux_constants::SCP_20_PNG),
                                        &mut Cursor::new(lux_constants::SCP_20_BINCODE)));
        let loaded_30 = try!(read_atlas(&mut Cursor::new(lux_constants::SCP_30_PNG),
                                        &mut Cursor::new(lux_constants::SCP_30_BINCODE)));
        try!(window.cache("SourceCodePro", 12, loaded_12));
        try!(window.cache("SourceCodePro", 20, loaded_20));
        try!(window.cache("SourceCodePro", 30, loaded_30));


        Ok(window)
    }

    /// Add the events from an iterator of events back to the internal event queue.
    pub fn restock_events<I: DoubleEndedIterator<Item=Event>>(&mut self, mut i: I) {
        while let Some(e) = i.next_back() {
            self.event_store.push_front(e);
        }
    }

    /// Query the underlying window system for events and add them to the
    /// the interal event queue.
    ///
    /// This function is automatically called by `is_open()`, `events()`.
    pub fn process_events(&mut self) {
        use glutin::Event as glevent;
        use super::interactive::*;
        use super::interactive::Event::*;
        use super::interactive::MouseButton::*;

        self.events_since_last_render = true;
        fn t_mouse(button: glutin::MouseButton) -> MouseButton {
            match button {
                glutin::MouseButton::Left=> Left,
                glutin::MouseButton::Right=> Right,
                glutin::MouseButton::Middle=> Middle,
                glutin::MouseButton::Other(a) => Other(a)
            }
        }

        let mut last_char = None;
        for event in self.display.poll_events() {
            match event {
            glevent::MouseMoved((x, y)) => {
                self.mouse_pos = (x as i32, y as i32);
                self.event_store.push_back(MouseMoved((x as i32, y as i32)))
            }
            glevent::MouseInput(glutin::ElementState::Pressed, button) => {
                self.event_store.push_back(MouseDown(t_mouse(button)));
                self.mouse_down_count += 1;
            }
            glevent::MouseInput(glutin::ElementState::Released, button) => {
                self.event_store.push_back(MouseUp(t_mouse(button)));

                // Don't underflow!
                if self.mouse_down_count != 0 {
                    self.mouse_down_count -= 1;
                }
            }
            glevent::Resized(w, h) => {
                self.window_size = (w as u32, h as u32);
                self.event_store.push_back(WindowResized(self.window_size));
            }
            glevent::Moved(x, y) => {
                self.window_pos = (x as i32, y as i32);
                self.event_store.push_back(WindowMoved(self.window_pos));
            }
            glevent::MouseWheel(wheel_delta) => {
                // TODO: remove this when this code breaks.
                let wheel_delta = match wheel_delta {
                    glutin::MouseScrollDelta::LineDelta(x, y) => MouseScrollDelta::LineDelta(x, y),
                    glutin::MouseScrollDelta::PixelDelta(x, y) => MouseScrollDelta::PixelDelta(x, y)
                };
                self.event_store.push_back(MouseWheel(wheel_delta));
            }
            glevent::ReceivedCharacter(c) => {
                last_char = Some(c);
            }
            glevent::KeyboardInput(glutin::ElementState::Pressed, code, virt)  => {
                let c = virt.and_then(keycode_to_char)
                            .or(last_char.take())
                            .or_else(|| self.code_to_char.get(&(code as usize))
                                                         .map(|a| *a));
                self.event_store.push_back(KeyPressed(code, c, virt));

                if c.is_some() && !self.code_to_char.contains_key(&(code as usize)) {
                    self.code_to_char.insert(code as usize, c.unwrap());
                }

                self.codes_pressed.insert(code, true);
                if let Some(chr) = c {
                    self.chars_pressed.insert(chr, true);
                }
                if let Some(v_key) = virt {
                    self.virtual_keys_pressed.insert(v_key, true);
                }
            }
            glevent::KeyboardInput(glutin::ElementState::Released, code, virt) => {
                let c = virt.and_then(keycode_to_char)
                            .or_else(|| self.code_to_char.get(&(code as usize))
                                                         .map(|a| *a));
                self.event_store.push_back(KeyReleased(code, c, virt));
                self.codes_pressed.insert(code, false);
                if let Some(chr) = c {
                    self.chars_pressed.insert(chr, false);
                }
                if let Some(v_key) = virt {
                    self.virtual_keys_pressed.insert(v_key, false);
                }
            }
            glevent::Focused(f) => {
                self.focused = f;
            }
            glevent::Closed => {
                self.closed = true;
            }
            glevent::DroppedFile(buf) => {
                self.event_store.push_back(FileDropped(buf))
            }
            glevent::Awakened => {
                // TODO: handle this
            }
            glevent::Refresh => {
                // TODO: handle this
            }
            glevent::Suspended(_) => {

            }
            glevent::Touch(_) => {
                // TODO: -- high priority -- handle this.
            }
        }}
    }

    /// Produce a frame that has been cleared with a color.
    pub fn cleared_frame<C: Color>(&mut self, clear_color: C) -> Frame {
        Frame::new(&self.display,
                   self.color_program.clone(),
                   self.tex_program.clone(),
                   self.idx_cache.clone(),
                   self.tex_vtx_cache.clone(),
                   self.color_vtx_cache.clone(),
                   Some(clear_color.to_rgba()),
                   self.font_cache.clone())
    }

    /// Produce a frame that has not been cleared.
    pub fn frame(&mut self) -> Frame {
        Frame::new(&self.display,
                   self.color_program.clone(),
                   self.tex_program.clone(),
                   self.idx_cache.clone(),
                   self.tex_vtx_cache.clone(),
                   self.color_vtx_cache.clone(),
                   None,
                   self.font_cache.clone())
    }
}

#[allow(unused_variables)]
impl Canvas for Frame {
    fn size(&self) -> (f32, f32) {
        use glium::Surface;
        let (w, h) = self.f.get_dimensions();
        (w as f32, h as f32)
    }
}

impl Interactive for Window {
    fn is_open(&mut self) -> bool {
        self.process_events();
        !self.closed
    }

    fn was_open(&self) -> bool {
        !self.closed
    }

    fn title(&self) -> &str {
        &self.title[..]
    }

    fn set_title(&mut self, _title: &str) {
        // TODO: implement this somehow.  Is it possible yet?
        unimplemented!();
    }

    fn set_size(&mut self, _width: u32, _height: u32) {
        unimplemented!();
    }

    fn get_size_u(&self) -> (u32, u32) {
        self.window_size
    }

    fn get_size(&self) -> (Float, Float) {
        let (x, y) = self.get_size_u();
        (x as Float, y as Float)
    }

    fn is_focused(&self) -> bool {
        self.focused
    }

    fn mouse_pos_i(&self) -> (i32, i32) {
        self.mouse_pos
    }

    fn mouse_pos(&self) -> (f32, f32) {
        (self.mouse_pos.0 as f32, self.mouse_pos.1 as f32)
    }

    fn is_mouse_down(&self) -> bool {
        self.mouse_down_count != 0
    }

    fn events(&mut self) -> EventIterator {
        use std::mem::replace;
        self.process_events();
        EventIterator::from_deque(replace(&mut self.event_store, VecDeque::new()))
    }

    fn is_key_pressed<K: AbstractKey>(&self, k: K) -> bool {
        match k.to_key() {
            (Some(code), _, _) => self.codes_pressed.get(&code).cloned(),
            (_, Some(chr), _) => self.chars_pressed.get(&chr).cloned(),
            (_, _, Some(key)) => self.virtual_keys_pressed.get(&key).cloned(),
            (None, None, None) => None
        }.unwrap_or(false)
    }
}

impl Transform for Frame {
    fn current_matrix_mut(&mut self) -> &mut [[f32; 4]; 4] {
        &mut self.basis_matrix
    }

    fn current_matrix(&self) -> &[[f32; 4]; 4] {
        &self.basis_matrix
    }
}

impl Colored for Frame {
    fn get_color(&self) -> [f32; 4] {
        self.color
    }

    fn color<C: Color>(&mut self, color: C) -> &mut Frame {
        self.color = color.to_rgba();
        self
    }
}

impl HasDisplay for Window {
    fn borrow_display(&self) -> &glium::Display {
        &self.display
    }
}

impl HasFontCache for Window {
    fn font_cache(&self) -> RefMut<FontCache> {
        self.font_cache.borrow_mut()
    }
}

impl HasDisplay for Frame {
    fn borrow_display(&self) -> &glium::Display {
        &self.display
    }
}

impl HasFontCache for Frame {
    fn font_cache(&self) -> RefMut<FontCache> {
        self.font_cache.borrow_mut()
    }
}

impl HasSurface for Frame {
    type Out = glium::Frame;

    fn surface(&mut self) -> &mut Self::Out {
        &mut self.f
    }

    fn surface_and_texture_shader(&mut self) -> (&mut Self::Out, &glium::Program) {
        (&mut self.f, &*self.tex_program)
    }

    fn surface_and_color_shader(&mut self) -> (&mut Self::Out, &glium::Program) {
        (&mut self.f, &*self.color_program)
    }
}

impl HasDrawCache for Frame {
    fn color_draw_cache(&self) -> &Option<CachedColorDraw> {
        &self.color_draw_cache
    }
    fn tex_draw_cache(&self) -> &Option<CachedTexDraw> {
        &self.tex_draw_cache
    }

    fn color_draw_cache_mut(&mut self) -> &mut Option<CachedColorDraw> {
        &mut self.color_draw_cache
    }
    fn tex_draw_cache_mut(&mut self) -> &mut Option<CachedTexDraw> {
        &mut self.tex_draw_cache
    }
}

impl HasPrograms for Window {
    fn texture_shader(&self) -> &glium::Program {
        &*self.tex_program
    }

    fn color_shader(&self) -> &glium::Program {
        &*self.color_program
    }
}

impl HasPrograms for Frame {
    fn texture_shader(&self) -> &glium::Program {
        &*self.tex_program
    }

    fn color_shader(&self) -> &glium::Program {
        &*self.color_program
    }
}

impl Fetch<Vec<Idx>> for Frame {
    fn fetch(&self) -> poison_pool::Item<Vec<Idx>> {
        let mut ret = self.idx_cache.get_or_else(|| vec![]);
        ret.clear();
        ret
    }
}

impl Fetch<Vec<TexVertex>> for Frame {
    fn fetch(&self) -> poison_pool::Item<Vec<TexVertex>> {
        let mut ret = self.tex_vtx_cache.get_or_else(|| vec![]);
        ret.clear();
        ret
    }
}

impl Fetch<Vec<ColorVertex>> for Frame {
    fn fetch(&self) -> poison_pool::Item<Vec<ColorVertex>> {
        let mut ret = self.color_vtx_cache.get_or_else(|| vec![]);
        ret.clear();
        ret
    }
}

impl DrawParamMod for Frame {
    fn draw_param_mod(&self) -> &DrawParamModifier {
        &self.draw_mod
    }
    fn draw_param_mod_mut(&mut self) -> &mut DrawParamModifier {
        &mut self.draw_mod
    }
}