forked from StrafesNET/strafe-client
Compare commits
9 Commits
master
...
physics-th
Author | SHA1 | Date | |
---|---|---|---|
6f4af1c694 | |||
40af48068a | |||
edd3ca566a | |||
a1f9a62c89 | |||
b5ee40e48d | |||
3c521089cb | |||
77ea099880 | |||
54a21ae00b | |||
dd61c64ddd |
259
src/main.rs
259
src/main.rs
@ -44,14 +44,65 @@ pub struct GraphicsPipelines{
|
|||||||
model: wgpu::RenderPipeline,
|
model: wgpu::RenderPipeline,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub struct GraphicsCamera{
|
||||||
|
screen_size: glam::UVec2,
|
||||||
|
fov: glam::Vec2,//slope
|
||||||
|
//camera angles and such are extrapolated and passed in every time
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn perspective_rh(fov_x_slope: f32, fov_y_slope: f32, z_near: f32, z_far: f32) -> glam::Mat4 {
|
||||||
|
//glam_assert!(z_near > 0.0 && z_far > 0.0);
|
||||||
|
let r = z_far / (z_near - z_far);
|
||||||
|
glam::Mat4::from_cols(
|
||||||
|
glam::Vec4::new(1.0/fov_x_slope, 0.0, 0.0, 0.0),
|
||||||
|
glam::Vec4::new(0.0, 1.0/fov_y_slope, 0.0, 0.0),
|
||||||
|
glam::Vec4::new(0.0, 0.0, r, -1.0),
|
||||||
|
glam::Vec4::new(0.0, 0.0, r * z_near, 0.0),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
impl GraphicsCamera{
|
||||||
|
pub fn new(screen_size:glam::UVec2,fov_y:f32)->Self{
|
||||||
|
Self{
|
||||||
|
screen_size,
|
||||||
|
fov: glam::vec2(fov_y*(screen_size.x as f32)/(screen_size.y as f32),fov_y),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pub fn proj(&self)->glam::Mat4{
|
||||||
|
perspective_rh(self.fov.x, self.fov.y, 0.5, 2000.0)
|
||||||
|
}
|
||||||
|
pub fn view(&self,pos:glam::Vec3,angles:glam::Vec2)->glam::Mat4{
|
||||||
|
//f32 good enough for view matrix
|
||||||
|
glam::Mat4::from_translation(pos) * glam::Mat4::from_euler(glam::EulerRot::YXZ, angles.x, angles.y, 0f32)
|
||||||
|
}
|
||||||
|
pub fn set_screen_size(&mut self,screen_size:glam::UVec2){
|
||||||
|
self.screen_size=screen_size;
|
||||||
|
self.fov.x=self.fov.y*(screen_size.x as f32)/(screen_size.y as f32);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn to_uniform_data(&self,(pos,angles): (glam::Vec3,glam::Vec2)) -> [f32; 16 * 3 + 4] {
|
||||||
|
let proj=self.proj();
|
||||||
|
let proj_inv = proj.inverse();
|
||||||
|
let view=self.view(pos,angles);
|
||||||
|
let view_inv = view.inverse();
|
||||||
|
|
||||||
|
let mut raw = [0f32; 16 * 3 + 4];
|
||||||
|
raw[..16].copy_from_slice(&AsRef::<[f32; 16]>::as_ref(&proj)[..]);
|
||||||
|
raw[16..32].copy_from_slice(&AsRef::<[f32; 16]>::as_ref(&proj_inv)[..]);
|
||||||
|
raw[32..48].copy_from_slice(&AsRef::<[f32; 16]>::as_ref(&view_inv)[..]);
|
||||||
|
raw[48..52].copy_from_slice(AsRef::<[f32; 4]>::as_ref(&view.col(3)));
|
||||||
|
raw
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub struct GraphicsState{
|
pub struct GraphicsState{
|
||||||
screen_size: (u32, u32),
|
|
||||||
pipelines: GraphicsPipelines,
|
pipelines: GraphicsPipelines,
|
||||||
bind_groups: GraphicsBindGroups,
|
bind_groups: GraphicsBindGroups,
|
||||||
bind_group_layouts: GraphicsBindGroupLayouts,
|
bind_group_layouts: GraphicsBindGroupLayouts,
|
||||||
samplers: GraphicsSamplers,
|
samplers: GraphicsSamplers,
|
||||||
temp_squid_texture_view: wgpu::TextureView,
|
camera:GraphicsCamera,
|
||||||
camera_buf: wgpu::Buffer,
|
camera_buf: wgpu::Buffer,
|
||||||
|
temp_squid_texture_view: wgpu::TextureView,
|
||||||
models: Vec<ModelGraphics>,
|
models: Vec<ModelGraphics>,
|
||||||
depth_view: wgpu::TextureView,
|
depth_view: wgpu::TextureView,
|
||||||
staging_belt: wgpu::util::StagingBelt,
|
staging_belt: wgpu::util::StagingBelt,
|
||||||
@ -66,8 +117,9 @@ impl GraphicsState{
|
|||||||
pub struct GlobalState{
|
pub struct GlobalState{
|
||||||
start_time: std::time::Instant,
|
start_time: std::time::Instant,
|
||||||
manual_mouse_lock:bool,
|
manual_mouse_lock:bool,
|
||||||
|
mouse:physics::MouseState,
|
||||||
graphics:GraphicsState,
|
graphics:GraphicsState,
|
||||||
physics:physics::PhysicsState,
|
physics_thread:worker::CompatWorker<TimedInstruction<InputInstruction>,physics::PhysicsOutputState,Box<dyn FnMut(TimedInstruction<InputInstruction>)->physics::PhysicsOutputState>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl GlobalState{
|
impl GlobalState{
|
||||||
@ -95,77 +147,6 @@ impl GlobalState{
|
|||||||
depth_texture.create_view(&wgpu::TextureViewDescriptor::default())
|
depth_texture.create_view(&wgpu::TextureViewDescriptor::default())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn generate_model_physics(&mut self,indexed_models:&model::IndexedModelInstances){
|
|
||||||
let mut starts=Vec::new();
|
|
||||||
let mut spawns=Vec::new();
|
|
||||||
let mut ordered_checkpoints=Vec::new();
|
|
||||||
let mut unordered_checkpoints=Vec::new();
|
|
||||||
for model in &indexed_models.models{
|
|
||||||
//make aabb and run vertices to get realistic bounds
|
|
||||||
for model_instance in &model.instances{
|
|
||||||
if let Some(model_physics)=physics::ModelPhysics::from_model(model,model_instance){
|
|
||||||
let model_id=self.physics.models.len() as u32;
|
|
||||||
self.physics.models.push(model_physics);
|
|
||||||
for attr in &model_instance.temp_indexing{
|
|
||||||
match attr{
|
|
||||||
model::TempIndexedAttributes::Start{mode_id}=>starts.push((*mode_id,model_id)),
|
|
||||||
model::TempIndexedAttributes::Spawn{mode_id,stage_id}=>spawns.push((*mode_id,model_id,*stage_id)),
|
|
||||||
model::TempIndexedAttributes::OrderedCheckpoint{mode_id,checkpoint_id}=>ordered_checkpoints.push((*mode_id,model_id,*checkpoint_id)),
|
|
||||||
model::TempIndexedAttributes::UnorderedCheckpoint{mode_id}=>unordered_checkpoints.push((*mode_id,model_id)),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
//I don't wanna write structs for temporary structures
|
|
||||||
//this code builds ModeDescriptions from the unsorted lists at the top of the function
|
|
||||||
starts.sort_by_key(|tup|tup.0);
|
|
||||||
let mut eshmep=std::collections::HashMap::new();
|
|
||||||
let mut modedatas:Vec<(u32,Vec<(u32,u32)>,Vec<(u32,u32)>,Vec<u32>)>=starts.into_iter().enumerate().map(|(i,tup)|{
|
|
||||||
eshmep.insert(tup.0,i);
|
|
||||||
(tup.1,Vec::new(),Vec::new(),Vec::new())
|
|
||||||
}).collect();
|
|
||||||
for tup in spawns{
|
|
||||||
if let Some(mode_id)=eshmep.get(&tup.0){
|
|
||||||
if let Some(modedata)=modedatas.get_mut(*mode_id){
|
|
||||||
modedata.1.push((tup.2,tup.1));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for tup in ordered_checkpoints{
|
|
||||||
if let Some(mode_id)=eshmep.get(&tup.0){
|
|
||||||
if let Some(modedata)=modedatas.get_mut(*mode_id){
|
|
||||||
modedata.2.push((tup.2,tup.1));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for tup in unordered_checkpoints{
|
|
||||||
if let Some(mode_id)=eshmep.get(&tup.0){
|
|
||||||
if let Some(modedata)=modedatas.get_mut(*mode_id){
|
|
||||||
modedata.3.push(tup.1);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let num_modes=self.physics.modes.len();
|
|
||||||
for (mode_id,mode) in eshmep{
|
|
||||||
self.physics.mode_from_mode_id.insert(mode_id,num_modes+mode);
|
|
||||||
}
|
|
||||||
self.physics.modes.append(&mut modedatas.into_iter().map(|mut tup|{
|
|
||||||
tup.1.sort_by_key(|tup|tup.0);
|
|
||||||
tup.2.sort_by_key(|tup|tup.0);
|
|
||||||
let mut eshmep1=std::collections::HashMap::new();
|
|
||||||
let mut eshmep2=std::collections::HashMap::new();
|
|
||||||
model::ModeDescription{
|
|
||||||
start:tup.0,
|
|
||||||
spawns:tup.1.into_iter().enumerate().map(|(i,tup)|{eshmep1.insert(tup.0,i);tup.1}).collect(),
|
|
||||||
ordered_checkpoints:tup.2.into_iter().enumerate().map(|(i,tup)|{eshmep2.insert(tup.0,i);tup.1}).collect(),
|
|
||||||
unordered_checkpoints:tup.3,
|
|
||||||
spawn_from_stage_id:eshmep1,
|
|
||||||
ordered_checkpoint_from_checkpoint_id:eshmep2,
|
|
||||||
}
|
|
||||||
}).collect());
|
|
||||||
println!("Physics Objects: {}",self.physics.models.len());
|
|
||||||
}
|
|
||||||
fn generate_model_graphics(&mut self,device:&wgpu::Device,queue:&wgpu::Queue,indexed_models:model::IndexedModelInstances){
|
fn generate_model_graphics(&mut self,device:&wgpu::Device,queue:&wgpu::Queue,indexed_models:model::IndexedModelInstances){
|
||||||
//generate texture view per texture
|
//generate texture view per texture
|
||||||
|
|
||||||
@ -408,20 +389,6 @@ fn get_instances_buffer_data(instances:&[ModelGraphicsInstance]) -> Vec<f32> {
|
|||||||
raw
|
raw
|
||||||
}
|
}
|
||||||
|
|
||||||
fn to_uniform_data(camera: &physics::Camera, pos: glam::Vec3) -> [f32; 16 * 3 + 4] {
|
|
||||||
let proj=camera.proj();
|
|
||||||
let proj_inv = proj.inverse();
|
|
||||||
let view=camera.view(pos);
|
|
||||||
let view_inv = view.inverse();
|
|
||||||
|
|
||||||
let mut raw = [0f32; 16 * 3 + 4];
|
|
||||||
raw[..16].copy_from_slice(&AsRef::<[f32; 16]>::as_ref(&proj)[..]);
|
|
||||||
raw[16..32].copy_from_slice(&AsRef::<[f32; 16]>::as_ref(&proj_inv)[..]);
|
|
||||||
raw[32..48].copy_from_slice(&AsRef::<[f32; 16]>::as_ref(&view_inv)[..]);
|
|
||||||
raw[48..52].copy_from_slice(AsRef::<[f32; 4]>::as_ref(&view.col(3)));
|
|
||||||
raw
|
|
||||||
}
|
|
||||||
|
|
||||||
impl framework::Example for GlobalState {
|
impl framework::Example for GlobalState {
|
||||||
fn optional_features() -> wgpu::Features {
|
fn optional_features() -> wgpu::Features {
|
||||||
wgpu::Features::TEXTURE_COMPRESSION_ASTC
|
wgpu::Features::TEXTURE_COMPRESSION_ASTC
|
||||||
@ -582,25 +549,6 @@ impl framework::Example for GlobalState {
|
|||||||
source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(include_str!("shader.wgsl"))),
|
source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(include_str!("shader.wgsl"))),
|
||||||
});
|
});
|
||||||
|
|
||||||
let physics = physics::PhysicsState {
|
|
||||||
spawn_point:glam::vec3(0.0,50.0,0.0),
|
|
||||||
body: physics::Body::with_pva(glam::vec3(0.0,50.0,0.0),glam::vec3(0.0,0.0,0.0),glam::vec3(0.0,-100.0,0.0)),
|
|
||||||
time: 0,
|
|
||||||
style:physics::StyleModifiers::default(),
|
|
||||||
grounded: false,
|
|
||||||
contacts: std::collections::HashMap::new(),
|
|
||||||
intersects: std::collections::HashMap::new(),
|
|
||||||
models: Vec::new(),
|
|
||||||
walk: physics::WalkState::new(),
|
|
||||||
camera: physics::Camera::from_offset(glam::vec3(0.0,4.5-2.5,0.0),(config.width as f32)/(config.height as f32)),
|
|
||||||
mouse_interpolation: physics::MouseInterpolationState::new(),
|
|
||||||
controls: 0,
|
|
||||||
world:physics::WorldState{},
|
|
||||||
game:physics::GameMechanicsState::default(),
|
|
||||||
modes:Vec::new(),
|
|
||||||
mode_from_mode_id:std::collections::HashMap::new(),
|
|
||||||
};
|
|
||||||
|
|
||||||
//load textures
|
//load textures
|
||||||
let device_features = device.features();
|
let device_features = device.features();
|
||||||
|
|
||||||
@ -795,7 +743,10 @@ impl framework::Example for GlobalState {
|
|||||||
multiview: None,
|
multiview: None,
|
||||||
});
|
});
|
||||||
|
|
||||||
let camera_uniforms = to_uniform_data(&physics.camera,physics.body.extrapolated_position(0));
|
let mut physics = physics::PhysicsState::default();
|
||||||
|
|
||||||
|
let camera=GraphicsCamera::new(glam::uvec2(config.width,config.height), 1.0);
|
||||||
|
let camera_uniforms = camera.to_uniform_data(physics.output().adjust_mouse(&physics.next_mouse));
|
||||||
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),
|
||||||
@ -811,6 +762,7 @@ impl framework::Example for GlobalState {
|
|||||||
],
|
],
|
||||||
label: Some("Camera"),
|
label: Some("Camera"),
|
||||||
});
|
});
|
||||||
|
|
||||||
let skybox_texture_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
let skybox_texture_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||||
layout: &skybox_texture_bind_group_layout,
|
layout: &skybox_texture_bind_group_layout,
|
||||||
entries: &[
|
entries: &[
|
||||||
@ -829,7 +781,6 @@ impl framework::Example for GlobalState {
|
|||||||
let depth_view = Self::create_depth_texture(config, device);
|
let depth_view = Self::create_depth_texture(config, device);
|
||||||
|
|
||||||
let graphics=GraphicsState {
|
let graphics=GraphicsState {
|
||||||
screen_size: (config.width,config.height),
|
|
||||||
pipelines:GraphicsPipelines{
|
pipelines:GraphicsPipelines{
|
||||||
skybox:sky_pipeline,
|
skybox:sky_pipeline,
|
||||||
model:model_pipeline
|
model:model_pipeline
|
||||||
@ -838,6 +789,7 @@ impl framework::Example for GlobalState {
|
|||||||
camera:camera_bind_group,
|
camera:camera_bind_group,
|
||||||
skybox_texture:skybox_texture_bind_group,
|
skybox_texture:skybox_texture_bind_group,
|
||||||
},
|
},
|
||||||
|
camera,
|
||||||
camera_buf,
|
camera_buf,
|
||||||
models: Vec::new(),
|
models: Vec::new(),
|
||||||
depth_view,
|
depth_view,
|
||||||
@ -847,20 +799,30 @@ impl framework::Example for GlobalState {
|
|||||||
temp_squid_texture_view: squid_texture_view,
|
temp_squid_texture_view: squid_texture_view,
|
||||||
};
|
};
|
||||||
|
|
||||||
let mut state=GlobalState{
|
|
||||||
start_time:Instant::now(),
|
|
||||||
manual_mouse_lock:false,
|
|
||||||
graphics,
|
|
||||||
physics,
|
|
||||||
};
|
|
||||||
|
|
||||||
let indexed_model_instances=model::IndexedModelInstances{
|
let indexed_model_instances=model::IndexedModelInstances{
|
||||||
textures:Vec::new(),
|
textures:Vec::new(),
|
||||||
models:indexed_models,
|
models:indexed_models,
|
||||||
spawn_point:glam::Vec3::Y*50.0,
|
spawn_point:glam::Vec3::Y*50.0,
|
||||||
modes:Vec::new(),
|
modes:Vec::new(),
|
||||||
};
|
};
|
||||||
state.generate_model_physics(&indexed_model_instances);
|
|
||||||
|
//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(),
|
||||||
|
graphics,
|
||||||
|
physics_thread,
|
||||||
|
};
|
||||||
state.generate_model_graphics(&device,&queue,indexed_model_instances);
|
state.generate_model_graphics(&device,&queue,indexed_model_instances);
|
||||||
|
|
||||||
let args:Vec<String>=std::env::args().collect();
|
let args:Vec<String>=std::env::args().collect();
|
||||||
@ -884,7 +846,6 @@ impl framework::Example for GlobalState {
|
|||||||
//.snf = "SNMF"
|
//.snf = "SNMF"
|
||||||
//.snf = "SNBF"
|
//.snf = "SNBF"
|
||||||
if let (Ok(()),Ok(()))=(std::io::Read::read_exact(&mut input, &mut first_8),std::io::Seek::rewind(&mut input)){
|
if let (Ok(()),Ok(()))=(std::io::Read::read_exact(&mut input, &mut first_8),std::io::Seek::rewind(&mut input)){
|
||||||
//
|
|
||||||
if let Some(indexed_model_instances)={
|
if let Some(indexed_model_instances)={
|
||||||
match &first_8[0..4]{
|
match &first_8[0..4]{
|
||||||
b"<rob"=>{
|
b"<rob"=>{
|
||||||
@ -911,18 +872,20 @@ impl framework::Example for GlobalState {
|
|||||||
}{
|
}{
|
||||||
let spawn_point=indexed_model_instances.spawn_point;
|
let spawn_point=indexed_model_instances.spawn_point;
|
||||||
//if generate_indexed_models succeeds, clear the previous ones
|
//if generate_indexed_models succeeds, clear the previous ones
|
||||||
self.physics.clear();
|
|
||||||
self.graphics.clear();
|
self.graphics.clear();
|
||||||
self.physics.game.stage_id=0;
|
|
||||||
self.physics.spawn_point=spawn_point;
|
let mut physics=physics::PhysicsState::default();
|
||||||
self.generate_model_physics(&indexed_model_instances);
|
physics.game.stage_id=0;
|
||||||
|
physics.spawn_point=spawn_point;
|
||||||
|
physics.process_instruction(instruction::TimedInstruction{
|
||||||
|
time:physics.time,
|
||||||
|
instruction: PhysicsInstruction::Input(physics::PhysicsInputInstruction::Reset),
|
||||||
|
});
|
||||||
|
physics.generate_models(&indexed_model_instances);
|
||||||
|
self.physics_thread=physics.into_worker();
|
||||||
|
|
||||||
self.generate_model_graphics(device,queue,indexed_model_instances);
|
self.generate_model_graphics(device,queue,indexed_model_instances);
|
||||||
//manual reset
|
//manual reset
|
||||||
let time=self.physics.time;
|
|
||||||
instruction::InstructionConsumer::process_instruction(&mut self.physics, instruction::TimedInstruction{
|
|
||||||
time,
|
|
||||||
instruction: PhysicsInstruction::Input(InputInstruction::Reset),
|
|
||||||
});
|
|
||||||
}else{
|
}else{
|
||||||
println!("No modeldatas were generated");
|
println!("No modeldatas were generated");
|
||||||
}
|
}
|
||||||
@ -983,7 +946,7 @@ impl framework::Example for GlobalState {
|
|||||||
15=>{//Tab
|
15=>{//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.screen_size.0 as f32/2.0, self.graphics.screen_size.1 as f32/2.0)){
|
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)){
|
||||||
Ok(())=>(),
|
Ok(())=>(),
|
||||||
Err(e)=>println!("Could not set cursor position: {:?}",e),
|
Err(e)=>println!("Could not set cursor position: {:?}",e),
|
||||||
}
|
}
|
||||||
@ -1012,18 +975,17 @@ impl framework::Example for GlobalState {
|
|||||||
},
|
},
|
||||||
_ => {println!("scancode {}",keycode);None},
|
_ => {println!("scancode {}",keycode);None},
|
||||||
}{
|
}{
|
||||||
self.physics.run(time);
|
self.physics_thread.send(TimedInstruction{
|
||||||
self.physics.process_instruction(TimedInstruction{
|
|
||||||
time,
|
time,
|
||||||
instruction:PhysicsInstruction::Input(input_instruction),
|
instruction:input_instruction,
|
||||||
})
|
}).unwrap();
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
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.screen_size.0 as f32/2.0, self.graphics.screen_size.1 as f32/2.0)){
|
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)){
|
||||||
Ok(())=>(),
|
Ok(())=>(),
|
||||||
Err(e)=>println!("Could not set cursor position: {:?}",e),
|
Err(e)=>println!("Could not set cursor position: {:?}",e),
|
||||||
}
|
}
|
||||||
@ -1031,21 +993,22 @@ impl framework::Example for GlobalState {
|
|||||||
//do not step the physics because the mouse polling rate is higher than the physics can run.
|
//do not step the physics because the mouse polling rate is higher than the physics can run.
|
||||||
//essentially the previous input will be overwritten until a true step runs
|
//essentially the previous input will be overwritten until a true step runs
|
||||||
//which is fine because they run all the time.
|
//which is fine because they run all the time.
|
||||||
self.physics.process_instruction(TimedInstruction{
|
let delta=glam::ivec2(delta.0 as i32,delta.1 as i32);
|
||||||
|
self.mouse.pos+=delta;
|
||||||
|
self.physics_thread.send(TimedInstruction{
|
||||||
time,
|
time,
|
||||||
instruction:PhysicsInstruction::Input(InputInstruction::MoveMouse(glam::ivec2(delta.0 as i32,delta.1 as i32))),
|
instruction:InputInstruction::MoveMouse(self.mouse.pos),
|
||||||
})
|
}).unwrap();
|
||||||
},
|
},
|
||||||
winit::event::DeviceEvent::MouseWheel {
|
winit::event::DeviceEvent::MouseWheel {
|
||||||
delta,
|
delta,
|
||||||
} => {
|
} => {
|
||||||
println!("mousewheel {:?}",delta);
|
println!("mousewheel {:?}",delta);
|
||||||
if false{//self.physics.style.use_scroll{
|
if false{//self.physics.style.use_scroll{
|
||||||
self.physics.run(time);
|
self.physics_thread.send(TimedInstruction{
|
||||||
self.physics.process_instruction(TimedInstruction{
|
|
||||||
time,
|
time,
|
||||||
instruction:PhysicsInstruction::Input(InputInstruction::Jump(true)),//activates the immediate jump path, but the style modifier prevents controls&CONTROL_JUMP bit from being set to auto jump
|
instruction:InputInstruction::Jump(true),//activates the immediate jump path, but the style modifier prevents controls&CONTROL_JUMP bit from being set to auto jump
|
||||||
})
|
}).unwrap();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
_=>(),
|
_=>(),
|
||||||
@ -1059,8 +1022,7 @@ impl framework::Example for GlobalState {
|
|||||||
_queue: &wgpu::Queue,
|
_queue: &wgpu::Queue,
|
||||||
) {
|
) {
|
||||||
self.graphics.depth_view = Self::create_depth_texture(config, device);
|
self.graphics.depth_view = Self::create_depth_texture(config, device);
|
||||||
self.graphics.screen_size = (config.width, config.height);
|
self.graphics.camera.set_screen_size(glam::uvec2(config.width, config.height));
|
||||||
self.physics.camera.set_fov_aspect(1.0,(config.width as f32)/(config.height as f32));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn render(
|
fn render(
|
||||||
@ -1070,15 +1032,20 @@ impl framework::Example for GlobalState {
|
|||||||
queue: &wgpu::Queue,
|
queue: &wgpu::Queue,
|
||||||
_spawner: &framework::Spawner,
|
_spawner: &framework::Spawner,
|
||||||
) {
|
) {
|
||||||
|
//ideally this would be scheduled to execute and finish right before the render.
|
||||||
let time=self.start_time.elapsed().as_nanos() as i64;
|
let time=self.start_time.elapsed().as_nanos() as i64;
|
||||||
|
self.physics_thread.send(TimedInstruction{
|
||||||
self.physics.run(time);
|
time,
|
||||||
|
instruction: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 = to_uniform_data(&self.physics.camera,self.physics.body.extrapolated_position(time));
|
let camera_uniforms = self.graphics.camera.to_uniform_data(self.physics_thread.grab_clone().adjust_mouse(&self.mouse));
|
||||||
self.graphics.staging_belt
|
self.graphics.staging_belt
|
||||||
.write_buffer(
|
.write_buffer(
|
||||||
&mut encoder,
|
&mut encoder,
|
||||||
@ -1089,6 +1056,7 @@ impl framework::Example for GlobalState {
|
|||||||
)
|
)
|
||||||
.copy_from_slice(bytemuck::cast_slice(&camera_uniforms));
|
.copy_from_slice(bytemuck::cast_slice(&camera_uniforms));
|
||||||
//This code only needs to run when the uniforms change
|
//This code only needs to run when the uniforms change
|
||||||
|
/*
|
||||||
for model in self.graphics.models.iter() {
|
for model in self.graphics.models.iter() {
|
||||||
let model_uniforms = get_instances_buffer_data(&model.instances);
|
let model_uniforms = get_instances_buffer_data(&model.instances);
|
||||||
self.graphics.staging_belt
|
self.graphics.staging_belt
|
||||||
@ -1101,6 +1069,7 @@ impl framework::Example for GlobalState {
|
|||||||
)
|
)
|
||||||
.copy_from_slice(bytemuck::cast_slice(&model_uniforms));
|
.copy_from_slice(bytemuck::cast_slice(&model_uniforms));
|
||||||
}
|
}
|
||||||
|
*/
|
||||||
self.graphics.staging_belt.finish();
|
self.graphics.staging_belt.finish();
|
||||||
|
|
||||||
{
|
{
|
||||||
|
383
src/physics.rs
383
src/physics.rs
@ -13,7 +13,22 @@ pub enum PhysicsInstruction {
|
|||||||
// bool,//true = Force
|
// bool,//true = Force
|
||||||
// )
|
// )
|
||||||
//InputInstructions conditionally activate RefreshWalkTarget (by doing what SetWalkTargetVelocity used to do and then flagging it)
|
//InputInstructions conditionally activate RefreshWalkTarget (by doing what SetWalkTargetVelocity used to do and then flagging it)
|
||||||
Input(InputInstruction),
|
Input(PhysicsInputInstruction),
|
||||||
|
}
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub enum PhysicsInputInstruction {
|
||||||
|
ReplaceMouse(MouseState,MouseState),
|
||||||
|
SetNextMouse(MouseState),
|
||||||
|
SetMoveForward(bool),
|
||||||
|
SetMoveLeft(bool),
|
||||||
|
SetMoveBack(bool),
|
||||||
|
SetMoveRight(bool),
|
||||||
|
SetMoveUp(bool),
|
||||||
|
SetMoveDown(bool),
|
||||||
|
SetJump(bool),
|
||||||
|
SetZoom(bool),
|
||||||
|
Reset,
|
||||||
|
Idle,
|
||||||
}
|
}
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub enum InputInstruction {
|
pub enum InputInstruction {
|
||||||
@ -32,7 +47,7 @@ pub enum InputInstruction {
|
|||||||
//for interpolation / networking / playback reasons, most playback heads will always want
|
//for interpolation / networking / playback reasons, most playback heads will always want
|
||||||
//to be 1 instruction ahead to generate the next state for interpolation.
|
//to be 1 instruction ahead to generate the next state for interpolation.
|
||||||
}
|
}
|
||||||
#[derive(Clone,Debug)]
|
#[derive(Clone)]
|
||||||
pub struct Body {
|
pub struct Body {
|
||||||
position: glam::Vec3,//I64 where 2^32 = 1 u
|
position: glam::Vec3,//I64 where 2^32 = 1 u
|
||||||
velocity: glam::Vec3,//I64 where 2^32 = 1 u/s
|
velocity: glam::Vec3,//I64 where 2^32 = 1 u/s
|
||||||
@ -91,49 +106,30 @@ impl crate::instruction::InstructionConsumer<InputInstruction> for InputState{
|
|||||||
}
|
}
|
||||||
*/
|
*/
|
||||||
|
|
||||||
enum MouseInterpolation {
|
|
||||||
First,//just checks the last value
|
|
||||||
Lerp,//lerps between
|
|
||||||
}
|
|
||||||
|
|
||||||
//hey dumbass just use a delta
|
//hey dumbass just use a delta
|
||||||
pub struct MouseInterpolationState {
|
#[derive(Clone,Debug)]
|
||||||
interpolation: MouseInterpolation,
|
pub struct MouseState {
|
||||||
time0: TIME,
|
pub pos: glam::IVec2,
|
||||||
time1: TIME,
|
pub time: TIME,
|
||||||
mouse0: glam::IVec2,
|
|
||||||
mouse1: glam::IVec2,
|
|
||||||
}
|
}
|
||||||
|
impl Default for MouseState{
|
||||||
impl MouseInterpolationState {
|
fn default() -> Self {
|
||||||
pub fn new() -> Self {
|
|
||||||
Self {
|
Self {
|
||||||
interpolation:MouseInterpolation::First,
|
time:0,
|
||||||
time0:0,
|
pos:glam::IVec2::ZERO,
|
||||||
time1:1,//ONE NANOSECOND!!!! avoid divide by zero
|
|
||||||
mouse0:glam::IVec2::ZERO,
|
|
||||||
mouse1:glam::IVec2::ZERO,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
pub fn move_mouse(&mut self,time:TIME,delta:glam::IVec2){
|
}
|
||||||
self.time0=self.time1;
|
impl MouseState {
|
||||||
self.mouse0=self.mouse1;
|
pub fn lerp(&self,target:&MouseState,time:TIME)->glam::IVec2 {
|
||||||
self.time1=time;
|
let m0=self.pos.as_i64vec2();
|
||||||
self.mouse1=self.mouse1+delta;
|
let m1=target.pos.as_i64vec2();
|
||||||
}
|
//these are deltas
|
||||||
pub fn interpolated_position(&self,time:TIME) -> glam::IVec2 {
|
//let time=time.clamp(self.time, target.time);
|
||||||
match self.interpolation {
|
let t1t=(target.time-time) as i64;
|
||||||
MouseInterpolation::First => self.mouse0,
|
let tt0=(time-self.time) as i64;
|
||||||
MouseInterpolation::Lerp => {
|
let dt=(target.time-self.time) as i64;
|
||||||
let m0=self.mouse0.as_i64vec2();
|
((m0*t1t+m1*tt0)/dt).as_ivec2()
|
||||||
let m1=self.mouse1.as_i64vec2();
|
|
||||||
//these are deltas
|
|
||||||
let t1t=(self.time1-time) as i64;
|
|
||||||
let tt0=(time-self.time0) as i64;
|
|
||||||
let dt=(self.time1-self.time0) as i64;
|
|
||||||
((m0*t1t+m1*tt0)/dt).as_ivec2()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -156,15 +152,14 @@ impl WalkState {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Note: we use the Y=up coordinate space in this example.
|
#[derive(Clone)]
|
||||||
pub struct Camera {
|
pub struct PhysicsCamera {
|
||||||
offset: glam::Vec3,
|
offset: glam::Vec3,
|
||||||
angles: glam::DVec2,//YAW AND THEN PITCH
|
angles: glam::DVec2,//YAW AND THEN PITCH
|
||||||
//punch: glam::Vec3,
|
//punch: glam::Vec3,
|
||||||
//punch_velocity: glam::Vec3,
|
//punch_velocity: glam::Vec3,
|
||||||
fov: glam::Vec2,//slope
|
|
||||||
sensitivity: glam::DVec2,
|
sensitivity: glam::DVec2,
|
||||||
time: TIME,
|
mouse:MouseState,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
@ -176,45 +171,22 @@ fn mat3_from_rotation_y_f64(angle: f64) -> glam::Mat3 {
|
|||||||
glam::Vec3::new(sina as f32, 0.0, cosa as f32),
|
glam::Vec3::new(sina as f32, 0.0, cosa as f32),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
#[inline]
|
impl PhysicsCamera {
|
||||||
fn perspective_rh(fov_x_slope: f32, fov_y_slope: f32, z_near: f32, z_far: f32) -> glam::Mat4 {
|
pub fn from_offset(offset:glam::Vec3) -> Self {
|
||||||
//glam_assert!(z_near > 0.0 && z_far > 0.0);
|
|
||||||
let r = z_far / (z_near - z_far);
|
|
||||||
glam::Mat4::from_cols(
|
|
||||||
glam::Vec4::new(1.0/fov_x_slope, 0.0, 0.0, 0.0),
|
|
||||||
glam::Vec4::new(0.0, 1.0/fov_y_slope, 0.0, 0.0),
|
|
||||||
glam::Vec4::new(0.0, 0.0, r, -1.0),
|
|
||||||
glam::Vec4::new(0.0, 0.0, r * z_near, 0.0),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
impl Camera {
|
|
||||||
pub fn from_offset(offset:glam::Vec3,aspect:f32) -> Self {
|
|
||||||
Self{
|
Self{
|
||||||
offset,
|
offset,
|
||||||
angles: glam::DVec2::ZERO,
|
angles: glam::DVec2::ZERO,
|
||||||
fov: glam::vec2(aspect,1.0),
|
|
||||||
sensitivity: glam::dvec2(1.0/16384.0,1.0/16384.0),
|
sensitivity: glam::dvec2(1.0/16384.0,1.0/16384.0),
|
||||||
time: 0,
|
mouse:MouseState{pos:glam::IVec2::ZERO,time:-1},//escape initialization hell divide by zero
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
fn simulate_move_angles(&self, delta: glam::IVec2) -> glam::DVec2 {
|
pub fn simulate_move_angles(&self, mouse_pos: glam::IVec2) -> glam::DVec2 {
|
||||||
let mut a=self.angles-self.sensitivity*delta.as_dvec2();
|
let mut a=self.angles-self.sensitivity*(mouse_pos-self.mouse.pos).as_dvec2();
|
||||||
a.y=a.y.clamp(-std::f64::consts::FRAC_PI_2, std::f64::consts::FRAC_PI_2);
|
a.y=a.y.clamp(-std::f64::consts::FRAC_PI_2, std::f64::consts::FRAC_PI_2);
|
||||||
return a
|
return a
|
||||||
}
|
}
|
||||||
fn simulate_move_rotation_y(&self, delta_x: i32) -> glam::Mat3 {
|
fn simulate_move_rotation_y(&self, mouse_pos_x: i32) -> glam::Mat3 {
|
||||||
mat3_from_rotation_y_f64(self.angles.x-self.sensitivity.x*(delta_x as f64))
|
mat3_from_rotation_y_f64(self.angles.x-self.sensitivity.x*((mouse_pos_x-self.mouse.pos.x) as f64))
|
||||||
}
|
|
||||||
pub fn proj(&self)->glam::Mat4{
|
|
||||||
perspective_rh(self.fov.x, self.fov.y, 0.5, 2000.0)
|
|
||||||
}
|
|
||||||
pub fn view(&self,pos:glam::Vec3)->glam::Mat4{
|
|
||||||
//f32 good enough for view matrix
|
|
||||||
glam::Mat4::from_translation(pos+self.offset) * glam::Mat4::from_euler(glam::EulerRot::YXZ, self.angles.x as f32, self.angles.y as f32, 0f32)
|
|
||||||
}
|
|
||||||
pub fn set_fov_aspect(&mut self,fov:f32,aspect:f32){
|
|
||||||
self.fov.x=fov*aspect;
|
|
||||||
self.fov.y=fov;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -275,7 +247,7 @@ impl StyleModifiers{
|
|||||||
const UP_DIR:glam::Vec3 = glam::Vec3::Y;
|
const UP_DIR:glam::Vec3 = glam::Vec3::Y;
|
||||||
|
|
||||||
fn get_control(&self,control:u32,controls:u32)->bool{
|
fn get_control(&self,control:u32,controls:u32)->bool{
|
||||||
controls&self.controls_mask&control!=0
|
controls&self.controls_mask&control==control
|
||||||
}
|
}
|
||||||
|
|
||||||
fn get_control_dir(&self,controls:u32)->glam::Vec3{
|
fn get_control_dir(&self,controls:u32)->glam::Vec3{
|
||||||
@ -319,8 +291,8 @@ pub struct PhysicsState{
|
|||||||
pub intersects:std::collections::HashMap::<u32,RelativeCollision>,
|
pub intersects:std::collections::HashMap::<u32,RelativeCollision>,
|
||||||
//pub intersections: Vec<ModelId>,
|
//pub intersections: Vec<ModelId>,
|
||||||
//camera must exist in state because wormholes modify the camera, also camera punch
|
//camera must exist in state because wormholes modify the camera, also camera punch
|
||||||
pub camera:Camera,
|
pub camera:PhysicsCamera,
|
||||||
pub mouse_interpolation:MouseInterpolationState,
|
pub next_mouse:MouseState,//Where is the mouse headed next
|
||||||
pub controls:u32,
|
pub controls:u32,
|
||||||
pub walk:WalkState,
|
pub walk:WalkState,
|
||||||
pub grounded:bool,
|
pub grounded:bool,
|
||||||
@ -333,6 +305,16 @@ 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
|
||||||
pub spawn_point:glam::Vec3,
|
pub spawn_point:glam::Vec3,
|
||||||
}
|
}
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct PhysicsOutputState{
|
||||||
|
camera:PhysicsCamera,
|
||||||
|
body:Body,
|
||||||
|
}
|
||||||
|
impl PhysicsOutputState{
|
||||||
|
pub fn adjust_mouse(&self,mouse:&MouseState)->(glam::Vec3,glam::Vec2){
|
||||||
|
(self.body.extrapolated_position(mouse.time)+self.camera.offset,self.camera.simulate_move_angles(mouse.pos).as_vec2())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Debug,Clone,Copy,Hash,Eq,PartialEq)]
|
#[derive(Debug,Clone,Copy,Hash,Eq,PartialEq)]
|
||||||
pub enum AabbFace{
|
pub enum AabbFace{
|
||||||
@ -554,6 +536,29 @@ impl Body {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl Default for PhysicsState{
|
||||||
|
fn default() -> Self {
|
||||||
|
Self{
|
||||||
|
spawn_point:glam::vec3(0.0,50.0,0.0),
|
||||||
|
body: Body::with_pva(glam::vec3(0.0,50.0,0.0),glam::vec3(0.0,0.0,0.0),glam::vec3(0.0,-100.0,0.0)),
|
||||||
|
time: 0,
|
||||||
|
style:StyleModifiers::default(),
|
||||||
|
grounded: false,
|
||||||
|
contacts: std::collections::HashMap::new(),
|
||||||
|
intersects: std::collections::HashMap::new(),
|
||||||
|
models: Vec::new(),
|
||||||
|
walk: WalkState::new(),
|
||||||
|
camera: PhysicsCamera::from_offset(glam::vec3(0.0,4.5-2.5,0.0)),
|
||||||
|
next_mouse: MouseState::default(),
|
||||||
|
controls: 0,
|
||||||
|
world:WorldState{},
|
||||||
|
game:GameMechanicsState::default(),
|
||||||
|
modes:Vec::new(),
|
||||||
|
mode_from_mode_id:std::collections::HashMap::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
impl PhysicsState {
|
impl PhysicsState {
|
||||||
pub fn clear(&mut self){
|
pub fn clear(&mut self){
|
||||||
self.models.clear();
|
self.models.clear();
|
||||||
@ -561,6 +566,173 @@ impl PhysicsState {
|
|||||||
self.contacts.clear();
|
self.contacts.clear();
|
||||||
self.intersects.clear();
|
self.intersects.clear();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn into_worker(mut self)->crate::worker::CompatWorker<TimedInstruction<InputInstruction>,PhysicsOutputState,Box<dyn FnMut(TimedInstruction<InputInstruction>)->PhysicsOutputState>>{
|
||||||
|
let mut mouse_blocking=true;
|
||||||
|
let mut last_mouse_time=self.next_mouse.time;
|
||||||
|
let mut timeline=std::collections::VecDeque::new();
|
||||||
|
crate::worker::CompatWorker::new(self.output(),Box::new(move |ins:TimedInstruction<InputInstruction>|{
|
||||||
|
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.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::Idle=>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 10_000_000<ins.time-self.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.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.run(instruction.time);
|
||||||
|
self.process_instruction(TimedInstruction{
|
||||||
|
time:instruction.time,
|
||||||
|
instruction:PhysicsInstruction::Input(instruction.instruction),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
self.output()
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn output(&self)->PhysicsOutputState{
|
||||||
|
PhysicsOutputState{
|
||||||
|
body:self.body.clone(),
|
||||||
|
camera:self.camera.clone(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn generate_models(&mut self,indexed_models:&crate::model::IndexedModelInstances){
|
||||||
|
let mut starts=Vec::new();
|
||||||
|
let mut spawns=Vec::new();
|
||||||
|
let mut ordered_checkpoints=Vec::new();
|
||||||
|
let mut unordered_checkpoints=Vec::new();
|
||||||
|
for model in &indexed_models.models{
|
||||||
|
//make aabb and run vertices to get realistic bounds
|
||||||
|
for model_instance in &model.instances{
|
||||||
|
if let Some(model_physics)=ModelPhysics::from_model(model,model_instance){
|
||||||
|
let model_id=self.models.len() as u32;
|
||||||
|
self.models.push(model_physics);
|
||||||
|
for attr in &model_instance.temp_indexing{
|
||||||
|
match attr{
|
||||||
|
crate::model::TempIndexedAttributes::Start{mode_id}=>starts.push((*mode_id,model_id)),
|
||||||
|
crate::model::TempIndexedAttributes::Spawn{mode_id,stage_id}=>spawns.push((*mode_id,model_id,*stage_id)),
|
||||||
|
crate::model::TempIndexedAttributes::OrderedCheckpoint{mode_id,checkpoint_id}=>ordered_checkpoints.push((*mode_id,model_id,*checkpoint_id)),
|
||||||
|
crate::model::TempIndexedAttributes::UnorderedCheckpoint{mode_id}=>unordered_checkpoints.push((*mode_id,model_id)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
//I don't wanna write structs for temporary structures
|
||||||
|
//this code builds ModeDescriptions from the unsorted lists at the top of the function
|
||||||
|
starts.sort_by_key(|tup|tup.0);
|
||||||
|
let mut eshmep=std::collections::HashMap::new();
|
||||||
|
let mut modedatas:Vec<(u32,Vec<(u32,u32)>,Vec<(u32,u32)>,Vec<u32>)>=starts.into_iter().enumerate().map(|(i,tup)|{
|
||||||
|
eshmep.insert(tup.0,i);
|
||||||
|
(tup.1,Vec::new(),Vec::new(),Vec::new())
|
||||||
|
}).collect();
|
||||||
|
for tup in spawns{
|
||||||
|
if let Some(mode_id)=eshmep.get(&tup.0){
|
||||||
|
if let Some(modedata)=modedatas.get_mut(*mode_id){
|
||||||
|
modedata.1.push((tup.2,tup.1));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for tup in ordered_checkpoints{
|
||||||
|
if let Some(mode_id)=eshmep.get(&tup.0){
|
||||||
|
if let Some(modedata)=modedatas.get_mut(*mode_id){
|
||||||
|
modedata.2.push((tup.2,tup.1));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for tup in unordered_checkpoints{
|
||||||
|
if let Some(mode_id)=eshmep.get(&tup.0){
|
||||||
|
if let Some(modedata)=modedatas.get_mut(*mode_id){
|
||||||
|
modedata.3.push(tup.1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let num_modes=self.modes.len();
|
||||||
|
for (mode_id,mode) in eshmep{
|
||||||
|
self.mode_from_mode_id.insert(mode_id,num_modes+mode);
|
||||||
|
}
|
||||||
|
self.modes.append(&mut modedatas.into_iter().map(|mut tup|{
|
||||||
|
tup.1.sort_by_key(|tup|tup.0);
|
||||||
|
tup.2.sort_by_key(|tup|tup.0);
|
||||||
|
let mut eshmep1=std::collections::HashMap::new();
|
||||||
|
let mut eshmep2=std::collections::HashMap::new();
|
||||||
|
crate::model::ModeDescription{
|
||||||
|
start:tup.0,
|
||||||
|
spawns:tup.1.into_iter().enumerate().map(|(i,tup)|{eshmep1.insert(tup.0,i);tup.1}).collect(),
|
||||||
|
ordered_checkpoints:tup.2.into_iter().enumerate().map(|(i,tup)|{eshmep2.insert(tup.0,i);tup.1}).collect(),
|
||||||
|
unordered_checkpoints:tup.3,
|
||||||
|
spawn_from_stage_id:eshmep1,
|
||||||
|
ordered_checkpoint_from_checkpoint_id:eshmep2,
|
||||||
|
}
|
||||||
|
}).collect());
|
||||||
|
println!("Physics Objects: {}",self.models.len());
|
||||||
|
}
|
||||||
|
|
||||||
pub fn get_mode(&self,mode_id:u32)->Option<&crate::model::ModeDescription>{
|
pub fn get_mode(&self,mode_id:u32)->Option<&crate::model::ModeDescription>{
|
||||||
if let Some(&mode)=self.mode_from_mode_id.get(&mode_id){
|
if let Some(&mode)=self.mode_from_mode_id.get(&mode_id){
|
||||||
self.modes.get(mode)
|
self.modes.get(mode)
|
||||||
@ -1004,13 +1176,15 @@ impl crate::instruction::InstructionEmitter<PhysicsInstruction> for PhysicsState
|
|||||||
impl crate::instruction::InstructionConsumer<PhysicsInstruction> for PhysicsState {
|
impl crate::instruction::InstructionConsumer<PhysicsInstruction> for PhysicsState {
|
||||||
fn process_instruction(&mut self, ins:TimedInstruction<PhysicsInstruction>) {
|
fn process_instruction(&mut self, ins:TimedInstruction<PhysicsInstruction>) {
|
||||||
match &ins.instruction {
|
match &ins.instruction {
|
||||||
PhysicsInstruction::StrafeTick => (),
|
PhysicsInstruction::Input(PhysicsInputInstruction::Idle)
|
||||||
PhysicsInstruction::Input(InputInstruction::MoveMouse(_)) => (),
|
|PhysicsInstruction::Input(PhysicsInputInstruction::SetNextMouse(_))
|
||||||
|
|PhysicsInstruction::Input(PhysicsInputInstruction::ReplaceMouse(_,_))
|
||||||
|
|PhysicsInstruction::StrafeTick => (),
|
||||||
_=>println!("{}|{:?}",ins.time,ins.instruction),
|
_=>println!("{}|{:?}",ins.time,ins.instruction),
|
||||||
}
|
}
|
||||||
//selectively update body
|
//selectively update body
|
||||||
match &ins.instruction {
|
match &ins.instruction {
|
||||||
PhysicsInstruction::Input(InputInstruction::MoveMouse(_)) => (),//dodge time for mouse movement
|
//PhysicsInstruction::Input(InputInstruction::MoveMouse(_)) => (),//dodge time for mouse movement
|
||||||
PhysicsInstruction::Input(_)
|
PhysicsInstruction::Input(_)
|
||||||
|PhysicsInstruction::ReachWalkTargetVelocity
|
|PhysicsInstruction::ReachWalkTargetVelocity
|
||||||
|PhysicsInstruction::CollisionStart(_)
|
|PhysicsInstruction::CollisionStart(_)
|
||||||
@ -1032,10 +1206,8 @@ impl crate::instruction::InstructionConsumer<PhysicsInstruction> for PhysicsStat
|
|||||||
_ => (),
|
_ => (),
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
match &general.booster{
|
//check ground
|
||||||
Some(booster)=>self.body.velocity+=booster.velocity,
|
self.contacts.insert(c.model,c);
|
||||||
None=>(),
|
|
||||||
}
|
|
||||||
match &general.stage_element{
|
match &general.stage_element{
|
||||||
Some(stage_element)=>{
|
Some(stage_element)=>{
|
||||||
if stage_element.force||self.game.stage_id<stage_element.stage_id{
|
if stage_element.force||self.game.stage_id<stage_element.stage_id{
|
||||||
@ -1065,11 +1237,16 @@ impl crate::instruction::InstructionConsumer<PhysicsInstruction> for PhysicsStat
|
|||||||
},
|
},
|
||||||
None=>(),
|
None=>(),
|
||||||
}
|
}
|
||||||
//check ground
|
|
||||||
self.contacts.insert(c.model,c);
|
|
||||||
//flatten v
|
//flatten v
|
||||||
let mut v=self.body.velocity;
|
let mut v=self.body.velocity;
|
||||||
self.contact_constrain_velocity(&mut v);
|
self.contact_constrain_velocity(&mut v);
|
||||||
|
match &general.booster{
|
||||||
|
Some(booster)=>{
|
||||||
|
v+=booster.velocity;
|
||||||
|
self.contact_constrain_velocity(&mut v);
|
||||||
|
},
|
||||||
|
None=>(),
|
||||||
|
}
|
||||||
self.body.velocity=v;
|
self.body.velocity=v;
|
||||||
if self.grounded&&self.style.get_control(StyleModifiers::CONTROL_JUMP,self.controls){
|
if self.grounded&&self.style.get_control(StyleModifiers::CONTROL_JUMP,self.controls){
|
||||||
self.jump();
|
self.jump();
|
||||||
@ -1105,7 +1282,7 @@ impl crate::instruction::InstructionConsumer<PhysicsInstruction> for PhysicsStat
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
PhysicsInstruction::StrafeTick => {
|
PhysicsInstruction::StrafeTick => {
|
||||||
let camera_mat=self.camera.simulate_move_rotation_y(self.mouse_interpolation.interpolated_position(self.time).x-self.mouse_interpolation.mouse0.x);
|
let camera_mat=self.camera.simulate_move_rotation_y(self.camera.mouse.lerp(&self.next_mouse,self.time).x);
|
||||||
let control_dir=camera_mat*self.style.get_control_dir(self.controls);
|
let control_dir=camera_mat*self.style.get_control_dir(self.controls);
|
||||||
let d=self.body.velocity.dot(control_dir);
|
let d=self.body.velocity.dot(control_dir);
|
||||||
if d<self.style.mv {
|
if d<self.style.mv {
|
||||||
@ -1128,28 +1305,32 @@ impl crate::instruction::InstructionConsumer<PhysicsInstruction> for PhysicsStat
|
|||||||
let mut refresh_walk_target=true;
|
let mut refresh_walk_target=true;
|
||||||
let mut refresh_walk_target_velocity=true;
|
let mut refresh_walk_target_velocity=true;
|
||||||
match input_instruction{
|
match input_instruction{
|
||||||
InputInstruction::MoveMouse(m) => {
|
PhysicsInputInstruction::SetNextMouse(m) => {
|
||||||
self.camera.angles=self.camera.simulate_move_angles(self.mouse_interpolation.mouse1-self.mouse_interpolation.mouse0);
|
self.camera.angles=self.camera.simulate_move_angles(self.next_mouse.pos);
|
||||||
self.mouse_interpolation.move_mouse(self.time,m);
|
(self.camera.mouse,self.next_mouse)=(self.next_mouse.clone(),m);
|
||||||
},
|
},
|
||||||
InputInstruction::MoveForward(s) => self.set_control(StyleModifiers::CONTROL_MOVEFORWARD,s),
|
PhysicsInputInstruction::ReplaceMouse(m0,m1) => {
|
||||||
InputInstruction::MoveLeft(s) => self.set_control(StyleModifiers::CONTROL_MOVELEFT,s),
|
self.camera.angles=self.camera.simulate_move_angles(m0.pos);
|
||||||
InputInstruction::MoveBack(s) => self.set_control(StyleModifiers::CONTROL_MOVEBACK,s),
|
(self.camera.mouse,self.next_mouse)=(m0,m1);
|
||||||
InputInstruction::MoveRight(s) => self.set_control(StyleModifiers::CONTROL_MOVERIGHT,s),
|
},
|
||||||
InputInstruction::MoveUp(s) => self.set_control(StyleModifiers::CONTROL_MOVEUP,s),
|
PhysicsInputInstruction::SetMoveForward(s) => self.set_control(StyleModifiers::CONTROL_MOVEFORWARD,s),
|
||||||
InputInstruction::MoveDown(s) => self.set_control(StyleModifiers::CONTROL_MOVEDOWN,s),
|
PhysicsInputInstruction::SetMoveLeft(s) => self.set_control(StyleModifiers::CONTROL_MOVELEFT,s),
|
||||||
InputInstruction::Jump(s) => {
|
PhysicsInputInstruction::SetMoveBack(s) => self.set_control(StyleModifiers::CONTROL_MOVEBACK,s),
|
||||||
|
PhysicsInputInstruction::SetMoveRight(s) => self.set_control(StyleModifiers::CONTROL_MOVERIGHT,s),
|
||||||
|
PhysicsInputInstruction::SetMoveUp(s) => self.set_control(StyleModifiers::CONTROL_MOVEUP,s),
|
||||||
|
PhysicsInputInstruction::SetMoveDown(s) => self.set_control(StyleModifiers::CONTROL_MOVEDOWN,s),
|
||||||
|
PhysicsInputInstruction::SetJump(s) => {
|
||||||
self.set_control(StyleModifiers::CONTROL_JUMP,s);
|
self.set_control(StyleModifiers::CONTROL_JUMP,s);
|
||||||
if self.grounded{
|
if self.grounded{
|
||||||
self.jump();
|
self.jump();
|
||||||
}
|
}
|
||||||
refresh_walk_target_velocity=false;
|
refresh_walk_target_velocity=false;
|
||||||
},
|
},
|
||||||
InputInstruction::Zoom(s) => {
|
PhysicsInputInstruction::SetZoom(s) => {
|
||||||
self.set_control(StyleModifiers::CONTROL_ZOOM,s);
|
self.set_control(StyleModifiers::CONTROL_ZOOM,s);
|
||||||
refresh_walk_target=false;
|
refresh_walk_target=false;
|
||||||
},
|
},
|
||||||
InputInstruction::Reset => {
|
PhysicsInputInstruction::Reset => {
|
||||||
//temp
|
//temp
|
||||||
self.body.position=self.spawn_point;
|
self.body.position=self.spawn_point;
|
||||||
self.body.velocity=glam::Vec3::ZERO;
|
self.body.velocity=glam::Vec3::ZERO;
|
||||||
@ -1160,12 +1341,12 @@ impl crate::instruction::InstructionConsumer<PhysicsInstruction> for PhysicsStat
|
|||||||
self.grounded=false;
|
self.grounded=false;
|
||||||
refresh_walk_target=false;
|
refresh_walk_target=false;
|
||||||
},
|
},
|
||||||
InputInstruction::Idle => {refresh_walk_target=false;},//literally idle!
|
PhysicsInputInstruction::Idle => {refresh_walk_target=false;},//literally idle!
|
||||||
}
|
}
|
||||||
if refresh_walk_target{
|
if refresh_walk_target{
|
||||||
//calculate walk target velocity
|
//calculate walk target velocity
|
||||||
if refresh_walk_target_velocity{
|
if refresh_walk_target_velocity{
|
||||||
let camera_mat=self.camera.simulate_move_rotation_y(self.mouse_interpolation.interpolated_position(self.time).x-self.mouse_interpolation.mouse0.x);
|
let camera_mat=self.camera.simulate_move_rotation_y(self.camera.mouse.lerp(&self.next_mouse,self.time).x);
|
||||||
let control_dir=camera_mat*self.style.get_control_dir(self.controls);
|
let control_dir=camera_mat*self.style.get_control_dir(self.controls);
|
||||||
self.walk.target_velocity=self.style.walkspeed*control_dir;
|
self.walk.target_velocity=self.style.walkspeed*control_dir;
|
||||||
}
|
}
|
||||||
|
@ -6,13 +6,13 @@ use parking_lot::Mutex;
|
|||||||
//The worker thread publishes the result of its work back to the worker object for every item in the work queue.
|
//The worker thread publishes the result of its work back to the worker object for every item in the work queue.
|
||||||
//The physics (target use case) knows when it has not changed the body, so not updating the value is also an option.
|
//The physics (target use case) knows when it has not changed the body, so not updating the value is also an option.
|
||||||
|
|
||||||
struct Worker<Task:Send,Value:Clone> {
|
pub struct Worker<Task:Send,Value:Clone> {
|
||||||
sender: mpsc::Sender<Task>,
|
sender: mpsc::Sender<Task>,
|
||||||
value:Arc<Mutex<Value>>,
|
value:Arc<Mutex<Value>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<Task:Send+'static,Value:Clone+Send+'static> Worker<Task,Value> {
|
impl<Task:Send+'static,Value:Clone+Send+'static> Worker<Task,Value> {
|
||||||
fn new<F:Fn(Task)->Value+Send+'static>(value:Value,f:F) -> Self {
|
pub fn new<F:FnMut(Task)->Value+Send+'static>(value:Value,mut f:F) -> Self {
|
||||||
let (sender, receiver) = mpsc::channel::<Task>();
|
let (sender, receiver) = mpsc::channel::<Task>();
|
||||||
let ret=Self {
|
let ret=Self {
|
||||||
sender,
|
sender,
|
||||||
@ -23,8 +23,6 @@ impl<Task:Send+'static,Value:Clone+Send+'static> Worker<Task,Value> {
|
|||||||
loop {
|
loop {
|
||||||
match receiver.recv() {
|
match receiver.recv() {
|
||||||
Ok(task) => {
|
Ok(task) => {
|
||||||
println!("Worker got a task");
|
|
||||||
// Process the task
|
|
||||||
let v=f(task);//make sure function is evaluated before lock is acquired
|
let v=f(task);//make sure function is evaluated before lock is acquired
|
||||||
*value.lock()=v;
|
*value.lock()=v;
|
||||||
}
|
}
|
||||||
@ -38,15 +36,40 @@ impl<Task:Send+'static,Value:Clone+Send+'static> Worker<Task,Value> {
|
|||||||
ret
|
ret
|
||||||
}
|
}
|
||||||
|
|
||||||
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)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn grab_clone(&self)->Value{
|
pub fn grab_clone(&self)->Value{
|
||||||
self.value.lock().clone()
|
self.value.lock().clone()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub struct CompatWorker<Task,Value:Clone,F>{
|
||||||
|
data:std::marker::PhantomData<Task>,
|
||||||
|
f:F,
|
||||||
|
value:Value,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<Task,Value:Clone,F:FnMut(Task)->Value> CompatWorker<Task,Value,F> {
|
||||||
|
pub fn new(value:Value,f:F) -> Self {
|
||||||
|
Self {
|
||||||
|
f,
|
||||||
|
value,
|
||||||
|
data:std::marker::PhantomData,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn send(&mut self,task:Task)->Result<(),()>{
|
||||||
|
self.value=(self.f)(task);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn grab_clone(&self)->Value{
|
||||||
|
self.value.clone()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[test]//How to run this test with printing: cargo test --release -- --nocapture
|
#[test]//How to run this test with printing: cargo test --release -- --nocapture
|
||||||
fn test_worker() {
|
fn test_worker() {
|
||||||
println!("hiiiii");
|
println!("hiiiii");
|
||||||
|
Loading…
Reference in New Issue
Block a user