Compare commits

..

7 Commits

Author SHA1 Message Date
0a5a0f4c66 please fix this man 2023-10-04 23:13:45 -07:00
c61b6cfb90 this adds lag and is unnecessary 2023-10-04 22:21:13 -07:00
e8cb4a6f70 use absolute pos 2023-10-04 22:20:49 -07:00
8a81a57036 bro it takes 4 seconds to build now 2023-10-04 22:20:10 -07:00
17331ba609 time must advance! (2 bugs related to this)
global.mouse.time
physics.time
2023-10-04 20:39:42 -07:00
a24f8f5ff1 move physics to its own thread 2023-10-04 20:19:42 -07:00
e90520bb89 rename body to physics 2023-10-04 20:19:24 -07:00
13 changed files with 362 additions and 967 deletions

9
Cargo.lock generated

@ -331,12 +331,6 @@ dependencies = [
"crossbeam-utils", "crossbeam-utils",
] ]
[[package]]
name = "configparser"
version = "3.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5458d9d1a587efaf5091602c59d299696a3877a439c8f6d461a2d3cce11df87a"
[[package]] [[package]]
name = "constant_time_eq" name = "constant_time_eq"
version = "0.3.0" version = "0.3.0"
@ -1688,11 +1682,10 @@ checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"
[[package]] [[package]]
name = "strafe-client" name = "strafe-client"
version = "0.8.0" version = "0.7.0"
dependencies = [ dependencies = [
"async-executor", "async-executor",
"bytemuck", "bytemuck",
"configparser",
"ddsfile", "ddsfile",
"env_logger", "env_logger",
"glam", "glam",

@ -1,6 +1,6 @@
[package] [package]
name = "strafe-client" name = "strafe-client"
version = "0.8.0" version = "0.7.0"
edition = "2021" edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
@ -8,7 +8,6 @@ edition = "2021"
[dependencies] [dependencies]
async-executor = "1.5.1" async-executor = "1.5.1"
bytemuck = { version = "1.13.1", features = ["derive"] } bytemuck = { version = "1.13.1", features = ["derive"] }
configparser = "3.0.2"
ddsfile = "0.5.1" ddsfile = "0.5.1"
env_logger = "0.10.0" env_logger = "0.10.0"
glam = "0.24.1" glam = "0.24.1"

@ -1,91 +0,0 @@
#[derive(Debug,Clone,Copy,Hash,Eq,PartialEq)]
pub enum AabbFace{
Right,//+X
Top,
Back,
Left,
Bottom,
Front,
}
#[derive(Clone)]
pub struct Aabb {
pub min: glam::Vec3,
pub max: glam::Vec3,
}
impl Default for Aabb {
fn default() -> Self {
Aabb::new()
}
}
impl Aabb {
const VERTEX_DATA: [glam::Vec3; 8] = [
glam::vec3(1., -1., -1.),
glam::vec3(1., 1., -1.),
glam::vec3(1., 1., 1.),
glam::vec3(1., -1., 1.),
glam::vec3(-1., -1., 1.),
glam::vec3(-1., 1., 1.),
glam::vec3(-1., 1., -1.),
glam::vec3(-1., -1., -1.),
];
pub fn new() -> Self {
Self {min: glam::Vec3::INFINITY,max: glam::Vec3::NEG_INFINITY}
}
pub fn grow(&mut self, point:glam::Vec3){
self.min=self.min.min(point);
self.max=self.max.max(point);
}
pub fn join(&mut self, aabb:&Aabb){
self.min=self.min.min(aabb.min);
self.max=self.max.max(aabb.max);
}
pub fn inflate(&mut self, hs:glam::Vec3){
self.min-=hs;
self.max+=hs;
}
pub fn intersects(&self,aabb:&Aabb)->bool{
(self.min.cmplt(aabb.max)&aabb.min.cmplt(self.max)).all()
}
pub fn normal(face:AabbFace) -> glam::Vec3 {
match face {
AabbFace::Right => glam::vec3(1.,0.,0.),
AabbFace::Top => glam::vec3(0.,1.,0.),
AabbFace::Back => glam::vec3(0.,0.,1.),
AabbFace::Left => glam::vec3(-1.,0.,0.),
AabbFace::Bottom => glam::vec3(0.,-1.,0.),
AabbFace::Front => glam::vec3(0.,0.,-1.),
}
}
pub fn unit_vertices() -> [glam::Vec3;8] {
return Self::VERTEX_DATA;
}
pub fn face(&self,face:AabbFace) -> Aabb {
let mut aabb=self.clone();
//in this implementation face = worldspace aabb face
match face {
AabbFace::Right => aabb.min.x=aabb.max.x,
AabbFace::Top => aabb.min.y=aabb.max.y,
AabbFace::Back => aabb.min.z=aabb.max.z,
AabbFace::Left => aabb.max.x=aabb.min.x,
AabbFace::Bottom => aabb.max.y=aabb.min.y,
AabbFace::Front => aabb.max.z=aabb.min.z,
}
return aabb;
}
pub fn center(&self)->glam::Vec3{
return (self.min+self.max)/2.0
}
//probably use floats for area & volume because we don't care about precision
pub fn area_weight(&self)->f32{
let d=self.max-self.min;
d.x*d.y+d.y*d.z+d.z*d.x
}
pub fn volume(&self)->f32{
let d=self.max-self.min;
d.x*d.y*d.z
}
}

@ -1,107 +0,0 @@
use crate::aabb::Aabb;
//da algaritum
//lista boxens
//sort by {minx,maxx,miny,maxy,minz,maxz} (6 lists)
//find the sets that minimizes the sum of surface areas
//splitting is done when the minimum split sum of surface areas is larger than the node's own surface area
//start with bisection into octrees because a bad bvh is still 1000x better than no bvh
//sort the centerpoints on each axis (3 lists)
//bv is put into octant based on whether it is upper or lower in each list
#[derive(Default)]
pub struct BvhNode{
children:Vec<Self>,
models:Vec<u32>,
aabb:Aabb,
}
impl BvhNode{
pub fn the_tester<F:FnMut(u32)>(&self,aabb:&Aabb,f:&mut F){
for &model in &self.models{
f(model);
}
for child in &self.children{
if aabb.intersects(&child.aabb){
child.the_tester(aabb,f);
}
}
}
}
pub fn generate_bvh(boxen:Vec<Aabb>)->BvhNode{
generate_bvh_node(boxen.into_iter().enumerate().collect())
}
fn generate_bvh_node(boxen:Vec<(usize,Aabb)>)->BvhNode{
let n=boxen.len();
if n<20{
let mut aabb=Aabb::new();
let models=boxen.into_iter().map(|b|{aabb.join(&b.1);b.0 as u32}).collect();
BvhNode{
children:Vec::new(),
models,
aabb,
}
}else{
let mut octant=std::collections::HashMap::with_capacity(n);//this ids which octant the boxen is put in
let mut sort_x=Vec::with_capacity(n);
let mut sort_y=Vec::with_capacity(n);
let mut sort_z=Vec::with_capacity(n);
for (i,aabb) in boxen.iter(){
let center=aabb.center();
octant.insert(*i,0);
sort_x.push((*i,center.x));
sort_y.push((*i,center.y));
sort_z.push((*i,center.z));
}
sort_x.sort_by(|tup0,tup1|tup0.1.partial_cmp(&tup1.1).unwrap());
sort_y.sort_by(|tup0,tup1|tup0.1.partial_cmp(&tup1.1).unwrap());
sort_z.sort_by(|tup0,tup1|tup0.1.partial_cmp(&tup1.1).unwrap());
let h=n/2;
let median_x=sort_x[h].1;
let median_y=sort_y[h].1;
let median_z=sort_z[h].1;
for (i,c) in sort_x{
if median_x<c{
octant.insert(i,octant[&i]+1<<0);
}
}
for (i,c) in sort_y{
if median_y<c{
octant.insert(i,octant[&i]+1<<1);
}
}
for (i,c) in sort_z{
if median_z<c{
octant.insert(i,octant[&i]+1<<2);
}
}
//generate lists for unique octant values
let mut list_list=Vec::with_capacity(8);
let mut octant_list=Vec::with_capacity(8);
for (i,aabb) in boxen.into_iter(){
let octant_id=octant[&i];
let list_id=if let Some(list_id)=octant_list.iter().position(|&id|id==octant_id){
list_id
}else{
let list_id=list_list.len();
octant_list.push(octant_id);
list_list.push(Vec::new());
list_id
};
list_list[list_id].push((i,aabb));
}
let mut aabb=Aabb::new();
let children=list_list.into_iter().map(|b|{
let node=generate_bvh_node(b);
aabb.join(&node.aabb);
node
}).collect();
BvhNode{
children,
models:Vec::new(),
aabb,
}
}
}

@ -34,12 +34,11 @@ fn get_attributes(name:&str,can_collide:bool,velocity:glam::Vec3,force_intersect
let mut general=crate::model::GameMechanicAttributes::default(); let mut general=crate::model::GameMechanicAttributes::default();
let mut intersecting=crate::model::IntersectingAttributes::default(); let mut intersecting=crate::model::IntersectingAttributes::default();
let mut contacting=crate::model::ContactingAttributes::default(); let mut contacting=crate::model::ContactingAttributes::default();
let mut force_can_collide=can_collide;
match name{ match name{
//"Water"=>intersecting.water=Some(crate::model::IntersectingWater{density:1.0,drag:1.0}), //"Water"=>intersecting.water=Some(crate::model::IntersectingWater{density:1.0,drag:1.0}),
"Accelerator"=>{force_can_collide=false;intersecting.accelerator=Some(crate::model::IntersectingAccelerator{acceleration:velocity})}, "Accelerator"=>intersecting.accelerator=Some(crate::model::IntersectingAccelerator{acceleration:velocity}),
"MapFinish"=>{force_can_collide=false;general.zone=Some(crate::model::GameMechanicZone{mode_id:0,behaviour:crate::model::ZoneBehaviour::Finish})}, "MapFinish"=>general.zone=Some(crate::model::GameMechanicZone{mode_id:0,behaviour:crate::model::ZoneBehaviour::Finish}),
"MapAnticheat"=>{force_can_collide=false;general.zone=Some(crate::model::GameMechanicZone{mode_id:0,behaviour:crate::model::ZoneBehaviour::Anitcheat})}, "MapAnticheat"=>general.zone=Some(crate::model::GameMechanicZone{mode_id:0,behaviour:crate::model::ZoneBehaviour::Anitcheat}),
"Platform"=>general.stage_element=Some(crate::model::GameMechanicStageElement{ "Platform"=>general.stage_element=Some(crate::model::GameMechanicStageElement{
mode_id:0, mode_id:0,
stage_id:0, stage_id:0,
@ -58,15 +57,14 @@ fn get_attributes(name:&str,can_collide:bool,velocity:glam::Vec3,force_intersect
}, },
behaviour:match &captures[2]{ behaviour:match &captures[2]{
"Spawn"|"SpawnAt"=>crate::model::StageElementBehaviour::SpawnAt, "Spawn"|"SpawnAt"=>crate::model::StageElementBehaviour::SpawnAt,
"Trigger"=>{force_can_collide=false;crate::model::StageElementBehaviour::Trigger}, "Trigger"=>crate::model::StageElementBehaviour::Trigger,
"Teleport"=>{force_can_collide=false;crate::model::StageElementBehaviour::Teleport}, "Teleport"=>crate::model::StageElementBehaviour::Teleport,
"Platform"=>crate::model::StageElementBehaviour::Platform, "Platform"=>crate::model::StageElementBehaviour::Platform,
_=>panic!("regex1[2] messed up bad"), _=>panic!("regex1[2] messed up bad"),
} }
}) })
}else if let Some(captures)=lazy_regex::regex!(r"^Bonus(Finish|Anticheat)(\d+)$") }else if let Some(captures)=lazy_regex::regex!(r"^Bonus(Finish|Anticheat)(\d+)$")
.captures(other){ .captures(other){
force_can_collide=false;
match &captures[1]{ match &captures[1]{
"Finish"=>general.zone=Some(crate::model::GameMechanicZone{mode_id:captures[2].parse::<u32>().unwrap(),behaviour:crate::model::ZoneBehaviour::Finish}), "Finish"=>general.zone=Some(crate::model::GameMechanicZone{mode_id:captures[2].parse::<u32>().unwrap(),behaviour:crate::model::ZoneBehaviour::Finish}),
"Anticheat"=>general.zone=Some(crate::model::GameMechanicZone{mode_id:captures[2].parse::<u32>().unwrap(),behaviour:crate::model::ZoneBehaviour::Anitcheat}), "Anticheat"=>general.zone=Some(crate::model::GameMechanicZone{mode_id:captures[2].parse::<u32>().unwrap(),behaviour:crate::model::ZoneBehaviour::Anitcheat}),
@ -79,7 +77,7 @@ fn get_attributes(name:&str,can_collide:bool,velocity:glam::Vec3,force_intersect
if velocity!=glam::Vec3::ZERO{ if velocity!=glam::Vec3::ZERO{
general.booster=Some(crate::model::GameMechanicBooster{velocity}); general.booster=Some(crate::model::GameMechanicBooster{velocity});
} }
match force_can_collide{ match can_collide{
true=>{ true=>{
match name{ match name{
//"Bounce"=>(), //"Bounce"=>(),
@ -178,7 +176,7 @@ impl RobloxFaceTextureDescription{
} }
type RobloxPartDescription=[Option<RobloxFaceTextureDescription>;6]; type RobloxPartDescription=[Option<RobloxFaceTextureDescription>;6];
type RobloxWedgeDescription=[Option<RobloxFaceTextureDescription>;5]; type RobloxWedgeDescription=[Option<RobloxFaceTextureDescription>;5];
type RobloxCornerWedgeDescription=[Option<RobloxFaceTextureDescription>;5]; type RobloxCornerWedgeDescription=[Option<RobloxFaceTextureDescription>;4];
#[derive(Clone,Eq,Hash,PartialEq)] #[derive(Clone,Eq,Hash,PartialEq)]
enum RobloxBasePartDescription{ enum RobloxBasePartDescription{
Sphere, Sphere,
@ -311,7 +309,9 @@ pub fn generate_indexed_models(dom:rbx_dom_weak::WeakDom) -> crate::model::Index
}; };
let normal_id=normalid.to_u32(); let normal_id=normalid.to_u32();
if normal_id<6{ if normal_id<6{
let (roblox_texture_color,roblox_texture_transform)=if decal.class=="Texture"{ let mut roblox_texture_transform=RobloxTextureTransform::default();
let mut roblox_texture_color=glam::Vec4::ONE;
if decal.class=="Texture"{
//generate tranform //generate tranform
if let ( if let (
Some(rbx_dom_weak::types::Variant::Float32(ox)), Some(rbx_dom_weak::types::Variant::Float32(ox)),
@ -334,19 +334,13 @@ pub fn generate_indexed_models(dom:rbx_dom_weak::WeakDom) -> crate::model::Index
5=>(size.x,size.y),//front 5=>(size.x,size.y),//front
_=>panic!("unreachable"), _=>panic!("unreachable"),
}; };
( roblox_texture_transform=RobloxTextureTransform{
glam::vec4(decal_color3.r,decal_color3.g,decal_color3.b,1.0-*decal_transparency), offset_u:*ox/(*sx),offset_v:*oy/(*sy),
RobloxTextureTransform{ scale_u:size_u/(*sx),scale_v:size_v/(*sy),
offset_u:*ox/(*sx),offset_v:*oy/(*sy), };
scale_u:size_u/(*sx),scale_v:size_v/(*sy), roblox_texture_color=glam::vec4(decal_color3.r,decal_color3.g,decal_color3.b,1.0-*decal_transparency);
}
)
}else{
(glam::Vec4::ONE,RobloxTextureTransform::default())
} }
}else{ }
(glam::Vec4::ONE,RobloxTextureTransform::default())
};
part_texture_description[normal_id as usize]=Some(RobloxFaceTextureDescription{ part_texture_description[normal_id as usize]=Some(RobloxFaceTextureDescription{
texture:texture_id, texture:texture_id,
color:roblox_texture_color, color:roblox_texture_color,
@ -380,11 +374,9 @@ pub fn generate_indexed_models(dom:rbx_dom_weak::WeakDom) -> crate::model::Index
f3,//Cube::Left->Wedge::Left f3,//Cube::Left->Wedge::Left
f4,//Cube::Bottom->Wedge::Bottom f4,//Cube::Bottom->Wedge::Bottom
]), ]),
//TODO: fix Left+Back texture coordinates to match roblox when not overwridden by Top
primitives::Primitives::CornerWedge=>RobloxBasePartDescription::CornerWedge([ primitives::Primitives::CornerWedge=>RobloxBasePartDescription::CornerWedge([
f0,//Cube::Right->CornerWedge::Right f0,//Cube::Right->CornerWedge::Right
if f2.is_some(){f2}else{f1.clone()},//Cube::Back|Cube::Top->CornerWedge::TopBack f1,//Cube::Top->CornerWedge::Top
if f3.is_some(){f3}else{f1},//Cube::Left|Cube::Top->CornerWedge::TopLeft
f4,//Cube::Bottom->CornerWedge::Bottom f4,//Cube::Bottom->CornerWedge::Bottom
f5,//Cube::Front->CornerWedge::Front f5,//Cube::Front->CornerWedge::Front
]), ]),
@ -443,11 +435,10 @@ pub fn generate_indexed_models(dom:rbx_dom_weak::WeakDom) -> crate::model::Index
for (face_id,roblox_face_description) in cornerwedge_texture_description.iter().enumerate(){ for (face_id,roblox_face_description) in cornerwedge_texture_description.iter().enumerate(){
cornerwedge_face_description.insert( cornerwedge_face_description.insert(
match face_id{ match face_id{
0=>primitives::CornerWedgeFace::Right, 0=>primitives::CornerWedgeFace::Top,
1=>primitives::CornerWedgeFace::TopBack, 1=>primitives::CornerWedgeFace::Right,
2=>primitives::CornerWedgeFace::TopLeft, 2=>primitives::CornerWedgeFace::Bottom,
3=>primitives::CornerWedgeFace::Bottom, 3=>primitives::CornerWedgeFace::Front,
4=>primitives::CornerWedgeFace::Front,
_=>panic!("unreachable"), _=>panic!("unreachable"),
}, },
match roblox_face_description{ match roblox_face_description{

@ -2,16 +2,14 @@ use std::{borrow::Cow, time::Instant};
use wgpu::{util::DeviceExt, AstcBlock, AstcChannel}; use wgpu::{util::DeviceExt, AstcBlock, AstcChannel};
use model::{Vertex,ModelInstance,ModelGraphicsInstance}; use model::{Vertex,ModelInstance,ModelGraphicsInstance};
use physics::{InputInstruction, PhysicsInstruction}; use physics::{InputInstruction, PhysicsInstruction};
use instruction::{TimedInstruction, InstructionConsumer}; use instruction::TimedInstruction;
use crate::instruction::InstructionConsumer;
mod bvh;
mod aabb;
mod model; mod model;
mod timers;
mod zeroes; mod zeroes;
mod worker; mod worker;
mod physics; mod physics;
mod settings;
mod framework; mod framework;
mod primitives; mod primitives;
mod instruction; mod instruction;
@ -66,31 +64,35 @@ fn perspective_rh(fov_x_slope: f32, fov_y_slope: f32, z_near: f32, z_far: f32) -
) )
} }
impl GraphicsCamera{ impl GraphicsCamera{
pub fn new(screen_size:glam::UVec2,fov:glam::Vec2)->Self{ pub fn new(screen_size:glam::UVec2,fov_y:f32)->Self{
Self{ Self{
screen_size, screen_size,
fov, fov: glam::vec2(fov_y*(screen_size.x as f32)/(screen_size.y as f32),fov_y),
} }
} }
pub fn proj(&self)->glam::Mat4{ pub fn proj(&self)->glam::Mat4{
perspective_rh(self.fov.x, self.fov.y, 0.5, 2000.0) perspective_rh(self.fov.x, self.fov.y, 0.5, 2000.0)
} }
pub fn world(&self,pos:glam::Vec3,angles:glam::Vec2)->glam::Mat4{ pub fn view(&self,pos:glam::Vec3,angles:glam::Vec2)->glam::Mat4{
//f32 good enough for view matrix //f32 good enough for view matrix
glam::Mat4::from_translation(pos) * glam::Mat4::from_euler(glam::EulerRot::YXZ, angles.x, angles.y, 0f32) 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 * 4] { pub fn to_uniform_data(&self,(pos,angles): (glam::Vec3,glam::Vec2)) -> [f32; 16 * 3 + 4] {
let proj=self.proj(); let proj=self.proj();
let proj_inv = proj.inverse(); let proj_inv = proj.inverse();
let view_inv=self.world(pos,angles); let view=self.view(pos,angles);
let view=view_inv.inverse(); let view_inv = view.inverse();
let mut raw = [0f32; 16 * 4]; let mut raw = [0f32; 16 * 3 + 4];
raw[..16].copy_from_slice(&AsRef::<[f32; 16]>::as_ref(&proj)[..]); 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[16..32].copy_from_slice(&AsRef::<[f32; 16]>::as_ref(&proj_inv)[..]);
raw[32..48].copy_from_slice(&AsRef::<[f32; 16]>::as_ref(&view)[..]); raw[32..48].copy_from_slice(&AsRef::<[f32; 16]>::as_ref(&view_inv)[..]);
raw[48..64].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 raw
} }
} }
@ -112,18 +114,14 @@ impl GraphicsState{
pub fn clear(&mut self){ pub fn clear(&mut self){
self.models.clear(); self.models.clear();
} }
pub fn load_user_settings(&mut self,user_settings:&settings::UserSettings){
self.camera.fov=user_settings.calculate_fov(1.0,&self.camera.screen_size).as_vec2();
}
} }
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, mouse:physics::MouseState,
user_settings:settings::UserSettings,
graphics:GraphicsState, graphics:GraphicsState,
physics_thread:worker::CompatWorker<TimedInstruction<InputInstruction>,physics::PhysicsOutputState,Box<dyn FnMut(TimedInstruction<InputInstruction>)->physics::PhysicsOutputState>>, physics_thread:worker::Worker<TimedInstruction<InputInstruction>,physics::PhysicsOutputState>,
} }
impl GlobalState{ impl GlobalState{
@ -228,7 +226,7 @@ impl GlobalState{
}else{ }else{
Some(ModelGraphicsInstance{ Some(ModelGraphicsInstance{
transform: glam::Mat4::from(instance.transform), transform: glam::Mat4::from(instance.transform),
normal_transform: glam::Mat3::from(instance.transform.matrix3.inverse().transpose()), normal_transform: glam::Mat4::from(instance.transform.inverse()).transpose(),
color: instance.color, color: instance.color,
}) })
} }
@ -237,7 +235,7 @@ impl GlobalState{
let id=unique_texture_models.len(); let id=unique_texture_models.len();
let mut unique_textures=Vec::new(); let mut unique_textures=Vec::new();
for group in model.groups.into_iter(){ for group in model.groups.into_iter(){
//ignore zero copy optimization for now //ignore zero coppy optimization for now
let texture_index=if let Some(texture_index)=unique_textures.iter().position(|&texture|texture==group.texture){ let texture_index=if let Some(texture_index)=unique_textures.iter().position(|&texture|texture==group.texture){
texture_index texture_index
}else{ }else{
@ -267,9 +265,9 @@ impl GlobalState{
let mut vertices = Vec::new(); let mut vertices = Vec::new();
let mut index_from_vertex = std::collections::HashMap::new();//::<IndexedVertex,usize> let mut index_from_vertex = std::collections::HashMap::new();//::<IndexedVertex,usize>
let mut entities = Vec::new(); let mut entities = Vec::new();
//this mut be combined in a more complex way if the models use different render patterns per group //TODO: combine groups using the same render pattern
let mut indices = Vec::new();
for group in model.groups { for group in model.groups {
let mut indices = Vec::new();
for poly in group.polys { for poly in group.polys {
for end_index in 2..poly.vertices.len() { for end_index in 2..poly.vertices.len() {
for &index in &[0, end_index - 1, end_index] { for &index in &[0, end_index - 1, end_index] {
@ -291,8 +289,8 @@ impl GlobalState{
} }
} }
} }
}
entities.push(indices); entities.push(indices);
}
models.push(model::ModelSingleTexture{ models.push(model::ModelSingleTexture{
instances:model.instances, instances:model.instances,
vertices, vertices,
@ -376,7 +374,7 @@ impl GlobalState{
} }
} }
const MODEL_BUFFER_SIZE:usize=4*4 + 12 + 4;//let size=std::mem::size_of::<ModelInstance>(); const MODEL_BUFFER_SIZE:usize=4*4 + 4*4 + 4;//let size=std::mem::size_of::<ModelInstance>();
const MODEL_BUFFER_SIZE_BYTES:usize=MODEL_BUFFER_SIZE*4; const MODEL_BUFFER_SIZE_BYTES:usize=MODEL_BUFFER_SIZE*4;
fn get_instances_buffer_data(instances:&[ModelGraphicsInstance]) -> Vec<f32> { fn get_instances_buffer_data(instances:&[ModelGraphicsInstance]) -> Vec<f32> {
let mut raw = Vec::with_capacity(MODEL_BUFFER_SIZE*instances.len()); let mut raw = Vec::with_capacity(MODEL_BUFFER_SIZE*instances.len());
@ -385,12 +383,7 @@ fn get_instances_buffer_data(instances:&[ModelGraphicsInstance]) -> Vec<f32> {
//model transform //model transform
raw.extend_from_slice(&AsRef::<[f32; 4*4]>::as_ref(&mi.transform)[..]); raw.extend_from_slice(&AsRef::<[f32; 4*4]>::as_ref(&mi.transform)[..]);
//normal transform //normal transform
raw.extend_from_slice(AsRef::<[f32; 3]>::as_ref(&mi.normal_transform.x_axis)); raw.extend_from_slice(&AsRef::<[f32; 4*4]>::as_ref(&mi.normal_transform)[..]);
raw.extend_from_slice(&[0.0]);
raw.extend_from_slice(AsRef::<[f32; 3]>::as_ref(&mi.normal_transform.y_axis));
raw.extend_from_slice(&[0.0]);
raw.extend_from_slice(AsRef::<[f32; 3]>::as_ref(&mi.normal_transform.z_axis));
raw.extend_from_slice(&[0.0]);
//color //color
raw.extend_from_slice(AsRef::<[f32; 4]>::as_ref(&mi.color)); raw.extend_from_slice(AsRef::<[f32; 4]>::as_ref(&mi.color));
raw.append(&mut v); raw.append(&mut v);
@ -415,8 +408,6 @@ impl framework::Example for GlobalState {
device: &wgpu::Device, device: &wgpu::Device,
queue: &wgpu::Queue, queue: &wgpu::Queue,
) -> Self { ) -> Self {
//wee
let user_settings=settings::read_user_settings();
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.as_ref())); 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.as_ref()));
indexed_models.push(primitives::unit_sphere()); indexed_models.push(primitives::unit_sphere());
@ -756,11 +747,7 @@ impl framework::Example for GlobalState {
let mut physics = physics::PhysicsState::default(); let mut physics = physics::PhysicsState::default();
physics.load_user_settings(&user_settings); let camera=GraphicsCamera::new(glam::uvec2(config.width,config.height), 1.0);
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(&physics.next_mouse)); 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"),
@ -795,7 +782,7 @@ impl framework::Example for GlobalState {
let depth_view = Self::create_depth_texture(config, device); let depth_view = Self::create_depth_texture(config, device);
let mut graphics=GraphicsState { let graphics=GraphicsState {
pipelines:GraphicsPipelines{ pipelines:GraphicsPipelines{
skybox:sky_pipeline, skybox:sky_pipeline,
model:model_pipeline model:model_pipeline
@ -814,8 +801,6 @@ impl framework::Example for GlobalState {
temp_squid_texture_view: squid_texture_view, temp_squid_texture_view: squid_texture_view,
}; };
graphics.load_user_settings(&user_settings);
let indexed_model_instances=model::IndexedModelInstances{ let indexed_model_instances=model::IndexedModelInstances{
textures:Vec::new(), textures:Vec::new(),
models:indexed_models, models:indexed_models,
@ -837,7 +822,6 @@ impl framework::Example for GlobalState {
start_time:Instant::now(), start_time:Instant::now(),
manual_mouse_lock:false, manual_mouse_lock:false,
mouse:physics::MouseState::default(), mouse:physics::MouseState::default(),
user_settings,
graphics, graphics,
physics_thread, physics_thread,
}; };
@ -864,6 +848,7 @@ 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"=>{
@ -897,13 +882,11 @@ impl framework::Example for GlobalState {
physics.spawn_point=spawn_point; physics.spawn_point=spawn_point;
physics.process_instruction(instruction::TimedInstruction{ physics.process_instruction(instruction::TimedInstruction{
time:physics.time, time:physics.time,
instruction: PhysicsInstruction::Input(physics::PhysicsInputInstruction::Reset), instruction: PhysicsInstruction::Input(InputInstruction::Reset),
}); });
physics.load_user_settings(&self.user_settings);
physics.generate_models(&indexed_model_instances); physics.generate_models(&indexed_model_instances);
self.physics_thread=physics.into_worker(); self.physics_thread=physics.into_worker();
//graphics.load_user_settings(&self.user_settings);
self.generate_model_graphics(device,queue,indexed_model_instances); self.generate_model_graphics(device,queue,indexed_model_instances);
//manual reset //manual reset
}else{ }else{
@ -919,23 +902,51 @@ impl framework::Example for GlobalState {
#[allow(clippy::single_match)] #[allow(clippy::single_match)]
fn update(&mut self, window: &winit::window::Window, device: &wgpu::Device, queue: &wgpu::Queue, event: winit::event::WindowEvent) { fn update(&mut self, window: &winit::window::Window, device: &wgpu::Device, queue: &wgpu::Queue, event: winit::event::WindowEvent) {
let time=self.start_time.elapsed().as_nanos() as i64;
match event { match event {
winit::event::WindowEvent::DroppedFile(path) => self.load_file(path,device,queue), winit::event::WindowEvent::DroppedFile(path) => self.load_file(path,device,queue),
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 { _=>(),
input:winit::event::KeyboardInput{state, virtual_keycode,..}, }
}
fn device_event(&mut self, window: &winit::window::Window, event: winit::event::DeviceEvent) {
//there's no way this is the best way get a timestamp.
let time=self.start_time.elapsed().as_nanos() as i64;
match event {
winit::event::DeviceEvent::Key(winit::event::KeyboardInput {
state,
scancode: keycode,
.. ..
}=>{ }) => {
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{ if let Some(input_instruction)=match keycode {
Some(winit::event::VirtualKeyCode::Tab)=>{ 17=>Some(InputInstruction::MoveForward(s)),//W
30=>Some(InputInstruction::MoveLeft(s)),//A
31=>Some(InputInstruction::MoveBack(s)),//S
32=>Some(InputInstruction::MoveRight(s)),//D
18=>Some(InputInstruction::MoveUp(s)),//E
16=>Some(InputInstruction::MoveDown(s)),//Q
57=>Some(InputInstruction::Jump(s)),//Space
44=>Some(InputInstruction::Zoom(s)),//Z
19=>if s{Some(InputInstruction::Reset)}else{None},//R
01=>{//Esc
if s{
self.manual_mouse_lock=false;
match window.set_cursor_grab(winit::window::CursorGrabMode::None){
Ok(())=>(),
Err(e)=>println!("Could not release cursor: {:?}",e),
}
window.set_cursor_visible(true);
}
None
},
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.camera.screen_size.x as f32/2.0, self.graphics.camera.screen_size.y 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)){
@ -963,56 +974,16 @@ impl framework::Example for GlobalState {
} }
} }
window.set_cursor_visible(s); window.set_cursor_visible(s);
None
}, },
Some(winit::event::VirtualKeyCode::F11)=>{ _ => {println!("scancode {}",keycode);None},
if s{ }{
if window.fullscreen().is_some(){ self.physics_thread.send(TimedInstruction{
window.set_fullscreen(None); time,
}else{ instruction:input_instruction,
window.set_fullscreen(Some(winit::window::Fullscreen::Borderless(None))); }).unwrap();
}
}
},
Some(winit::event::VirtualKeyCode::Escape)=>{
if s{
self.manual_mouse_lock=false;
match window.set_cursor_grab(winit::window::CursorGrabMode::None){
Ok(())=>(),
Err(e)=>println!("Could not release cursor: {:?}",e),
}
window.set_cursor_visible(true);
}
},
Some(keycode)=>{
if let Some(input_instruction)=match keycode {
winit::event::VirtualKeyCode::W => Some(InputInstruction::MoveForward(s)),
winit::event::VirtualKeyCode::A => Some(InputInstruction::MoveLeft(s)),
winit::event::VirtualKeyCode::S => Some(InputInstruction::MoveBack(s)),
winit::event::VirtualKeyCode::D => Some(InputInstruction::MoveRight(s)),
winit::event::VirtualKeyCode::E => Some(InputInstruction::MoveUp(s)),
winit::event::VirtualKeyCode::Q => Some(InputInstruction::MoveDown(s)),
winit::event::VirtualKeyCode::Space => Some(InputInstruction::Jump(s)),
winit::event::VirtualKeyCode::Z => Some(InputInstruction::Zoom(s)),
winit::event::VirtualKeyCode::R => if s{Some(InputInstruction::Reset)}else{None},
_ => None,
}{
self.physics_thread.send(TimedInstruction{
time,
instruction:input_instruction,
}).unwrap();
}
},
_=>(),
} }
}, },
_=>(),
}
}
fn device_event(&mut self, window: &winit::window::Window, event: winit::event::DeviceEvent) {
//there's no way this is the best way get a timestamp.
let time=self.start_time.elapsed().as_nanos() as i64;
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
} => { } => {
@ -1054,8 +1025,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.camera.screen_size=glam::uvec2(config.width, config.height); self.graphics.camera.set_screen_size(glam::uvec2(config.width, config.height));
self.graphics.load_user_settings(&self.user_settings);
} }
fn render( fn render(

@ -52,7 +52,7 @@ pub struct ModelSingleTexture{
#[derive(Clone)] #[derive(Clone)]
pub struct ModelGraphicsInstance{ pub struct ModelGraphicsInstance{
pub transform:glam::Mat4, pub transform:glam::Mat4,
pub normal_transform:glam::Mat3, pub normal_transform:glam::Mat4,
pub color:glam::Vec4, pub color:glam::Vec4,
} }
pub struct ModelInstance{ pub struct ModelInstance{

@ -13,42 +13,26 @@ 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(PhysicsInputInstruction), Input(InputInstruction),
}
#[derive(Debug)]
pub enum PhysicsInputInstruction {
ReplaceMouse(MouseState,MouseState),
SetNextMouse(MouseState),
SetMoveRight(bool),
SetMoveUp(bool),
SetMoveBack(bool),
SetMoveLeft(bool),
SetMoveDown(bool),
SetMoveForward(bool),
SetJump(bool),
SetZoom(bool),
Reset,
Idle,
} }
#[derive(Debug)] #[derive(Debug)]
pub enum InputInstruction { pub enum InputInstruction {
MoveMouse(glam::IVec2), MoveMouse(glam::IVec2),
MoveForward(bool),
MoveLeft(bool),
MoveBack(bool),
MoveRight(bool), MoveRight(bool),
MoveUp(bool), MoveUp(bool),
MoveBack(bool),
MoveLeft(bool),
MoveDown(bool), MoveDown(bool),
MoveForward(bool),
Jump(bool), Jump(bool),
Zoom(bool), Zoom(bool),
Reset, Reset,
SetPaused(bool),
Idle, Idle,
//Idle: there were no input events, but the simulation is safe to advance to this timestep //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 //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
@ -108,7 +92,7 @@ impl crate::instruction::InstructionConsumer<InputInstruction> for InputState{
*/ */
//hey dumbass just use a delta //hey dumbass just use a delta
#[derive(Clone,Debug)] #[derive(Clone)]
pub struct MouseState { pub struct MouseState {
pub pos: glam::IVec2, pub pos: glam::IVec2,
pub time: TIME, pub time: TIME,
@ -122,6 +106,10 @@ impl Default for MouseState{
} }
} }
impl MouseState { impl MouseState {
pub fn move_mouse(&mut self,pos:glam::IVec2,time:TIME){
self.time=time;
self.pos=pos;
}
pub fn lerp(&self,target:&MouseState,time:TIME)->glam::IVec2 { pub fn lerp(&self,target:&MouseState,time:TIME)->glam::IVec2 {
let m0=self.pos.as_i64vec2(); let m0=self.pos.as_i64vec2();
let m1=target.pos.as_i64vec2(); let m1=target.pos.as_i64vec2();
@ -176,7 +164,7 @@ impl PhysicsCamera {
Self{ Self{
offset, offset,
angles: glam::DVec2::ZERO, angles: glam::DVec2::ZERO,
sensitivity: glam::dvec2(1.0/1024.0,1.0/1024.0), sensitivity: glam::dvec2(1.0/16384.0,1.0/16384.0),
mouse:MouseState{pos:glam::IVec2::ZERO,time:-1},//escape initialization hell divide by zero mouse:MouseState{pos:glam::IVec2::ZERO,time:-1},//escape initialization hell divide by zero
} }
} }
@ -298,7 +286,6 @@ pub struct PhysicsState{
pub grounded:bool, pub grounded:bool,
//all models //all models
pub models:Vec<ModelPhysics>, pub models:Vec<ModelPhysics>,
pub bvh:crate::bvh::BvhNode,
pub modes:Vec<crate::model::ModeDescription>, pub modes:Vec<crate::model::ModeDescription>,
pub mode_from_mode_id:std::collections::HashMap::<u32,usize>, pub mode_from_mode_id:std::collections::HashMap::<u32,usize>,
@ -313,13 +300,118 @@ pub struct PhysicsOutputState{
} }
impl PhysicsOutputState{ impl PhysicsOutputState{
pub fn adjust_mouse(&self,mouse:&MouseState)->(glam::Vec3,glam::Vec2){ 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()) (self.body.extrapolated_position(mouse.time),self.camera.simulate_move_angles(mouse.pos).as_vec2())
}
}
#[derive(Debug,Clone,Copy,Hash,Eq,PartialEq)]
pub enum AabbFace{
Right,//+X
Top,
Back,
Left,
Bottom,
Front,
}
#[derive(Clone)]
pub struct Aabb {
min: glam::Vec3,
max: glam::Vec3,
}
impl Aabb {
// const FACE_DATA: [[f32; 3]; 6] = [
// [0.0f32, 0., 1.],
// [0.0f32, 0., -1.],
// [1.0f32, 0., 0.],
// [-1.0f32, 0., 0.],
// [0.0f32, 1., 0.],
// [0.0f32, -1., 0.],
// ];
const VERTEX_DATA: [glam::Vec3; 8] = [
glam::vec3(1., -1., -1.),
glam::vec3(1., 1., -1.),
glam::vec3(1., 1., 1.),
glam::vec3(1., -1., 1.),
glam::vec3(-1., -1., 1.),
glam::vec3(-1., 1., 1.),
glam::vec3(-1., 1., -1.),
glam::vec3(-1., -1., -1.),
];
const VERTEX_DATA_RIGHT: [glam::Vec3; 4] = [
glam::vec3(1., -1., -1.),
glam::vec3(1., 1., -1.),
glam::vec3(1., 1., 1.),
glam::vec3(1., -1., 1.),
];
const VERTEX_DATA_TOP: [glam::Vec3; 4] = [
glam::vec3(1., 1., -1.),
glam::vec3(-1., 1., -1.),
glam::vec3(-1., 1., 1.),
glam::vec3(1., 1., 1.),
];
const VERTEX_DATA_BACK: [glam::Vec3; 4] = [
glam::vec3(-1., -1., 1.),
glam::vec3(1., -1., 1.),
glam::vec3(1., 1., 1.),
glam::vec3(-1., 1., 1.),
];
const VERTEX_DATA_LEFT: [glam::Vec3; 4] = [
glam::vec3(-1., -1., 1.),
glam::vec3(-1., 1., 1.),
glam::vec3(-1., 1., -1.),
glam::vec3(-1., -1., -1.),
];
const VERTEX_DATA_BOTTOM: [glam::Vec3; 4] = [
glam::vec3(1., -1., 1.),
glam::vec3(-1., -1., 1.),
glam::vec3(-1., -1., -1.),
glam::vec3(1., -1., -1.),
];
const VERTEX_DATA_FRONT: [glam::Vec3; 4] = [
glam::vec3(-1., 1., -1.),
glam::vec3(1., 1., -1.),
glam::vec3(1., -1., -1.),
glam::vec3(-1., -1., -1.),
];
pub fn new() -> Self {
Self {min: glam::Vec3::INFINITY,max: glam::Vec3::NEG_INFINITY}
}
pub fn grow(&mut self, point:glam::Vec3){
self.min=self.min.min(point);
self.max=self.max.max(point);
}
pub fn normal(face:AabbFace) -> glam::Vec3 {
match face {
AabbFace::Right => glam::vec3(1.,0.,0.),
AabbFace::Top => glam::vec3(0.,1.,0.),
AabbFace::Back => glam::vec3(0.,0.,1.),
AabbFace::Left => glam::vec3(-1.,0.,0.),
AabbFace::Bottom => glam::vec3(0.,-1.,0.),
AabbFace::Front => glam::vec3(0.,0.,-1.),
}
}
pub fn unit_vertices() -> [glam::Vec3;8] {
return Self::VERTEX_DATA;
}
pub fn unit_face_vertices(face:AabbFace) -> [glam::Vec3;4] {
match face {
AabbFace::Right => Self::VERTEX_DATA_RIGHT,
AabbFace::Top => Self::VERTEX_DATA_TOP,
AabbFace::Back => Self::VERTEX_DATA_BACK,
AabbFace::Left => Self::VERTEX_DATA_LEFT,
AabbFace::Bottom => Self::VERTEX_DATA_BOTTOM,
AabbFace::Front => Self::VERTEX_DATA_FRONT,
}
} }
} }
//pretend to be using what we want to eventually do //pretend to be using what we want to eventually do
type TreyMeshFace = crate::aabb::AabbFace; type TreyMeshFace = AabbFace;
type TreyMesh = crate::aabb::Aabb; type TreyMesh = Aabb;
enum PhysicsCollisionAttributes{ enum PhysicsCollisionAttributes{
Contact{//track whether you are contacting the object Contact{//track whether you are contacting the object
@ -342,7 +434,7 @@ pub struct ModelPhysics {
impl ModelPhysics { impl ModelPhysics {
fn from_model_transform_attributes(model:&crate::model::IndexedModel,transform:&glam::Affine3A,attributes:PhysicsCollisionAttributes)->Self{ fn from_model_transform_attributes(model:&crate::model::IndexedModel,transform:&glam::Affine3A,attributes:PhysicsCollisionAttributes)->Self{
let mut aabb=TreyMesh::new(); let mut aabb=Aabb::new();
for indexed_vertex in &model.unique_vertices { for indexed_vertex in &model.unique_vertices {
aabb.grow(transform.transform_point3(glam::Vec3::from_array(model.unique_pos[indexed_vertex.pos as usize]))); aabb.grow(transform.transform_point3(glam::Vec3::from_array(model.unique_pos[indexed_vertex.pos as usize])));
} }
@ -360,16 +452,29 @@ impl ModelPhysics {
} }
} }
pub fn unit_vertices(&self) -> [glam::Vec3;8] { pub fn unit_vertices(&self) -> [glam::Vec3;8] {
TreyMesh::unit_vertices() Aabb::unit_vertices()
} }
pub fn mesh(&self) -> &TreyMesh { pub fn mesh(&self) -> &TreyMesh {
return &self.mesh; return &self.mesh;
} }
pub fn face_mesh(&self,face:TreyMeshFace)->TreyMesh{ pub fn unit_face_vertices(&self,face:TreyMeshFace) -> [glam::Vec3;4] {
self.mesh.face(face) Aabb::unit_face_vertices(face)
}
pub fn face_mesh(&self,face:TreyMeshFace) -> TreyMesh {
let mut aabb=self.mesh.clone();
//in this implementation face = worldspace aabb face
match face {
AabbFace::Right => aabb.min.x=aabb.max.x,
AabbFace::Top => aabb.min.y=aabb.max.y,
AabbFace::Back => aabb.min.z=aabb.max.z,
AabbFace::Left => aabb.max.x=aabb.min.x,
AabbFace::Bottom => aabb.max.y=aabb.min.y,
AabbFace::Front => aabb.max.z=aabb.min.z,
}
return aabb;
} }
pub fn face_normal(&self,face:TreyMeshFace) -> glam::Vec3 { pub fn face_normal(&self,face:TreyMeshFace) -> glam::Vec3 {
TreyMesh::normal(face)//this is wrong for scale Aabb::normal(face)//this is wrong for scale
} }
} }
@ -430,7 +535,6 @@ impl Default for PhysicsState{
contacts: std::collections::HashMap::new(), contacts: std::collections::HashMap::new(),
intersects: std::collections::HashMap::new(), intersects: std::collections::HashMap::new(),
models: Vec::new(), models: Vec::new(),
bvh:crate::bvh::BvhNode::default(),
walk: WalkState::new(), walk: WalkState::new(),
camera: PhysicsCamera::from_offset(glam::vec3(0.0,4.5-2.5,0.0)), camera: PhysicsCamera::from_offset(glam::vec3(0.0,4.5-2.5,0.0)),
next_mouse: MouseState::default(), next_mouse: MouseState::default(),
@ -451,101 +555,64 @@ impl PhysicsState {
self.intersects.clear(); self.intersects.clear();
} }
pub fn into_worker(mut self)->crate::worker::CompatWorker<TimedInstruction<InputInstruction>,PhysicsOutputState,Box<dyn FnMut(TimedInstruction<InputInstruction>)->PhysicsOutputState>>{ pub fn into_worker(mut self)->crate::worker::Worker<TimedInstruction<InputInstruction>,PhysicsOutputState>{
let mut mouse_blocking=true; let mut last_time=0;
let mut last_mouse_time=self.next_mouse.time; //last_time: this indicates the last time the mouse position was known.
let mut simulation_timer=crate::timers::UnscaledTimer::unpaused(); //Only used to generate a MouseState right before mouse movement
//to finalize a long period of no movement and avoid interpolating from a long out-of-date MouseState.
let mut mouse_blocking=true;//waiting for next_mouse to be written
let mut timeline=std::collections::VecDeque::new(); let mut timeline=std::collections::VecDeque::new();
crate::worker::CompatWorker::new(self.output(),Box::new(move |ins:TimedInstruction<InputInstruction>|{ crate::worker::Worker::new(self.output(),move |ins:TimedInstruction<InputInstruction>|{
if if let Some(phys_input)=match ins.instruction{ let run_queue=match &ins.instruction{
InputInstruction::MoveMouse(m)=>{ InputInstruction::MoveMouse(_)=>{
if mouse_blocking{ //I FORGOT TO EDIT THE MOVE MOUSE TIMESTAMPS
//tell the game state which is living in the past about its future if !mouse_blocking{
timeline.push_front(TimedInstruction{ //mouse has not been moving for a while.
time:simulation_timer.time(last_mouse_time), //make sure not to interpolate between two distant MouseStates.
instruction:PhysicsInputInstruction::SetNextMouse(MouseState{time:ins.time,pos:m}), //generate a mouse instruction with no movement timestamped at last InputInstruction
}); //Idle instructions are CRITICAL to keeping this value up to date
}else{ //interpolate normally (now that prev mouse pos is up to date)
//mouse has just started moving again after being still for longer than 10ms. // timeline.push_back(TimedInstruction{
//replace the entire mouse interpolation state to avoid an intermediate state with identical m0.t m1.t timestamps which will divide by zero // time:last_time,
timeline.push_front(TimedInstruction{ // instruction:InputInstruction::MoveMouse(self.next_mouse.pos),
time:simulation_timer.time(last_mouse_time), // });
instruction:PhysicsInputInstruction::ReplaceMouse(
MouseState{time:simulation_timer.time(last_mouse_time),pos:self.next_mouse.pos},
MouseState{time:simulation_timer.time(ins.time),pos:m}
),
});
//delay physics execution until we have an interpolation target
mouse_blocking=true;
} }
last_mouse_time=ins.time; mouse_blocking=true;//block physics until the next mouse event or mouse event timeout.
None true//empty queue
}, },
InputInstruction::SetPaused(s)=>{ _=>{
if s{ if mouse_blocking{
simulation_timer.pause(ins.time); //maybe I can turn this inside out by making this anotehr state machine where 50_000_000 is an instruction timestamp
//check if last mouse move is within 50ms
if ins.time-self.next_mouse.time<50_000_000{
false//do not empty queue
}else{
mouse_blocking=false;
// timeline.push_back(TimedInstruction{
// time:ins.time,
// instruction:InputInstruction::MoveMouse(self.next_mouse.pos),
// });
true
}
}else{ }else{
simulation_timer.unpause(ins.time);
}
Some(PhysicsInputInstruction::Idle)
}
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:simulation_timer.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:simulation_timer.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 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_time=ins.time;
last_mouse_time=ins.time; timeline.push_back(ins);
true if run_queue{
}
}else{
//mouse event
true
}{
//empty queue //empty queue
while let Some(instruction)=timeline.pop_front(){ while let Some(instruction)=timeline.pop_front(){
let simulation_time=simulation_timer.time(instruction.time); self.run(instruction.time);
self.run(simulation_time);
self.process_instruction(TimedInstruction{ self.process_instruction(TimedInstruction{
time:simulation_time, time:instruction.time,
instruction:PhysicsInstruction::Input(instruction.instruction), instruction:PhysicsInstruction::Input(instruction.instruction),
}); });
} }
} }
self.output() self.output()
})) })
} }
pub fn output(&self)->PhysicsOutputState{ pub fn output(&self)->PhysicsOutputState{
@ -577,7 +644,6 @@ impl PhysicsState {
} }
} }
} }
self.bvh=crate::bvh::generate_bvh(self.models.iter().map(|m|m.mesh().clone()).collect());
//I don't wanna write structs for temporary structures //I don't wanna write structs for temporary structures
//this code builds ModeDescriptions from the unsorted lists at the top of the function //this code builds ModeDescriptions from the unsorted lists at the top of the function
starts.sort_by_key(|tup|tup.0); starts.sort_by_key(|tup|tup.0);
@ -628,10 +694,6 @@ impl PhysicsState {
println!("Physics Objects: {}",self.models.len()); println!("Physics Objects: {}",self.models.len());
} }
pub fn load_user_settings(&mut self,user_settings:&crate::settings::UserSettings){
self.camera.sensitivity=user_settings.calculate_sensitivity();
}
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)
@ -761,8 +823,8 @@ impl PhysicsState {
} }
} }
fn mesh(&self) -> TreyMesh { fn mesh(&self) -> TreyMesh {
let mut aabb=TreyMesh::new(); let mut aabb=Aabb::new();
for vertex in TreyMesh::unit_vertices(){ for vertex in Aabb::unit_vertices(){
aabb.grow(self.body.position+self.style.hitbox_halfsize*vertex); aabb.grow(self.body.position+self.style.hitbox_halfsize*vertex);
} }
aabb aabb
@ -779,7 +841,7 @@ impl PhysicsState {
let (v,a)=(-self.body.velocity,self.body.acceleration); let (v,a)=(-self.body.velocity,self.body.acceleration);
//collect x //collect x
match collision_data.face { match collision_data.face {
TreyMeshFace::Top|TreyMeshFace::Back|TreyMeshFace::Bottom|TreyMeshFace::Front=>{ AabbFace::Top|AabbFace::Back|AabbFace::Bottom|AabbFace::Front=>{
for t in zeroes2(mesh0.max.x-mesh1.min.x,v.x,0.5*a.x) { for t in zeroes2(mesh0.max.x-mesh1.min.x,v.x,0.5*a.x) {
//negative t = back in time //negative t = back in time
//must be moving towards surface to collide //must be moving towards surface to collide
@ -807,14 +869,14 @@ impl PhysicsState {
} }
} }
}, },
TreyMeshFace::Left=>{ AabbFace::Left=>{
//generate event if v.x<0||a.x<0 //generate event if v.x<0||a.x<0
if -v.x<0f32{ if -v.x<0f32{
best_time=time; best_time=time;
exit_face=Some(TreyMeshFace::Left); exit_face=Some(TreyMeshFace::Left);
} }
}, },
TreyMeshFace::Right=>{ AabbFace::Right=>{
//generate event if 0<v.x||0<a.x //generate event if 0<v.x||0<a.x
if 0f32<(-v.x){ if 0f32<(-v.x){
best_time=time; best_time=time;
@ -824,7 +886,7 @@ impl PhysicsState {
} }
//collect y //collect y
match collision_data.face { match collision_data.face {
TreyMeshFace::Left|TreyMeshFace::Back|TreyMeshFace::Right|TreyMeshFace::Front=>{ AabbFace::Left|AabbFace::Back|AabbFace::Right|AabbFace::Front=>{
for t in zeroes2(mesh0.max.y-mesh1.min.y,v.y,0.5*a.y) { for t in zeroes2(mesh0.max.y-mesh1.min.y,v.y,0.5*a.y) {
//negative t = back in time //negative t = back in time
//must be moving towards surface to collide //must be moving towards surface to collide
@ -852,14 +914,14 @@ impl PhysicsState {
} }
} }
}, },
TreyMeshFace::Bottom=>{ AabbFace::Bottom=>{
//generate event if v.y<0||a.y<0 //generate event if v.y<0||a.y<0
if -v.y<0f32{ if -v.y<0f32{
best_time=time; best_time=time;
exit_face=Some(TreyMeshFace::Bottom); exit_face=Some(TreyMeshFace::Bottom);
} }
}, },
TreyMeshFace::Top=>{ AabbFace::Top=>{
//generate event if 0<v.y||0<a.y //generate event if 0<v.y||0<a.y
if 0f32<(-v.y){ if 0f32<(-v.y){
best_time=time; best_time=time;
@ -869,7 +931,7 @@ impl PhysicsState {
} }
//collect z //collect z
match collision_data.face { match collision_data.face {
TreyMeshFace::Left|TreyMeshFace::Bottom|TreyMeshFace::Right|TreyMeshFace::Top=>{ AabbFace::Left|AabbFace::Bottom|AabbFace::Right|AabbFace::Top=>{
for t in zeroes2(mesh0.max.z-mesh1.min.z,v.z,0.5*a.z) { for t in zeroes2(mesh0.max.z-mesh1.min.z,v.z,0.5*a.z) {
//negative t = back in time //negative t = back in time
//must be moving towards surface to collide //must be moving towards surface to collide
@ -897,14 +959,14 @@ impl PhysicsState {
} }
} }
}, },
TreyMeshFace::Front=>{ AabbFace::Front=>{
//generate event if v.z<0||a.z<0 //generate event if v.z<0||a.z<0
if -v.z<0f32{ if -v.z<0f32{
best_time=time; best_time=time;
exit_face=Some(TreyMeshFace::Front); exit_face=Some(TreyMeshFace::Front);
} }
}, },
TreyMeshFace::Back=>{ AabbFace::Back=>{
//generate event if 0<v.z||0<a.z //generate event if 0<v.z||0<a.z
if 0f32<(-v.z){ if 0f32<(-v.z){
best_time=time; best_time=time;
@ -922,18 +984,18 @@ impl PhysicsState {
None None
} }
fn predict_collision_start(&self,time:TIME,time_limit:TIME,model_id:u32) -> Option<TimedInstruction<PhysicsInstruction>> { fn predict_collision_start(&self,time:TIME,time_limit:TIME,model_id:u32) -> Option<TimedInstruction<PhysicsInstruction>> {
let mesh0=self.mesh();
let mesh1=self.models.get(model_id as usize).unwrap().mesh();
let (p,v,a,time)=(self.body.position,self.body.velocity,self.body.acceleration,self.body.time);
//find best t //find best t
let mut best_time=time_limit; let mut best_time=time_limit;
let mut best_face:Option<TreyMeshFace>=None; let mut best_face:Option<TreyMeshFace>=None;
let mesh0=self.mesh();
let mesh1=self.models.get(model_id as usize).unwrap().mesh();
let (p,v,a)=(self.body.position,self.body.velocity,self.body.acceleration);
//collect x //collect x
for t in zeroes2(mesh0.max.x-mesh1.min.x,v.x,0.5*a.x) { for t in zeroes2(mesh0.max.x-mesh1.min.x,v.x,0.5*a.x) {
//must collide now or in the future //must collide now or in the future
//must beat the current soonest collision time //must beat the current soonest collision time
//must be moving towards surface //must be moving towards surface
let t_time=time+((t as f64)*1_000_000_000f64) as TIME; let t_time=self.body.time+((t as f64)*1_000_000_000f64) as TIME;
if time<=t_time&&t_time<best_time&&0f32<v.x+a.x*t{ if time<=t_time&&t_time<best_time&&0f32<v.x+a.x*t{
let dp=self.body.extrapolated_position(t_time)-p; let dp=self.body.extrapolated_position(t_time)-p;
//faces must be overlapping //faces must be overlapping
@ -949,7 +1011,7 @@ impl PhysicsState {
//must collide now or in the future //must collide now or in the future
//must beat the current soonest collision time //must beat the current soonest collision time
//must be moving towards surface //must be moving towards surface
let t_time=time+((t as f64)*1_000_000_000f64) as TIME; let t_time=self.body.time+((t as f64)*1_000_000_000f64) as TIME;
if time<=t_time&&t_time<best_time&&v.x+a.x*t<0f32{ if time<=t_time&&t_time<best_time&&v.x+a.x*t<0f32{
let dp=self.body.extrapolated_position(t_time)-p; let dp=self.body.extrapolated_position(t_time)-p;
//faces must be overlapping //faces must be overlapping
@ -966,7 +1028,7 @@ impl PhysicsState {
//must collide now or in the future //must collide now or in the future
//must beat the current soonest collision time //must beat the current soonest collision time
//must be moving towards surface //must be moving towards surface
let t_time=time+((t as f64)*1_000_000_000f64) as TIME; let t_time=self.body.time+((t as f64)*1_000_000_000f64) as TIME;
if time<=t_time&&t_time<best_time&&0f32<v.y+a.y*t{ if time<=t_time&&t_time<best_time&&0f32<v.y+a.y*t{
let dp=self.body.extrapolated_position(t_time)-p; let dp=self.body.extrapolated_position(t_time)-p;
//faces must be overlapping //faces must be overlapping
@ -982,7 +1044,7 @@ impl PhysicsState {
//must collide now or in the future //must collide now or in the future
//must beat the current soonest collision time //must beat the current soonest collision time
//must be moving towards surface //must be moving towards surface
let t_time=time+((t as f64)*1_000_000_000f64) as TIME; let t_time=self.body.time+((t as f64)*1_000_000_000f64) as TIME;
if time<=t_time&&t_time<best_time&&v.y+a.y*t<0f32{ if time<=t_time&&t_time<best_time&&v.y+a.y*t<0f32{
let dp=self.body.extrapolated_position(t_time)-p; let dp=self.body.extrapolated_position(t_time)-p;
//faces must be overlapping //faces must be overlapping
@ -999,7 +1061,7 @@ impl PhysicsState {
//must collide now or in the future //must collide now or in the future
//must beat the current soonest collision time //must beat the current soonest collision time
//must be moving towards surface //must be moving towards surface
let t_time=time+((t as f64)*1_000_000_000f64) as TIME; let t_time=self.body.time+((t as f64)*1_000_000_000f64) as TIME;
if time<=t_time&&t_time<best_time&&0f32<v.z+a.z*t{ if time<=t_time&&t_time<best_time&&0f32<v.z+a.z*t{
let dp=self.body.extrapolated_position(t_time)-p; let dp=self.body.extrapolated_position(t_time)-p;
//faces must be overlapping //faces must be overlapping
@ -1015,7 +1077,7 @@ impl PhysicsState {
//must collide now or in the future //must collide now or in the future
//must beat the current soonest collision time //must beat the current soonest collision time
//must be moving towards surface //must be moving towards surface
let t_time=time+((t as f64)*1_000_000_000f64) as TIME; let t_time=self.body.time+((t as f64)*1_000_000_000f64) as TIME;
if time<=t_time&&t_time<best_time&&v.z+a.z*t<0f32{ if time<=t_time&&t_time<best_time&&v.z+a.z*t<0f32{
let dp=self.body.extrapolated_position(t_time)-p; let dp=self.body.extrapolated_position(t_time)-p;
//faces must be overlapping //faces must be overlapping
@ -1054,15 +1116,13 @@ impl crate::instruction::InstructionEmitter<PhysicsInstruction> for PhysicsState
// collector.collect(self.predict_collision_end2(self.time,time_limit,collision_data)); // collector.collect(self.predict_collision_end2(self.time,time_limit,collision_data));
// } // }
//check for collision start instructions (against every part in the game with no optimization!!) //check for collision start instructions (against every part in the game with no optimization!!)
let mut aabb=crate::aabb::Aabb::new(); for i in 0..self.models.len() {
aabb.grow(self.body.extrapolated_position(self.time)); let i=i as u32;
aabb.grow(self.body.extrapolated_position(time_limit)); if self.contacts.contains_key(&i)||self.intersects.contains_key(&i){
aabb.inflate(self.style.hitbox_halfsize); continue;
self.bvh.the_tester(&aabb,&mut |id|{
if !(self.contacts.contains_key(&id)||self.intersects.contains_key(&id)){
collector.collect(self.predict_collision_start(self.time,time_limit,id));
} }
}); collector.collect(self.predict_collision_start(self.time,time_limit,i));
}
if self.grounded { if self.grounded {
//walk maintenance //walk maintenance
collector.collect(self.next_walk_instruction()); collector.collect(self.next_walk_instruction());
@ -1077,11 +1137,10 @@ 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::Input(PhysicsInputInstruction::Idle) PhysicsInstruction::Input(InputInstruction::Idle)
|PhysicsInstruction::Input(PhysicsInputInstruction::SetNextMouse(_)) |PhysicsInstruction::Input(InputInstruction::MoveMouse(_))
|PhysicsInstruction::Input(PhysicsInputInstruction::ReplaceMouse(_,_))
|PhysicsInstruction::StrafeTick => (), |PhysicsInstruction::StrafeTick => (),
_=>println!("{}|{:?}",ins.time,ins.instruction), _=>println!("{:?}",ins),
} }
//selectively update body //selectively update body
match &ins.instruction { match &ins.instruction {
@ -1100,7 +1159,7 @@ impl crate::instruction::InstructionConsumer<PhysicsInstruction> for PhysicsStat
match &contacting.surf{ match &contacting.surf{
Some(surf)=>println!("I'm surfing!"), Some(surf)=>println!("I'm surfing!"),
None=>match &c.face { None=>match &c.face {
TreyMeshFace::Top => { AabbFace::Top => {
//ground //ground
self.grounded=true; self.grounded=true;
}, },
@ -1109,35 +1168,35 @@ impl crate::instruction::InstructionConsumer<PhysicsInstruction> for PhysicsStat
} }
//check ground //check ground
self.contacts.insert(c.model,c); self.contacts.insert(c.model,c);
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{
self.game.stage_id=stage_element.stage_id; self.game.stage_id=stage_element.stage_id;
} }
match stage_element.behaviour{ match stage_element.behaviour{
crate::model::StageElementBehaviour::SpawnAt=>(), crate::model::StageElementBehaviour::SpawnAt=>(),
crate::model::StageElementBehaviour::Trigger crate::model::StageElementBehaviour::Trigger
|crate::model::StageElementBehaviour::Teleport=>{ |crate::model::StageElementBehaviour::Teleport=>{
//TODO make good //TODO make good
if let Some(mode)=self.get_mode(stage_element.mode_id){ if let Some(mode)=self.get_mode(stage_element.mode_id){
if let Some(&spawn)=mode.get_spawn_model_id(self.game.stage_id){ if let Some(&spawn)=mode.get_spawn_model_id(self.game.stage_id){
if let Some(model)=self.models.get(spawn as usize){ if let Some(model)=self.models.get(spawn as usize){
self.body.position=model.transform.transform_point3(glam::Vec3::Y)+glam::Vec3::Y*(self.style.hitbox_halfsize.y+0.1); self.body.position=model.transform.transform_point3(glam::Vec3::Y)+glam::Vec3::Y*(self.style.hitbox_halfsize.y+0.1);
//manual clear //for c in self.contacts{process_instruction(CollisionEnd(c))} //manual clear //for c in self.contacts{process_instruction(CollisionEnd(c))}
self.contacts.clear(); self.contacts.clear();
self.intersects.clear(); self.intersects.clear();
self.body.acceleration=self.style.gravity; self.body.acceleration=self.style.gravity;
self.walk.state=WalkEnum::Reached; self.walk.state=WalkEnum::Reached;
self.grounded=false; self.grounded=false;
}else{println!("bad1");} }else{println!("bad1");}
}else{println!("bad2");} }else{println!("bad2");}
}else{println!("bad3");} }else{println!("bad3");}
}, },
crate::model::StageElementBehaviour::Platform=>(), crate::model::StageElementBehaviour::Platform=>(),
} }
}, },
None=>(), None=>(),
} }
//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);
@ -1157,35 +1216,6 @@ impl crate::instruction::InstructionConsumer<PhysicsInstruction> for PhysicsStat
PhysicsCollisionAttributes::Intersect{intersecting,general}=>{ PhysicsCollisionAttributes::Intersect{intersecting,general}=>{
//I think that setting the velocity to 0 was preventing surface contacts from entering an infinite loop //I think that setting the velocity to 0 was preventing surface contacts from entering an infinite loop
self.intersects.insert(c.model,c); self.intersects.insert(c.model,c);
match &general.stage_element{
Some(stage_element)=>{
if stage_element.force||self.game.stage_id<stage_element.stage_id{
self.game.stage_id=stage_element.stage_id;
}
match stage_element.behaviour{
crate::model::StageElementBehaviour::SpawnAt=>(),
crate::model::StageElementBehaviour::Trigger
|crate::model::StageElementBehaviour::Teleport=>{
//TODO make good
if let Some(mode)=self.get_mode(stage_element.mode_id){
if let Some(&spawn)=mode.get_spawn_model_id(self.game.stage_id){
if let Some(model)=self.models.get(spawn as usize){
self.body.position=model.transform.transform_point3(glam::Vec3::Y)+glam::Vec3::Y*(self.style.hitbox_halfsize.y+0.1);
//manual clear //for c in self.contacts{process_instruction(CollisionEnd(c))}
self.contacts.clear();
self.intersects.clear();
self.body.acceleration=self.style.gravity;
self.walk.state=WalkEnum::Reached;
self.grounded=false;
}else{println!("bad1");}
}else{println!("bad2");}
}else{println!("bad3");}
},
crate::model::StageElementBehaviour::Platform=>(),
}
},
None=>(),
}
}, },
} }
}, },
@ -1199,7 +1229,7 @@ impl crate::instruction::InstructionConsumer<PhysicsInstruction> for PhysicsStat
self.body.acceleration=a; self.body.acceleration=a;
//check ground //check ground
match &c.face { match &c.face {
TreyMeshFace::Top => { AabbFace::Top => {
self.grounded=false; self.grounded=false;
}, },
_ => (), _ => (),
@ -1235,32 +1265,29 @@ 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{
PhysicsInputInstruction::SetNextMouse(m) => { InputInstruction::MoveMouse(m) => {
self.camera.angles=self.camera.simulate_move_angles(self.next_mouse.pos); self.camera.angles=self.camera.simulate_move_angles(self.next_mouse.pos);
(self.camera.mouse,self.next_mouse)=(self.next_mouse.clone(),m); self.camera.mouse.move_mouse(self.next_mouse.pos,self.next_mouse.time);
self.next_mouse.move_mouse(m,self.time);
}, },
PhysicsInputInstruction::ReplaceMouse(m0,m1) => { InputInstruction::MoveForward(s) => self.set_control(StyleModifiers::CONTROL_MOVEFORWARD,s),
self.camera.angles=self.camera.simulate_move_angles(m0.pos); InputInstruction::MoveLeft(s) => self.set_control(StyleModifiers::CONTROL_MOVELEFT,s),
(self.camera.mouse,self.next_mouse)=(m0,m1); InputInstruction::MoveBack(s) => self.set_control(StyleModifiers::CONTROL_MOVEBACK,s),
}, InputInstruction::MoveRight(s) => self.set_control(StyleModifiers::CONTROL_MOVERIGHT,s),
PhysicsInputInstruction::SetMoveForward(s) => self.set_control(StyleModifiers::CONTROL_MOVEFORWARD,s), InputInstruction::MoveUp(s) => self.set_control(StyleModifiers::CONTROL_MOVEUP,s),
PhysicsInputInstruction::SetMoveLeft(s) => self.set_control(StyleModifiers::CONTROL_MOVELEFT,s), InputInstruction::MoveDown(s) => self.set_control(StyleModifiers::CONTROL_MOVEDOWN,s),
PhysicsInputInstruction::SetMoveBack(s) => self.set_control(StyleModifiers::CONTROL_MOVEBACK,s), InputInstruction::Jump(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;
}, },
PhysicsInputInstruction::SetZoom(s) => { InputInstruction::Zoom(s) => {
self.set_control(StyleModifiers::CONTROL_ZOOM,s); self.set_control(StyleModifiers::CONTROL_ZOOM,s);
refresh_walk_target=false; refresh_walk_target=false;
}, },
PhysicsInputInstruction::Reset => { InputInstruction::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;
@ -1271,7 +1298,7 @@ impl crate::instruction::InstructionConsumer<PhysicsInstruction> for PhysicsStat
self.grounded=false; self.grounded=false;
refresh_walk_target=false; refresh_walk_target=false;
}, },
PhysicsInputInstruction::Idle => {refresh_walk_target=false;},//literally idle! InputInstruction::Idle => {refresh_walk_target=false;},//literally idle!
} }
if refresh_walk_target{ if refresh_walk_target{
//calculate walk target velocity //calculate walk target velocity

@ -107,9 +107,8 @@ local cornerWedgeVerticies = {
*/ */
#[derive(Hash,PartialEq,Eq)] #[derive(Hash,PartialEq,Eq)]
pub enum CornerWedgeFace{ pub enum CornerWedgeFace{
Top,
Right, Right,
TopBack,
TopLeft,
Bottom, Bottom,
Front, Front,
} }
@ -163,8 +162,7 @@ pub type CornerWedgeFaceDescription=std::collections::HashMap::<CornerWedgeFace,
pub fn unit_cornerwedge()->crate::model::IndexedModel{ pub fn unit_cornerwedge()->crate::model::IndexedModel{
let mut t=CornerWedgeFaceDescription::new(); let mut t=CornerWedgeFaceDescription::new();
t.insert(CornerWedgeFace::Right,FaceDescription::default()); t.insert(CornerWedgeFace::Right,FaceDescription::default());
t.insert(CornerWedgeFace::TopBack,FaceDescription::default()); t.insert(CornerWedgeFace::Top,FaceDescription::default());
t.insert(CornerWedgeFace::TopLeft,FaceDescription::default());
t.insert(CornerWedgeFace::Bottom,FaceDescription::default()); t.insert(CornerWedgeFace::Bottom,FaceDescription::default());
t.insert(CornerWedgeFace::Front,FaceDescription::default()); t.insert(CornerWedgeFace::Front,FaceDescription::default());
generate_partial_unit_cornerwedge(t) generate_partial_unit_cornerwedge(t)
@ -458,10 +456,9 @@ pub fn generate_partial_unit_cornerwedge(face_descriptions:CornerWedgeFaceDescri
} as u32; } as u32;
let face_id=match face{ let face_id=match face{
CornerWedgeFace::Right => 0, CornerWedgeFace::Right => 0,
CornerWedgeFace::TopBack => 1, CornerWedgeFace::Top => 1,
CornerWedgeFace::TopLeft => 2, CornerWedgeFace::Bottom => 2,
CornerWedgeFace::Bottom => 3, CornerWedgeFace::Front => 3,
CornerWedgeFace::Front => 4,
}; };
//always push normal //always push normal
let normal_index=generated_normal.len() as u32; let normal_index=generated_normal.len() as u32;

@ -1,123 +0,0 @@
struct Ratio{
ratio:f64,
}
enum DerivedFov{
FromScreenAspect,
FromAspect(Ratio),
}
enum Fov{
Exactly{x:f64,y:f64},
DeriveX{x:DerivedFov,y:f64},
DeriveY{x:f64,y:DerivedFov},
}
impl Default for Fov{
fn default() -> Self {
Fov::DeriveX{x:DerivedFov::FromScreenAspect,y:1.0}
}
}
enum Sensitivity{
Exactly{x:f64,y:f64},
DeriveX{x:Ratio,y:f64},
DeriveY{x:f64,y:Ratio},
}
impl Default for Sensitivity{
fn default() -> Self {
Sensitivity::DeriveY{x:0.001,y:Ratio{ratio:1.0}}
}
}
#[derive(Default)]
pub struct UserSettings{
fov:Fov,
sensitivity:Sensitivity,
}
impl UserSettings{
pub fn calculate_fov(&self,zoom:f64,screen_size:&glam::UVec2)->glam::DVec2{
zoom*match &self.fov{
&Fov::Exactly{x,y}=>glam::dvec2(x,y),
Fov::DeriveX{x,y}=>match x{
DerivedFov::FromScreenAspect=>glam::dvec2(y*(screen_size.x as f64/screen_size.y as f64),*y),
DerivedFov::FromAspect(ratio)=>glam::dvec2(y*ratio.ratio,*y),
},
Fov::DeriveY{x,y}=>match y{
DerivedFov::FromScreenAspect=>glam::dvec2(*x,x*(screen_size.y as f64/screen_size.x as f64)),
DerivedFov::FromAspect(ratio)=>glam::dvec2(*x,x*ratio.ratio),
},
}
}
pub fn calculate_sensitivity(&self)->glam::DVec2{
match &self.sensitivity{
&Sensitivity::Exactly{x,y}=>glam::dvec2(x,y),
Sensitivity::DeriveX{x,y}=>glam::dvec2(y*x.ratio,*y),
Sensitivity::DeriveY{x,y}=>glam::dvec2(*x,x*y.ratio),
}
}
}
/*
//sensitivity is raw input dots (i.e. dpi = dots per inch) to radians conversion factor
sensitivity_x=0.001
sensitivity_y_from_x_ratio=1
Sensitivity::DeriveY{x:0.0.001,y:DerivedSensitivity{ratio:1.0}}
*/
pub fn read_user_settings()->UserSettings{
let mut cfg=configparser::ini::Ini::new();
if let Ok(_)=cfg.load("settings.conf"){
let (cfg_fov_x,cfg_fov_y)=(cfg.getfloat("camera","fov_x"),cfg.getfloat("camera","fov_y"));
let fov=match(cfg_fov_x,cfg_fov_y){
(Ok(Some(fov_x)),Ok(Some(fov_y)))=>Fov::Exactly {
x:fov_x,
y:fov_y
},
(Ok(Some(fov_x)),Ok(None))=>Fov::DeriveY{
x:fov_x,
y:if let Ok(Some(fov_y_from_x_ratio))=cfg.getfloat("camera","fov_y_from_x_ratio"){
DerivedFov::FromAspect(Ratio{ratio:fov_y_from_x_ratio})
}else{
DerivedFov::FromScreenAspect
}
},
(Ok(None),Ok(Some(fov_y)))=>Fov::DeriveX{
x:if let Ok(Some(fov_x_from_y_ratio))=cfg.getfloat("camera","fov_x_from_y_ratio"){
DerivedFov::FromAspect(Ratio{ratio:fov_x_from_y_ratio})
}else{
DerivedFov::FromScreenAspect
},
y:fov_y,
},
_=>{
Fov::default()
},
};
let (cfg_sensitivity_x,cfg_sensitivity_y)=(cfg.getfloat("camera","sensitivity_x"),cfg.getfloat("camera","sensitivity_y"));
let sensitivity=match(cfg_sensitivity_x,cfg_sensitivity_y){
(Ok(Some(sensitivity_x)),Ok(Some(sensitivity_y)))=>Sensitivity::Exactly {
x:sensitivity_x,
y:sensitivity_y
},
(Ok(Some(sensitivity_x)),Ok(None))=>Sensitivity::DeriveY{
x:sensitivity_x,
y:Ratio{
ratio:if let Ok(Some(sensitivity_y_from_x_ratio))=cfg.getfloat("camera","sensitivity_y_from_x_ratio"){sensitivity_y_from_x_ratio}else{1.0}
}
},
(Ok(None),Ok(Some(sensitivity_y)))=>Sensitivity::DeriveX{
x:Ratio{
ratio:if let Ok(Some(sensitivity_x_from_y_ratio))=cfg.getfloat("camera","sensitivity_x_from_y_ratio"){sensitivity_x_from_y_ratio}else{1.0}
},
y:sensitivity_y,
},
_=>{
Sensitivity::default()
},
};
UserSettings{
fov,
sensitivity,
}
}else{
UserSettings::default()
}
}

@ -5,8 +5,8 @@ struct Camera {
proj_inv: mat4x4<f32>, proj_inv: mat4x4<f32>,
// from world to camera // from world to camera
view: mat4x4<f32>, view: mat4x4<f32>,
// from camera to world // camera position
view_inv: mat4x4<f32>, cam_pos: vec4<f32>,
}; };
//group 0 is the camera //group 0 is the camera
@ -31,7 +31,8 @@ fn vs_sky(@builtin(vertex_index) vertex_index: u32) -> SkyOutput {
1.0 1.0
); );
let inv_model_view = mat3x3<f32>(camera.view_inv[0].xyz, camera.view_inv[1].xyz, camera.view_inv[2].xyz); // transposition = inversion for this orthonormal matrix
let inv_model_view = transpose(mat3x3<f32>(camera.view[0].xyz, camera.view[1].xyz, camera.view[2].xyz));
let unprojected = camera.proj_inv * pos; let unprojected = camera.proj_inv * pos;
var result: SkyOutput; var result: SkyOutput;
@ -42,7 +43,7 @@ fn vs_sky(@builtin(vertex_index) vertex_index: u32) -> SkyOutput {
struct ModelInstance{ struct ModelInstance{
transform:mat4x4<f32>, transform:mat4x4<f32>,
normal_transform:mat3x3<f32>, normal_transform:mat4x4<f32>,
color:vec4<f32>, color:vec4<f32>,
} }
//my fancy idea is to create a megatexture for each model that includes all the textures each intance will need //my fancy idea is to create a megatexture for each model that includes all the textures each intance will need
@ -77,11 +78,11 @@ fn vs_entity_texture(
) -> EntityOutputTexture { ) -> EntityOutputTexture {
var position: vec4<f32> = model_instances[instance].transform * vec4<f32>(pos, 1.0); var position: vec4<f32> = model_instances[instance].transform * vec4<f32>(pos, 1.0);
var result: EntityOutputTexture; var result: EntityOutputTexture;
result.normal = model_instances[instance].normal_transform * normal; result.normal = (model_instances[instance].normal_transform * vec4<f32>(normal, 1.0)).xyz;
result.texture = texture; result.texture = texture;
result.color = color; result.color = color;
result.model_color = model_instances[instance].color; result.model_color = model_instances[instance].color;
result.view = position.xyz - camera.view_inv[3].xyz;//col(3) result.view = position.xyz - camera.cam_pos.xyz;
result.position = camera.proj * camera.view * position; result.position = camera.proj * camera.view * position;
return result; return result;
} }
@ -108,5 +109,5 @@ fn fs_entity_texture(vertex: EntityOutputTexture) -> @location(0) vec4<f32> {
let fragment_color = textureSample(model_texture, model_sampler, vertex.texture)*vertex.color; let fragment_color = textureSample(model_texture, model_sampler, vertex.texture)*vertex.color;
let reflected_color = textureSample(cube_texture, cube_sampler, reflected).rgb; let reflected_color = textureSample(cube_texture, cube_sampler, reflected).rgb;
return mix(vec4<f32>(vec3<f32>(0.05) + 0.2 * reflected_color,1.0),mix(vertex.model_color,vec4<f32>(fragment_color.rgb,1.0),fragment_color.a),0.5+0.5*abs(d)); return mix(vec4<f32>(vec3<f32>(0.05) + 0.2 * reflected_color,1.0),mix(vertex.model_color,vec4<f32>(fragment_color.rgb,1.0),fragment_color.a),1.0-pow(1.0-abs(d),2.0));
} }

@ -1,237 +0,0 @@
type TIME=crate::physics::TIME;
#[derive(Clone)]
pub struct Timescale{
num:i64,
den:std::num::NonZeroU64,
}
#[derive(Clone)]
pub struct Paused{}
#[derive(Clone)]
pub struct Unpaused{}
#[derive(Clone)]
pub struct PausedScaled{scale:Timescale}
#[derive(Clone)]
pub struct UnpausedScaled{scale:Timescale}
pub trait TimerState{}
impl TimerState for Paused{}
impl TimerState for Unpaused{}
impl TimerState for PausedScaled{}
impl TimerState for UnpausedScaled{}
pub trait IsPaused{}
impl IsPaused for Paused{}
impl IsPaused for PausedScaled{}
pub trait IsUnpaused{}
impl IsUnpaused for Unpaused{}
impl IsUnpaused for UnpausedScaled{}
pub trait IsScaled{}
impl IsScaled for PausedScaled{}
impl IsScaled for UnpausedScaled{}
pub trait IsUnscaled{}
impl IsUnscaled for Paused{}
impl IsUnscaled for Unpaused{}
//scaled timer wrapper
enum Scaled{
Paused(Timer<PausedScaled>),
Unpaused(Timer<UnpausedScaled>),
}
pub struct ScaledTimer{
timer:Scaled,
}
impl ScaledTimer{
pub fn unpaused()->Self{
Self{
timer:Scaled::Unpaused(unpaused_scaled(Timescale{num:1,den:std::num::NonZeroU64::new(1).unwrap()}))
}
}
pub fn time(&self,time:TIME)->TIME{
match &self.timer{
Scaled::Paused(timer)=>timer.time(),
Scaled::Unpaused(timer)=>timer.time(time),
}
}
pub fn pause(&mut self,time:TIME){
match &self.timer{
Scaled::Paused(_)=>(),
Scaled::Unpaused(timer)=>self.timer=Scaled::Paused(timer.clone().pause(time)),
};
}
pub fn unpause(&mut self,time:TIME){
match &self.timer{
Scaled::Paused(timer)=>self.timer=Scaled::Unpaused(timer.clone().unpause(time)),
Scaled::Unpaused(_)=>(),
};
}
}
//unscaled timer wrapper
enum Unscaled{
Paused(Timer<Paused>),
Unpaused(Timer<Unpaused>),
}
pub struct UnscaledTimer{
timer:Unscaled,
}
impl UnscaledTimer{
pub fn unpaused()->Self{
Self{
timer:Unscaled::Unpaused(unpaused())
}
}
pub fn time(&self,time:TIME)->TIME{
match &self.timer{
Unscaled::Paused(timer)=>timer.time(),
Unscaled::Unpaused(timer)=>timer.time(time),
}
}
pub fn pause(&mut self,time:TIME){
match &self.timer{
Unscaled::Paused(_)=>(),
Unscaled::Unpaused(timer)=>self.timer=Unscaled::Paused(timer.clone().pause(time)),
};
}
pub fn unpause(&mut self,time:TIME){
match &self.timer{
Unscaled::Paused(timer)=>self.timer=Unscaled::Unpaused(timer.clone().unpause(time)),
Unscaled::Unpaused(_)=>(),
};
}
}
#[derive(Clone)]
pub struct Timer<State:TimerState>{
offset:crate::physics::TIME,
state:State,
}
fn get_offset(time:TIME,write_time:TIME)->TIME{
write_time-time
}
fn get_offset_scaled(time:TIME,write_time:TIME,scale:&Timescale)->TIME{
write_time-time*scale.num/scale.den.get() as i64
}
fn paused()->Timer<Paused>{
Timer{
offset:0,
state:Paused{},
}
}
fn unpaused()->Timer<Unpaused>{
Timer{
offset:0,
state:Unpaused{},
}
}
fn paused_scaled(scale:Timescale)->Timer<PausedScaled>{
Timer{
offset:0,
state:PausedScaled{scale},
}
}
fn unpaused_scaled(scale:Timescale)->Timer<UnpausedScaled>{
Timer{
offset:0,
state:UnpausedScaled{scale},
}
}
impl Timer<Paused>{
pub fn time(&self)->TIME{
self.offset
}
pub fn unpause(self,time:TIME)->Timer<Unpaused>{
Timer{
offset:get_offset(time,self.time()),
state:Unpaused{},
}
}
pub fn set_time(&mut self,time:TIME,write_time:TIME){
self.offset=get_offset(time,write_time);
}
pub fn set_scale(self,time:TIME,scale:Timescale)->Timer<PausedScaled>{
Timer{
offset:get_offset_scaled(time,self.time(),&scale),
state:PausedScaled{scale},
}
}
}
impl Timer<Unpaused>{
pub fn time(&self,time:TIME)->TIME{
self.offset+time
}
pub fn pause(self,time:TIME)->Timer<Paused>{
Timer{
offset:self.time(time),
state:Paused{},
}
}
pub fn set_time(&mut self,time:TIME,write_time:TIME){
self.offset=get_offset(time,write_time);
}
pub fn set_scale(self,time:TIME,scale:Timescale)->Timer<UnpausedScaled>{
Timer{
offset:get_offset_scaled(time,self.time(time),&scale),
state:UnpausedScaled{scale},
}
}
}
impl Timer<PausedScaled>{
pub fn time(&self)->TIME{
self.offset
}
pub fn unpause(self,time:TIME)->Timer<UnpausedScaled>{
Timer{
offset:get_offset_scaled(time,self.time(),&self.state.scale),
state:UnpausedScaled{scale:self.state.scale},
}
}
pub fn set_time(&mut self,time:TIME,write_time:TIME){
self.offset=get_offset_scaled(time,write_time,&self.state.scale);
}
pub fn set_scale(self,time:TIME,scale:Timescale)->Timer<PausedScaled>{
Timer{
offset:get_offset_scaled(time,self.time(),&scale),
state:PausedScaled{scale},
}
}
}
impl Timer<UnpausedScaled>{
pub fn time(&self,time:TIME)->TIME{
self.offset+time*self.state.scale.num/self.state.scale.den.get() as i64
}
pub fn pause(self,time:TIME)->Timer<PausedScaled>{
Timer{
offset:self.time(time),
state:PausedScaled{scale:self.state.scale},
}
}
pub fn set_time(&mut self,time:TIME,write_time:TIME){
self.offset=get_offset_scaled(time,write_time,&self.state.scale);
}
pub fn set_scale(self,time:TIME,scale:Timescale)->Timer<UnpausedScaled>{
Timer{
offset:get_offset_scaled(time,self.time(time),&scale),
//self.offset+time*self.state.scale.num/self.state.scale.den.get() as i64-time*scale.num/scale.den.get() as i64
state:UnpausedScaled{scale},
}
}
}
#[test]
fn test_timer_unscaled(){
const ONE_SECOND:TIME=1_000_000_000;
let run_prepare=paused();
let run_start=run_prepare.unpause(ONE_SECOND);
let run_finish=run_start.pause(11*ONE_SECOND);
assert_eq!(run_finish.time(),10*ONE_SECOND);
}

@ -45,31 +45,6 @@ impl<Task:Send+'static,Value:Clone+Send+'static> Worker<Task,Value> {
} }
} }
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");