fluffl 0.0.5

A cross-platform multimedia layer that exposes opengl,sockets,and audio utilities for desktop and browser
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
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
use super::{
    event_util::{constants::*, FlufflEvent},
    *,
};
use crate::FlufflState;

use glow::*;

use std::{cell::RefCell, mem, rc::Rc, sync::Arc};

use be_sdl2::{event::Event, keyboard::Scancode, mouse::MouseButton, video::FullscreenType};

///Global for touch tracker
static mut GLOBAL_TOUCH_TRACKER: Option<TouchTracker<i32>> = None;

impl TouchTracker<i32> {
    /// # Description
    /// Initalizes tracker. Tracker routines will panic if this function isn't called.
    pub fn init() {
        unsafe {
            GLOBAL_TOUCH_TRACKER = Some(TouchTracker::new());
        }
    }
    pub fn get_mut() -> &'static mut Self {
        unsafe {
            GLOBAL_TOUCH_TRACKER
                .as_mut()
                .expect("tracker not initalized")
        }
    }
}

/// # Description
/// A Custom SDL2 Window pointer type. This is needed because `RenderLoop<T>` takes the window provided by the
/// sdl2 wrapper and never gives it back.
struct CustomSDL2Window {
    #[allow(dead_code)]
    context: Rc<be_sdl2::video::WindowContext>,
}

impl CustomSDL2Window {
    fn new(context: Rc<be_sdl2::video::WindowContext>) -> Self {
        Self { context }
    }

    fn as_sdl2_window_mut(&mut self) -> &mut be_sdl2::video::Window {
        let mut_ref: &mut Self = self;
        unsafe { mem::transmute(mut_ref) }
    }
}

/// a very simple macro to shorten up text a little bit
macro_rules! push_event {
    ( $event_pump:ident , $event:expr  ) => {
        $event_pump.as_mut().unwrap().push_event($event)
    };
}

#[allow(dead_code)]
/// A cross-platform window handler, use it to set up opengl and listen to input devices in a platform
/// agnostic fashion
pub struct FlufflWindow {
    glue_event: Option<FlufflEvent>,
    sdl_state: be_sdl2::Sdl,
    sdl_gl_context: be_sdl2::video::GLContext,
    sdl_event_pump: be_sdl2::EventPump,
    gl: GlowGL,
    render_loop: Option<RenderLoop<be_sdl2::video::Window>>,
    audio_context: FlufflAudioContext,
    video_ss: be_sdl2::VideoSubsystem,
    window_width: u32,
    window_height: u32,
    window_pointer: CustomSDL2Window,
}

impl FlufflWindow {
    //moves renderloop out of glue_window and calls it
    fn get_render_loop(&mut self) -> impl glow::HasRenderLoop {
        self.render_loop.take().unwrap()
    }

    /// Loops infinitely unless caller mutates `running` to false. Just executes the user defined taske over and over while also \
    /// doing basic matenence for events and the window
    /// # Arguments
    /// * `fluffl_window` an initalized fluffl window
    /// * `app_state` is the variables and memory that is needed throughout the entire lifespan of the program
    /// * `core_loop` is the user-defined 'main_loop'
    pub fn run<Loop, LoopOut, State>(self, app_state: State, core_loop: Loop)
    where
        Loop: Fn(FlufflWindowPtr, FlufflRunning, FlufflState<State>) -> LoopOut + Copy + 'static,
        LoopOut: std::future::Future<Output = ()>,
        State: 'static,
    {
        let mut fluffl_window = self;
        let render_loop = fluffl_window.get_render_loop();

        let window_ptr = FlufflWindowPtr {
            ptr: Arc::new(RefCell::new(fluffl_window)),
        };

        let state_ptr = FlufflState::new(app_state);

        render_loop.run(move |running| {
            window_ptr.window_mut().collect_events();

            let unexecuted_iteration = core_loop(
                window_ptr.clone(),
                FlufflRunning::new(running),
                state_ptr.clone(),
            );

            //execute future
            futures::executor::block_on(unexecuted_iteration);
        });
    }
}

impl HasFlufflWindow for FlufflWindow {
    fn width(&self) -> u32 {
        self.window_width
    }

    fn height(&self) -> u32 {
        self.window_height
    }

    fn audio_context(&self) -> FlufflAudioContext {
        self.audio_context.clone()
    }

    fn gl(&self) -> Arc<Box<Context>> {
        self.gl.clone()
    }

