glapp 0.1.3

GL context creation wrapper
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
use std::ffi::{CString};
use std::num::NonZeroU32;

use winit::event::{Event, WindowEvent};
use winit::window::WindowBuilder;
use winit::event_loop::{EventLoopBuilder};

use raw_window_handle::HasRawWindowHandle;

use glutin::config::ConfigTemplateBuilder;
use glutin::context::{ContextApi, ContextAttributesBuilder, Version};
use glutin::display::GetGlDisplay;
use glutin::prelude::*;

use crate::AppWindowBuilder;
//use glutin::surface::SwapInterval;

use glutin_winit::{self, DisplayBuilder, GlWindow};

#[cfg(target_os="android")]
use winit::platform::android::EventLoopBuilderExtAndroid;

#[cfg(target_os="android")]
pub use winit::platform::android::activity::AndroidApp;

use crate::{AppWindow, AppEvent, MouseKind, MouseButton, AppUnits};

pub struct AppWindowBuilderGlutin {
    #[cfg(target_os="android")]
    android_app: Option<winit::platform::android::activity::AndroidApp>,

    title:String,
    size: (f32,f32),
    units: AppUnits,
}

impl AppWindowBuilder for AppWindowBuilderGlutin {
    fn build(self:Box<Self>)->Box<dyn AppWindow> {
        Box::new(AppWindowGlutin::new(&self)) //.title.clone()))


        /*let mut event_loop_builder=EventLoopBuilder::new();

        #[cfg(target_os="android")] {
            event_loop_builder.with_android_app(self.android_app.take().unwrap());
        }

        Box::new(GlutinAppWindow::new(
            event_loop_builder.build(),
            self.title.clone()
        ))*/
    }

    fn title(&mut self, title:String) {
        self.title=title;
    }

    fn size(&mut self, w:f32, h:f32) {
        self.size=(w,h);
    }

    fn units(&mut self, units: AppUnits) {
        self.units=units;
    }
}

impl AppWindowBuilderGlutin {
    pub fn new()->Box<Self> {
        Box::new(Self {
            title: "Unknown".to_string(),
            size: (800.,600.),
            units: AppUnits::HardwarePixels
        })
    }

    #[cfg(target_os="android")]
    pub fn with_android_app(mut self, android_app:winit::platform::android::activity::AndroidApp)
            ->Self {
        self.android_app=Some(android_app);
        self
    }

    pub fn build_event_loop(&self)->winit::event_loop::EventLoop<()> {
        let mut event_loop_builder=EventLoopBuilder::new();

        #[cfg(target_os="android")] {
            event_loop_builder.with_android_app(self.android_app.take().unwrap());
        }

        event_loop_builder.build()
    }
}

pub struct AppWindowGlutin {
    gl_config: glutin::config::Config,
    event_loop: Option<winit::event_loop::EventLoop<()>>,
    window: Option<winit::window::Window>,
    not_current_gl_context: Option<glutin::context::NotCurrentContext>,
    gl_context: Option<glutin::context::PossiblyCurrentContext>,
    gl_surface: Option<glutin::surface::Surface<glutin::surface::WindowSurface>>,
    hw_size: (f32,f32),
    mouse_position: winit::dpi::PhysicalPosition<f64>,
    pixel_ratio: f32,
    units: AppUnits,
}

impl AppWindow for AppWindowGlutin {
    fn size(&self)->(f32,f32) {
        if self.hw_size.0<=0. {
            panic!("We have no window at this point");
        }

        (
            self.units.hw_to_units(self.pixel_ratio,self.hw_size.0),
            self.units.hw_to_units(self.pixel_ratio,self.hw_size.1)
        )
    }

    fn pixel_ratio(&self)->f32 {
        if self.pixel_ratio<=0. {
            panic!("We have no window at this point");
        }

        self.pixel_ratio
    }

    fn post_redisplay(&mut self) {
        //println!("request redraw...");
        self.window.as_ref().unwrap().request_redraw();
    }

    fn run(self: Box<Self>, handler:Box<dyn FnMut(&mut dyn AppWindow,AppEvent)>) {
        self.run_impl(handler);
    }
}

