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.

389 lines
10 KiB

extern crate tobj;
extern crate winit;
use std::rc::Rc;
use std::sync::Arc;
#[cfg(not(target_arch = "wasm32"))]
use std::time::{Duration, Instant};
use bytemuck::__core::ops::Range;
use cgmath::{Matrix4, Point3};
use futures::task::LocalSpawn;
use legion::*;
use wgpu::{BindGroup, Buffer};
use wgpu_subscriber;
use winit::platform::unix::x11::ffi::Time;
use winit::{
event::{self, WindowEvent},
event_loop::{ControlFlow, EventLoop},
};
4 years ago
use crate::render::Renderer;
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,
z: f32,
mx: Matrix4<f32>,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Color {
r: f32,
g: f32,
b: f32,
a: f32,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Velocity {
dx: f32,
dy: f32,
rs: 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)]
pub struct Mesh {
index_buffer: Arc<Buffer>,
index_count: usize,
vertex_buffer: Arc<Buffer>,
uniform_buffer: Arc<Buffer>,
bind_group: Arc<BindGroup>,
}
4 years ago
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");
4 years ago
use legion::*;
let mut world = World::default();
/*
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);
}
*/
#[cfg(not(target_arch = "wasm32"))]
let (mut pool, spawner) = {
let local_pool = futures::executor::LocalPool::new();
let spawner = local_pool.spawner();
(local_pool, spawner)
};
let mut render_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
// I think right here is where I can start pulling everything into the renderer
let window = builder.build(&event_loop).unwrap();
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(window);
let untitled_mesh =
renderer.load_mesh_to_buffer("./resources/untitled.obj");
// This could be used for relationships between entities...???
let light_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 mesh_entity: Entity = world.push((
Position {
x: -5.0,
y: 7.0,
z: 10.0,
mx: OPENGL_TO_WGPU_MATRIX,
},
untitled_mesh,
Color {
r: 1.0,
g: 0.5,
b: 0.5,
a: 1.0,
},
));
4 years ago
let entities: &[Entity] = world.extend(vec![
(
Position {
x: 0.0,
y: 0.0,
z: 0.0,
mx: OPENGL_TO_WGPU_MATRIX,
},
Velocity {
dx: 0.0,
dy: 0.0,
rs: 0.0,
},
),
(
Position {
x: 1.0,
y: 1.0,
z: 0.0,
mx: OPENGL_TO_WGPU_MATRIX,
},
Velocity {
dx: 0.0,
dy: 0.0,
rs: 0.0,
},
),
(
Position {
x: 2.0,
y: 2.0,
z: 0.0,
mx: OPENGL_TO_WGPU_MATRIX,
},
Velocity {
dx: 0.0,
dy: 0.0,
rs: 0.0,
},
),
]);
4 years ago
// Init, this wants the references to the buffers...
let mut runtime = runtime::Runtime::init();
4 years ago
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
}
};
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();
resources
.get_mut::<Renderer>()
.unwrap()
.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);
let width = size.width;
let height = size.height;
4 years ago
resources
.get_mut::<Renderer>()
.unwrap()
.resize(width, height);
//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(_) => {
render_schedule.execute(&mut world, &mut resources);
//resources.get_mut::<Renderer>().unwrap().render();
4 years ago
}
_ => {}
4 years ago
}
});
4 years ago
}