extern crate tobj; extern crate winit; #[cfg(not(target_arch = "wasm32"))] use std::time::{Duration, Instant}; use futures::task::LocalSpawn; use wgpu_subscriber; use winit::{ event::{self, WindowEvent}, event_loop::{ControlFlow, EventLoop}, }; use crate::render::Renderer; use bytemuck::__core::ops::Range; use cgmath::Point3; use std::rc::Rc; use wgpu::Buffer; use winit::platform::unix::x11::ffi::Time; use legion::*; mod framework; mod geometry; mod light; mod render; mod runtime; /* Collision detection https://crates.io/crates/mgf Obj file format http://paulbourke.net/dataformats/obj/ tobj obj loader https://docs.rs/tobj/2.0.3/tobj/index.html mesh generator lib, might be useful https://docs.rs/genmesh/0.6.2/genmesh/ legion ECS https://github.com/amethyst/legion mvp: ECS animation render 3d input/io collision / physics entities & behaviours */ #[cfg_attr(rustfmt, rustfmt_skip)] #[allow(unused)] pub const OPENGL_TO_WGPU_MATRIX: cgmath::Matrix4 = cgmath::Matrix4::new( 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.5, 1.0, ); #[allow(dead_code)] pub fn cast_slice(data: &[T]) -> &[u8] { use std::{mem::size_of, slice::from_raw_parts}; unsafe { from_raw_parts(data.as_ptr() as *const u8, data.len() * size_of::()) } } #[allow(dead_code)] pub enum ShaderStage { Vertex, Fragment, Compute, } /* window: winit::window::Window, event_loop: EventLoop<()>, instance: wgpu::Instance, size: winit::dpi::PhysicalSize, surface: wgpu::Surface, adapter: wgpu::Adapter, device: wgpu::Device, queue: wgpu::Queue, */ // a component is any type that is 'static, sized, send and sync #[derive(Clone, Copy, Debug, PartialEq)] struct Position { x: f32, y: f32, } #[derive(Clone, Copy, Debug, PartialEq)] struct Velocity { dx: f32, dy: f32, } #[derive(Clone, Default, PartialEq, Eq, Hash, Copy, Debug)] pub struct RangeCopy { pub start: Idx, pub end: Idx, } #[derive(Clone, Copy, Debug, PartialEq)] struct DirectionalLight { color: wgpu::Color, fov: f32, depth: RangeCopy } #[derive(Clone, Debug)] struct Mesh { index_buffer: Rc, vertex_buffer: Rc, } fn main() { // #[cfg(not(target_arch = "wasm32"))] // { // let chrome_tracing_dir = std::env::var("WGPU_CHROME_TRACE"); // wgpu_subscriber::initialize_default_subscriber( // chrome_tracing_dir.as_ref().map(std::path::Path::new).ok(), // ); // }; // #[cfg(target_arch = "wasm32")] // console_log::init().expect("could not initialize logger"); use legion::*; let mut world = World::default(); // This could be used for relationships between entities...??? let entity: Entity = world.push(( cgmath::Point3 { x: -5.0, y: 7.0, z: 10.0, }, DirectionalLight { color: wgpu::Color { r: 1.0, g: 0.5, b: 0.5, a: 1.0, }, fov: 45.0, depth: RangeCopy { start: 1.0, end: 20.0 }, } )); let entities: &[Entity] = world.extend(vec![ (Position { x: 0.0, y: 0.0 }, Velocity { dx: 0.0, dy: 0.0 }), (Position { x: 1.0, y: 1.0 }, Velocity { dx: 0.0, dy: 0.0 }), (Position { x: 2.0, y: 2.0 }, Velocity { dx: 0.0, dy: 0.0 }), ]); /* Querying entities by their handle // entries return `None` if the entity does not exist if let Some(mut entry) = world.entry(entity) { // access information about the entity's archetype //println!("{:?} has {:?}", entity, entry.archetype().layout().component_types()); // add an extra component //entry.add_component(12f32); // access the entity's components, returns `None` if the entity does not have the component //assert_eq!(entry.get_component::().unwrap(), &12f32); } */ // construct a schedule (you should do this on init) let mut schedule = Schedule::builder() // .add_system(Renderer::render_test) .build(); // run our schedule (you should do this each update) //schedule.execute(&mut world, &mut resources); // Querying entities by component is just defining the component type! let mut query = Read::::query(); // you can then iterate through the components found in the world for position in query.iter(&world) { println!("{:?}", position); } let event_loop = EventLoop::new(); let mut builder = winit::window::WindowBuilder::new(); builder = builder.with_title("title"); // I don't know what they are doing here #[cfg(windows_OFF)] // TODO { use winit::platform::windows::WindowBuilderExtWindows; builder = builder.with_no_redirection_bitmap(true); } let window = builder.build(&event_loop).unwrap(); log::info!("Initializing the surface..."); // Grab the GPU instance, and query its features let instance = wgpu::Instance::new(wgpu::BackendBit::PRIMARY); let (size, surface) = unsafe { let size = window.inner_size(); let surface = instance.create_surface(&window); (size, surface) }; let adapter = instance .request_adapter(&wgpu::RequestAdapterOptions { power_preference: wgpu::PowerPreference::HighPerformance, compatible_surface: Some(&surface), }); let adapter = futures::executor::block_on(adapter).unwrap(); let optional_features = Renderer::optional_features(); let required_features = Renderer::required_features(); let adapter_features = adapter.features(); // assert!( // adapter_features.contains(required_features), // "Adapter does not support required features for this example: {:?}", // required_features - adapter_features // ); let needed_limits = wgpu::Limits::default();//Renderer::required_limits(); // Maybe for debug tracing??? let trace_dir = std::env::var("WGPU_TRACE"); // And then get the device we want let device = adapter .request_device( &wgpu::DeviceDescriptor { features: (optional_features & adapter_features) | required_features, limits: needed_limits, shader_validation: true, }, trace_dir.ok().as_ref().map(std::path::Path::new), ); let (device, queue) = futures::executor::block_on(device).unwrap(); let device = Rc::new(device); #[cfg(not(target_arch = "wasm32"))] let (mut pool, spawner) = { let local_pool = futures::executor::LocalPool::new(); let spawner = local_pool.spawner(); (local_pool, spawner) }; // This is some gross-ass web shit /*#[cfg(target_arch = "wasm32")] let spawner = { use futures::{future::LocalFutureObj, task::SpawnError}; use winit::platform::web::WindowExtWebSys; struct WebSpawner {} impl LocalSpawn for WebSpawner { fn spawn_local_obj( &self, future: LocalFutureObj<'static, ()>, ) -> Result<(), SpawnError> { Ok(wasm_bindgen_futures::spawn_local(future)) } } std::panic::set_hook(Box::new(console_error_panic_hook::hook)); // On wasm, append the canvas to the document body web_sys::window() .and_then(|win| win.document()) .and_then(|doc| doc.body()) .and_then(|body| { body.append_child(&web_sys::Element::from(window.canvas())) .ok() }) .expect("couldn't append canvas to document body"); WebSpawner {} };*/ let mut sc_desc = wgpu::SwapChainDescriptor { // Allows a texture to be a output attachment of a renderpass. usage: wgpu::TextureUsage::OUTPUT_ATTACHMENT, format: if cfg!(target_arch = "wasm32") { wgpu::TextureFormat::Bgra8Unorm } else { wgpu::TextureFormat::Bgra8UnormSrgb }, width: size.width, height: size.height, // The presentation engine waits for the next vertical blanking period to update present_mode: wgpu::PresentMode::Mailbox, }; let mut swap_chain = device.create_swap_chain(&surface, &sc_desc); log::info!("Done doing the loading part..."); // Not sure why this is guarded, maybe we don't handle the event loop timing? #[cfg(not(target_arch = "wasm32"))] let mut last_update_inst = Instant::now(); log::info!("Entering render loop..."); // Load up the renderer (and the resources) let mut renderer = render::Renderer::init(device.clone(), &sc_desc); let (plane_vertex_buffer, plane_index_buffer) = Renderer::load_mesh_to_buffer(device.clone(), "plane.obj"); // Init, this wants the references to the buffers... let mut runtime = runtime::Runtime::init(&sc_desc, &device, &queue); // This is just an winit event loop event_loop.run(move |event, _, control_flow| { let _ = (&instance, &adapter); // force ownership by the closure (wtf??) // Override the control flow behaviour based on our system *control_flow = if cfg!(feature = "metal-auto-capture") { ControlFlow::Exit } else { #[cfg(not(target_arch = "wasm32"))] { // Artificially slows the loop rate to 10 millis // This is called after redraw events cleared ControlFlow::WaitUntil(Instant::now() + Duration::from_millis(10)) } #[cfg(target_arch = "wasm32")] { ControlFlow::Poll } }; match event { event::Event::MainEventsCleared => { #[cfg(not(target_arch = "wasm32"))] { // ask for a redraw every 20 millis if last_update_inst.elapsed() > Duration::from_millis(20) { window.request_redraw(); last_update_inst = Instant::now(); } pool.run_until_stalled(); } #[cfg(target_arch = "wasm32")] window.request_redraw(); } // Resizing will queue a request_redraw event::Event::WindowEvent { event: WindowEvent::Resized(size), .. } => { log::info!("Resizing to {:?}", size); sc_desc.width = size.width; sc_desc.height = size.height; renderer.resize(&sc_desc, &device, &queue); swap_chain = device.create_swap_chain(&surface, &sc_desc); } event::Event::WindowEvent { event, .. } => match event { WindowEvent::KeyboardInput { input: event::KeyboardInput { virtual_keycode: Some(event::VirtualKeyCode::Escape), state: event::ElementState::Pressed, .. }, .. } | WindowEvent::CloseRequested => { *control_flow = ControlFlow::Exit; } _ => { //renderer.update(event); } }, event::Event::RedrawRequested(_) => { let frame = match swap_chain.get_current_frame() { Ok(frame) => frame, Err(_) => { swap_chain = device.create_swap_chain(&surface, &sc_desc); swap_chain .get_current_frame() .expect("Failed to acquire next swap chain texture!") } }; renderer.render(&frame.output, &device, &queue, &spawner); } _ => {} } }); //framework::run::("shadow"); }