impl AppWindowGlutin {
    pub fn new(builder:&AppWindowBuilderGlutin)->Self {
        let event_loop=builder.build_event_loop();

        let window_builder=
            if cfg!(target_os = "android") {None}
            else {Some(WindowBuilder::new())};

        let template =
            ConfigTemplateBuilder::new();//.with_alpha_size(8);.with_transparency(true);

        let display_builder = DisplayBuilder::new().with_window_builder(window_builder);

        let (window, gl_config) = display_builder
            .build(&event_loop, template, |configs| {
                // Find the config with the maximum number of samples.
                configs
                    .reduce(|accum, config| {
                        if config.num_samples() > accum.num_samples() {
                            config
                        } else {
                            accum
                        }
                    })
                    .unwrap()
            })
            .unwrap();

        if window.is_some() {
            window.as_ref().unwrap().set_title(&builder.title);
        }

        let pixel_ratio=if window.is_some() {
            window.as_ref().unwrap().scale_factor() as f32
        }

        else {
            -1.0
        };

        println!("Picked a config with {} samples", gl_config.num_samples());

        let raw_window_handle = window.as_ref().map(|window| window.raw_window_handle());

        // XXX The display could be obtained from the any object created by it, so we
        // can query it from the config.
        let gl_display = gl_config.display();

        // The context creation part. It can be created before surface and that's how
        // it's expected in multithreaded + multiwindow operation mode, since you
        // can send NotCurrentContext, but not Surface.
        let context_attributes = ContextAttributesBuilder::new().build(raw_window_handle);

        // Since glutin by default tries to create OpenGL core context, which may not be
        // present we should try gles.
        let fallback_context_attributes = ContextAttributesBuilder::new()
            .with_context_api(ContextApi::Gles(None))
            .build(raw_window_handle);

        // There are also some old devices that support neither modern OpenGL nor GLES.
        // To support these we can try and create a 2.1 context.
        let legacy_context_attributes = ContextAttributesBuilder::new()
            .with_context_api(ContextApi::OpenGl(Some(Version::new(2, 1))))
            .build(raw_window_handle);

        let not_current_gl_context = Some(unsafe {
            gl_display.create_context(&gl_config, &context_attributes).unwrap_or_else(|_| {
                gl_display.create_context(&gl_config, &fallback_context_attributes).unwrap_or_else(
                    |_| {
                        gl_display
                            .create_context(&gl_config, &legacy_context_attributes)
                            .expect("failed to create context")
                    },
                )
            })
        });

        gl::load_with(|symbol| {
            let symbol = CString::new(symbol).unwrap();
            gl_display.get_proc_address(symbol.as_c_str()).cast()
        });

        //let inner_size=window.as_ref().unwrap().inner_size();

        AppWindowGlutin {
            gl_config,
            event_loop: Some(event_loop),
            window,
            not_current_gl_context,
            gl_context: None,
            gl_surface: None,
            hw_size: (-1.,-1.),
            mouse_position: winit::dpi::PhysicalPosition::<f64>{x:0.0, y:0.0},
            pixel_ratio: pixel_ratio,
            units: builder.units.clone()
        }
    }

