Compare commits
29 Commits
worker-poo
...
graphics-t
| Author | SHA1 | Date | |
|---|---|---|---|
| 14f3b4fb0d | |||
| 6377885d6d | |||
| f81a1c82bf | |||
| 2ee70138d1 | |||
| f14b30138b | |||
| 2116621672 | |||
| e2fdf9442c | |||
| 75f958348c | |||
| b5a0cf7045 | |||
| 657e5dff7f | |||
| 5d9308eccc | |||
| b7844bb308 | |||
| 8113ede3e0 | |||
| 4cf10dad78 | |||
| de063f4d74 | |||
| 83cdb0413c | |||
| 4655f43f5f | |||
| 9c9d8f8f8f | |||
| cbc7b56f28 | |||
| 44831bd14b | |||
| 099915c980 | |||
| 62e8953ba9 | |||
| 03a4a60db2 | |||
| c4ad4fbdf9 | |||
| b445277346 | |||
| f6f2995ae0 | |||
| 4cad20da09 | |||
| 7805c4db6d | |||
| 3775fd0b14 |
718
Cargo.lock
generated
718
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
@@ -19,7 +19,7 @@ rbx_dom_weak = "2.5.0"
|
|||||||
rbx_reflection_database = "0.2.7"
|
rbx_reflection_database = "0.2.7"
|
||||||
rbx_xml = "0.13.1"
|
rbx_xml = "0.13.1"
|
||||||
wgpu = "0.17.0"
|
wgpu = "0.17.0"
|
||||||
winit = "0.28.6"
|
winit = { version = "0.29.2", features = ["rwh_05"] }
|
||||||
|
|
||||||
#[profile.release]
|
#[profile.release]
|
||||||
#lto = true
|
#lto = true
|
||||||
|
|||||||
21
src/compat_worker.rs
Normal file
21
src/compat_worker.rs
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
pub type QNWorker<'a,Task>=CompatNWorker<'a,Task>;
|
||||||
|
pub type INWorker<'a,Task>=CompatNWorker<'a,Task>;
|
||||||
|
|
||||||
|
pub struct CompatNWorker<'a,Task>{
|
||||||
|
data:std::marker::PhantomData<Task>,
|
||||||
|
f:Box<dyn FnMut(Task)+'a>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a,Task> CompatNWorker<'a,Task>{
|
||||||
|
pub fn new(f:impl FnMut(Task)+'a)->CompatNWorker<'a,Task>{
|
||||||
|
Self{
|
||||||
|
data:std::marker::PhantomData,
|
||||||
|
f:Box::new(f),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn send(&mut self,task:Task)->Result<(),()>{
|
||||||
|
(self.f)(task);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -8,12 +8,6 @@ pub struct ModelUpdate{
|
|||||||
color:Option<glam::Vec4>,
|
color:Option<glam::Vec4>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone)]
|
|
||||||
pub enum GraphicsInstruction{
|
|
||||||
UpdateModel(ModelUpdate),
|
|
||||||
Render,
|
|
||||||
}
|
|
||||||
|
|
||||||
struct Entity {
|
struct Entity {
|
||||||
index_count: u32,
|
index_count: u32,
|
||||||
index_buf: wgpu::Buffer,
|
index_buf: wgpu::Buffer,
|
||||||
@@ -91,6 +85,14 @@ impl GraphicsCamera{
|
|||||||
raw
|
raw
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
impl std::default::Default for GraphicsCamera{
|
||||||
|
fn default()->Self{
|
||||||
|
Self{
|
||||||
|
screen_size:glam::UVec2::ONE,
|
||||||
|
fov:glam::Vec2::ONE,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub struct GraphicsState{
|
pub struct GraphicsState{
|
||||||
pipelines: GraphicsPipelines,
|
pipelines: GraphicsPipelines,
|
||||||
@@ -134,7 +136,7 @@ impl GraphicsState{
|
|||||||
pub fn load_user_settings(&mut self,user_settings:&crate::settings::UserSettings){
|
pub fn load_user_settings(&mut self,user_settings:&crate::settings::UserSettings){
|
||||||
self.camera.fov=user_settings.calculate_fov(1.0,&self.camera.screen_size).as_vec2();
|
self.camera.fov=user_settings.calculate_fov(1.0,&self.camera.screen_size).as_vec2();
|
||||||
}
|
}
|
||||||
fn generate_model_graphics(&mut self,device:&wgpu::Device,queue:&wgpu::Queue,indexed_models:crate::model::IndexedModelInstances){
|
pub fn generate_models(&mut self,device:&wgpu::Device,queue:&wgpu::Queue,indexed_models:crate::model::IndexedModelInstances){
|
||||||
//generate texture view per texture
|
//generate texture view per texture
|
||||||
|
|
||||||
//idk how to do this gooder lol
|
//idk how to do this gooder lol
|
||||||
@@ -454,7 +456,7 @@ impl GraphicsState{
|
|||||||
//.into_iter() the modeldata vec so entities can be /moved/ to models.entities
|
//.into_iter() the modeldata vec so entities can be /moved/ to models.entities
|
||||||
let mut model_count=0;
|
let mut model_count=0;
|
||||||
let mut instance_count=0;
|
let mut instance_count=0;
|
||||||
let uniform_buffer_binding_size=crate::graphics_context::required_limits().max_uniform_buffer_binding_size as usize;
|
let uniform_buffer_binding_size=crate::setup::required_limits().max_uniform_buffer_binding_size as usize;
|
||||||
let chunk_size=uniform_buffer_binding_size/MODEL_BUFFER_SIZE_BYTES;
|
let chunk_size=uniform_buffer_binding_size/MODEL_BUFFER_SIZE_BYTES;
|
||||||
self.models.reserve(models.len());
|
self.models.reserve(models.len());
|
||||||
for model in models.into_iter() {
|
for model in models.into_iter() {
|
||||||
@@ -528,10 +530,9 @@ impl GraphicsState{
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn new(
|
pub fn new(
|
||||||
config: &wgpu::SurfaceConfiguration,
|
device:&wgpu::Device,
|
||||||
_adapter: &wgpu::Adapter,
|
queue:&wgpu::Queue,
|
||||||
device: &wgpu::Device,
|
config:&wgpu::SurfaceConfiguration,
|
||||||
queue: &wgpu::Queue,
|
|
||||||
)->Self{
|
)->Self{
|
||||||
let camera_bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
let camera_bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||||
label: None,
|
label: None,
|
||||||
@@ -814,14 +815,8 @@ impl GraphicsState{
|
|||||||
multiview: None,
|
multiview: None,
|
||||||
});
|
});
|
||||||
|
|
||||||
let mut physics = crate::physics::PhysicsState::default();
|
let camera=GraphicsCamera::default();
|
||||||
|
let camera_uniforms = camera.to_uniform_data(crate::physics::PhysicsOutputState::default().extrapolate(glam::IVec2::ZERO,crate::integer::Time::ZERO));
|
||||||
physics.load_user_settings(&user_settings);
|
|
||||||
|
|
||||||
let screen_size=glam::uvec2(config.width,config.height);
|
|
||||||
|
|
||||||
let camera=GraphicsCamera::new(screen_size,user_settings.calculate_fov(1.0,&screen_size).as_vec2());
|
|
||||||
let camera_uniforms = camera.to_uniform_data(physics.output().adjust_mouse(&crate::physics::MouseState::default()));
|
|
||||||
let camera_buf = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
let camera_buf = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||||
label: Some("Camera"),
|
label: Some("Camera"),
|
||||||
contents: bytemuck::cast_slice(&camera_uniforms),
|
contents: bytemuck::cast_slice(&camera_uniforms),
|
||||||
@@ -876,32 +871,30 @@ impl GraphicsState{
|
|||||||
}
|
}
|
||||||
pub fn resize(
|
pub fn resize(
|
||||||
&mut self,
|
&mut self,
|
||||||
context:&crate::graphics_context::GraphicsContext,
|
device:&wgpu::Device,
|
||||||
|
config:&wgpu::SurfaceConfiguration,
|
||||||
|
user_settings:&crate::settings::UserSettings,
|
||||||
) {
|
) {
|
||||||
self.depth_view = Self::create_depth_texture(&context.config,&context.device);
|
self.depth_view = Self::create_depth_texture(config,device);
|
||||||
self.camera.screen_size=glam::uvec2(context.config.width, context.config.height);
|
self.camera.screen_size=glam::uvec2(config.width, config.height);
|
||||||
self.load_user_settings(&self.user_settings);
|
self.load_user_settings(user_settings);
|
||||||
}
|
}
|
||||||
pub fn render(
|
pub fn render(
|
||||||
&mut self,
|
&mut self,
|
||||||
view: &wgpu::TextureView,
|
view:&wgpu::TextureView,
|
||||||
device: &wgpu::Device,
|
device:&wgpu::Device,
|
||||||
queue: &wgpu::Queue,
|
queue:&wgpu::Queue,
|
||||||
|
physics_output:crate::physics::PhysicsOutputState,
|
||||||
|
predicted_time:crate::integer::Time,
|
||||||
|
mouse_pos:glam::IVec2,
|
||||||
) {
|
) {
|
||||||
//ideally this would be scheduled to execute and finish right before the render.
|
//TODO: use scheduled frame times to create beautiful smoothing simulation physics extrapolation assuming no input
|
||||||
let time=crate::integer::Time::from_nanos(self.start_time.elapsed().as_nanos() as i64);
|
|
||||||
self.physics_thread.send(crate::instruction::TimedInstruction{
|
|
||||||
time,
|
|
||||||
instruction:crate::render_thread::InputInstruction::Idle,
|
|
||||||
}).unwrap();
|
|
||||||
//update time lol
|
|
||||||
self.mouse.time=time;
|
|
||||||
|
|
||||||
let mut encoder =
|
let mut encoder =
|
||||||
device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None });
|
device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None });
|
||||||
|
|
||||||
// update rotation
|
// update rotation
|
||||||
let camera_uniforms = self.camera.to_uniform_data(self.physics_thread.grab_clone().adjust_mouse(&self.mouse));
|
let camera_uniforms = self.camera.to_uniform_data(physics_output.extrapolate(mouse_pos,predicted_time));
|
||||||
self.staging_belt
|
self.staging_belt
|
||||||
.write_buffer(
|
.write_buffer(
|
||||||
&mut encoder,
|
&mut encoder,
|
||||||
|
|||||||
62
src/graphics_worker.rs
Normal file
62
src/graphics_worker.rs
Normal file
@@ -0,0 +1,62 @@
|
|||||||
|
pub enum Instruction{
|
||||||
|
Render(crate::physics::PhysicsOutputState,crate::integer::Time,glam::IVec2),
|
||||||
|
//UpdateModel(crate::graphics::ModelUpdate),
|
||||||
|
Resize(winit::dpi::PhysicalSize<u32>,crate::settings::UserSettings),
|
||||||
|
GenerateModels(crate::model::IndexedModelInstances),
|
||||||
|
ClearModels,
|
||||||
|
}
|
||||||
|
|
||||||
|
//Ideally the graphics thread worker description is:
|
||||||
|
/*
|
||||||
|
WorkerDescription{
|
||||||
|
input:Immediate,
|
||||||
|
output:Realtime(PoolOrdering::Ordered(3)),
|
||||||
|
}
|
||||||
|
*/
|
||||||
|
//up to three frames in flight, dropping new frame requests when all three are busy, and dropping output frames when one renders out of order
|
||||||
|
|
||||||
|
pub fn new<'a>(
|
||||||
|
mut graphics:crate::graphics::GraphicsState,
|
||||||
|
mut config:wgpu::SurfaceConfiguration,
|
||||||
|
surface:wgpu::Surface,
|
||||||
|
device:wgpu::Device,
|
||||||
|
queue:wgpu::Queue,
|
||||||
|
)->crate::compat_worker::INWorker<'a,Instruction>{
|
||||||
|
crate::compat_worker::INWorker::new(move |ins:Instruction|{
|
||||||
|
match ins{
|
||||||
|
Instruction::GenerateModels(indexed_model_instances)=>{
|
||||||
|
graphics.generate_models(&device,&queue,indexed_model_instances);
|
||||||
|
},
|
||||||
|
Instruction::ClearModels=>{
|
||||||
|
graphics.clear();
|
||||||
|
},
|
||||||
|
Instruction::Resize(size,user_settings)=>{
|
||||||
|
println!("Resizing to {:?}",size);
|
||||||
|
config.width=size.width.max(1);
|
||||||
|
config.height=size.height.max(1);
|
||||||
|
surface.configure(&device,&config);
|
||||||
|
graphics.resize(&device,&config,&user_settings);
|
||||||
|
}
|
||||||
|
Instruction::Render(physics_output,predicted_time,mouse_pos)=>{
|
||||||
|
//this has to go deeper somehow
|
||||||
|
let frame=match surface.get_current_texture(){
|
||||||
|
Ok(frame)=>frame,
|
||||||
|
Err(_)=>{
|
||||||
|
surface.configure(&device,&config);
|
||||||
|
surface
|
||||||
|
.get_current_texture()
|
||||||
|
.expect("Failed to acquire next surface texture!")
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let view=frame.texture.create_view(&wgpu::TextureViewDescriptor{
|
||||||
|
format:Some(config.view_formats[0]),
|
||||||
|
..wgpu::TextureViewDescriptor::default()
|
||||||
|
});
|
||||||
|
|
||||||
|
graphics.render(&view,&device,&queue,physics_output,predicted_time,mouse_pos);
|
||||||
|
|
||||||
|
frame.present();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -41,6 +41,11 @@ impl std::fmt::Display for Time{
|
|||||||
write!(f,"{}s+{:09}ns",self.0/Self::ONE_SECOND.0,self.0%Self::ONE_SECOND.0)
|
write!(f,"{}s+{:09}ns",self.0/Self::ONE_SECOND.0,self.0%Self::ONE_SECOND.0)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
impl std::default::Default for Time{
|
||||||
|
fn default()->Self{
|
||||||
|
Self(0)
|
||||||
|
}
|
||||||
|
}
|
||||||
impl std::ops::Neg for Time{
|
impl std::ops::Neg for Time{
|
||||||
type Output=Time;
|
type Output=Time;
|
||||||
#[inline]
|
#[inline]
|
||||||
|
|||||||
77
src/main.rs
77
src/main.rs
@@ -1,11 +1,7 @@
|
|||||||
use std::time::Instant;
|
|
||||||
use physics::PhysicsInstruction;
|
|
||||||
use render_thread::InputInstruction;
|
|
||||||
use instruction::{TimedInstruction, InstructionConsumer};
|
|
||||||
|
|
||||||
mod bvh;
|
mod bvh;
|
||||||
mod aabb;
|
mod aabb;
|
||||||
mod model;
|
mod model;
|
||||||
|
mod setup;
|
||||||
mod window;
|
mod window;
|
||||||
mod worker;
|
mod worker;
|
||||||
mod zeroes;
|
mod zeroes;
|
||||||
@@ -16,27 +12,10 @@ mod settings;
|
|||||||
mod primitives;
|
mod primitives;
|
||||||
mod instruction;
|
mod instruction;
|
||||||
mod load_roblox;
|
mod load_roblox;
|
||||||
mod render_thread;
|
mod compat_worker;
|
||||||
mod model_graphics;
|
mod model_graphics;
|
||||||
mod graphics_context;
|
mod physics_worker;
|
||||||
|
mod graphics_worker;
|
||||||
|
|
||||||
pub struct GlobalState{
|
|
||||||
start_time: std::time::Instant,
|
|
||||||
manual_mouse_lock:bool,
|
|
||||||
mouse:std::sync::Arc<std::sync::Mutex<physics::MouseState>>,
|
|
||||||
user_settings:settings::UserSettings,
|
|
||||||
//Ideally the graphics thread worker description is:
|
|
||||||
/*
|
|
||||||
WorkerDescription{
|
|
||||||
input:Immediate,
|
|
||||||
output:Realtime(PoolOrdering::Ordered(3)),
|
|
||||||
}
|
|
||||||
*/
|
|
||||||
//up to three frames in flight, dropping new frame requests when all three are busy, and dropping output frames when one renders out of order
|
|
||||||
graphics_thread:worker::INWorker<graphics::GraphicsInstruction>,
|
|
||||||
physics_thread:worker::QNWorker<TimedInstruction<InputInstruction>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
fn load_file(path: std::path::PathBuf)->Option<model::IndexedModelInstances>{
|
fn load_file(path: std::path::PathBuf)->Option<model::IndexedModelInstances>{
|
||||||
println!("Loading file: {:?}", &path);
|
println!("Loading file: {:?}", &path);
|
||||||
@@ -83,7 +62,7 @@ fn load_file(path: std::path::PathBuf)->Option<model::IndexedModelInstances>{
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn default_models()->model::IndexedModelInstances{
|
pub fn default_models()->model::IndexedModelInstances{
|
||||||
let mut indexed_models = Vec::new();
|
let mut indexed_models = Vec::new();
|
||||||
indexed_models.append(&mut model::generate_indexed_model_list_from_obj(obj::ObjData::load_buf(&include_bytes!("../models/teslacyberv3.0.obj")[..]).unwrap(),glam::Vec4::ONE));
|
indexed_models.append(&mut model::generate_indexed_model_list_from_obj(obj::ObjData::load_buf(&include_bytes!("../models/teslacyberv3.0.obj")[..]).unwrap(),glam::Vec4::ONE));
|
||||||
indexed_models.push(primitives::unit_sphere());
|
indexed_models.push(primitives::unit_sphere());
|
||||||
@@ -139,49 +118,7 @@ fn default_models()->model::IndexedModelInstances{
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl GlobalState {
|
|
||||||
fn init() -> Self {
|
|
||||||
//wee
|
|
||||||
let user_settings=settings::read_user_settings();
|
|
||||||
|
|
||||||
let mut graphics=GraphicsState::new();
|
|
||||||
|
|
||||||
graphics.load_user_settings(&user_settings);
|
|
||||||
|
|
||||||
//how to multithread
|
|
||||||
|
|
||||||
//1. build
|
|
||||||
physics.generate_models(&indexed_model_instances);
|
|
||||||
|
|
||||||
//2. move
|
|
||||||
let physics_thread=physics.into_worker();
|
|
||||||
|
|
||||||
//3. forget
|
|
||||||
|
|
||||||
let mut state=GlobalState{
|
|
||||||
start_time:Instant::now(),
|
|
||||||
manual_mouse_lock:false,
|
|
||||||
mouse:physics::MouseState::default(),
|
|
||||||
user_settings,
|
|
||||||
graphics,
|
|
||||||
physics_thread,
|
|
||||||
};
|
|
||||||
state.generate_model_graphics(&device,&queue,indexed_model_instances);
|
|
||||||
|
|
||||||
let args:Vec<String>=std::env::args().collect();
|
|
||||||
if args.len()==2{
|
|
||||||
let indexed_model_instances=load_file(std::path::PathBuf::from(&args[1]));
|
|
||||||
state.render_thread=RenderThread::new(user_settings,indexed_model_instances);
|
|
||||||
}
|
|
||||||
|
|
||||||
return state;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn main(){
|
fn main(){
|
||||||
let title=format!("Strafe Client v{}",env!("CARGO_PKG_VERSION")).as_str();
|
let context=setup::setup(format!("Strafe Client v{}",env!("CARGO_PKG_VERSION")).as_str());
|
||||||
let context=graphics_context::setup(title);
|
context.start();//creates and runs a window context
|
||||||
let global_state=GlobalState::init();//new
|
|
||||||
global_state.replace_models(&context,default_models());
|
|
||||||
context.start(global_state);
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -31,9 +31,12 @@ pub enum PhysicsInputInstruction {
|
|||||||
SetZoom(bool),
|
SetZoom(bool),
|
||||||
Reset,
|
Reset,
|
||||||
Idle,
|
Idle,
|
||||||
|
//Idle: there were no input events, but the simulation is safe to advance to this timestep
|
||||||
|
//for interpolation / networking / playback reasons, most playback heads will always want
|
||||||
|
//to be 1 instruction ahead to generate the next state for interpolation.
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone,Hash)]
|
#[derive(Clone,Hash,Default)]
|
||||||
pub struct Body {
|
pub struct Body {
|
||||||
position: Planar64Vec3,//I64 where 2^32 = 1 u
|
position: Planar64Vec3,//I64 where 2^32 = 1 u
|
||||||
velocity: Planar64Vec3,//I64 where 2^32 = 1 u/s
|
velocity: Planar64Vec3,//I64 where 2^32 = 1 u/s
|
||||||
@@ -241,6 +244,19 @@ impl PhysicsCamera {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl std::default::Default for PhysicsCamera{
|
||||||
|
fn default()->Self{
|
||||||
|
Self{
|
||||||
|
offset:Planar64Vec3::ZERO,//TODO: delete this from PhysicsCamera, it should be GraphicsCamera only
|
||||||
|
sensitivity:Ratio64Vec2::ONE*200_000,
|
||||||
|
mouse:MouseState::default(),//t=0 does not cause divide by zero because it's immediately replaced
|
||||||
|
clamped_mouse_pos:glam::IVec2::ZERO,
|
||||||
|
angle_pitch_lower_limit:-Angle32::FRAC_PI_2,
|
||||||
|
angle_pitch_upper_limit:Angle32::FRAC_PI_2,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub struct GameMechanicsState{
|
pub struct GameMechanicsState{
|
||||||
pub stage_id:u32,
|
pub stage_id:u32,
|
||||||
//jump_counts:HashMap<u32,u32>,
|
//jump_counts:HashMap<u32,u32>,
|
||||||
@@ -527,14 +543,14 @@ pub struct PhysicsState{
|
|||||||
//This is not the same as Reset which teleports you to Spawn0
|
//This is not the same as Reset which teleports you to Spawn0
|
||||||
spawn_point:Planar64Vec3,
|
spawn_point:Planar64Vec3,
|
||||||
}
|
}
|
||||||
#[derive(Clone)]
|
#[derive(Clone,Default)]
|
||||||
pub struct PhysicsOutputState{
|
pub struct PhysicsOutputState{
|
||||||
camera:PhysicsCamera,
|
camera:PhysicsCamera,
|
||||||
body:Body,
|
body:Body,
|
||||||
}
|
}
|
||||||
impl PhysicsOutputState{
|
impl PhysicsOutputState{
|
||||||
pub fn adjust_mouse(&self,mouse:&MouseState)->(glam::Vec3,glam::Vec2){
|
pub fn extrapolate(&self,mouse_pos:glam::IVec2,time:Time)->(glam::Vec3,glam::Vec2){
|
||||||
((self.body.extrapolated_position(mouse.time)+self.camera.offset).into(),self.camera.simulate_move_angles(mouse.pos))
|
((self.body.extrapolated_position(time)+self.camera.offset).into(),self.camera.simulate_move_angles(mouse_pos))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -718,6 +734,7 @@ impl PhysicsState {
|
|||||||
self.models.clear();
|
self.models.clear();
|
||||||
self.modes.clear();
|
self.modes.clear();
|
||||||
self.touching.clear();
|
self.touching.clear();
|
||||||
|
self.bvh=crate::bvh::BvhNode::default();
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn output(&self)->PhysicsOutputState{
|
pub fn output(&self)->PhysicsOutputState{
|
||||||
|
|||||||
133
src/physics_worker.rs
Normal file
133
src/physics_worker.rs
Normal file
@@ -0,0 +1,133 @@
|
|||||||
|
use crate::integer::Time;
|
||||||
|
use crate::physics::{MouseState,PhysicsInputInstruction};
|
||||||
|
use crate::instruction::{TimedInstruction,InstructionConsumer};
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub enum InputInstruction {
|
||||||
|
MoveMouse(glam::IVec2),
|
||||||
|
MoveRight(bool),
|
||||||
|
MoveUp(bool),
|
||||||
|
MoveBack(bool),
|
||||||
|
MoveLeft(bool),
|
||||||
|
MoveDown(bool),
|
||||||
|
MoveForward(bool),
|
||||||
|
Jump(bool),
|
||||||
|
Zoom(bool),
|
||||||
|
Reset,
|
||||||
|
}
|
||||||
|
pub enum Instruction{
|
||||||
|
Input(InputInstruction),
|
||||||
|
Render,
|
||||||
|
Resize(winit::dpi::PhysicalSize<u32>,crate::settings::UserSettings),
|
||||||
|
GenerateModels(crate::model::IndexedModelInstances),
|
||||||
|
ClearModels,
|
||||||
|
//Graphics(crate::graphics_worker::Instruction),
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn new(mut physics:crate::physics::PhysicsState,mut graphics_worker:crate::compat_worker::INWorker<crate::graphics_worker::Instruction>)->crate::compat_worker::QNWorker<TimedInstruction<Instruction>>{
|
||||||
|
let mut mouse_blocking=true;
|
||||||
|
let mut last_mouse_time=physics.next_mouse.time;
|
||||||
|
let mut timeline=std::collections::VecDeque::new();
|
||||||
|
crate::compat_worker::QNWorker::new(move |ins:TimedInstruction<Instruction>|{
|
||||||
|
if if let Some(phys_input)=match &ins.instruction{
|
||||||
|
Instruction::Input(input_instruction)=>match input_instruction{
|
||||||
|
&InputInstruction::MoveMouse(m)=>{
|
||||||
|
if mouse_blocking{
|
||||||
|
//tell the game state which is living in the past about its future
|
||||||
|
timeline.push_front(TimedInstruction{
|
||||||
|
time:last_mouse_time,
|
||||||
|
instruction:PhysicsInputInstruction::SetNextMouse(MouseState{time:ins.time,pos:m}),
|
||||||
|
});
|
||||||
|
}else{
|
||||||
|
//mouse has just started moving again after being still for longer than 10ms.
|
||||||
|
//replace the entire mouse interpolation state to avoid an intermediate state with identical m0.t m1.t timestamps which will divide by zero
|
||||||
|
timeline.push_front(TimedInstruction{
|
||||||
|
time:last_mouse_time,
|
||||||
|
instruction:PhysicsInputInstruction::ReplaceMouse(
|
||||||
|
MouseState{time:last_mouse_time,pos:physics.next_mouse.pos},
|
||||||
|
MouseState{time:ins.time,pos:m}
|
||||||
|
),
|
||||||
|
});
|
||||||
|
//delay physics execution until we have an interpolation target
|
||||||
|
mouse_blocking=true;
|
||||||
|
}
|
||||||
|
last_mouse_time=ins.time;
|
||||||
|
None
|
||||||
|
},
|
||||||
|
&InputInstruction::MoveForward(s)=>Some(PhysicsInputInstruction::SetMoveForward(s)),
|
||||||
|
&InputInstruction::MoveLeft(s)=>Some(PhysicsInputInstruction::SetMoveLeft(s)),
|
||||||
|
&InputInstruction::MoveBack(s)=>Some(PhysicsInputInstruction::SetMoveBack(s)),
|
||||||
|
&InputInstruction::MoveRight(s)=>Some(PhysicsInputInstruction::SetMoveRight(s)),
|
||||||
|
&InputInstruction::MoveUp(s)=>Some(PhysicsInputInstruction::SetMoveUp(s)),
|
||||||
|
&InputInstruction::MoveDown(s)=>Some(PhysicsInputInstruction::SetMoveDown(s)),
|
||||||
|
&InputInstruction::Jump(s)=>Some(PhysicsInputInstruction::SetJump(s)),
|
||||||
|
&InputInstruction::Zoom(s)=>Some(PhysicsInputInstruction::SetZoom(s)),
|
||||||
|
InputInstruction::Reset=>Some(PhysicsInputInstruction::Reset),
|
||||||
|
},
|
||||||
|
Instruction::GenerateModels(_)=>Some(PhysicsInputInstruction::Idle),
|
||||||
|
Instruction::ClearModels=>Some(PhysicsInputInstruction::Idle),
|
||||||
|
Instruction::Resize(_,_)=>Some(PhysicsInputInstruction::Idle),
|
||||||
|
Instruction::Render=>Some(PhysicsInputInstruction::Idle),
|
||||||
|
}{
|
||||||
|
//non-mouse event
|
||||||
|
timeline.push_back(TimedInstruction{
|
||||||
|
time:ins.time,
|
||||||
|
instruction:phys_input,
|
||||||
|
});
|
||||||
|
|
||||||
|
if mouse_blocking{
|
||||||
|
//assume the mouse has stopped moving after 10ms.
|
||||||
|
//shitty mice are 125Hz which is 8ms so this should cover that.
|
||||||
|
//setting this to 100us still doesn't print even though it's 10x lower than the polling rate,
|
||||||
|
//so mouse events are probably not handled separately from drawing and fire right before it :(
|
||||||
|
if Time::from_millis(10)<ins.time-physics.next_mouse.time{
|
||||||
|
//push an event to extrapolate no movement from
|
||||||
|
timeline.push_front(TimedInstruction{
|
||||||
|
time:last_mouse_time,
|
||||||
|
instruction:PhysicsInputInstruction::SetNextMouse(MouseState{time:ins.time,pos:physics.next_mouse.pos}),
|
||||||
|
});
|
||||||
|
last_mouse_time=ins.time;
|
||||||
|
//stop blocking. the mouse is not moving so the physics does not need to live in the past and wait for interpolation targets.
|
||||||
|
mouse_blocking=false;
|
||||||
|
true
|
||||||
|
}else{
|
||||||
|
false
|
||||||
|
}
|
||||||
|
}else{
|
||||||
|
//keep this up to date so that it can be used as a known-timestamp
|
||||||
|
//that the mouse was not moving when the mouse starts moving again
|
||||||
|
last_mouse_time=ins.time;
|
||||||
|
true
|
||||||
|
}
|
||||||
|
}else{
|
||||||
|
//mouse event
|
||||||
|
true
|
||||||
|
}{
|
||||||
|
//empty queue
|
||||||
|
while let Some(instruction)=timeline.pop_front(){
|
||||||
|
physics.run(instruction.time);
|
||||||
|
physics.process_instruction(TimedInstruction{
|
||||||
|
time:instruction.time,
|
||||||
|
instruction:crate::physics::PhysicsInstruction::Input(instruction.instruction),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
match ins.instruction{
|
||||||
|
Instruction::Render=>{
|
||||||
|
graphics_worker.send(crate::graphics_worker::Instruction::Render(physics.output(),ins.time,physics.next_mouse.pos)).unwrap();
|
||||||
|
},
|
||||||
|
Instruction::Resize(size,user_settings)=>{
|
||||||
|
graphics_worker.send(crate::graphics_worker::Instruction::Resize(size,user_settings)).unwrap();
|
||||||
|
},
|
||||||
|
Instruction::GenerateModels(indexed_model_instances)=>{
|
||||||
|
physics.generate_models(&indexed_model_instances);
|
||||||
|
physics.spawn(indexed_model_instances.spawn_point);
|
||||||
|
graphics_worker.send(crate::graphics_worker::Instruction::GenerateModels(indexed_model_instances)).unwrap();
|
||||||
|
},
|
||||||
|
Instruction::ClearModels=>{
|
||||||
|
physics.clear();
|
||||||
|
graphics_worker.send(crate::graphics_worker::Instruction::ClearModels).unwrap();
|
||||||
|
},
|
||||||
|
_=>(),
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -1,129 +0,0 @@
|
|||||||
use crate::integer::Time;
|
|
||||||
use crate::physics::{MouseState,PhysicsInputInstruction};
|
|
||||||
use crate::instruction::{TimedInstruction,InstructionConsumer};
|
|
||||||
|
|
||||||
#[derive(Debug)]
|
|
||||||
pub enum InputInstruction {
|
|
||||||
MoveMouse(glam::IVec2),
|
|
||||||
MoveRight(bool),
|
|
||||||
MoveUp(bool),
|
|
||||||
MoveBack(bool),
|
|
||||||
MoveLeft(bool),
|
|
||||||
MoveDown(bool),
|
|
||||||
MoveForward(bool),
|
|
||||||
Jump(bool),
|
|
||||||
Zoom(bool),
|
|
||||||
Reset,
|
|
||||||
Render,
|
|
||||||
//Idle: there were no input events, but the simulation is safe to advance to this timestep
|
|
||||||
//for interpolation / networking / playback reasons, most playback heads will always want
|
|
||||||
//to be 1 instruction ahead to generate the next state for interpolation.
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct RenderState{
|
|
||||||
physics:crate::physics::PhysicsState,
|
|
||||||
graphics:crate::graphics::GraphicsState,
|
|
||||||
}
|
|
||||||
impl RenderState{
|
|
||||||
pub fn new(user_settings:&crate::settings::UserSettings,indexed_model_instances:crate::model::IndexedModelInstances){
|
|
||||||
|
|
||||||
let mut physics=crate::physics::PhysicsState::default();
|
|
||||||
physics.spawn(indexed_model_instances.spawn_point);
|
|
||||||
physics.load_user_settings(user_settings);
|
|
||||||
physics.generate_models(&indexed_model_instances);
|
|
||||||
|
|
||||||
let mut graphics=Self::new_graphics_state();
|
|
||||||
graphics.load_user_settings(user_settings);
|
|
||||||
graphics.generate_models(indexed_model_instances);
|
|
||||||
//manual reset
|
|
||||||
}
|
|
||||||
pub fn into_worker(mut self)->crate::worker::CNWorker<TimedInstruction<InputInstruction>>{
|
|
||||||
let mut mouse_blocking=true;
|
|
||||||
let mut last_mouse_time=self.physics.next_mouse.time;
|
|
||||||
let mut timeline=std::collections::VecDeque::new();
|
|
||||||
crate::worker::CNWorker::new(move |ins:TimedInstruction<InputInstruction>|{
|
|
||||||
let mut render=false;
|
|
||||||
if if let Some(phys_input)=match ins.instruction{
|
|
||||||
InputInstruction::MoveMouse(m)=>{
|
|
||||||
if mouse_blocking{
|
|
||||||
//tell the game state which is living in the past about its future
|
|
||||||
timeline.push_front(TimedInstruction{
|
|
||||||
time:last_mouse_time,
|
|
||||||
instruction:PhysicsInputInstruction::SetNextMouse(MouseState{time:ins.time,pos:m}),
|
|
||||||
});
|
|
||||||
}else{
|
|
||||||
//mouse has just started moving again after being still for longer than 10ms.
|
|
||||||
//replace the entire mouse interpolation state to avoid an intermediate state with identical m0.t m1.t timestamps which will divide by zero
|
|
||||||
timeline.push_front(TimedInstruction{
|
|
||||||
time:last_mouse_time,
|
|
||||||
instruction:PhysicsInputInstruction::ReplaceMouse(
|
|
||||||
MouseState{time:last_mouse_time,pos:self.physics.next_mouse.pos},
|
|
||||||
MouseState{time:ins.time,pos:m}
|
|
||||||
),
|
|
||||||
});
|
|
||||||
//delay physics execution until we have an interpolation target
|
|
||||||
mouse_blocking=true;
|
|
||||||
}
|
|
||||||
last_mouse_time=ins.time;
|
|
||||||
None
|
|
||||||
},
|
|
||||||
InputInstruction::MoveForward(s)=>Some(PhysicsInputInstruction::SetMoveForward(s)),
|
|
||||||
InputInstruction::MoveLeft(s)=>Some(PhysicsInputInstruction::SetMoveLeft(s)),
|
|
||||||
InputInstruction::MoveBack(s)=>Some(PhysicsInputInstruction::SetMoveBack(s)),
|
|
||||||
InputInstruction::MoveRight(s)=>Some(PhysicsInputInstruction::SetMoveRight(s)),
|
|
||||||
InputInstruction::MoveUp(s)=>Some(PhysicsInputInstruction::SetMoveUp(s)),
|
|
||||||
InputInstruction::MoveDown(s)=>Some(PhysicsInputInstruction::SetMoveDown(s)),
|
|
||||||
InputInstruction::Jump(s)=>Some(PhysicsInputInstruction::SetJump(s)),
|
|
||||||
InputInstruction::Zoom(s)=>Some(PhysicsInputInstruction::SetZoom(s)),
|
|
||||||
InputInstruction::Reset=>Some(PhysicsInputInstruction::Reset),
|
|
||||||
InputInstruction::Render=>{render=true;Some(PhysicsInputInstruction::Idle)},
|
|
||||||
}{
|
|
||||||
//non-mouse event
|
|
||||||
timeline.push_back(TimedInstruction{
|
|
||||||
time:ins.time,
|
|
||||||
instruction:phys_input,
|
|
||||||
});
|
|
||||||
|
|
||||||
if mouse_blocking{
|
|
||||||
//assume the mouse has stopped moving after 10ms.
|
|
||||||
//shitty mice are 125Hz which is 8ms so this should cover that.
|
|
||||||
//setting this to 100us still doesn't print even though it's 10x lower than the polling rate,
|
|
||||||
//so mouse events are probably not handled separately from drawing and fire right before it :(
|
|
||||||
if Time::from_millis(10)<ins.time-self.physics.next_mouse.time{
|
|
||||||
//push an event to extrapolate no movement from
|
|
||||||
timeline.push_front(TimedInstruction{
|
|
||||||
time:last_mouse_time,
|
|
||||||
instruction:PhysicsInputInstruction::SetNextMouse(MouseState{time:ins.time,pos:self.physics.next_mouse.pos}),
|
|
||||||
});
|
|
||||||
last_mouse_time=ins.time;
|
|
||||||
//stop blocking. the mouse is not moving so the physics does not need to live in the past and wait for interpolation targets.
|
|
||||||
mouse_blocking=false;
|
|
||||||
true
|
|
||||||
}else{
|
|
||||||
false
|
|
||||||
}
|
|
||||||
}else{
|
|
||||||
//keep this up to date so that it can be used as a known-timestamp
|
|
||||||
//that the mouse was not moving when the mouse starts moving again
|
|
||||||
last_mouse_time=ins.time;
|
|
||||||
true
|
|
||||||
}
|
|
||||||
}else{
|
|
||||||
//mouse event
|
|
||||||
true
|
|
||||||
}{
|
|
||||||
//empty queue
|
|
||||||
while let Some(instruction)=timeline.pop_front(){
|
|
||||||
self.physics.run(instruction.time);
|
|
||||||
self.physics.process_instruction(TimedInstruction{
|
|
||||||
time:instruction.time,
|
|
||||||
instruction:crate::physics::PhysicsInstruction::Input(instruction.instruction),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if render{
|
|
||||||
self.graphics.render();
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,11 +1,14 @@
|
|||||||
use crate::integer::{Ratio64,Ratio64Vec2};
|
use crate::integer::{Ratio64,Ratio64Vec2};
|
||||||
|
#[derive(Clone)]
|
||||||
struct Ratio{
|
struct Ratio{
|
||||||
ratio:f64,
|
ratio:f64,
|
||||||
}
|
}
|
||||||
|
#[derive(Clone)]
|
||||||
enum DerivedFov{
|
enum DerivedFov{
|
||||||
FromScreenAspect,
|
FromScreenAspect,
|
||||||
FromAspect(Ratio),
|
FromAspect(Ratio),
|
||||||
}
|
}
|
||||||
|
#[derive(Clone)]
|
||||||
enum Fov{
|
enum Fov{
|
||||||
Exactly{x:f64,y:f64},
|
Exactly{x:f64,y:f64},
|
||||||
SpecifyXDeriveY{x:f64,y:DerivedFov},
|
SpecifyXDeriveY{x:f64,y:DerivedFov},
|
||||||
@@ -16,9 +19,11 @@ impl Default for Fov{
|
|||||||
Fov::SpecifyYDeriveX{x:DerivedFov::FromScreenAspect,y:1.0}
|
Fov::SpecifyYDeriveX{x:DerivedFov::FromScreenAspect,y:1.0}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
#[derive(Clone)]
|
||||||
enum DerivedSensitivity{
|
enum DerivedSensitivity{
|
||||||
FromRatio(Ratio64),
|
FromRatio(Ratio64),
|
||||||
}
|
}
|
||||||
|
#[derive(Clone)]
|
||||||
enum Sensitivity{
|
enum Sensitivity{
|
||||||
Exactly{x:Ratio64,y:Ratio64},
|
Exactly{x:Ratio64,y:Ratio64},
|
||||||
SpecifyXDeriveY{x:Ratio64,y:DerivedSensitivity},
|
SpecifyXDeriveY{x:Ratio64,y:DerivedSensitivity},
|
||||||
@@ -30,7 +35,7 @@ impl Default for Sensitivity{
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Default)]
|
#[derive(Default,Clone)]
|
||||||
pub struct UserSettings{
|
pub struct UserSettings{
|
||||||
fov:Fov,
|
fov:Fov,
|
||||||
sensitivity:Sensitivity,
|
sensitivity:Sensitivity,
|
||||||
|
|||||||
@@ -1,28 +1,42 @@
|
|||||||
fn optional_features() -> wgpu::Features {
|
use crate::instruction::TimedInstruction;
|
||||||
wgpu::Features::empty()
|
use crate::window::WindowInstruction;
|
||||||
|
|
||||||
|
fn optional_features()->wgpu::Features{
|
||||||
|
wgpu::Features::TEXTURE_COMPRESSION_ASTC
|
||||||
|
|wgpu::Features::TEXTURE_COMPRESSION_ETC2
|
||||||
}
|
}
|
||||||
fn required_features() -> wgpu::Features {
|
fn required_features()->wgpu::Features{
|
||||||
wgpu::Features::empty()
|
wgpu::Features::TEXTURE_COMPRESSION_BC
|
||||||
}
|
}
|
||||||
fn required_downlevel_capabilities() -> wgpu::DownlevelCapabilities {
|
fn required_downlevel_capabilities()->wgpu::DownlevelCapabilities{
|
||||||
wgpu::DownlevelCapabilities {
|
wgpu::DownlevelCapabilities{
|
||||||
flags: wgpu::DownlevelFlags::empty(),
|
flags:wgpu::DownlevelFlags::empty(),
|
||||||
shader_model: wgpu::ShaderModel::Sm5,
|
shader_model:wgpu::ShaderModel::Sm5,
|
||||||
..wgpu::DownlevelCapabilities::default()
|
..wgpu::DownlevelCapabilities::default()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
pub fn required_limits() -> wgpu::Limits {
|
pub fn required_limits()->wgpu::Limits{
|
||||||
wgpu::Limits::downlevel_webgl2_defaults() // These downlevel limits will allow the code to run on all possible hardware
|
wgpu::Limits::default()
|
||||||
}
|
}
|
||||||
|
|
||||||
struct GraphicsContextPartial1{
|
struct SetupContextPartial1{
|
||||||
backends:wgpu::Backends,
|
backends:wgpu::Backends,
|
||||||
instance:wgpu::Instance,
|
instance:wgpu::Instance,
|
||||||
}
|
}
|
||||||
fn create_instance()->GraphicsContextPartial1{
|
fn create_window(title:&str,event_loop:&winit::event_loop::EventLoop<()>)->Result<winit::window::Window,winit::error::OsError>{
|
||||||
|
let mut builder = winit::window::WindowBuilder::new();
|
||||||
|
builder = builder.with_title(title);
|
||||||
|
#[cfg(windows_OFF)] // TODO
|
||||||
|
{
|
||||||
|
use winit::platform::windows::WindowBuilderExtWindows;
|
||||||
|
builder = builder.with_no_redirection_bitmap(true);
|
||||||
|
}
|
||||||
|
builder.build(event_loop)
|
||||||
|
}
|
||||||
|
fn create_instance()->SetupContextPartial1{
|
||||||
let backends=wgpu::util::backend_bits_from_env().unwrap_or_else(wgpu::Backends::all);
|
let backends=wgpu::util::backend_bits_from_env().unwrap_or_else(wgpu::Backends::all);
|
||||||
let dx12_shader_compiler=wgpu::util::dx12_shader_compiler_from_env().unwrap_or_default();
|
let dx12_shader_compiler=wgpu::util::dx12_shader_compiler_from_env().unwrap_or_default();
|
||||||
GraphicsContextPartial1{
|
SetupContextPartial1{
|
||||||
backends,
|
backends,
|
||||||
instance:wgpu::Instance::new(wgpu::InstanceDescriptor{
|
instance:wgpu::Instance::new(wgpu::InstanceDescriptor{
|
||||||
backends,
|
backends,
|
||||||
@@ -30,22 +44,22 @@ fn create_instance()->GraphicsContextPartial1{
|
|||||||
}),
|
}),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
impl GraphicsContextPartial1{
|
impl SetupContextPartial1{
|
||||||
fn create_surface(self,window:&winit::window::Window)->Result<GraphicsContextPartial2,wgpu::CreateSurfaceError>{
|
fn create_surface(self,window:&winit::window::Window)->Result<SetupContextPartial2,wgpu::CreateSurfaceError>{
|
||||||
Ok(GraphicsContextPartial2{
|
Ok(SetupContextPartial2{
|
||||||
backends:self.backends,
|
backends:self.backends,
|
||||||
|
surface:unsafe{self.instance.create_surface(window)}?,
|
||||||
instance:self.instance,
|
instance:self.instance,
|
||||||
surface:unsafe{self.instance.create_surface(window)}?
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
struct GraphicsContextPartial2{
|
struct SetupContextPartial2{
|
||||||
backends:wgpu::Backends,
|
backends:wgpu::Backends,
|
||||||
instance:wgpu::Instance,
|
instance:wgpu::Instance,
|
||||||
surface:wgpu::Surface,
|
surface:wgpu::Surface,
|
||||||
}
|
}
|
||||||
impl GraphicsContextPartial2{
|
impl SetupContextPartial2{
|
||||||
fn pick_adapter(self)->GraphicsContextPartial3{
|
fn pick_adapter(self)->SetupContextPartial3{
|
||||||
let adapter;
|
let adapter;
|
||||||
|
|
||||||
let optional_features=optional_features();
|
let optional_features=optional_features();
|
||||||
@@ -99,20 +113,20 @@ impl GraphicsContextPartial2{
|
|||||||
"Adapter does not support the downlevel capabilities required to run this example: {:?}",
|
"Adapter does not support the downlevel capabilities required to run this example: {:?}",
|
||||||
required_downlevel_capabilities.flags - downlevel_capabilities.flags
|
required_downlevel_capabilities.flags - downlevel_capabilities.flags
|
||||||
);
|
);
|
||||||
GraphicsContextPartial3{
|
SetupContextPartial3{
|
||||||
instance:self.instance,
|
instance:self.instance,
|
||||||
surface:self.surface,
|
surface:self.surface,
|
||||||
adapter,
|
adapter,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
struct GraphicsContextPartial3{
|
struct SetupContextPartial3{
|
||||||
instance:wgpu::Instance,
|
instance:wgpu::Instance,
|
||||||
surface:wgpu::Surface,
|
surface:wgpu::Surface,
|
||||||
adapter:wgpu::Adapter,
|
adapter:wgpu::Adapter,
|
||||||
}
|
}
|
||||||
impl GraphicsContextPartial3{
|
impl SetupContextPartial3{
|
||||||
fn request_device(self)->GraphicsContextPartial4{
|
fn request_device(self)->SetupContextPartial4{
|
||||||
let optional_features=optional_features();
|
let optional_features=optional_features();
|
||||||
let required_features=required_features();
|
let required_features=required_features();
|
||||||
|
|
||||||
@@ -131,7 +145,7 @@ impl GraphicsContextPartial3{
|
|||||||
))
|
))
|
||||||
.expect("Unable to find a suitable GPU adapter!");
|
.expect("Unable to find a suitable GPU adapter!");
|
||||||
|
|
||||||
GraphicsContextPartial4{
|
SetupContextPartial4{
|
||||||
instance:self.instance,
|
instance:self.instance,
|
||||||
surface:self.surface,
|
surface:self.surface,
|
||||||
adapter:self.adapter,
|
adapter:self.adapter,
|
||||||
@@ -140,15 +154,15 @@ impl GraphicsContextPartial3{
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
struct GraphicsContextPartial4{
|
struct SetupContextPartial4{
|
||||||
instance:wgpu::Instance,
|
instance:wgpu::Instance,
|
||||||
surface:wgpu::Surface,
|
surface:wgpu::Surface,
|
||||||
adapter:wgpu::Adapter,
|
adapter:wgpu::Adapter,
|
||||||
device:wgpu::Device,
|
device:wgpu::Device,
|
||||||
queue:wgpu::Queue,
|
queue:wgpu::Queue,
|
||||||
}
|
}
|
||||||
impl GraphicsContextPartial4{
|
impl SetupContextPartial4{
|
||||||
fn configure_surface(self,size:&winit::dpi::PhysicalSize<u32>)->GraphicsContext{
|
fn configure_surface(self,size:&winit::dpi::PhysicalSize<u32>)->SetupContext{
|
||||||
let mut config=self.surface
|
let mut config=self.surface
|
||||||
.get_default_config(&self.adapter, size.width, size.height)
|
.get_default_config(&self.adapter, size.width, size.height)
|
||||||
.expect("Surface isn't supported by the adapter.");
|
.expect("Surface isn't supported by the adapter.");
|
||||||
@@ -156,29 +170,27 @@ impl GraphicsContextPartial4{
|
|||||||
config.view_formats.push(surface_view_format);
|
config.view_formats.push(surface_view_format);
|
||||||
self.surface.configure(&self.device, &config);
|
self.surface.configure(&self.device, &config);
|
||||||
|
|
||||||
GraphicsContext{
|
SetupContext{
|
||||||
instance:self.instance,
|
instance:self.instance,
|
||||||
surface:self.surface,
|
surface:self.surface,
|
||||||
adapter:self.adapter,
|
|
||||||
device:self.device,
|
device:self.device,
|
||||||
queue:self.queue,
|
queue:self.queue,
|
||||||
config,
|
config,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
pub struct GraphicsContext{
|
pub struct SetupContext{
|
||||||
pub instance:wgpu::Instance,
|
pub instance:wgpu::Instance,
|
||||||
pub surface:wgpu::Surface,
|
pub surface:wgpu::Surface,
|
||||||
pub adapter:wgpu::Adapter,
|
|
||||||
pub device:wgpu::Device,
|
pub device:wgpu::Device,
|
||||||
pub queue:wgpu::Queue,
|
pub queue:wgpu::Queue,
|
||||||
pub config:wgpu::SurfaceConfiguration,
|
pub config:wgpu::SurfaceConfiguration,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn setup(title:&str)->GraphicsContextSetup{
|
pub fn setup(title:&str)->SetupContextSetup{
|
||||||
let event_loop=winit::event_loop::EventLoop::new();
|
let event_loop=winit::event_loop::EventLoop::new().unwrap();
|
||||||
|
|
||||||
let window=crate::window::WindowState::create_window(title,&event_loop).unwrap();
|
let window=create_window(title,&event_loop).unwrap();
|
||||||
|
|
||||||
println!("Initializing the surface...");
|
println!("Initializing the surface...");
|
||||||
|
|
||||||
@@ -190,126 +202,99 @@ pub fn setup(title:&str)->GraphicsContextSetup{
|
|||||||
|
|
||||||
let partial_4=partial_3.request_device();
|
let partial_4=partial_3.request_device();
|
||||||
|
|
||||||
GraphicsContextSetup{
|
SetupContextSetup{
|
||||||
window,
|
window,
|
||||||
event_loop,
|
event_loop,
|
||||||
partial_graphics_context:partial_4,
|
partial_context:partial_4,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
struct GraphicsContextSetup{
|
pub struct SetupContextSetup{
|
||||||
window:winit::window::Window,
|
window:winit::window::Window,
|
||||||
event_loop:winit::event_loop::EventLoop<()>,
|
event_loop:winit::event_loop::EventLoop<()>,
|
||||||
partial_graphics_context:GraphicsContextPartial4,
|
partial_context:SetupContextPartial4,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl GraphicsContextSetup{
|
impl SetupContextSetup{
|
||||||
fn into_split(self)->(winit::window::Window,winit::event_loop::EventLoop<()>,GraphicsContext){
|
fn into_split(self)->(winit::window::Window,winit::event_loop::EventLoop<()>,SetupContext){
|
||||||
let size=self.window.inner_size();
|
let size=self.window.inner_size();
|
||||||
//Steal values and drop self
|
//Steal values and drop self
|
||||||
(
|
(
|
||||||
self.window,
|
self.window,
|
||||||
self.event_loop,
|
self.event_loop,
|
||||||
self.partial_graphics_context.configure_surface(&size),
|
self.partial_context.configure_surface(&size),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
pub fn start(self,mut global_state:crate::GlobalState){
|
pub fn start(self){
|
||||||
let (window,event_loop,graphics_context)=self.into_split();
|
let (window,event_loop,setup_context)=self.into_split();
|
||||||
|
|
||||||
println!("Entering render loop...");
|
//dedicated thread to ping request redraw back and resize the window doesn't seem logical
|
||||||
event_loop.run(move |event,_,control_flow|{
|
|
||||||
*control_flow=if cfg!(feature="metal-auto-capture"){
|
let window=crate::window::WindowContextSetup::new(&setup_context,window);
|
||||||
winit::event_loop::ControlFlow::Exit
|
//the thread that spawns the physics thread
|
||||||
}else{
|
let window_thread=window.into_worker(setup_context);
|
||||||
winit::event_loop::ControlFlow::Poll
|
|
||||||
};
|
println!("Entering event loop...");
|
||||||
|
let root_time=std::time::Instant::now();
|
||||||
|
run_event_loop(event_loop,window_thread,root_time).unwrap();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn run_event_loop(
|
||||||
|
event_loop:winit::event_loop::EventLoop<()>,
|
||||||
|
mut window_thread:crate::compat_worker::QNWorker<TimedInstruction<WindowInstruction>>,
|
||||||
|
root_time:std::time::Instant
|
||||||
|
)->Result<(),winit::error::EventLoopError>{
|
||||||
|
event_loop.run(move |event,elwt|{
|
||||||
|
let time=crate::integer::Time::from_nanos(root_time.elapsed().as_nanos() as i64);
|
||||||
|
// *control_flow=if cfg!(feature="metal-auto-capture"){
|
||||||
|
// winit::event_loop::ControlFlow::Exit
|
||||||
|
// }else{
|
||||||
|
// winit::event_loop::ControlFlow::Poll
|
||||||
|
// };
|
||||||
match event{
|
match event{
|
||||||
winit::event::Event::RedrawEventsCleared=>{
|
winit::event::Event::AboutToWait=>{
|
||||||
window.request_redraw();
|
window_thread.send(TimedInstruction{time,instruction:WindowInstruction::RequestRedraw}).unwrap();
|
||||||
}
|
}
|
||||||
winit::event::Event::WindowEvent {
|
winit::event::Event::WindowEvent {
|
||||||
event:
|
event:
|
||||||
winit::event::WindowEvent::Resized(size)
|
// WindowEvent::Resized(size)
|
||||||
| winit::event::WindowEvent::ScaleFactorChanged {
|
// | WindowEvent::ScaleFactorChanged {
|
||||||
new_inner_size:&mut size,
|
// new_inner_size: &mut size,
|
||||||
..
|
// ..
|
||||||
},
|
// },
|
||||||
..
|
winit::event::WindowEvent::Resized(size),//ignoring scale factor changed for now because mutex bruh
|
||||||
|
window_id:_,
|
||||||
} => {
|
} => {
|
||||||
// Once winit is fixed, the detection conditions here can be removed.
|
window_thread.send(TimedInstruction{time,instruction:WindowInstruction::Resize(size)}).unwrap();
|
||||||
// https://github.com/rust-windowing/winit/issues/2876
|
|
||||||
// this has been fixed if I update winit (remove the if statement and only use the else case)
|
|
||||||
//drop adapter when you delete this
|
|
||||||
let max_dimension=graphics_context.adapter.limits().max_texture_dimension_2d;
|
|
||||||
if max_dimension<size.width||max_dimension<size.height{
|
|
||||||
println!(
|
|
||||||
"The resizing size {:?} exceeds the limit of {}.",
|
|
||||||
size,
|
|
||||||
max_dimension
|
|
||||||
);
|
|
||||||
}else{
|
|
||||||
println!("Resizing to {:?}",size);
|
|
||||||
graphics_context.config.width=size.width.max(1);
|
|
||||||
graphics_context.config.height=size.height.max(1);
|
|
||||||
window.resize(&graphics_context);
|
|
||||||
graphics_context.surface.configure(&graphics_context.device,&graphics_context.config);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
winit::event::Event::WindowEvent{event,..}=>match event{
|
winit::event::Event::WindowEvent{event,..}=>match event{
|
||||||
winit::event::WindowEvent::KeyboardInput{
|
winit::event::WindowEvent::KeyboardInput{
|
||||||
input:
|
event:
|
||||||
winit::event::KeyboardInput{
|
winit::event::KeyEvent {
|
||||||
virtual_keycode:Some(winit::event::VirtualKeyCode::Escape),
|
logical_key: winit::keyboard::Key::Named(winit::keyboard::NamedKey::Escape),
|
||||||
state: winit::event::ElementState::Pressed,
|
state: winit::event::ElementState::Pressed,
|
||||||
..
|
..
|
||||||
},
|
},
|
||||||
..
|
..
|
||||||
}
|
}
|
||||||
|winit::event::WindowEvent::CloseRequested=>{
|
|winit::event::WindowEvent::CloseRequested=>{
|
||||||
*control_flow=winit::event_loop::ControlFlow::Exit;
|
elwt.exit();
|
||||||
}
|
}
|
||||||
winit::event::WindowEvent::KeyboardInput{
|
winit::event::WindowEvent::RedrawRequested=>{
|
||||||
input:
|
window_thread.send(TimedInstruction{time,instruction:WindowInstruction::Render}).unwrap();
|
||||||
winit::event::KeyboardInput{
|
|
||||||
virtual_keycode:Some(winit::event::VirtualKeyCode::Scroll),
|
|
||||||
state: winit::event::ElementState::Pressed,
|
|
||||||
..
|
|
||||||
},
|
|
||||||
..
|
|
||||||
}=>{
|
|
||||||
println!("{:#?}",graphics_context.instance.generate_report());
|
|
||||||
}
|
}
|
||||||
_=>{
|
_=>{
|
||||||
global_state.update(event);
|
window_thread.send(TimedInstruction{time,instruction:WindowInstruction::WindowEvent(event)}).unwrap();
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
winit::event::Event::DeviceEvent{
|
winit::event::Event::DeviceEvent{
|
||||||
event,
|
event,
|
||||||
..
|
..
|
||||||
} => {
|
} => {
|
||||||
global_state.device_event(event);
|
window_thread.send(TimedInstruction{time,instruction:WindowInstruction::DeviceEvent(event)}).unwrap();
|
||||||
},
|
},
|
||||||
winit::event::Event::RedrawRequested(_)=>{
|
|
||||||
let frame=match graphics_context.surface.get_current_texture(){
|
|
||||||
Ok(frame)=>frame,
|
|
||||||
Err(_)=>{
|
|
||||||
graphics_context.surface.configure(&graphics_context.device,&graphics_context.config);
|
|
||||||
graphics_context.surface
|
|
||||||
.get_current_texture()
|
|
||||||
.expect("Failed to acquire next surface texture!")
|
|
||||||
}
|
|
||||||
};
|
|
||||||
let view=frame.texture.create_view(&wgpu::TextureViewDescriptor{
|
|
||||||
format:Some(graphics_context.config.view_formats[0]),
|
|
||||||
..wgpu::TextureViewDescriptor::default()
|
|
||||||
});
|
|
||||||
|
|
||||||
graphics.render(&view,&graphics_context.device,&graphics_context.queue);
|
|
||||||
|
|
||||||
frame.present();
|
|
||||||
}
|
|
||||||
_=>{}
|
_=>{}
|
||||||
}
|
}
|
||||||
});
|
})
|
||||||
}
|
|
||||||
}
|
}
|
||||||
209
src/window.rs
209
src/window.rs
@@ -1,50 +1,68 @@
|
|||||||
pub struct WindowState{
|
use crate::instruction::TimedInstruction;
|
||||||
//ok
|
use crate::physics_worker::InputInstruction;
|
||||||
}
|
|
||||||
impl WindowState{
|
|
||||||
fn resize(&mut self);
|
|
||||||
fn render(&self);
|
|
||||||
|
|
||||||
fn update(&mut self, window: &winit::window::Window, event: winit::event::WindowEvent) {
|
pub enum WindowInstruction{
|
||||||
let time=integer::Time::from_nanos(self.start_time.elapsed().as_nanos() as i64);
|
Resize(winit::dpi::PhysicalSize<u32>),
|
||||||
|
WindowEvent(winit::event::WindowEvent),
|
||||||
|
DeviceEvent(winit::event::DeviceEvent),
|
||||||
|
RequestRedraw,
|
||||||
|
Render,
|
||||||
|
}
|
||||||
|
|
||||||
|
//holds thread handles to dispatch to
|
||||||
|
struct WindowContext<'a>{
|
||||||
|
manual_mouse_lock:bool,
|
||||||
|
mouse:crate::physics::MouseState,//std::sync::Arc<std::sync::Mutex<>>
|
||||||
|
screen_size:glam::UVec2,
|
||||||
|
user_settings:crate::settings::UserSettings,
|
||||||
|
window:winit::window::Window,
|
||||||
|
physics_thread:crate::compat_worker::QNWorker<'a, TimedInstruction<crate::physics_worker::Instruction>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl WindowContext<'_>{
|
||||||
|
fn get_middle_of_screen(&self)->winit::dpi::PhysicalPosition<f32>{
|
||||||
|
winit::dpi::PhysicalPosition::new(self.screen_size.x as f32/2.0, self.screen_size.y as f32/2.0)
|
||||||
|
}
|
||||||
|
fn window_event(&mut self,time:crate::integer::Time,event: winit::event::WindowEvent) {
|
||||||
match event {
|
match event {
|
||||||
winit::event::WindowEvent::DroppedFile(path)=>{
|
winit::event::WindowEvent::DroppedFile(path)=>{
|
||||||
std::thread::spawn(move ||{
|
//blocking because it's simpler...
|
||||||
let indexed_model_instances=load_file(path);
|
if let Some(indexed_model_instances)=crate::load_file(path){
|
||||||
self.render_thread.send(Instruction::Die(indexed_model_instances));
|
self.physics_thread.send(TimedInstruction{time,instruction:crate::physics_worker::Instruction::ClearModels}).unwrap();
|
||||||
});
|
self.physics_thread.send(TimedInstruction{time,instruction:crate::physics_worker::Instruction::GenerateModels(indexed_model_instances)}).unwrap();
|
||||||
|
}
|
||||||
},
|
},
|
||||||
winit::event::WindowEvent::Focused(state)=>{
|
winit::event::WindowEvent::Focused(state)=>{
|
||||||
//pause unpause
|
//pause unpause
|
||||||
//recalculate pressed keys on focus
|
//recalculate pressed keys on focus
|
||||||
},
|
},
|
||||||
winit::event::WindowEvent::KeyboardInput {
|
winit::event::WindowEvent::KeyboardInput{
|
||||||
input:winit::event::KeyboardInput{state, virtual_keycode,..},
|
event:winit::event::KeyEvent{state,logical_key,repeat:false,..},
|
||||||
..
|
..
|
||||||
}=>{
|
}=>{
|
||||||
let s=match state {
|
let s=match state{
|
||||||
winit::event::ElementState::Pressed => true,
|
winit::event::ElementState::Pressed=>true,
|
||||||
winit::event::ElementState::Released => false,
|
winit::event::ElementState::Released=>false,
|
||||||
};
|
};
|
||||||
match virtual_keycode{
|
match logical_key{
|
||||||
Some(winit::event::VirtualKeyCode::Tab)=>{
|
winit::keyboard::Key::Named(winit::keyboard::NamedKey::Tab)=>{
|
||||||
if s{
|
if s{
|
||||||
self.manual_mouse_lock=false;
|
self.manual_mouse_lock=false;
|
||||||
match window.set_cursor_position(winit::dpi::PhysicalPosition::new(self.graphics.camera.screen_size.x as f32/2.0, self.graphics.camera.screen_size.y as f32/2.0)){
|
match self.window.set_cursor_position(self.get_middle_of_screen()){
|
||||||
Ok(())=>(),
|
Ok(())=>(),
|
||||||
Err(e)=>println!("Could not set cursor position: {:?}",e),
|
Err(e)=>println!("Could not set cursor position: {:?}",e),
|
||||||
}
|
}
|
||||||
match window.set_cursor_grab(winit::window::CursorGrabMode::None){
|
match self.window.set_cursor_grab(winit::window::CursorGrabMode::None){
|
||||||
Ok(())=>(),
|
Ok(())=>(),
|
||||||
Err(e)=>println!("Could not release cursor: {:?}",e),
|
Err(e)=>println!("Could not release cursor: {:?}",e),
|
||||||
}
|
}
|
||||||
}else{
|
}else{
|
||||||
//if cursor is outside window don't lock but apparently there's no get pos function
|
//if cursor is outside window don't lock but apparently there's no get pos function
|
||||||
//let pos=window.get_cursor_pos();
|
//let pos=window.get_cursor_pos();
|
||||||
match window.set_cursor_grab(winit::window::CursorGrabMode::Locked){
|
match self.window.set_cursor_grab(winit::window::CursorGrabMode::Locked){
|
||||||
Ok(())=>(),
|
Ok(())=>(),
|
||||||
Err(_)=>{
|
Err(_)=>{
|
||||||
match window.set_cursor_grab(winit::window::CursorGrabMode::Confined){
|
match self.window.set_cursor_grab(winit::window::CursorGrabMode::Confined){
|
||||||
Ok(())=>(),
|
Ok(())=>(),
|
||||||
Err(e)=>{
|
Err(e)=>{
|
||||||
self.manual_mouse_lock=true;
|
self.manual_mouse_lock=true;
|
||||||
@@ -54,62 +72,62 @@ impl WindowState{
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
window.set_cursor_visible(s);
|
self.window.set_cursor_visible(s);
|
||||||
},
|
},
|
||||||
Some(winit::event::VirtualKeyCode::F11)=>{
|
winit::keyboard::Key::Named(winit::keyboard::NamedKey::F11)=>{
|
||||||
if s{
|
if s{
|
||||||
if window.fullscreen().is_some(){
|
if self.window.fullscreen().is_some(){
|
||||||
window.set_fullscreen(None);
|
self.window.set_fullscreen(None);
|
||||||
}else{
|
}else{
|
||||||
window.set_fullscreen(Some(winit::window::Fullscreen::Borderless(None)));
|
self.window.set_fullscreen(Some(winit::window::Fullscreen::Borderless(None)));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
Some(winit::event::VirtualKeyCode::Escape)=>{
|
winit::keyboard::Key::Named(winit::keyboard::NamedKey::Escape)=>{
|
||||||
if s{
|
if s{
|
||||||
self.manual_mouse_lock=false;
|
self.manual_mouse_lock=false;
|
||||||
match window.set_cursor_grab(winit::window::CursorGrabMode::None){
|
match self.window.set_cursor_grab(winit::window::CursorGrabMode::None){
|
||||||
Ok(())=>(),
|
Ok(())=>(),
|
||||||
Err(e)=>println!("Could not release cursor: {:?}",e),
|
Err(e)=>println!("Could not release cursor: {:?}",e),
|
||||||
}
|
}
|
||||||
window.set_cursor_visible(true);
|
self.window.set_cursor_visible(true);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
Some(keycode)=>{
|
keycode=>{
|
||||||
if let Some(input_instruction)=match keycode {
|
if let Some(input_instruction)=match keycode{
|
||||||
winit::event::VirtualKeyCode::W => Some(InputInstruction::MoveForward(s)),
|
winit::keyboard::Key::Named(winit::keyboard::NamedKey::Space)=>Some(InputInstruction::Jump(s)),
|
||||||
winit::event::VirtualKeyCode::A => Some(InputInstruction::MoveLeft(s)),
|
winit::keyboard::Key::Character(key)=>match key.as_str(){
|
||||||
winit::event::VirtualKeyCode::S => Some(InputInstruction::MoveBack(s)),
|
"w"=>Some(InputInstruction::MoveForward(s)),
|
||||||
winit::event::VirtualKeyCode::D => Some(InputInstruction::MoveRight(s)),
|
"a"=>Some(InputInstruction::MoveLeft(s)),
|
||||||
winit::event::VirtualKeyCode::E => Some(InputInstruction::MoveUp(s)),
|
"s"=>Some(InputInstruction::MoveBack(s)),
|
||||||
winit::event::VirtualKeyCode::Q => Some(InputInstruction::MoveDown(s)),
|
"d"=>Some(InputInstruction::MoveRight(s)),
|
||||||
winit::event::VirtualKeyCode::Space => Some(InputInstruction::Jump(s)),
|
"e"=>Some(InputInstruction::MoveUp(s)),
|
||||||
winit::event::VirtualKeyCode::Z => Some(InputInstruction::Zoom(s)),
|
"q"=>Some(InputInstruction::MoveDown(s)),
|
||||||
winit::event::VirtualKeyCode::R => if s{Some(InputInstruction::Reset)}else{None},
|
"z"=>Some(InputInstruction::Zoom(s)),
|
||||||
_ => None,
|
"r"=>if s{Some(InputInstruction::Reset)}else{None},
|
||||||
|
_=>None,
|
||||||
|
},
|
||||||
|
_=>None,
|
||||||
}{
|
}{
|
||||||
self.physics_thread.send(TimedInstruction{
|
self.physics_thread.send(TimedInstruction{
|
||||||
time,
|
time,
|
||||||
instruction:input_instruction,
|
instruction:crate::physics_worker::Instruction::Input(input_instruction),
|
||||||
}).unwrap();
|
}).unwrap();
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
_=>(),
|
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
_=>(),
|
_=>(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn device_event(&mut self, window: &winit::window::Window, event: winit::event::DeviceEvent) {
|
fn device_event(&mut self,time:crate::integer::Time,event: winit::event::DeviceEvent) {
|
||||||
//there's no way this is the best way get a timestamp.
|
|
||||||
let time=integer::Time::from_nanos(self.start_time.elapsed().as_nanos() as i64);
|
|
||||||
match event {
|
match event {
|
||||||
winit::event::DeviceEvent::MouseMotion {
|
winit::event::DeviceEvent::MouseMotion {
|
||||||
delta,//these (f64,f64) are integers on my machine
|
delta,//these (f64,f64) are integers on my machine
|
||||||
} => {
|
} => {
|
||||||
if self.manual_mouse_lock{
|
if self.manual_mouse_lock{
|
||||||
match window.set_cursor_position(winit::dpi::PhysicalPosition::new(self.graphics.camera.screen_size.x as f32/2.0, self.graphics.camera.screen_size.y as f32/2.0)){
|
match self.window.set_cursor_position(self.get_middle_of_screen()){
|
||||||
Ok(())=>(),
|
Ok(())=>(),
|
||||||
Err(e)=>println!("Could not set cursor position: {:?}",e),
|
Err(e)=>println!("Could not set cursor position: {:?}",e),
|
||||||
}
|
}
|
||||||
@@ -121,7 +139,7 @@ impl WindowState{
|
|||||||
self.mouse.pos+=delta;
|
self.mouse.pos+=delta;
|
||||||
self.physics_thread.send(TimedInstruction{
|
self.physics_thread.send(TimedInstruction{
|
||||||
time,
|
time,
|
||||||
instruction:InputInstruction::MoveMouse(self.mouse.pos),
|
instruction:crate::physics_worker::Instruction::Input(InputInstruction::MoveMouse(self.mouse.pos)),
|
||||||
}).unwrap();
|
}).unwrap();
|
||||||
},
|
},
|
||||||
winit::event::DeviceEvent::MouseWheel {
|
winit::event::DeviceEvent::MouseWheel {
|
||||||
@@ -131,22 +149,95 @@ impl WindowState{
|
|||||||
if false{//self.physics.style.use_scroll{
|
if false{//self.physics.style.use_scroll{
|
||||||
self.physics_thread.send(TimedInstruction{
|
self.physics_thread.send(TimedInstruction{
|
||||||
time,
|
time,
|
||||||
instruction:InputInstruction::Jump(true),//activates the immediate jump path, but the style modifier prevents controls&CONTROL_JUMP bit from being set to auto jump
|
instruction:crate::physics_worker::Instruction::Input(InputInstruction::Jump(true)),//activates the immediate jump path, but the style modifier prevents controls&CONTROL_JUMP bit from being set to auto jump
|
||||||
}).unwrap();
|
}).unwrap();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
_=>(),
|
_=>(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub fn create_window(title:&str,event_loop:&winit::event_loop::EventLoop<()>)->Result<winit::window::Window,winit::error::OsError>{
|
pub struct WindowContextSetup{
|
||||||
let mut builder = winit::window::WindowBuilder::new();
|
user_settings:crate::settings::UserSettings,
|
||||||
builder = builder.with_title(title);
|
window:winit::window::Window,
|
||||||
#[cfg(windows_OFF)] // TODO
|
physics:crate::physics::PhysicsState,
|
||||||
{
|
graphics:crate::graphics::GraphicsState,
|
||||||
use winit::platform::windows::WindowBuilderExtWindows;
|
}
|
||||||
builder = builder.with_no_redirection_bitmap(true);
|
|
||||||
|
impl WindowContextSetup{
|
||||||
|
pub fn new(context:&crate::setup::SetupContext,window:winit::window::Window)->Self{
|
||||||
|
//wee
|
||||||
|
let user_settings=crate::settings::read_user_settings();
|
||||||
|
|
||||||
|
let args:Vec<String>=std::env::args().collect();
|
||||||
|
let indexed_model_instances=if args.len()==2{
|
||||||
|
crate::load_file(std::path::PathBuf::from(&args[1]))
|
||||||
|
}else{
|
||||||
|
None
|
||||||
|
}.unwrap_or(crate::default_models());
|
||||||
|
|
||||||
|
let mut physics=crate::physics::PhysicsState::default();
|
||||||
|
physics.load_user_settings(&user_settings);
|
||||||
|
physics.generate_models(&indexed_model_instances);
|
||||||
|
physics.spawn(indexed_model_instances.spawn_point);
|
||||||
|
|
||||||
|
let mut graphics=crate::graphics::GraphicsState::new(&context.device,&context.queue,&context.config);
|
||||||
|
graphics.load_user_settings(&user_settings);
|
||||||
|
graphics.generate_models(&context.device,&context.queue,indexed_model_instances);
|
||||||
|
|
||||||
|
Self{
|
||||||
|
user_settings,
|
||||||
|
window,
|
||||||
|
graphics,
|
||||||
|
physics,
|
||||||
}
|
}
|
||||||
builder.build(event_loop)
|
}
|
||||||
|
|
||||||
|
fn into_context<'a>(self,setup_context:crate::setup::SetupContext)->WindowContext<'a>{
|
||||||
|
let screen_size=glam::uvec2(setup_context.config.width,setup_context.config.height);
|
||||||
|
let graphics_thread=crate::graphics_worker::new(self.graphics,setup_context.config,setup_context.surface,setup_context.device,setup_context.queue);
|
||||||
|
WindowContext{
|
||||||
|
manual_mouse_lock:false,
|
||||||
|
mouse:crate::physics::MouseState::default(),
|
||||||
|
//make sure to update this!!!!!
|
||||||
|
screen_size,
|
||||||
|
user_settings:self.user_settings,
|
||||||
|
window:self.window,
|
||||||
|
physics_thread:crate::physics_worker::new(self.physics,graphics_thread),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn into_worker<'a>(self,setup_context:crate::setup::SetupContext)->crate::compat_worker::QNWorker<'a,TimedInstruction<WindowInstruction>>{
|
||||||
|
let mut window_context=self.into_context(setup_context);
|
||||||
|
crate::compat_worker::QNWorker::new(move |ins:TimedInstruction<WindowInstruction>|{
|
||||||
|
match ins.instruction{
|
||||||
|
WindowInstruction::RequestRedraw=>{
|
||||||
|
window_context.window.request_redraw();
|
||||||
|
}
|
||||||
|
WindowInstruction::WindowEvent(window_event)=>{
|
||||||
|
window_context.window_event(ins.time,window_event);
|
||||||
|
},
|
||||||
|
WindowInstruction::DeviceEvent(device_event)=>{
|
||||||
|
window_context.device_event(ins.time,device_event);
|
||||||
|
},
|
||||||
|
WindowInstruction::Resize(size)=>{
|
||||||
|
window_context.physics_thread.send(
|
||||||
|
TimedInstruction{
|
||||||
|
time:ins.time,
|
||||||
|
instruction:crate::physics_worker::Instruction::Resize(size,window_context.user_settings.clone())
|
||||||
|
}
|
||||||
|
).unwrap();
|
||||||
|
}
|
||||||
|
WindowInstruction::Render=>{
|
||||||
|
window_context.physics_thread.send(
|
||||||
|
TimedInstruction{
|
||||||
|
time:ins.time,
|
||||||
|
instruction:crate::physics_worker::Instruction::Render
|
||||||
|
}
|
||||||
|
).unwrap();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
121
src/worker.rs
121
src/worker.rs
@@ -104,17 +104,15 @@ QN = WorkerDescription{
|
|||||||
}
|
}
|
||||||
*/
|
*/
|
||||||
//None Output Worker does all its work internally from the perspective of the work submitter
|
//None Output Worker does all its work internally from the perspective of the work submitter
|
||||||
pub struct QNWorker<Task:Send> {
|
pub struct QNWorker<'a,Task:Send>{
|
||||||
sender: mpsc::Sender<Task>,
|
sender: mpsc::Sender<Task>,
|
||||||
|
handle:thread::ScopedJoinHandle<'a,()>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<Task:Send+'static> QNWorker<Task>{
|
impl<'a,Task:Send+'a> QNWorker<'a,Task>{
|
||||||
pub fn new<F:FnMut(Task)+Send+'static>(mut f:F)->Self{
|
pub fn new<F:FnMut(Task)+Send+'a>(scope:&'a thread::Scope<'a,'_>,mut f:F)->QNWorker<'a,Task>{
|
||||||
let (sender,receiver)=mpsc::channel::<Task>();
|
let (sender,receiver)=mpsc::channel::<Task>();
|
||||||
let ret=Self {
|
let handle=scope.spawn(move ||{
|
||||||
sender,
|
|
||||||
};
|
|
||||||
thread::spawn(move ||{
|
|
||||||
loop {
|
loop {
|
||||||
match receiver.recv() {
|
match receiver.recv() {
|
||||||
Ok(task)=>f(task),
|
Ok(task)=>f(task),
|
||||||
@@ -125,7 +123,10 @@ impl<Task:Send+'static> QNWorker<Task>{
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
ret
|
Self{
|
||||||
|
sender,
|
||||||
|
handle,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
pub fn send(&self,task:Task)->Result<(),mpsc::SendError<Task>>{
|
pub fn send(&self,task:Task)->Result<(),mpsc::SendError<Task>>{
|
||||||
self.sender.send(task)
|
self.sender.send(task)
|
||||||
@@ -139,104 +140,36 @@ IN = WorkerDescription{
|
|||||||
}
|
}
|
||||||
*/
|
*/
|
||||||
//Inputs are dropped if the worker is busy
|
//Inputs are dropped if the worker is busy
|
||||||
pub struct INWorker<Task:Clone>{
|
pub struct INWorker<'a,Task:Send>{
|
||||||
input:Arc<(Mutex<Task>,Condvar)>,
|
sender: mpsc::SyncSender<Task>,
|
||||||
|
handle:thread::ScopedJoinHandle<'a,()>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<Task:Clone+Send+'static> INWorker<Task>{
|
impl<'a,Task:Send+'a> INWorker<'a,Task>{
|
||||||
pub fn new<F:FnMut(Task)+Send+'static>(task:Task,mut f:F)->Self{
|
pub fn new<F:FnMut(Task)+Send+'a>(scope:&'a thread::Scope<'a,'_>,mut f:F)->INWorker<'a,Task>{
|
||||||
let ret=Self {
|
let (sender,receiver)=mpsc::sync_channel::<Task>(1);
|
||||||
input:Arc::new((Mutex::new(task),Condvar::new())),
|
let handle=scope.spawn(move ||{
|
||||||
};
|
|
||||||
let input=ret.input.clone();
|
|
||||||
thread::spawn(move ||{
|
|
||||||
loop {
|
loop {
|
||||||
input.1.wait(&mut input.0.lock());
|
match receiver.recv() {
|
||||||
f(input.0.lock().clone());
|
Ok(task)=>f(task),
|
||||||
}
|
|
||||||
});
|
|
||||||
ret
|
|
||||||
}
|
|
||||||
pub fn send(&self,task:Task){
|
|
||||||
*self.input.0.lock()=task;
|
|
||||||
self.input.1.notify_one();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
//worker pools work by cloning a mpsc and passing it into the thread, the thread sends its results through that
|
|
||||||
//worker pools have a master thread that manages the pool so that the work submission thread does not need to implement async
|
|
||||||
|
|
||||||
pub struct QQWorkerPool<Task:Send,Value:Send>{
|
|
||||||
sender:mpsc::Sender<Task>,
|
|
||||||
queue:Arc<Mutex<std::collections::VecDeque<Value>>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<Task:Send+'static,Value:Send+'static> QQWorkerPool<Task,Value>{
|
|
||||||
pub fn new<F:Fn(Task)->Value+Send+'static>(pool_size:usize,f:F)->Self{
|
|
||||||
let (task_sender,task_receiver)=mpsc::channel::<Task>();
|
|
||||||
let (value_sender,value_receiver)=mpsc::channel::<Value>();
|
|
||||||
let ret=Self{
|
|
||||||
sender:task_sender,
|
|
||||||
queue:Arc::new(Mutex::new(std::collections::VecDeque::new())),
|
|
||||||
};
|
|
||||||
let mut queue_collect=ret.queue.clone();
|
|
||||||
let mut worker_senders=Vec::with_capacity(pool_size);
|
|
||||||
let mut active_workers_collect=Arc::new(Mutex::new(0usize));
|
|
||||||
let mut active_workers_dispatch=active_workers_collect.clone();
|
|
||||||
let mut condvar_collect=Arc::new(Condvar::new());
|
|
||||||
let mut condvar_dispatch=condvar_collect.clone();
|
|
||||||
//task dispatch thread
|
|
||||||
thread::spawn(move ||{
|
|
||||||
loop{
|
|
||||||
//block if no workers are available, value collection thread will notify
|
|
||||||
let n=*active_workers_dispatch.lock();
|
|
||||||
if n==pool_size{
|
|
||||||
//wait for notifiy
|
|
||||||
condvar_dispatch.wait(&mut active_workers_dispatch.lock());
|
|
||||||
}
|
|
||||||
match task_receiver.recv(){
|
|
||||||
Ok(task)=>{
|
|
||||||
*active_workers_dispatch.lock()+=1;
|
|
||||||
//workers are never full here
|
|
||||||
//else if workers busy: spawn a new worker
|
|
||||||
//else: send task to an available worker
|
|
||||||
}
|
|
||||||
Err(_)=>{
|
Err(_)=>{
|
||||||
println!("Dispatch stopping.",);
|
println!("Worker stopping.",);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
//value collection thread (bad idea, put this logic in each thread)
|
Self{
|
||||||
thread::spawn(move ||{
|
sender,
|
||||||
loop{
|
handle,
|
||||||
match value_receiver.recv(){
|
}
|
||||||
Ok(value)=>{
|
|
||||||
//maybe I can be smart with this as a signal that a worker finished a task
|
|
||||||
let n=*active_workers_collect.lock();
|
|
||||||
*active_workers_collect.lock()-=1;
|
|
||||||
if n==pool_size{
|
|
||||||
condvar_collect.notify_one();
|
|
||||||
}
|
|
||||||
(*queue_collect.lock()).push_front(value);
|
|
||||||
}
|
|
||||||
Err(_)=>{
|
|
||||||
println!("Collection stopping.",);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
ret
|
|
||||||
}
|
}
|
||||||
|
//blocking!
|
||||||
pub fn send(&self,task:Task)->Result<(),mpsc::SendError<Task>>{
|
pub fn blocking_send(&self,task:Task)->Result<(), mpsc::SendError<Task>>{
|
||||||
self.sender.send(task)
|
self.sender.send(task)
|
||||||
}
|
}
|
||||||
|
pub fn send(&self,task:Task)->Result<(), mpsc::TrySendError<Task>>{
|
||||||
pub fn get(&self)->Option<Value>{
|
self.sender.try_send(task)
|
||||||
(*self.queue.lock()).pop_back()
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user