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.

310 lines
7.5 KiB

extern crate tobj;
extern crate winit;
extern crate ncollide3d;
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, Decomposed, Quaternion, Rotation3, Deg, InnerSpace, SquareMatrix};
use futures::task::LocalSpawn;
use legion::*;
use wgpu::{BindGroup, Buffer, TextureView};
use wgpu_subscriber;
use winit::platform::unix::x11::ffi::Time;
use winit::{
event::{self, WindowEvent},
event_loop::{ControlFlow, EventLoop},
};
use crate::render::Renderer;
use winit::event::DeviceEvent::MouseMotion;
mod framework;
mod geometry;
mod light;
mod render;
/*
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<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,
);
#[allow(dead_code)]
pub fn cast_slice<T>(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::<T>()) }
}
#[allow(dead_code)]
pub enum ShaderStage {
Vertex,
Fragment,
Compute,
}
// 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, Debug)]
pub struct DirectionalLight {
color: wgpu::Color,
fov: f32,
depth: RangeCopy<f32>,
target_view: Arc<TextureView>,
}
#[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>,
}
//log::info!("");
fn main() {
let mut world = World::default();
let (mut pool, spawner) = {
let local_pool = futures::executor::LocalPool::new();
let spawner = local_pool.spawner();
(local_pool, spawner)
};
// Schedule for the render systen
let mut render_schedule = Schedule::builder()
.add_system(render::render_test_system())
.build();
// TODO schedule for the update system and others
let event_loop = EventLoop::new();
let mut builder = winit::window::WindowBuilder::new();
builder = builder.with_title("MVGE");
// 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();
let mut last_update_inst = Instant::now();
// Load up the renderer (and the resources)
let mut renderer = {
let mut renderer = render::Renderer::init(&window);
entity_loading(&mut world, &mut renderer);
renderer
};
let mut resources = Resources::default();
resources.insert(renderer);
event_loop.run(move |event, _, control_flow| {
// Artificially slows the loop rate to 10 millis
// This is called after redraw events cleared
*control_flow = ControlFlow::WaitUntil(Instant::now() + Duration::from_millis(10));
match event {
event::Event::MainEventsCleared => {
// 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();
}
event::Event::DeviceEvent {
event: MouseMotion{ delta },
..
} => {
resources
.get_mut::<Renderer>()
.unwrap()
.cam_look_delta((delta.0, delta.1));
//swap_chain = device.create_swap_chain(&surface, &sc_desc);
},
// 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;
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(_) => {
// Call the render system
render_schedule.execute(&mut world, &mut resources);
}
_ => {}
}
});
}
pub fn entity_loading(world: &mut World, renderer: &mut Renderer) {
let untitled_mesh =
renderer.load_mesh_to_buffer("./resources/monkey.obj");
// This could be used for relationships between entities...???
let light_entity: Entity = world.push((
cgmath::Point3 {
x: 7.0 as f32,
y: -5.0 as f32,
z: 10.0 as f32,
},
renderer.create_light(),
));
let light_entity: Entity = world.push((
cgmath::Point3 {
x: -5.0 as f32,
y: 7.0 as f32,
z: 10.0 as f32,
},
renderer.create_light(),
));
let offset = cgmath::vec3(2.0, 2.0, 2.0);
let transform = Decomposed {
disp: offset.clone(),
rot: Quaternion::from_axis_angle(offset.normalize(), Deg(50.0)),
scale: 1.0,
};
let mesh_entity: Entity = world.push((
Position {
x: 17.0,
y: 15.0,
z: 10.0,
mx: cgmath::Matrix4::from(transform),
},
untitled_mesh,
Color {
r: 1.0,
g: 0.5,
b: 0.5,
a: 1.0,
},
));
let plane_mesh =
renderer.create_plane(7.0);
let plane_entity: Entity = world.push((
Position {
x: 0.0,
y: 0.0,
z: 0.0,
mx: cgmath::Matrix4::identity(),
},
plane_mesh,
Color {
r: 1.0,
g: 0.5,
b: 0.5,
a: 1.0,
},
));
}