~starkingdoms/starkingdoms

ref: 27a53b0042cdb2a1a6c6e4d123ceb00455d77645 starkingdoms/crates/client/src/rendering/mod.rs -rw-r--r-- 11.5 KiB
27a53b00 — ghostly_zsh egui is faster and so is rendering 8 months ago
                                                                                
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
use std::num::NonZeroU32;
use std::sync::Arc;

use egui_glow::EguiGlow;
use glow::{HasContext, PixelUnpackData};
#[cfg(not(target_arch = "wasm32"))]
use glutin::surface::{Surface, WindowSurface, GlSurface, SwapInterval};
#[cfg(not(target_arch = "wasm32"))]
use glutin::{config::{ConfigTemplateBuilder, GlConfig}, context::{ContextApi, ContextAttributesBuilder, PossiblyCurrentContext}, display::GetGlDisplay, prelude::{GlDisplay, NotCurrentGlContext}};
#[cfg(not(target_arch = "wasm32"))]
use glutin_winit::{DisplayBuilder, GlWindow};
#[cfg(target_arch = "wasm32")]
use wasm_bindgen::{prelude::Closure, JsCast};
#[cfg(target_arch = "wasm32")]
use web_sys::{Event, HtmlCanvasElement};
use winit::event_loop::ControlFlow;
#[cfg(target_arch = "wasm32")]
use winit::platform::web::{WindowAttributesExtWebSys, WindowExtWebSys};
use winit::{application::ApplicationHandler, dpi::LogicalSize, event::WindowEvent, event_loop::ActiveEventLoop, raw_window_handle::HasWindowHandle, window::{Window, WindowAttributes}};

pub mod init;

#[derive(Default)]
pub struct App {
    window: Option<Window>,
    program: Option<glow::Program>,
    vertex_array: Option<glow::VertexArray>,
    vertex_buffer: Option<glow::Buffer>,
    element_buffer: Option<glow::Buffer>,
    texture_object: Option<glow::Texture>,
    #[cfg(not(target_arch = "wasm32"))]
    gl_surface: Option<Surface<WindowSurface>>,
    #[cfg(not(target_arch = "wasm32"))]
    gl_context: Option<PossiblyCurrentContext>,
    egui_glow: Option<EguiGlow>,
    gl: Option<Arc<glow::Context>>,
}

const VERTICES: [f32; 16] = [
    -1.0, -1.0,     0.0, 1.0,
    1.0, -1.0,      1.0, 1.0,
    1.0, 1.0,       1.0, 0.0,
    -1.0, 1.0,      0.0, 0.0,
];
const INDICES: [u32; 6] = [
    0, 1, 2,
    2, 3, 0,
];