    fn run_impl(mut self, mut handler:Box<dyn FnMut(&mut dyn AppWindow,AppEvent)>) {
        let event_loop=self.event_loop.take().unwrap();

        event_loop.run(move |event, window_target, control_flow| {
            control_flow.set_wait();

            //println!("{:?}",event);
            match event {
                Event::Resumed => {
                    if self.window.is_none() {
                        let window_builder = WindowBuilder::new();
                        self.window=Some(glutin_winit::finalize_window(window_target, window_builder, &self.gl_config).unwrap());
                    }

                    let inner_size=self.window.as_ref().unwrap().inner_size();
                    self.hw_size=(
                        inner_size.width as f32,
                        inner_size.height as f32
                    );
                    self.pixel_ratio=self.window.as_ref().unwrap().scale_factor() as f32;

                    let attrs = self.window.as_ref().unwrap().build_surface_attributes(<_>::default());
                    self.gl_surface=Some(unsafe {
                        self.gl_config.display().create_window_surface(&self.gl_config, &attrs).unwrap()
                    });

                    // Make it current.
                    self.gl_context =
                        Some(self.not_current_gl_context.take().unwrap().make_current(&self.gl_surface.as_ref().unwrap()).unwrap());

                    //assert!(state.replace((gl_surface)).is_none());
                    handler(&mut self,AppEvent::Show);

                    self.window.as_ref().unwrap().request_redraw();
                },
                Event::Suspended => {
                    // This event is only raised on Android, where the backing NativeWindow for a GL
                    // Surface can appear and disappear at any moment.
                    println!("Android window removed");

                    // Destroy the GL Surface and un-current the GL Context before ndk-glue releases
                    // the window back to the system.
//                    let (gl_context, ..) = state.take().unwrap();
                    let not_current=self.gl_context.take().unwrap().make_not_current();

                    self.not_current_gl_context=Some(not_current.unwrap());
                    self.gl_context=None;
                    self.gl_surface=None;
                },
                /*Event::RedrawEventsCleared => {
                    if let Some((gl_context, gl_surface, window)) = &state {
                        handler(AppEvent::Render);
                        window.request_redraw();
                        gl_surface.swap_buffers(gl_context).unwrap();
                    }
                },*/
                Event::RedrawRequested(_window_id)=>{
                    if self.gl_context.is_some() &&
                            self.gl_surface.is_some() {
                        unsafe {
                            gl::ClearColor(0.0,0.0,0.0,0.0);
                            gl::Clear(gl::COLOR_BUFFER_BIT);
                        }
                        handler(&mut self,AppEvent::Render);
                        self.gl_surface.as_ref().unwrap().swap_buffers(&self.gl_context.as_ref().unwrap()).unwrap();
                    }
                },
                Event::WindowEvent { event, .. } => match event {
                    WindowEvent::Resized(size) => {
                        self.gl_surface.as_ref().unwrap().resize(
                            &self.gl_context.as_ref().unwrap(),
                            NonZeroU32::new(size.width).unwrap(),
                            NonZeroU32::new(size.height).unwrap(),
                        );

                        unsafe {
                            gl::Viewport(0, 0, size.width as i32, size.height as i32);
                        }

                        self.hw_size=(
                            size.width as f32,
                            size.height as f32
                        );

                        let e=AppEvent::Resize{
                            width: self.units.hw_to_units(self.pixel_ratio,self.hw_size.0),
                            height: self.units.hw_to_units(self.pixel_ratio,self.hw_size.1)
                        };

                        handler(&mut self,e);
                        self.window.as_ref().unwrap().request_redraw();
                    },
                    WindowEvent::ScaleFactorChanged{new_inner_size,..}=>{
                        let size=new_inner_size;
                        self.gl_surface.as_ref().unwrap().resize(
                            &self.gl_context.as_ref().unwrap(),
                            NonZeroU32::new(size.width).unwrap(),
                            NonZeroU32::new(size.height).unwrap(),
                        );

                        unsafe {
                            gl::Viewport(0, 0, size.width as i32, size.height as i32);
                        }

                        self.pixel_ratio=self.window.as_ref().unwrap().scale_factor() as f32;
                        self.hw_size=(
                            size.width as f32,
                            size.height as f32
                        );

                        let e=AppEvent::Resize{
                            width: self.units.hw_to_units(self.pixel_ratio,self.hw_size.0),
                            height: self.units.hw_to_units(self.pixel_ratio,self.hw_size.1)
                        };

                        handler(&mut self,e);
                        self.window.as_ref().unwrap().request_redraw();
                    },
                    WindowEvent::CloseRequested => {
                        control_flow.set_exit();
                    },
                    WindowEvent::CursorMoved{position,..}=>{
                        self.mouse_position=position;
                        let e=AppEvent::MouseMove{
                            x:self.units.hw_to_units(self.pixel_ratio,position.x as f32),
                            y:self.units.hw_to_units(self.pixel_ratio,position.y as f32),
                            kind:MouseKind::Mouse
                        };

                        handler(&mut self,e);
                    },
                    WindowEvent::MouseInput{state,button,..}=>{
                        let event_button=match button {
                            winit::event::MouseButton::Left=>MouseButton::Left,
                            winit::event::MouseButton::Right=>MouseButton::Right,
                            _=>MouseButton::Unknown
                        };

                        let event=match state {
                            winit::event::ElementState::Pressed=>{
                                AppEvent::MouseDown{
                                    x: self.units.hw_to_units(self.pixel_ratio,self.mouse_position.x as f32),
                                    y: self.units.hw_to_units(self.pixel_ratio,self.mouse_position.y as f32),
                                    kind: MouseKind::Mouse,
                                    button: event_button
                                }
                            },
                            winit::event::ElementState::Released=>{
                                AppEvent::MouseUp{
                                    x: self.units.hw_to_units(self.pixel_ratio,self.mouse_position.x as f32),
                                    y: self.units.hw_to_units(self.pixel_ratio,self.mouse_position.y as f32),
                                    kind: MouseKind::Mouse,
                                    button: event_button
                                }
                            }
                        };

                        handler(&mut self,event);
                    },
                    WindowEvent::Touch(winit::event::Touch{phase,location,..})=>{
                        let event=match phase {
                            winit::event::TouchPhase::Started=>{
                                AppEvent::MouseDown{
                                    x: self.units.hw_to_units(self.pixel_ratio,location.x as f32),
                                    y: self.units.hw_to_units(self.pixel_ratio,location.y as f32),
                                    kind: MouseKind::Touch,
                                    button: MouseButton::Unknown
                                }
                            },
                            winit::event::TouchPhase::Moved=>{
                                AppEvent::MouseMove{
                                    x: self.units.hw_to_units(self.pixel_ratio,location.x as f32),
                                    y: self.units.hw_to_units(self.pixel_ratio,location.y as f32),
                                    kind: MouseKind::Touch,
                                }
                            },
                            winit::event::TouchPhase::Ended |
                            winit::event::TouchPhase::Cancelled=>{
                                AppEvent::MouseUp{
                                    x: self.units.hw_to_units(self.pixel_ratio,location.x as f32),
                                    y: self.units.hw_to_units(self.pixel_ratio,location.y as f32),
                                    kind: MouseKind::Touch,
                                    button: MouseButton::Unknown
                                }
                            },
                        };

                        handler(&mut self,event);
                    }
                    _ => (),
                },
                _ => (),
            }
        });
	}
}