    fn get_events(&mut self) -> &mut FlufflEvent {
        self.glue_event.as_mut().unwrap()
    }

    fn init(config: &str) -> Result<Self, FlufflError> {
        let settings = FlufflWindowConfigs::new().parser_config_file(config);

        // Create a context from a sdl2 window
        let sdl = be_sdl2::init()?;
        let audio = sdl.audio()?;
        let video = sdl.video()?;

        let gl_attr = video.gl_attr();

        gl_attr.set_context_profile(be_sdl2::video::GLProfile::Core);
        gl_attr.set_context_version(settings.context_major, settings.context_minor);
        //set stencil buffer
        video.gl_attr().set_stencil_size(8);

        let win_builder = video.window(settings.title.as_str(), settings.width, settings.height);

        let build_window_according_to_settings = |mut builder: be_sdl2::video::WindowBuilder| {
            let mut builder_ref = builder.opengl();
            if settings.resizable {
                builder_ref = builder.resizable();
            }
            if !settings.resizable && settings.fullscreen {
                builder_ref = builder.fullscreen();
            }

            builder_ref.build()
        };

        let window = build_window_according_to_settings(win_builder)?;

        // because be_sdl2::video::Window is a glorified smart pointer I can do this:
        let window_context_ref =
            unsafe { mem::transmute::<_, &Rc<be_sdl2::video::WindowContext>>(&window) };

        let gl_context = window.gl_create_context()?;

        let context = unsafe {
            glow::Context::from_loader_function(|s| video.gl_get_proc_address(s) as *const _)
        };

        let render_loop = Some(glow::RenderLoop::<be_sdl2::video::Window>::from_sdl_window(
            window,
        ));
        let event_loop = sdl.event_pump()?;

        TouchTracker::init();

        // disable vsync
        // video.gl_set_swap_interval(0).expect("failed to disable vsync:");

        let fluffl_window = Self {
            sdl_gl_context: gl_context,
            sdl_event_pump: event_loop,
            glue_event: Some(FlufflEvent::new()),
            gl: Arc::new(Box::new(context)),
            render_loop,
            window_width: settings.width,
            window_height: settings.height,
            sdl_state: sdl,
            audio_context: FlufflAudioContext {
                audio_ss: Arc::new(RefCell::new(audio)),
            },
            video_ss: video,
            window_pointer: CustomSDL2Window::new(window_context_ref.clone()),
        };

        Ok(fluffl_window)
    }

    fn set_fullscreen(&mut self, go_fullscreen: bool) {
        let window = self.window_pointer.as_sdl2_window_mut();
        if go_fullscreen {
            if let Err(msg) = window.set_fullscreen(FullscreenType::True) {
                panic!("Error:{}", msg)
            }
        } else if let Err(msg) = window.set_fullscreen(FullscreenType::Off) {
            panic!("Error:{}", msg)
        }
    }
}

impl From<String> for FlufflError {
    fn from(string: String) -> Self {
        Self::WindowInitError(string)
    }
}

impl From<be_sdl2::video::WindowBuildError> for FlufflError {
    fn from(build_err: be_sdl2::video::WindowBuildError) -> Self {
        FlufflError::WindowInitError(build_err.to_string())
    }
}

