Pool/src/app.rs

312 lines
9 KiB
Rust

use std::collections::HashMap;
// Credit of most code to https://sotrh.github.io/learn-wgpu/ since I'm not familiar with wgpu
use std::sync::Arc;
use glam::{Vec2, Affine3A, Vec3, Vec4, Mat4, EulerRot, Quat};
#[cfg(target_arch = "wasm32")]
use wasm_bindgen::prelude::*;
use winit::dpi::PhysicalPosition;
#[cfg(target_arch = "wasm32")]
use winit::platform::web::EventLoopExtWebSys;
use winit::{
application::ApplicationHandler,
event::*,
event_loop::{ActiveEventLoop, EventLoop},
keyboard::{KeyCode, PhysicalKey},
window::Window,
};
use crate::render;
use crate::render::{Renderer, SimpleTexture};
use crate::world::{SimpleObject, World};
struct Controller {
buttons: HashMap<MouseButton,bool>,
keys: HashMap<KeyCode,bool>,
mouse: Vec2,
}
impl Controller {
fn new() -> Controller {
Controller {
buttons: Default::default(),
keys: HashMap::new(),
mouse: Vec2::new(0.0,0.0),
}
}
}
pub struct AppState {
world: World,
controller: Controller,
window: Arc<Window>,
clients: Vec<SimpleObject>,
}
const BLOCKS: i32 = 50;
impl AppState {
// We don't need this to be async right now,
// but we will in the next tutorial
pub async fn new(window: Arc<Window>) -> Result<AppState,Box<dyn std::error::Error>> {
let size = window.inner_size();
let mut world = World::new();
world.add_renderer(Renderer::new(&window).await?);
let mut clients = Vec::new();
{
let file = world.renderer.as_mut().unwrap().load_from_gltf( include_bytes!("assets/cube.glb"));
let block = file.first_object().unwrap();
//let color = &renderer.load_texture_from_bytes(include_bytes!("assets/plank/color.png"));
//let normal = &renderer.load_texture_from_bytes(include_bytes!("assets/plank/normal.png"));
//let roughness = &renderer.load_texture_from_bytes(include_bytes!("assets/plank/roughness.png"));
//let mat = renderer.new_material(color,normal,roughness);
for x in -BLOCKS..BLOCKS {
for y in -BLOCKS..BLOCKS {
let block = block.hard_clone();
world.add_object(block.clone());
{
let mut model = block.0.borrow_mut();
model.model.as_mut().unwrap().instance.transform = Mat4::from_translation(Vec3::new(-x as f32 * 3.0,0.0,-y as f32 * 3.0))
* Mat4::from_rotation_z((x * y) as f32 / 1.23);
model.model.as_mut().unwrap().instance.color = Vec4::new(0.3,(x + BLOCKS) as f32 / BLOCKS as f32,(y + BLOCKS) as f32 / BLOCKS as f32,1.0);
}
clients.push(block)
}
}
}
Ok(Self {
world,
clients,
controller: Controller::new(),
window,
})
}
pub fn bounds(&self) -> (u32,u32) {
let size = self.window.inner_size();
(size.width,size.height)
}
pub fn resize(&mut self, width: u32, height: u32) {
if width > 0 && height > 0 {
let max = 2048;
self.world.renderer.as_mut().unwrap().resize(width,height);
}
}
fn update(&mut self) {
// ...
}
fn handle_key(&mut self, event_loop: &ActiveEventLoop, code: KeyCode, is_pressed: bool) {
match (code, is_pressed) {
(KeyCode::Escape, true) => event_loop.exit(),
(KeyCode::Space, true) => {},
(KeyCode::KeyR, true) => {
self.world.renderer.as_mut().unwrap().eye.frame = Affine3A::IDENTITY
}
_ => {}
}
self.controller.keys.insert(code, is_pressed);
}
fn handle_mouse_moved(&mut self, position: PhysicalPosition<f64>) {
if let Some(true) = self.controller.buttons.get(&MouseButton::Right) {
self.world.renderer.as_mut().unwrap().eye.rotate(position.x as f32 - self.controller.mouse.x, position.y as f32 - self.controller.mouse.y);
}
self.controller.mouse = Vec2::new(position.x as f32, position.y as f32);
}
fn handle_mouse_button(&mut self, button: MouseButton, state: ElementState ) {
self.controller.buttons.insert(button,state.is_pressed());
}
}
pub struct App {
#[cfg(target_arch = "wasm32")]
proxy: Option<winit::event_loop::EventLoopProxy<AppState>>,
state: Option<AppState>,
}
impl App {
pub fn new(#[cfg(target_arch = "wasm32")] event_loop: &EventLoop<AppState>) -> Self {
#[cfg(target_arch = "wasm32")]
let proxy = Some(event_loop.create_proxy());
Self {
state: None,
#[cfg(target_arch = "wasm32")]
proxy,
}
}
}
impl ApplicationHandler<AppState> for App {
fn resumed(&mut self, event_loop: &ActiveEventLoop) {
#[allow(unused_mut)]
let mut window_attributes = Window::default_attributes();
#[cfg(target_arch = "wasm32")]
{
use wasm_bindgen::JsCast;
use winit::platform::web::WindowAttributesExtWebSys;
const CANVAS_ID: &str = "canvas";
let window = wgpu::web_sys::window().unwrap_throw();
let document = window.document().unwrap_throw();
let canvas = document.get_element_by_id(CANVAS_ID).unwrap_throw();
let html_canvas_element = canvas.unchecked_into();
window_attributes = window_attributes.with_canvas(Some(html_canvas_element));
}
let window = Arc::new(event_loop.create_window(window_attributes).unwrap());
#[cfg(not(target_arch = "wasm32"))]
{
// If we are not on web we can use pollster to
// await the window creation
self.state = Some(pollster::block_on(AppState::new(window)).unwrap());
}
#[cfg(target_arch = "wasm32")]
{
// Run the future asynchronously and use the
// proxy to send the results to the event loop
if let Some(proxy) = self.proxy.take() {
wasm_bindgen_futures::spawn_local(async move {
assert!(
proxy
.send_event(
AppState::new(window)
.await
.expect("Unable to create canvas!!!")
)
.is_ok()
)
});
}
}
}
#[allow(unused_mut)]
fn user_event(&mut self, _event_loop: &ActiveEventLoop, mut event: AppState) {
// This is where proxy.send_event() ends up
#[cfg(target_arch = "wasm32")]
{
event.window.request_redraw();
event.resize(
event.window.inner_size().width,
event.window.inner_size().height,
);
}
self.state = Some(event);
}
fn window_event(
&mut self,
event_loop: &ActiveEventLoop,
_window_id: winit::window::WindowId,
event: WindowEvent,
) {
let state = match &mut self.state {
Some(canvas) => canvas,
None => return,
};
match event {
WindowEvent::CloseRequested => event_loop.exit(),
WindowEvent::Resized(size) => state.resize(size.width, size.height),
WindowEvent::RedrawRequested => {
state.update();
let mut movement = Vec3::new(0.0,0.0,0.0);
let pressed = |keycode: KeyCode| {
if let Some(true) = state.controller.keys.get(&keycode) {
true
} else {
false
}
};
if pressed(KeyCode::KeyA) {
movement.x -= 1.0;
}
if pressed(KeyCode::KeyD) {
movement.x += 1.0;
}
if pressed(KeyCode::KeyW) {
movement.z += 1.0;
}
if pressed(KeyCode::KeyS) {
movement.z -= 1.0;
}
if pressed(KeyCode::KeyE) {
movement.y += 1.0;
}
if pressed(KeyCode::KeyQ) {
movement.y -= 1.0;
}
state.world.renderer.as_mut().unwrap().eye.control(movement * 0.1);
match state.world.renderer.as_mut().unwrap().render(&state.window) {
Ok(_) => {}
Err(e) => {
// Log the error and exit gracefully
log::error!("{e}");
event_loop.exit();
}
}
for object in state.clients.iter() {
object.0.borrow_mut().model.as_mut().unwrap().instance.transform *= Mat4::from_rotation_translation(
Quat::from_euler(EulerRot::XYZ,0.001,-0.001,0.001),
Vec3::new(0.0,0.0,0.0)
);
}
}
WindowEvent::MouseInput { button, state: element, .. } => state.handle_mouse_button(button,element),
WindowEvent::CursorMoved { position: pos, .. } => state.handle_mouse_moved(pos),
WindowEvent::KeyboardInput {
event:
KeyEvent {
physical_key: PhysicalKey::Code(code),
state: key_state,
..
},
..
} => state.handle_key(event_loop, code, key_state.is_pressed()),
_ => {}
}
}
}
pub fn run() -> anyhow::Result<()> {
#[cfg(not(target_arch = "wasm32"))]
{
env_logger::init();
}
#[cfg(target_arch = "wasm32")]
{
console_log::init_with_level(log::Level::Info).unwrap_throw();
}
let event_loop = EventLoop::with_user_event().build()?;
#[cfg(not(target_arch = "wasm32"))]
{
let mut app = App::new();
event_loop.run_app(&mut app)?;
}
#[cfg(target_arch = "wasm32")]
{
let app = App::new(&event_loop);
event_loop.spawn_app(app);
}
Ok(())
}
#[cfg(target_arch = "wasm32")]
#[wasm_bindgen(start)]
pub fn run_web() -> Result<(), wasm_bindgen::JsValue> {
console_error_panic_hook::set_once();
run().unwrap_throw();
Ok(())
}