You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

422 lines
12 KiB

extern crate tobj;
extern crate winit;
4 years ago
#[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},
};
4 years ago
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::*;
4 years ago
4 years ago
mod framework;
mod geometry;
mod light;
mod render;
mod runtime;
4 years ago
/*
4 years ago
Collision detection
https://crates.io/crates/mgf
4 years ago
Obj file format
http://paulbourke.net/dataformats/obj/
4 years ago
tobj obj loader
https://docs.rs/tobj/2.0.3/tobj/index.html
4 years ago
mesh generator lib, might be useful
https://docs.rs/genmesh/0.6.2/genmesh/
4 years ago
legion ECS
https://github.com/amethyst/legion
4 years ago
4 years ago
mvp:
4 years ago
ECS
animation
render 3d
input/io
collision / physics
entities & behaviours
4 years ago
*/
4 years ago
#[cfg_attr(rustfmt, rustfmt_skip)]
#[allow(unused)]
pub const OPENGL_TO_WGPU_MATRIX: cgmath::Matrix4<f32> = 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,
);
4 years ago
#[allow(dead_code)]
pub fn cast_slice<T>(data: &[T]) -> &[u8] {
use std::{mem::size_of, slice::from_raw_parts};
4 years ago
unsafe { from_raw_parts(data.as_ptr() as *const u8, data.len() * size_of::<T>()) }
4 years ago
}
#[allow(dead_code)]
pub enum ShaderStage {
Vertex,
Fragment,
Compute,
4 years ago
}
/*
window: winit::window::Window,
event_loop: EventLoop<()>,
instance: wgpu::Instance,
size: winit::dpi::PhysicalSize<u32>,
surface: wgpu::Surface,
adapter: wgpu::Adapter,
device: wgpu::Device,
queue: wgpu::Queue,
*/
4 years ago
// a component is any type that is 'static, sized, send and sync
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Position {
x: f32,
y: f32,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Velocity {
dx: f32,
dy: f32,
}
#[derive(Clone, Default, PartialEq, Eq, Hash, Copy, Debug)]
pub struct RangeCopy<Idx> {
pub start: Idx,
pub end: Idx,
}
#[derive(Clone, Copy, Debug, PartialEq)]
struct DirectionalLight {
color: wgpu::Color,
fov: f32,
depth: RangeCopy<f32>
}
#[derive(Clone, Debug)]
struct Mesh {
index_buffer: Rc<Buffer>,
vertex_buffer: Rc<Buffer>,
}
fn main() {
4 years ago
// #[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");
4 years ago
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::<f32>().unwrap(), &12f32);
}
*/
// construct a schedule (you should do this on init)
let mut schedule = Schedule::builder()
.add_system(render::render_test_system())
.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::<Position>::query();
// you can then iterate through the components found in the world
for position in query.iter(&world) {
println!("{:?}", position);
}
4 years ago
let event_loop = EventLoop::new();
let mut builder = winit::window::WindowBuilder::new();
4 years ago
builder = builder.with_title("title");
4 years ago
// 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);
}
4 years ago
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)
4 years ago
};
let adapter =
4 years ago
instance
.request_adapter(&wgpu::RequestAdapterOptions {
power_preference: wgpu::PowerPreference::HighPerformance,
compatible_surface: Some(&surface),
});
let adapter = futures::executor::block_on(adapter).unwrap();
4 years ago
let optional_features = Renderer::optional_features();
let required_features = Renderer::required_features();
let adapter_features = adapter.features();
4 years ago
// assert!(
// adapter_features.contains(required_features),
// "Adapter does not support required features for this example: {:?}",
// required_features - adapter_features
// );
4 years ago
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,
4 years ago
},
trace_dir.ok().as_ref().map(std::path::Path::new),
);
4 years ago
let (device, queue) = futures::executor::block_on(device).unwrap();
4 years ago
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))
}
4 years ago
}
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()
4 years ago
})
.expect("couldn't append canvas to document body");
WebSpawner {}
};*/
4 years ago
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,
};
4 years ago
let mut swap_chain = device.create_swap_chain(&surface, &sc_desc);
log::info!("Done doing the loading part...");
4 years ago
// 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...");
4 years ago
4 years ago
// Load up the renderer (and the resources)
let mut renderer = render::Renderer::init(device.clone(), &sc_desc);
4 years ago
let (plane_vertex_buffer, plane_index_buffer) = Renderer::load_mesh_to_buffer(device.clone(), "./resources/untitled.obj");
4 years ago
// Init, this wants the references to the buffers...
let mut runtime = runtime::Runtime::init(&sc_desc, &device, &queue);
let mut resources = Resources::default();
resources.insert(runtime);
resources.insert(renderer);
4 years ago
// 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
4 years ago
}
};
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) {
schedule.execute(&mut world, &mut resources);
window.request_redraw();
last_update_inst = Instant::now();
}
pool.run_until_stalled();
}
#[cfg(target_arch = "wasm32")]
window.request_redraw();
4 years ago
}
// 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;
4 years ago
resources.get_mut::<Renderer>().unwrap().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,
..
4 years ago
},
..
}
| 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!")
}
};
resources.get_mut::<Renderer>().unwrap().render(&frame.output, &device, &queue, &spawner);
4 years ago
}
_ => {}
4 years ago
}
});
4 years ago
//framework::run::<Example>("shadow");
4 years ago
}