impl ApplicationHandler for App {
    fn resumed(&mut self, event_loop: &ActiveEventLoop) {
        #[cfg(target_arch = "wasm32")]
        let attributes = {
            let document = web_sys::window().unwrap().document().unwrap();
            let canvas = document.get_element_by_id("canvas").unwrap();
            let canvas = canvas.dyn_into::<web_sys::HtmlCanvasElement>()
                .map_err(|_| ()).unwrap();
            canvas.set_width(web_sys::window().unwrap().inner_width().unwrap().as_f64().unwrap() as u32);
            canvas.set_height(web_sys::window().unwrap().inner_height().unwrap().as_f64().unwrap() as u32);
            Window::default_attributes()
                .with_title("StarKingdoms.TK")
                .with_canvas(Some(canvas))
        };
        #[cfg(not(target_arch = "wasm32"))]
        let attributes = {
            Window::default_attributes().with_transparent(true).with_title("StarKingdoms.TK")
                .with_inner_size(LogicalSize::new(400, 300))
        };
        self.window = Some(event_loop.create_window(attributes.clone()).unwrap());
        let window = self.window.as_ref().unwrap();
        #[cfg(target_arch = "wasm32")]
        let context = window.canvas().unwrap().get_context("webgl2")
            .unwrap().unwrap()
            .dyn_into::<web_sys::WebGl2RenderingContext>()
            .unwrap();
        #[cfg(target_arch = "wasm32")]
        let (gl, shader_version) = (Arc::new(glow::Context::from_webgl2_context(context)), "#version 300 es");

        #[cfg(not(target_arch = "wasm32"))]
        let (gl, shader_version) = unsafe {
            let template = ConfigTemplateBuilder::new().with_transparency(true);

            let display_builder = DisplayBuilder::new().with_window_attributes(Some(attributes));

            let (window, gl_config) = display_builder.build(event_loop, template, |configs| {
                configs.reduce(|accum, config| {
                    let supports_transparency = config.supports_transparency().unwrap_or(false)
                        && !accum.supports_transparency().unwrap_or(false);
                    if supports_transparency || config.num_samples() > accum.num_samples() {
                        config
                    } else {
                        accum
                    }
                }).unwrap()
            }).unwrap();
            let raw_handle = window.as_ref().map(|window| window.window_handle().unwrap().window_handle().unwrap().as_raw());
            let gl_display = gl_config.display();
            let context_attributes = ContextAttributesBuilder::new()
                .with_context_api(ContextApi::OpenGl(Some(glutin::context::Version {
                    major: 3,
                    minor: 0,
                }))).build(raw_handle);

            let not_current_gl_context = gl_display.create_context(&gl_config, &context_attributes).unwrap();

            let window = window.unwrap();
            let surface_attributes = window.build_surface_attributes(Default::default()).unwrap();
            let gl_surface = gl_display.create_window_surface(&gl_config, &surface_attributes).unwrap();

            let gl_context = not_current_gl_context.make_current(&gl_surface).unwrap();

            let gl = glow::Context::from_loader_function_cstr(|s| gl_display.get_proc_address(s));

            gl_surface.set_swap_interval(&gl_context, SwapInterval::Wait(NonZeroU32::new(1).unwrap())).unwrap();

            self.gl_surface = Some(gl_surface);
            self.gl_context = Some(gl_context);

            (Arc::new(gl), "#version 300 es")
        };
        unsafe {
            let shaders = [
                ("vertex", include_str!("../shaders/vertex.glsl"), glow::VERTEX_SHADER),
                ("fragment", include_str!("../shaders/fragment.glsl"), glow::FRAGMENT_SHADER),
            ];
            let program = gl.create_program().expect("Failed to create program");

            for (name, source, shader_type) in shaders {
                let shader = gl.create_shader(shader_type).expect("Failed to create vertex shader");
                gl.shader_source(shader, &format!("{}\n{}", shader_version, source));
                gl.compile_shader(shader);
                if !gl.get_shader_compile_status(shader) {
                    tracing::error!("error in {} shader: {}", name, gl.get_shader_info_log(shader));
                }
                gl.attach_shader(program, shader);
                gl.delete_shader(shader);
            }
            gl.link_program(program);

            gl.use_program(Some(program));

            let vertex_array = gl.create_vertex_array().expect("Failed to create vertex array");
            gl.bind_vertex_array(Some(vertex_array));
            let vertex_buffer = gl.create_buffer().expect("Failed to create vertex buffer");
            gl.bind_buffer(glow::ARRAY_BUFFER, Some(vertex_buffer));
            let element_buffer = gl.create_buffer().expect("Failed to create element buffer");
            gl.bind_buffer(glow::ELEMENT_ARRAY_BUFFER, Some(element_buffer));
            gl.buffer_data_u8_slice(glow::ARRAY_BUFFER,
                std::slice::from_raw_parts(VERTICES.as_ptr() as *const u8, size_of_val(&VERTICES)),
                glow::STATIC_DRAW);
            gl.buffer_data_u8_slice(glow::ELEMENT_ARRAY_BUFFER,
                std::slice::from_raw_parts(INDICES.as_ptr() as *const u8, size_of_val(&INDICES)),
                glow::STATIC_DRAW);

            gl.vertex_attrib_pointer_f32(0, 2, glow::FLOAT, false, 4*size_of::<f32>() as i32, 0);
            gl.enable_vertex_attrib_array(0);
            gl.vertex_attrib_pointer_f32(1, 2, glow::FLOAT, false, 4*size_of::<f32>() as i32, 2*size_of::<f32>() as i32);
            gl.enable_vertex_attrib_array(1);

            let texture = gl.create_texture().expect("Failed to create texture object");
            gl.active_texture(glow::TEXTURE0);
            gl.bind_texture(glow::TEXTURE_2D, Some(texture));
            let image = image::load_from_memory(include_bytes!("../assets/happy-tree.png")).unwrap();
            let image = image.to_rgba8();
            gl.tex_image_2d(glow::TEXTURE_2D, 0, glow::RGBA as i32,
                image.width() as i32, image.height() as i32, 0, glow::RGBA,
                glow::UNSIGNED_BYTE, PixelUnpackData::Slice(Some(&image.into_raw())));
            gl.generate_mipmap(glow::TEXTURE_2D);

            gl.clear_color(0.0, 0.0, 0.0, 0.0);
            gl.viewport(0, 0, window.inner_size().width as i32, window.inner_size().height as i32);
            gl.enable(glow::BLEND);
            gl.blend_func(glow::SRC_ALPHA, glow::ONE_MINUS_SRC_ALPHA);

            self.program = Some(program);
            self.vertex_array = Some(vertex_array);
            self.vertex_buffer = Some(vertex_buffer);
            self.element_buffer = Some(element_buffer);
            self.texture_object = Some(texture);
        }
        #[cfg(target_arch = "wasm32")]
        web_sys::window().unwrap().set_onresize(Some(Closure::<dyn Fn(Event)>::new(move |_| {
            let document = web_sys::window().unwrap().document().unwrap();
            let canvas = document.get_element_by_id("canvas").unwrap();
            let canvas = canvas.dyn_into::<web_sys::HtmlCanvasElement>()
                .map_err(|_| ()).unwrap();
            canvas.set_width(web_sys::window().unwrap().inner_width().unwrap().as_f64().unwrap() as u32);
            canvas.set_height(web_sys::window().unwrap().inner_height().unwrap().as_f64().unwrap() as u32);
        }).into_js_value().as_ref().unchecked_ref()));

        let egui_glow = egui_glow::EguiGlow::new(event_loop, gl.clone(), None, None, true);
        self.egui_glow = Some(egui_glow);
        self.gl = Some(gl);
    }
    fn window_event(
        &mut self,
        event_loop: &ActiveEventLoop,
        window_id: winit::window::WindowId,
        event: winit::event::WindowEvent,
    ) {
        match event {
            WindowEvent::CloseRequested => {
                event_loop.exit();
            }
            WindowEvent::Resized(size) => {
                #[cfg(not(target_arch = "wasm32"))]
                self.gl_surface.as_ref().unwrap().resize(self.gl_context.as_ref().unwrap(),
                    NonZeroU32::new(size.width).unwrap(), NonZeroU32::new(size.height).unwrap());

                unsafe {
                    self.gl.as_ref().unwrap().viewport(0, 0, size.width as i32, size.height as i32);
                }
            }

            _ => {}
        }
        let event_response = self.egui_glow.as_mut().unwrap()
            .on_window_event(self.window.as_ref().unwrap(), &event);
    }
    fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) {
        let window = self.window.as_ref().unwrap();
        let gl = self.gl.as_ref().unwrap();

        self.egui_glow.as_mut().unwrap().run(
            self.window.as_ref().unwrap(),
            |ctx| {
                egui::Window::new("Main Menu").resizable(false).show(ctx, |ui| {
                    ui.heading("Starkingdoms.tk");
                });
            },
        );

        unsafe {
            gl.clear(glow::COLOR_BUFFER_BIT);
            gl.use_program(self.program);
            gl.active_texture(glow::TEXTURE0);
            gl.bind_texture(glow::TEXTURE_2D, self.texture_object);
            gl.bind_vertex_array(self.vertex_array);
            gl.bind_buffer(glow::ARRAY_BUFFER, self.vertex_buffer);
            gl.bind_buffer(glow::ELEMENT_ARRAY_BUFFER, self.element_buffer);
            gl.draw_elements(glow::TRIANGLES, 6, glow::UNSIGNED_INT, 0);
        }

        self.egui_glow.as_mut().unwrap().paint(self.window.as_ref().unwrap());

        #[cfg(not(target_arch = "wasm32"))]
        self.gl_surface.as_ref().unwrap().swap_buffers(self.gl_context.as_ref().unwrap()).unwrap();

        event_loop.set_control_flow(ControlFlow::WaitUntil(web_time::Instant::now().checked_add(web_time::Duration::from_millis(16)).unwrap()));
    }
}