impl HasEventCollection for FlufflWindow {
    //Basically passes events from SDL's event queue into a more Generic Queue
    fn collect_events(&mut self) {
        let mut gevent = self.glue_event.take();
        let mut width_update = None;
        let mut height_update = None;

        let (cur_width, cur_height) = self.get_bounds_f32();

        self.sdl_event_pump
            .poll_iter()
            .for_each(|event| match event {
                Event::Quit { .. } => {
                    push_event!(gevent, EventKind::Quit);
                }

                Event::FingerDown {
                    finger_id, x, y, ..
                } => {
                    let id = finger_id as i32;
                    let mouse_pos = [cur_width * x, cur_height * y];
                    let _ = TouchTracker::get_mut().get_touch_displacement(id, mouse_pos);
                    push_event!(
                        gevent,
                        EventKind::TouchDown {
                            finger_id: id,
                            x: mouse_pos[0],
                            y: mouse_pos[1],
                            dx: 0.,
                            dy: 0.,
                        }
                    );
                }

                Event::FingerMotion {
                    finger_id, x, y, ..
                } => {
                    let id = finger_id as i32;
                    let mouse_pos = [cur_width * x, cur_height * y];
                    let [dx, dy] = TouchTracker::get_mut().get_touch_displacement(id, mouse_pos);
                    push_event!(
                        gevent,
                        EventKind::TouchMove {
                            finger_id: id,
                            x: mouse_pos[0],
                            y: mouse_pos[1],
                            dx,
                            dy,
                        }
                    );
                }

                Event::FingerUp {
                    finger_id, x, y, ..
                } => {
                    let id = finger_id as i32;
                    let mouse_pos = [cur_width * x, cur_height * y];
                    let _ = TouchTracker::get_mut().get_touch_displacement(id, mouse_pos);
                    push_event!(
                        gevent,
                        EventKind::TouchUp {
                            finger_id: id,
                            x: mouse_pos[0],
                            y: mouse_pos[1],
                            dx: 0.,
                            dy: 0.,
                        }
                    );
                    // Its important to remove info associated with id when finger is released
                    // because SDL2 will assign a new id for every FingerDown
                    // and we only want to track unique fingers detected by the touchscreen
                    TouchTracker::get_mut().remove(&id);
                }

                Event::Window {
                    win_event: be_sdl2::event::WindowEvent::Resized(width, height),
                    ..
                } => {
                    push_event!(gevent, EventKind::Resize { width, height });
                    width_update = Some(width as u32);
                    height_update = Some(height as u32);
                }

                Event::KeyUp {
                    scancode: Some(sc), ..
                } => {
                    let code = map_scancode(sc);
                    push_event!(gevent, EventKind::KeyUp { code })
                }
                Event::KeyDown {
                    scancode: Some(sc), ..
                } => {
                    let code = map_scancode(sc);
                    push_event!(gevent, EventKind::KeyDown { code })
                }
                Event::MouseButtonDown {
                    mouse_btn, x, y, ..
                } => match mouse_btn {
                    MouseButton::Left => push_event!(
                        gevent,
                        EventKind::MouseDown {
                            button_code: MouseCode::LEFT_BUTTON,
                            x: x as f32,
                            y: y as f32,
                        }
                    ),
                    MouseButton::Right => push_event!(
                        gevent,
                        EventKind::MouseDown {
                            button_code: MouseCode::RIGHT_BUTTON,
                            x: x as f32,
                            y: y as f32,
                        }
                    ),
                    MouseButton::Middle => push_event!(
                        gevent,
                        EventKind::MouseDown {
                            button_code: MouseCode::WHEEL { direction: 0 },
                            x: x as f32,
                            y: y as f32,
                        }
                    ),
                    _ => (),
                },
                Event::MouseButtonUp {
                    mouse_btn, x, y, ..
                } => match mouse_btn {
                    MouseButton::Left => push_event!(
                        gevent,
                        EventKind::MouseUp {
                            button_code: MouseCode::LEFT_BUTTON,
                            x: x as f32,
                            y: y as f32,
                        }
                    ),
                    MouseButton::Right => push_event!(
                        gevent,
                        EventKind::MouseUp {
                            button_code: MouseCode::RIGHT_BUTTON,
                            x: x as f32,
                            y: y as f32,
                        }
                    ),
                    MouseButton::Middle => push_event!(
                        gevent,
                        EventKind::MouseUp {
                            button_code: MouseCode::WHEEL { direction: 0 },
                            x: x as f32,
                            y: y as f32,
                        }
                    ),
                    _ => (),
                },
                Event::MouseMotion {
                    x, y, xrel, yrel, ..
                } => {
                    push_event!(
                        gevent,
                        EventKind::MouseMove {
                            x: x as f32,
                            y: y as f32,
                            dx: xrel as f32,
                            dy: yrel as f32
                        }
                    );
                }
                Event::MouseWheel { y, .. } => {
                    push_event!(
                        gevent,
                        EventKind::MouseWheel {
                            button_code: MouseCode::WHEEL { direction: y }
                        }
                    );
                }
                _ => (),
            });

        if let Some(width) = width_update {
            self.window_width = width;
        }
        if let Some(height) = height_update {
            self.window_height = height;
        }
        //make sure to give the pollevent back
        self.glue_event = gevent;
    }
}

