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
|
pub mod utils;
pub mod ui;
pub mod context;
pub mod state;
pub mod framebuffer;
pub mod shader;
pub mod mesh;
pub mod texture;
pub mod scene;
pub mod font;
pub mod shadow;
pub mod audio;
pub mod net;
pub mod save;
use std::ops::Rem;
#[cfg(target_arch = "wasm32")]
use winit::platform::web::EventLoopExtWebSys;
#[cfg(target_arch = "wasm32")]
use winit::platform::web::WindowExtWebSys;
#[cfg(target_arch = "wasm32")]
use wasm_bindgen::JsCast;
#[cfg(not(target_arch = "wasm32"))]
use glfw::Context;
#[cfg(not(target_arch = "wasm32"))]
use bitflags::bitflags;
#[cfg(not(target_arch = "wasm32"))]
bitflags! {
pub struct Options: u32 {
const OVERLAY = 0b00000001;
const HIDDEN = 0b00000010;
}
}
static mut CTX: Option<*const context::Context> = None;
static mut ST: Option<*mut state::State> = None;
static mut G: Option<*mut std::ffi::c_void> = None;
pub fn contextualize<F, G>(mut f: F)
where
G: state::Game + 'static,
F: FnMut(&context::Context, &mut state::State, &mut G) {
unsafe {
match (CTX, ST, G) {
(Some(c), Some(s), Some(g)) => f(&*c, &mut*s, &mut*(g as *mut G)),
_ => log::info!("context not set"),
}
}
}
#[cfg(not(target_arch = "wasm32"))]
pub async fn run<'a, F, G, Fut>(title: &str, w: u32, h: u32, options: Options, gnew: F)
where
Fut: std::future::Future<Output = G>,
G: state::Game + 'static,
F: (Fn(&'a context::Context) -> Fut),
{
env_logger::Builder::new()
.filter(None, log::LevelFilter::Info)
.init();
log::info!("hello computer, starting up...");
let (rglfw, rwindow, gl, events) = {
use glfw::fail_on_errors;
let mut glfw = glfw::init(glfw::fail_on_errors!()).expect("failed to initialize GLFW");
// let gl_attr = video.gl_attr();
// gl_attr.set_context_profile(sdl2::video::GLProfile::Core);
// gl_attr.set_context_version(3, 0);
let (mut window, events) = glfw.with_primary_monitor(|glfw, primary| {
if options.contains(Options::HIDDEN) {
glfw.window_hint(glfw::WindowHint::Visible(false));
glfw.create_window(w as _, h as _, title, glfw::WindowMode::Windowed)
.expect("failed to create window")
} else if options.contains(Options::OVERLAY) {
let mon = primary.expect("failed to get monitor");
let mode = mon.get_video_mode().expect("failed to get video mode");
glfw.window_hint(glfw::WindowHint::RedBits(Some(mode.red_bits)));
glfw.window_hint(glfw::WindowHint::GreenBits(Some(mode.green_bits)));
glfw.window_hint(glfw::WindowHint::BlueBits(Some(mode.blue_bits)));
glfw.window_hint(glfw::WindowHint::RefreshRate(Some(mode.refresh_rate)));
glfw.window_hint(glfw::WindowHint::Resizable(false));
glfw.window_hint(glfw::WindowHint::Decorated(false));
glfw.window_hint(glfw::WindowHint::Floating(true));
glfw.window_hint(glfw::WindowHint::TransparentFramebuffer(true));
unsafe {
// glfw.window_hint(glfw::WindowHint::MousePassthrough(true));
glfw::ffi::glfwWindowHint(0x0002000D, 1); // mouse passthrough
}
glfw.create_window(mode.width, mode.height, title, glfw::WindowMode::FullScreen(mon))
.expect("failed to create window")
} else {
glfw.create_window(w as _, h as _, title, glfw::WindowMode::Windowed)
.expect("failed to create window")
}
});
window.make_current();
window.set_key_polling(true);
window.set_mouse_button_polling(true);
window.set_size_polling(true);
window.set_focus_polling(true);
window.set_cursor_pos_polling(true);
let gl = unsafe {
glow::Context::from_loader_function(|s| window.get_proc_address(s) as *const _)
};
(glfw, window, gl, events)
};
let glfw = std::cell::RefCell::new(rglfw);
let window = std::cell::RefCell::new(rwindow);
let ctx = Box::leak(Box::new(context::Context::new(glfw, window, gl, w as f32, h as f32)));
let game = Box::leak(Box::new(gnew(ctx).await));
let st = Box::leak(Box::new(state::State::new(&ctx)));
unsafe {
CTX = Some(ctx as _);
ST = Some(st as _);
G = Some(game as *mut G as *mut std::ffi::c_void);
}
'running: loop {
if ctx.window.borrow().should_close() {
log::info!("bye!");
break 'running;
}
ctx.glfw.borrow_mut().poll_events();
for (_, event) in glfw::flush_messages(&events) {
match event {
glfw::WindowEvent::Size(_, _) => st.handle_resize(&ctx),
glfw::WindowEvent::Focus(false) => {
st.keys = state::Keys::new();
},
glfw::WindowEvent::CursorPos(x, y) => {
st.mouse_moved(&ctx, x as f32, y as f32, game);
}
glfw::WindowEvent::MouseButton(_, glfw::Action::Press, _) => {
st.mouse_pressed(&ctx, game)
},
glfw::WindowEvent::MouseButton(_, glfw::Action::Release, _) => {
st.mouse_released(&ctx)
},
glfw::WindowEvent::Key(key, _, glfw::Action::Press, _) => {
st.key_pressed(&ctx, state::Keycode::new(key))
},
glfw::WindowEvent::Key(key, _, glfw::Action::Release, _) => {
st.key_released(&ctx, state::Keycode::new(key))
},
_ => {},
}
}
if ctx.resize_necessary() {
st.handle_resize(&ctx);
}
if let Some(f) = &mut st.request {
match std::future::Future::poll(f.as_mut(), &mut st.waker_ctx) {
std::task::Poll::Pending => {},
std::task::Poll::Ready(res) => {
st.request = None;
match res {
Ok(r) => st.request_returned(&ctx, game, r),
Err(e) => log::warn!("error during HTTP request: {}", e),
}
},
}
}
st.run_update(&ctx, game);
st.run_render(&ctx, game);
ctx.window.borrow_mut().swap_buffers();
}
// event_loop.set_control_flow(winit::event_loop::ControlFlow::Poll);
// event_loop.run(|event, elwt| {
// event_loop_body::<G>(event, elwt);
// }).expect("window closed");
}
#[cfg(target_arch = "wasm32")]
pub async fn run<'a, F, G, Fut>(w: u32, h: u32, gnew: F)
where
Fut: std::future::Future<Output = G>,
G: state::Game + 'static,
F: (Fn(&'a context::Context) -> Fut),
{
console_log::init_with_level(log::Level::Debug).unwrap();
console_error_panic_hook::set_once();
tracing_wasm::set_as_global_default();
log::info!("hello computer, starting up...");
let event_loop = winit::event_loop::EventLoop::new()
.expect("failed to initialize event loop");
let (window, gl) = {
let window = winit::window::WindowBuilder::new()
.with_maximized(true)
.with_decorations(false)
.build(&event_loop)
.expect("failed to initialize window");
let gl = web_sys::window()
.and_then(|win| win.document())
.and_then(|doc| {
let dst = doc.get_element_by_id("teleia-parent")?;
let canvas = web_sys::Element::from(window.canvas().expect("failed to find canvas"));
dst.append_child(&canvas).ok()?;
let c = canvas.dyn_into::<web_sys::HtmlCanvasElement>().ok()?;
let webgl2_context = c.get_context("webgl2").ok()??
.dyn_into::<web_sys::WebGl2RenderingContext>().ok()?;
Some(glow::Context::from_webgl2_context(webgl2_context))
})
.expect("couldn't add canvas to document");
(window, gl)
};
let ctx = Box::leak(Box::new(context::Context::new(window, gl, w as f32, h as f32)));
ctx.maximize_canvas();
let game = Box::leak(Box::new(gnew(ctx).await));
let st = Box::leak(Box::new(state::State::new(&ctx)));
unsafe {
CTX = Some(ctx as _);
ST = Some(st as _);
G = Some(game as *mut G as *mut std::ffi::c_void);
}
event_loop.set_control_flow(winit::event_loop::ControlFlow::Wait);
event_loop.spawn(|event, elwt| {
contextualize(|ctx, st, game: &mut G| {
match &event {
winit::event::Event::WindowEvent {
event: wev,
window_id,
..
} => match wev {
winit::event::WindowEvent::CloseRequested
if *window_id == ctx.window.id() => elwt.exit(),
winit::event::WindowEvent::Resized{..} => {
#[cfg(target_arch = "wasm32")]
ctx.maximize_canvas();
st.handle_resize(&ctx);
},
winit::event::WindowEvent::Focused(false) => {
st.keys = state::Keys::new();
},
winit::event::WindowEvent::CursorMoved { position, ..} => {
st.mouse_moved(&ctx, position.x as f32, position.y as f32, game);
},
winit::event::WindowEvent::MouseInput {
state,
..
} => match state {
winit::event::ElementState::Pressed => {
st.mouse_pressed(&ctx, game)
},
winit::event::ElementState::Released => {
st.mouse_released(&ctx)
},
}
winit::event::WindowEvent::KeyboardInput {
event: winit::event::KeyEvent {
physical_key: winit::keyboard::PhysicalKey::Code(key),
state,
repeat: false,
..
},
..
} => match state {
winit::event::ElementState::Pressed => {
st.key_pressed(&ctx, *key)
},
winit::event::ElementState::Released => {
st.key_released(&ctx, *key)
},
}
_ => {},
},
winit::event::Event::AboutToWait => {
if ctx.resize_necessary() {
#[cfg(target_arch = "wasm32")]
ctx.maximize_canvas();
st.handle_resize(&ctx);
}
if let Some(f) = &mut st.request {
match std::future::Future::poll(f.as_mut(), &mut st.waker_ctx) {
std::task::Poll::Pending => {},
std::task::Poll::Ready(res) => {
st.request = None;
match res {
Ok(r) => st.request_returned(&ctx, game, r),
Err(e) => log::warn!("error during HTTP request: {}", e),
}
},
}
// f.poll();
}
st.run_update(&ctx, game);
st.run_render(&ctx, game);
ctx.window.request_redraw();
},
_ => {},
}
});
});
}
#[cfg(target_arch = "wasm32")]
use wasm_bindgen::prelude::*;
pub struct TestGame {
font: font::Bitmap,
tt: font::TrueType,
// cube: mesh::Mesh,
fox: scene::Scene,
tex: texture::Texture,
shader: shader::Shader,
}
impl TestGame {
pub async fn new(ctx: &context::Context) -> Self {
Self {
font: font::Bitmap::new(ctx),
tt: font::TrueType::new(ctx, 12.0, include_bytes!("assets/fonts/ComicNeue-Regular.ttf")),
// cube: mesh::Mesh::from_obj(ctx, include_bytes!("assets/meshes/cube.obj")),
fox: scene::Scene::from_gltf(ctx, include_bytes!("assets/scenes/fox.glb")),
// fox: scene::Scene::from_gltf(ctx, include_bytes!("/home/llll/src/colonq/assets/lcolonq_flat.vrm")),
tex: texture::Texture::new(ctx, include_bytes!("assets/textures/test.png")),
shader: shader::Shader::new(ctx, include_str!("assets/shaders/scene/vert.glsl"), include_str!("assets/shaders/scene/frag.glsl")),
}
}
}
impl state::Game for TestGame {
fn update(&mut self, ctx: &context::Context, st: &mut state::State) -> Option<()> {
st.move_camera(
ctx,
&glam::Vec3::new(0.0, 0.0, -1.0),
&glam::Vec3::new(0.0, 0.0, 1.0),
&glam::Vec3::new(0.0, 1.0, 0.0),
);
Some(())
}
fn render(&mut self, ctx: &context::Context, st: &mut state::State) -> Option<()> {
// if let Some(n) = self.fox.nodes_by_name.get("J_Bip_C_Neck").and_then(|i| self.fox.nodes.get_mut(*i)) {
// n.transform *= glam::Mat4::from_rotation_z(0.05);
// }
self.fox.reflect_animation("Run", (st.tick as f32 / 60.0).rem(3.0));
st.bind_3d(ctx, &self.shader);
self.shader.set_position_3d(
ctx,
&glam::Mat4::from_scale_rotation_translation(
glam::Vec3::new(0.005, 0.005, 0.005),
// glam::Vec3::new(1.0, 1.0, 1.0),
glam::Quat::from_rotation_y(st.tick as f32 / 60.0),
glam::Vec3::new(0.0, -0.2, 0.0),
),
);
self.tex.bind(ctx);
self.fox.render(ctx, &self.shader);
self.font.render_text(ctx, &glam::Vec2::new(0.0, 10.0), "he's all FIXED up");
self.tt.render_text_helper(
ctx, &glam::Vec2::new(10.0, 60.0), &glam::Vec2::new(20.0, 30.0),
"tESTge",
&[
glam::Vec3::new(1.0, 0.0, 0.0),
glam::Vec3::new(0.0, 1.0, 0.0),
],
);
Some(())
}
}
#[cfg(target_arch = "wasm32")]
#[wasm_bindgen]
pub async fn main_js_test() {
run(240, 160, TestGame::new).await;
}
|