fn map_scancode(scancode: be_sdl2::keyboard::Scancode) -> KeyCode {
    match scancode {
        Scancode::A => KeyCode::KEY_A,
        Scancode::B => KeyCode::KEY_B,
        Scancode::C => KeyCode::KEY_C,
        Scancode::D => KeyCode::KEY_D,
        Scancode::E => KeyCode::KEY_E,
        Scancode::F => KeyCode::KEY_F,
        Scancode::G => KeyCode::KEY_G,
        Scancode::H => KeyCode::KEY_H,
        Scancode::I => KeyCode::KEY_I,
        Scancode::J => KeyCode::KEY_J,
        Scancode::K => KeyCode::KEY_K,
        Scancode::L => KeyCode::KEY_L,
        Scancode::M => KeyCode::KEY_M,
        Scancode::N => KeyCode::KEY_N,
        Scancode::O => KeyCode::KEY_O,
        Scancode::P => KeyCode::KEY_P,
        Scancode::Q => KeyCode::KEY_Q,
        Scancode::R => KeyCode::KEY_R,
        Scancode::S => KeyCode::KEY_S,
        Scancode::T => KeyCode::KEY_T,
        Scancode::U => KeyCode::KEY_U,
        Scancode::V => KeyCode::KEY_V,
        Scancode::W => KeyCode::KEY_W,
        Scancode::X => KeyCode::KEY_X,
        Scancode::Y => KeyCode::KEY_Y,
        Scancode::Z => KeyCode::KEY_Z,
        Scancode::Num0 => KeyCode::NUM_0,
        Scancode::Num1 => KeyCode::NUM_1,
        Scancode::Num2 => KeyCode::NUM_2,
        Scancode::Num3 => KeyCode::NUM_3,
        Scancode::Num4 => KeyCode::NUM_4,
        Scancode::Num5 => KeyCode::NUM_5,
        Scancode::Num6 => KeyCode::NUM_6,
        Scancode::Num7 => KeyCode::NUM_7,
        Scancode::Num8 => KeyCode::NUM_8,
        Scancode::Num9 => KeyCode::NUM_9,
        Scancode::Return => KeyCode::ENTER,
        Scancode::Escape => KeyCode::ESC,
        Scancode::Tab => KeyCode::TAB,
        Scancode::LShift => KeyCode::SHIFT_L,
        Scancode::RShift => KeyCode::SHIFT_R,
        Scancode::Space => KeyCode::SPACE,
        Scancode::Minus => KeyCode::MINUS,
        Scancode::Equals => KeyCode::EQUALS,
        Scancode::LeftBracket => KeyCode::BRACKET_L,
        Scancode::RightBracket => KeyCode::BRACKET_R,
        Scancode::Backslash => KeyCode::BACKSLASH,
        Scancode::NonUsHash => KeyCode::NUM_2,
        Scancode::Semicolon => KeyCode::COLON,
        Scancode::Apostrophe => KeyCode::QUOTE,
        Scancode::Grave => KeyCode::BACK_QUOTE,
        Scancode::Comma => KeyCode::COMMA,
        Scancode::Period => KeyCode::PERIOD,
        Scancode::Slash => KeyCode::FORDSLASH,
        Scancode::CapsLock => KeyCode::CAPSLOCK,
        Scancode::LCtrl => KeyCode::CTRL_L,
        Scancode::RCtrl => KeyCode::CTRL_R,
        Scancode::LAlt => KeyCode::ALT_L,
        Scancode::RAlt => KeyCode::ALT_R,
        Scancode::F1 => KeyCode::F1,
        Scancode::F2 => KeyCode::F2,
        Scancode::F3 => KeyCode::F3,
        Scancode::F4 => KeyCode::F4,
        Scancode::F5 => KeyCode::F5,
        Scancode::F6 => KeyCode::F6,
        Scancode::F7 => KeyCode::F7,
        Scancode::F8 => KeyCode::F8,
        Scancode::F9 => KeyCode::F9,
        Scancode::F10 => KeyCode::F10,
        Scancode::F11 => KeyCode::F11,
        Scancode::F12 => KeyCode::F12,
        Scancode::PrintScreen => KeyCode::PRINT_SCREEN,
        Scancode::ScrollLock => KeyCode::SCROLL_LOCK,
        Scancode::Pause => KeyCode::PAUSE,
        Scancode::Delete => KeyCode::DELETE,
        Scancode::End => KeyCode::END,
        Scancode::PageDown => KeyCode::PAGE_D,
        Scancode::PageUp => KeyCode::PAGE_U,
        Scancode::Left => KeyCode::ARROW_L,
        Scancode::Right => KeyCode::ARROW_R,
        Scancode::Up => KeyCode::ARROW_U,
        Scancode::Down => KeyCode::ARROW_D,
        Scancode::Backspace => KeyCode::BACKSPACE,
        _ => KeyCode::UNKNOWN,
    }
}