Compare commits

..

13 Commits

Author SHA1 Message Date
ede287acd6 unnecessary Arc Mutex just send it bud 2023-10-04 03:51:31 -07:00
9df4da9d26 yup the guard was guarded 2023-10-04 03:51:31 -07:00
77d060b90c I think I double taped this thing 2023-10-04 03:51:31 -07:00
f320520292 what the fuck did I make 2023-10-04 03:51:31 -07:00
6fc585e01e make main into a test 2023-10-04 03:51:31 -07:00
928654c7df make that shit compile 2023-10-04 03:51:31 -07:00
8000d1db29 gpt: park thread 2023-10-04 03:51:31 -07:00
194b9b9a11 gpt: muh parking_lot 2023-10-04 03:51:14 -07:00
4933543dbf add parking_lot dep 2023-10-04 03:51:06 -07:00
285a19a73a gpt: conditionally spawn new worker 2023-10-04 03:51:06 -07:00
f3f624c44c gpt: unconditionally spawn new worker 2023-10-04 03:50:55 -07:00
e547940f2b gpt 2023-10-04 01:30:33 -07:00
51aac7b214 code mess (SPLIT INTO MULTIPLE COMMITS) 2023-10-04 01:25:03 -07:00
14 changed files with 555 additions and 1202 deletions

183
Cargo.lock generated

@ -86,21 +86,6 @@ dependencies = [
"libc",
]
[[package]]
name = "approx"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f2a05fd1bd10b2527e20a2cd32d8873d115b8b39fe219ee25f42a8aca6ba278"
dependencies = [
"num-traits 0.2.16",
]
[[package]]
name = "array-init"
version = "2.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3d62b7694a562cdf5a74227903507c56ab2cc8bdd1f781ed5cb4cf9c9f810bfc"
[[package]]
name = "arrayref"
version = "0.3.7"
@ -178,30 +163,6 @@ version = "0.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9e1b586273c5702936fe7b7d6896644d8be71e6314cfe09d3167c95f712589e8"
[[package]]
name = "binrw"
version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f846d8732b2a55b569b885852ecc925a2b1f24568f4707f8b1ccd5dc6805ea9b"
dependencies = [
"array-init",
"binrw_derive",
"bytemuck",
]
[[package]]
name = "binrw_derive"
version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5c2aa66a5e35daf7f91ed44c945886597ef4c327f34f68b6bbf22951a250ceeb"
dependencies = [
"either",
"owo-colors",
"proc-macro2",
"quote",
"syn 1.0.109",
]
[[package]]
name = "bit-set"
version = "0.5.3"
@ -277,27 +238,12 @@ dependencies = [
"objc2-encode",
]
[[package]]
name = "build_const"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b4ae4235e6dac0694637c763029ecea1a2ec9e4e06ec2729bd21ba4d9c863eb7"
[[package]]
name = "bumpalo"
version = "3.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a3e2c3daef883ecc1b5d58c15adae93470a91d425f3532ba1695849656af3fc1"
[[package]]
name = "bv"
version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8834bb1d8ee5dc048ee3124f2c7c1afcc6bc9aed03f11e9dfd8c69470a5db340"
dependencies = [
"feature-probe",
]
[[package]]
name = "bytemuck"
version = "1.13.1"
@ -318,12 +264,6 @@ dependencies = [
"syn 2.0.29",
]
[[package]]
name = "byteorder"
version = "0.5.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0fc10e8cc6b2580fda3f36eb6dc5316657f812a3df879a44a66fc9f0fdbc4855"
[[package]]
name = "byteorder"
version = "1.4.3"
@ -366,16 +306,6 @@ version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fd16c4719339c4530435d38e511904438d07cce7950afa3718a84ac36c10e89e"
[[package]]
name = "cgmath"
version = "0.18.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1a98d30140e3296250832bbaaff83b27dcd6fa3cc70fb6f1f3e5c9c0023b5317"
dependencies = [
"approx",
"num-traits 0.2.16",
]
[[package]]
name = "codespan-reporting"
version = "0.11.1"
@ -401,12 +331,6 @@ dependencies = [
"crossbeam-utils",
]
[[package]]
name = "configparser"
version = "3.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5458d9d1a587efaf5091602c59d299696a3877a439c8f6d461a2d3cce11df87a"
[[package]]
name = "constant_time_eq"
version = "0.3.0"
@ -453,15 +377,6 @@ dependencies = [
"libc",
]
[[package]]
name = "crc"
version = "1.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d663548de7f5cca343f1e0a48d14dcfb0e9eb4e079ec58883b7251539fa10aeb"
dependencies = [
"build_const",
]
[[package]]
name = "crc32fast"
version = "1.3.2"
@ -508,7 +423,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "594ecd967c2f40db5dde8da4c356975fc1fe030e951c7c3962f6dc2e80042e87"
dependencies = [
"bitflags 1.3.2",
"byteorder 1.4.3",
"byteorder",
"enum_primitive",
]
@ -544,12 +459,6 @@ version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9ea835d29036a4087793836fa931b08837ad5e957da9e23886b29586fb9b6650"
[[package]]
name = "either"
version = "1.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a26ae43d7bcc3b814de94796a5e736d4029efb0ee900c12e2d54c993ad1a1e07"
[[package]]
name = "enum_primitive"
version = "0.1.1"
@ -623,12 +532,6 @@ dependencies = [
"simd-adler32",
]
[[package]]
name = "feature-probe"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "835a3dc7d1ec9e75e2b5fb4ba75396837112d2060b03f7d43bc1897c7f7211da"
[[package]]
name = "flate2"
version = "1.0.27"
@ -1028,25 +931,6 @@ dependencies = [
"libc",
]
[[package]]
name = "lzma"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "782ba3f542e8bc1349386c15e9dc3119ae6da96479f96b3863cc7a88bbdfd4e4"
dependencies = [
"byteorder 0.5.3",
]
[[package]]
name = "lzma-rs"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aba8ecb0450dfabce4ad72085eed0a75dffe8f21f7ada05638564ea9db2d7fb1"
dependencies = [
"byteorder 1.4.3",
"crc",
]
[[package]]
name = "malloc_buf"
version = "0.0.6"
@ -1351,12 +1235,6 @@ dependencies = [
"ttf-parser",
]
[[package]]
name = "owo-colors"
version = "3.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c1b04fb49957986fdce4d6ee7a65027d55d4b6d2265e5848bbb507b58ccfdb6f"
[[package]]
name = "parking"
version = "2.1.0"
@ -1651,7 +1529,7 @@ version = "0.8.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f9860a6cc38ed1da53456442089b4dfa35e7cedaa326df63017af88385e6b20"
dependencies = [
"byteorder 1.4.3",
"byteorder",
"num-traits 0.2.16",
"paste",
]
@ -1662,7 +1540,7 @@ version = "1.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bffea85eea980d8a74453e5d02a8d93028f3c34725de143085a844ebe953258a"
dependencies = [
"byteorder 1.4.3",
"byteorder",
"rmp",
"serde",
]
@ -1804,11 +1682,10 @@ checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"
[[package]]
name = "strafe-client"
version = "0.8.0"
version = "0.7.0"
dependencies = [
"async-executor",
"bytemuck",
"configparser",
"ddsfile",
"env_logger",
"glam",
@ -1821,7 +1698,6 @@ dependencies = [
"rbx_dom_weak",
"rbx_reflection_database",
"rbx_xml",
"vbsp",
"wgpu",
"winit",
]
@ -1860,17 +1736,6 @@ dependencies = [
"unicode-ident",
]
[[package]]
name = "syn_util"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6754c4559b79657554e9d8a0d56e65e490c76d382b9c23108364ec4125dea23c"
dependencies = [
"proc-macro2",
"quote",
"syn 1.0.109",
]
[[package]]
name = "termcolor"
version = "1.2.0"
@ -1972,35 +1837,6 @@ version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f962df74c8c05a667b5ee8bcf162993134c104e96440b663c8daa176dc772d8c"
[[package]]
name = "vbsp"
version = "0.1.0"
source = "git+https://github.com/icewind1991/vbsp?rev=0850bb8dbd695a770d39a06f2cc880aa9d626bf7#0850bb8dbd695a770d39a06f2cc880aa9d626bf7"
dependencies = [
"arrayvec",
"binrw",
"bitflags 1.3.2",
"bv",
"cgmath",
"lzma-rs",
"num_enum 0.5.11",
"static_assertions",
"thiserror",
"vbsp-derive",
"zip",
]
[[package]]
name = "vbsp-derive"
version = "0.1.0"
source = "git+https://github.com/icewind1991/vbsp?rev=0850bb8dbd695a770d39a06f2cc880aa9d626bf7#0850bb8dbd695a770d39a06f2cc880aa9d626bf7"
dependencies = [
"proc-macro2",
"quote",
"syn 1.0.109",
"syn_util",
]
[[package]]
name = "vec_map"
version = "0.8.2"
@ -2520,14 +2356,3 @@ name = "xml-rs"
version = "0.8.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "47430998a7b5d499ccee752b41567bc3afc57e1327dc855b1a2aa44ce29b5fa1"
[[package]]
name = "zip"
version = "0.6.3"
source = "git+https://github.com/icewind1991/zip?branch=lzma-decompression#67239e847f4fbe3a5b847707ee3228ac370388f5"
dependencies = [
"byteorder 1.4.3",
"crc32fast",
"crossbeam-utils",
"lzma",
]

@ -1,6 +1,6 @@
[package]
name = "strafe-client"
version = "0.8.0"
version = "0.7.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
@ -8,7 +8,6 @@ edition = "2021"
[dependencies]
async-executor = "1.5.1"
bytemuck = { version = "1.13.1", features = ["derive"] }
configparser = "3.0.2"
ddsfile = "0.5.1"
env_logger = "0.10.0"
glam = "0.24.1"
@ -21,11 +20,10 @@ rbx_binary = "0.7.1"
rbx_dom_weak = "2.5.0"
rbx_reflection_database = "0.2.7"
rbx_xml = "0.13.1"
vbsp = { git="https://github.com/icewind1991/vbsp", rev = "0850bb8dbd695a770d39a06f2cc880aa9d626bf7" }
wgpu = "0.17.0"
winit = "0.28.6"
#[profile.release]
#lto = true
#strip = true
#codegen-units = 1
[profile.release]
lto = true
strip = true
codegen-units = 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
}
}

@ -13,22 +13,9 @@ pub enum PhysicsInstruction {
// bool,//true = Force
// )
//InputInstructions conditionally activate RefreshWalkTarget (by doing what SetWalkTargetVelocity used to do and then flagging it)
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,
Input(InputInstruction),
//temp
SetSpawnPosition(glam::Vec3),
}
#[derive(Debug)]
pub enum InputInstruction {
@ -47,7 +34,7 @@ pub enum InputInstruction {
//for interpolation / networking / playback reasons, most playback heads will always want
//to be 1 instruction ahead to generate the next state for interpolation.
}
#[derive(Clone)]
#[derive(Clone,Debug)]
pub struct Body {
position: glam::Vec3,//I64 where 2^32 = 1 u
velocity: glam::Vec3,//I64 where 2^32 = 1 u/s
@ -106,29 +93,49 @@ impl crate::instruction::InstructionConsumer<InputInstruction> for InputState{
}
*/
//hey dumbass just use a delta
#[derive(Clone,Debug)]
pub struct MouseState {
pub pos: glam::IVec2,
pub time: TIME,
enum MouseInterpolation {
First,//just checks the last value
Lerp,//lerps between
}
impl Default for MouseState{
fn default() -> Self {
//hey dumbass just use a delta
pub struct MouseInterpolationState {
interpolation: MouseInterpolation,
time0: TIME,
time1: TIME,
mouse0: glam::IVec2,
mouse1: glam::IVec2,
}
impl MouseInterpolationState {
pub fn new() -> Self {
Self {
time:0,
pos:glam::IVec2::ZERO,
interpolation:MouseInterpolation::First,
time0:0,
time1:1,//ONE NANOSECOND!!!! avoid divide by zero
mouse0:glam::IVec2::ZERO,
mouse1:glam::IVec2::ZERO,
}
}
}
impl MouseState {
pub fn lerp(&self,target:&MouseState,time:TIME)->glam::IVec2 {
let m0=self.pos.as_i64vec2();
let m1=target.pos.as_i64vec2();
//these are deltas
let t1t=(target.time-time) as i64;
let tt0=(time-self.time) as i64;
let dt=(target.time-self.time) as i64;
((m0*t1t+m1*tt0)/dt).as_ivec2()
pub fn move_mouse(&mut self,time:TIME,delta:glam::IVec2){
self.time0=self.time1;
self.mouse0=self.mouse1;
self.time1=time;
self.mouse1=self.mouse1+delta;
}
pub fn interpolated_position(&self,time:TIME) -> glam::IVec2 {
match self.interpolation {
MouseInterpolation::First => self.mouse0,
MouseInterpolation::Lerp => {
let m0=self.mouse0.as_i64vec2();
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()
}
}
}
}
@ -151,14 +158,15 @@ impl WalkState {
}
}
#[derive(Clone)]
pub struct PhysicsCamera {
// Note: we use the Y=up coordinate space in this example.
pub struct Camera {
offset: glam::Vec3,
angles: glam::DVec2,//YAW AND THEN PITCH
//punch: glam::Vec3,
//punch_velocity: glam::Vec3,
fov: glam::Vec2,//slope
sensitivity: glam::DVec2,
mouse:MouseState,
time: TIME,
}
#[inline]
@ -170,22 +178,45 @@ fn mat3_from_rotation_y_f64(angle: f64) -> glam::Mat3 {
glam::Vec3::new(sina as f32, 0.0, cosa as f32),
)
}
impl PhysicsCamera {
pub fn from_offset(offset:glam::Vec3) -> Self {
#[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 Camera {
pub fn from_offset(offset:glam::Vec3,aspect:f32) -> Self {
Self{
offset,
angles: glam::DVec2::ZERO,
sensitivity: glam::dvec2(1.0/1024.0,1.0/1024.0),
mouse:MouseState{pos:glam::IVec2::ZERO,time:-1},//escape initialization hell divide by zero
fov: glam::vec2(aspect,1.0),
sensitivity: glam::dvec2(1.0/16384.0,1.0/16384.0),
time: 0,
}
}
pub fn simulate_move_angles(&self, mouse_pos: glam::IVec2) -> glam::DVec2 {
let mut a=self.angles-self.sensitivity*(mouse_pos-self.mouse.pos).as_dvec2();
fn simulate_move_angles(&self, delta: glam::IVec2) -> glam::DVec2 {
let mut a=self.angles-self.sensitivity*delta.as_dvec2();
a.y=a.y.clamp(-std::f64::consts::FRAC_PI_2, std::f64::consts::FRAC_PI_2);
return a
}
fn simulate_move_rotation_y(&self, mouse_pos_x: i32) -> glam::Mat3 {
mat3_from_rotation_y_f64(self.angles.x-self.sensitivity.x*((mouse_pos_x-self.mouse.pos.x) as f64))
fn simulate_move_rotation_y(&self, delta_x: i32) -> glam::Mat3 {
mat3_from_rotation_y_f64(self.angles.x-self.sensitivity.x*(delta_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;
}
}
@ -246,7 +277,7 @@ impl StyleModifiers{
const UP_DIR:glam::Vec3 = glam::Vec3::Y;
fn get_control(&self,control:u32,controls:u32)->bool{
controls&self.controls_mask&control==control
controls&self.controls_mask&control!=0
}
fn get_control_dir(&self,controls:u32)->glam::Vec3{
@ -290,14 +321,13 @@ pub struct PhysicsState{
pub intersects:std::collections::HashMap::<u32,RelativeCollision>,
//pub intersections: Vec<ModelId>,
//camera must exist in state because wormholes modify the camera, also camera punch
pub camera:PhysicsCamera,
pub next_mouse:MouseState,//Where is the mouse headed next
pub camera:Camera,
pub mouse_interpolation:MouseInterpolationState,
pub controls:u32,
pub walk:WalkState,
pub grounded:bool,
//all models
pub models:Vec<ModelPhysics>,
pub bvh:crate::bvh::BvhNode,
pub modes:Vec<crate::model::ModeDescription>,
pub mode_from_mode_id:std::collections::HashMap::<u32,usize>,
@ -305,20 +335,115 @@ pub struct PhysicsState{
//This is not the same as Reset which teleports you to Spawn0
pub spawn_point:glam::Vec3,
}
#[derive(Clone)]
pub struct PhysicsOutputState{
camera:PhysicsCamera,
body:Body,
#[derive(Debug,Clone,Copy,Hash,Eq,PartialEq)]
pub enum AabbFace{
Right,//+X
Top,
Back,
Left,
Bottom,
Front,
}
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(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
type TreyMeshFace = crate::aabb::AabbFace;
type TreyMesh = crate::aabb::Aabb;
type TreyMeshFace = AabbFace;
type TreyMesh = Aabb;
enum PhysicsCollisionAttributes{
Contact{//track whether you are contacting the object
@ -341,7 +466,7 @@ pub struct ModelPhysics {
impl ModelPhysics {
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 {
aabb.grow(transform.transform_point3(glam::Vec3::from_array(model.unique_pos[indexed_vertex.pos as usize])));
}
@ -359,16 +484,29 @@ impl ModelPhysics {
}
}
pub fn unit_vertices(&self) -> [glam::Vec3;8] {
TreyMesh::unit_vertices()
Aabb::unit_vertices()
}
pub fn mesh(&self) -> &TreyMesh {
return &self.mesh;
}
pub fn face_mesh(&self,face:TreyMeshFace)->TreyMesh{
self.mesh.face(face)
pub fn unit_face_vertices(&self,face:TreyMeshFace) -> [glam::Vec3;4] {
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 {
TreyMesh::normal(face)//this is wrong for scale
Aabb::normal(face)//this is wrong for scale
}
}
@ -418,30 +556,6 @@ 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(),
bvh:crate::bvh::BvhNode::default(),
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 {
pub fn clear(&mut self){
self.models.clear();
@ -449,178 +563,6 @@ impl PhysicsState {
self.contacts.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)),
}
}
}
}
}
self.bvh=crate::bvh::generate_bvh(self.models.iter().map(|m|m.mesh().clone()).collect());
//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 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>{
if let Some(&mode)=self.mode_from_mode_id.get(&mode_id){
self.modes.get(mode)
@ -750,8 +692,8 @@ impl PhysicsState {
}
}
fn mesh(&self) -> TreyMesh {
let mut aabb=TreyMesh::new();
for vertex in TreyMesh::unit_vertices(){
let mut aabb=Aabb::new();
for vertex in Aabb::unit_vertices(){
aabb.grow(self.body.position+self.style.hitbox_halfsize*vertex);
}
aabb
@ -768,7 +710,7 @@ impl PhysicsState {
let (v,a)=(-self.body.velocity,self.body.acceleration);
//collect x
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) {
//negative t = back in time
//must be moving towards surface to collide
@ -796,14 +738,14 @@ impl PhysicsState {
}
}
},
TreyMeshFace::Left=>{
AabbFace::Left=>{
//generate event if v.x<0||a.x<0
if -v.x<0f32{
best_time=time;
exit_face=Some(TreyMeshFace::Left);
}
},
TreyMeshFace::Right=>{
AabbFace::Right=>{
//generate event if 0<v.x||0<a.x
if 0f32<(-v.x){
best_time=time;
@ -813,7 +755,7 @@ impl PhysicsState {
}
//collect y
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) {
//negative t = back in time
//must be moving towards surface to collide
@ -841,14 +783,14 @@ impl PhysicsState {
}
}
},
TreyMeshFace::Bottom=>{
AabbFace::Bottom=>{
//generate event if v.y<0||a.y<0
if -v.y<0f32{
best_time=time;
exit_face=Some(TreyMeshFace::Bottom);
}
},
TreyMeshFace::Top=>{
AabbFace::Top=>{
//generate event if 0<v.y||0<a.y
if 0f32<(-v.y){
best_time=time;
@ -858,7 +800,7 @@ impl PhysicsState {
}
//collect z
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) {
//negative t = back in time
//must be moving towards surface to collide
@ -886,14 +828,14 @@ impl PhysicsState {
}
}
},
TreyMeshFace::Front=>{
AabbFace::Front=>{
//generate event if v.z<0||a.z<0
if -v.z<0f32{
best_time=time;
exit_face=Some(TreyMeshFace::Front);
}
},
TreyMeshFace::Back=>{
AabbFace::Back=>{
//generate event if 0<v.z||0<a.z
if 0f32<(-v.z){
best_time=time;
@ -911,18 +853,18 @@ impl PhysicsState {
None
}
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
let mut best_time=time_limit;
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
for t in zeroes2(mesh0.max.x-mesh1.min.x,v.x,0.5*a.x) {
//must collide now or in the future
//must beat the current soonest collision time
//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{
let dp=self.body.extrapolated_position(t_time)-p;
//faces must be overlapping
@ -938,7 +880,7 @@ impl PhysicsState {
//must collide now or in the future
//must beat the current soonest collision time
//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{
let dp=self.body.extrapolated_position(t_time)-p;
//faces must be overlapping
@ -955,7 +897,7 @@ impl PhysicsState {
//must collide now or in the future
//must beat the current soonest collision time
//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{
let dp=self.body.extrapolated_position(t_time)-p;
//faces must be overlapping
@ -971,7 +913,7 @@ impl PhysicsState {
//must collide now or in the future
//must beat the current soonest collision time
//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{
let dp=self.body.extrapolated_position(t_time)-p;
//faces must be overlapping
@ -988,7 +930,7 @@ impl PhysicsState {
//must collide now or in the future
//must beat the current soonest collision time
//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{
let dp=self.body.extrapolated_position(t_time)-p;
//faces must be overlapping
@ -1004,7 +946,7 @@ impl PhysicsState {
//must collide now or in the future
//must beat the current soonest collision time
//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{
let dp=self.body.extrapolated_position(t_time)-p;
//faces must be overlapping
@ -1043,15 +985,13 @@ impl crate::instruction::InstructionEmitter<PhysicsInstruction> for PhysicsState
// 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!!)
let mut aabb=crate::aabb::Aabb::new();
aabb.grow(self.body.extrapolated_position(self.time));
aabb.grow(self.body.extrapolated_position(time_limit));
aabb.inflate(self.style.hitbox_halfsize);
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));
for i in 0..self.models.len() {
let i=i as u32;
if self.contacts.contains_key(&i)||self.intersects.contains_key(&i){
continue;
}
});
collector.collect(self.predict_collision_start(self.time,time_limit,i));
}
if self.grounded {
//walk maintenance
collector.collect(self.next_walk_instruction());
@ -1066,22 +1006,24 @@ impl crate::instruction::InstructionEmitter<PhysicsInstruction> for PhysicsState
impl crate::instruction::InstructionConsumer<PhysicsInstruction> for PhysicsState {
fn process_instruction(&mut self, ins:TimedInstruction<PhysicsInstruction>) {
match &ins.instruction {
PhysicsInstruction::Input(PhysicsInputInstruction::Idle)
|PhysicsInstruction::Input(PhysicsInputInstruction::SetNextMouse(_))
|PhysicsInstruction::Input(PhysicsInputInstruction::ReplaceMouse(_,_))
|PhysicsInstruction::StrafeTick => (),
_=>println!("{}|{:?}",ins.time,ins.instruction),
PhysicsInstruction::StrafeTick => (),
PhysicsInstruction::Input(InputInstruction::MoveMouse(_)) => (),
_=>println!("{:?}",ins),
}
//selectively update body
match &ins.instruction {
//PhysicsInstruction::Input(InputInstruction::MoveMouse(_)) => (),//dodge time for mouse movement
PhysicsInstruction::Input(InputInstruction::MoveMouse(_)) => (),//dodge time for mouse movement
PhysicsInstruction::Input(_)
|PhysicsInstruction::SetSpawnPosition(_)
|PhysicsInstruction::ReachWalkTargetVelocity
|PhysicsInstruction::CollisionStart(_)
|PhysicsInstruction::CollisionEnd(_)
|PhysicsInstruction::StrafeTick => self.advance_time(ins.time),
}
match ins.instruction {
PhysicsInstruction::SetSpawnPosition(position)=>{
self.spawn_point=position;
}
PhysicsInstruction::CollisionStart(c) => {
let model=c.model(&self.models).unwrap();
match &model.attributes{
@ -1089,54 +1031,51 @@ impl crate::instruction::InstructionConsumer<PhysicsInstruction> for PhysicsStat
match &contacting.surf{
Some(surf)=>println!("I'm surfing!"),
None=>match &c.face {
TreyMeshFace::Top => {
AabbFace::Top => {
//ground
self.grounded=true;
},
_ => (),
},
}
//check ground
self.contacts.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=>(),
}
//flatten v
let mut v=self.body.velocity;
self.contact_constrain_velocity(&mut v);
match &general.booster{
Some(booster)=>{
v+=booster.velocity;
self.contact_constrain_velocity(&mut v);
Some(booster)=>self.body.velocity+=booster.velocity,
None=>(),
}
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=>(),
}
//check ground
self.contacts.insert(c.model,c);
//flatten v
let mut v=self.body.velocity;
self.contact_constrain_velocity(&mut v);
self.body.velocity=v;
if self.grounded&&self.style.get_control(StyleModifiers::CONTROL_JUMP,self.controls){
self.jump();
@ -1146,35 +1085,6 @@ impl crate::instruction::InstructionConsumer<PhysicsInstruction> for PhysicsStat
PhysicsCollisionAttributes::Intersect{intersecting,general}=>{
//I think that setting the velocity to 0 was preventing surface contacts from entering an infinite loop
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=>(),
}
},
}
},
@ -1188,7 +1098,7 @@ impl crate::instruction::InstructionConsumer<PhysicsInstruction> for PhysicsStat
self.body.acceleration=a;
//check ground
match &c.face {
TreyMeshFace::Top => {
AabbFace::Top => {
self.grounded=false;
},
_ => (),
@ -1201,7 +1111,7 @@ impl crate::instruction::InstructionConsumer<PhysicsInstruction> for PhysicsStat
}
},
PhysicsInstruction::StrafeTick => {
let camera_mat=self.camera.simulate_move_rotation_y(self.camera.mouse.lerp(&self.next_mouse,self.time).x);
let camera_mat=self.camera.simulate_move_rotation_y(self.mouse_interpolation.interpolated_position(self.time).x-self.mouse_interpolation.mouse0.x);
let control_dir=camera_mat*self.style.get_control_dir(self.controls);
let d=self.body.velocity.dot(control_dir);
if d<self.style.mv {
@ -1224,32 +1134,28 @@ impl crate::instruction::InstructionConsumer<PhysicsInstruction> for PhysicsStat
let mut refresh_walk_target=true;
let mut refresh_walk_target_velocity=true;
match input_instruction{
PhysicsInputInstruction::SetNextMouse(m) => {
self.camera.angles=self.camera.simulate_move_angles(self.next_mouse.pos);
(self.camera.mouse,self.next_mouse)=(self.next_mouse.clone(),m);
InputInstruction::MoveMouse(m) => {
self.camera.angles=self.camera.simulate_move_angles(self.mouse_interpolation.mouse1-self.mouse_interpolation.mouse0);
self.mouse_interpolation.move_mouse(self.time,m);
},
PhysicsInputInstruction::ReplaceMouse(m0,m1) => {
self.camera.angles=self.camera.simulate_move_angles(m0.pos);
(self.camera.mouse,self.next_mouse)=(m0,m1);
},
PhysicsInputInstruction::SetMoveForward(s) => self.set_control(StyleModifiers::CONTROL_MOVEFORWARD,s),
PhysicsInputInstruction::SetMoveLeft(s) => self.set_control(StyleModifiers::CONTROL_MOVELEFT,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) => {
InputInstruction::MoveForward(s) => self.set_control(StyleModifiers::CONTROL_MOVEFORWARD,s),
InputInstruction::MoveLeft(s) => self.set_control(StyleModifiers::CONTROL_MOVELEFT,s),
InputInstruction::MoveBack(s) => self.set_control(StyleModifiers::CONTROL_MOVEBACK,s),
InputInstruction::MoveRight(s) => self.set_control(StyleModifiers::CONTROL_MOVERIGHT,s),
InputInstruction::MoveUp(s) => self.set_control(StyleModifiers::CONTROL_MOVEUP,s),
InputInstruction::MoveDown(s) => self.set_control(StyleModifiers::CONTROL_MOVEDOWN,s),
InputInstruction::Jump(s) => {
self.set_control(StyleModifiers::CONTROL_JUMP,s);
if self.grounded{
self.jump();
}
refresh_walk_target_velocity=false;
},
PhysicsInputInstruction::SetZoom(s) => {
InputInstruction::Zoom(s) => {
self.set_control(StyleModifiers::CONTROL_ZOOM,s);
refresh_walk_target=false;
},
PhysicsInputInstruction::Reset => {
InputInstruction::Reset => {
//temp
self.body.position=self.spawn_point;
self.body.velocity=glam::Vec3::ZERO;
@ -1260,12 +1166,12 @@ impl crate::instruction::InstructionConsumer<PhysicsInstruction> for PhysicsStat
self.grounded=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{
//calculate walk target velocity
if refresh_walk_target_velocity{
let camera_mat=self.camera.simulate_move_rotation_y(self.camera.mouse.lerp(&self.next_mouse,self.time).x);
let camera_mat=self.camera.simulate_move_rotation_y(self.mouse_interpolation.interpolated_position(self.time).x-self.mouse_interpolation.mouse0.x);
let control_dir=camera_mat*self.style.get_control_dir(self.controls);
self.walk.target_velocity=self.style.walkspeed*control_dir;
}

@ -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,
}
}
}

@ -1,11 +1,11 @@
#[derive(Debug)]
pub struct TimedInstruction<I> {
pub time: crate::physics::TIME,
pub time: crate::body::TIME,
pub instruction: I,
}
pub trait InstructionEmitter<I> {
fn next_instruction(&self, time_limit:crate::physics::TIME) -> Option<TimedInstruction<I>>;
fn next_instruction(&self, time_limit:crate::body::TIME) -> Option<TimedInstruction<I>>;
}
pub trait InstructionConsumer<I> {
fn process_instruction(&mut self, instruction:TimedInstruction<I>);
@ -13,11 +13,11 @@ pub trait InstructionConsumer<I> {
//PROPER PRIVATE FIELDS!!!
pub struct InstructionCollector<I> {
time: crate::physics::TIME,
time: crate::body::TIME,
instruction: Option<I>,
}
impl<I> InstructionCollector<I> {
pub fn new(time:crate::physics::TIME) -> Self {
pub fn new(time:crate::body::TIME) -> Self {
Self{
time,
instruction:None

@ -1,24 +0,0 @@
pub fn generate_indexed_models<R:std::io::Read+std::io::Seek>(input:&mut R) -> crate::model::IndexedModelInstances{
let mut spawn_point=glam::Vec3::ZERO;
let mut indexed_models=Vec::new();
let mut s=Vec::new();
match input.read_to_end(&mut s){
Ok(guac)=>println!("readed to string {:?}", guac),
Err(e)=>println!("faile {:?}",e),
}
match vbsp::Bsp::read(s.as_slice()){
Ok(guac)=>println!("we got the guac {:?}", guac),
Err(e)=>println!("rotten {:?}",e),
}
crate::model::IndexedModelInstances{
textures:Vec::new(),
models:indexed_models,
spawn_point,
modes:Vec::new(),
}
}

@ -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 intersecting=crate::model::IntersectingAttributes::default();
let mut contacting=crate::model::ContactingAttributes::default();
let mut force_can_collide=can_collide;
match name{
//"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})},
"MapFinish"=>{force_can_collide=false;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})},
"Accelerator"=>intersecting.accelerator=Some(crate::model::IntersectingAccelerator{acceleration:velocity}),
"MapFinish"=>general.zone=Some(crate::model::GameMechanicZone{mode_id:0,behaviour:crate::model::ZoneBehaviour::Finish}),
"MapAnticheat"=>general.zone=Some(crate::model::GameMechanicZone{mode_id:0,behaviour:crate::model::ZoneBehaviour::Anitcheat}),
"Platform"=>general.stage_element=Some(crate::model::GameMechanicStageElement{
mode_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]{
"Spawn"|"SpawnAt"=>crate::model::StageElementBehaviour::SpawnAt,
"Trigger"=>{force_can_collide=false;crate::model::StageElementBehaviour::Trigger},
"Teleport"=>{force_can_collide=false;crate::model::StageElementBehaviour::Teleport},
"Trigger"=>crate::model::StageElementBehaviour::Trigger,
"Teleport"=>crate::model::StageElementBehaviour::Teleport,
"Platform"=>crate::model::StageElementBehaviour::Platform,
_=>panic!("regex1[2] messed up bad"),
}
})
}else if let Some(captures)=lazy_regex::regex!(r"^Bonus(Finish|Anticheat)(\d+)$")
.captures(other){
force_can_collide=false;
match &captures[1]{
"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}),
@ -79,7 +77,7 @@ fn get_attributes(name:&str,can_collide:bool,velocity:glam::Vec3,force_intersect
if velocity!=glam::Vec3::ZERO{
general.booster=Some(crate::model::GameMechanicBooster{velocity});
}
match force_can_collide{
match can_collide{
true=>{
match name{
//"Bounce"=>(),
@ -178,7 +176,7 @@ impl RobloxFaceTextureDescription{
}
type RobloxPartDescription=[Option<RobloxFaceTextureDescription>;6];
type RobloxWedgeDescription=[Option<RobloxFaceTextureDescription>;5];
type RobloxCornerWedgeDescription=[Option<RobloxFaceTextureDescription>;5];
type RobloxCornerWedgeDescription=[Option<RobloxFaceTextureDescription>;4];
#[derive(Clone,Eq,Hash,PartialEq)]
enum RobloxBasePartDescription{
Sphere,
@ -311,7 +309,9 @@ pub fn generate_indexed_models(dom:rbx_dom_weak::WeakDom) -> crate::model::Index
};
let normal_id=normalid.to_u32();
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
if let (
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
_=>panic!("unreachable"),
};
(
glam::vec4(decal_color3.r,decal_color3.g,decal_color3.b,1.0-*decal_transparency),
RobloxTextureTransform{
offset_u:*ox/(*sx),offset_v:*oy/(*sy),
scale_u:size_u/(*sx),scale_v:size_v/(*sy),
}
)
}else{
(glam::Vec4::ONE,RobloxTextureTransform::default())
roblox_texture_transform=RobloxTextureTransform{
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())
};
}
part_texture_description[normal_id as usize]=Some(RobloxFaceTextureDescription{
texture:texture_id,
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
f4,//Cube::Bottom->Wedge::Bottom
]),
//TODO: fix Left+Back texture coordinates to match roblox when not overwridden by Top
primitives::Primitives::CornerWedge=>RobloxBasePartDescription::CornerWedge([
f0,//Cube::Right->CornerWedge::Right
if f2.is_some(){f2}else{f1.clone()},//Cube::Back|Cube::Top->CornerWedge::TopBack
if f3.is_some(){f3}else{f1},//Cube::Left|Cube::Top->CornerWedge::TopLeft
f1,//Cube::Top->CornerWedge::Top
f4,//Cube::Bottom->CornerWedge::Bottom
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(){
cornerwedge_face_description.insert(
match face_id{
0=>primitives::CornerWedgeFace::Right,
1=>primitives::CornerWedgeFace::TopBack,
2=>primitives::CornerWedgeFace::TopLeft,
3=>primitives::CornerWedgeFace::Bottom,
4=>primitives::CornerWedgeFace::Front,
0=>primitives::CornerWedgeFace::Top,
1=>primitives::CornerWedgeFace::Right,
2=>primitives::CornerWedgeFace::Bottom,
3=>primitives::CornerWedgeFace::Front,
_=>panic!("unreachable"),
},
match roblox_face_description{

@ -1,21 +1,17 @@
use std::{borrow::Cow, time::Instant};
use wgpu::{util::DeviceExt, AstcBlock, AstcChannel};
use model::{Vertex,ModelInstance,ModelGraphicsInstance};
use physics::{InputInstruction, PhysicsInstruction};
use body::{InputInstruction, PhysicsInstruction};
use instruction::{TimedInstruction, InstructionConsumer};
mod bvh;
mod aabb;
mod body;
mod model;
mod zeroes;
mod worker;
mod physics;
mod settings;
mod framework;
mod primitives;
mod instruction;
mod load_bsp;
mod load_roblox;
mod worker;
struct Entity {
index_count: u32,
@ -48,61 +44,14 @@ pub struct GraphicsPipelines{
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:glam::Vec2)->Self{
Self{
screen_size,
fov,
}
}
pub fn proj(&self)->glam::Mat4{
perspective_rh(self.fov.x, self.fov.y, 0.5, 2000.0)
}
pub fn world(&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 to_uniform_data(&self,(pos,angles): (glam::Vec3,glam::Vec2)) -> [f32; 16 * 4] {
let proj=self.proj();
let proj_inv = proj.inverse();
let view_inv=self.world(pos,angles);
let view=view_inv.inverse();
let mut raw = [0f32; 16 * 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)[..]);
raw[48..64].copy_from_slice(&AsRef::<[f32; 16]>::as_ref(&view_inv)[..]);
raw
}
}
pub struct GraphicsState{
screen_size: (u32, u32),
pipelines: GraphicsPipelines,
bind_groups: GraphicsBindGroups,
bind_group_layouts: GraphicsBindGroupLayouts,
samplers: GraphicsSamplers,
camera:GraphicsCamera,
camera_buf: wgpu::Buffer,
temp_squid_texture_view: wgpu::TextureView,
camera_buf: wgpu::Buffer,
models: Vec<ModelGraphics>,
depth_view: wgpu::TextureView,
staging_belt: wgpu::util::StagingBelt,
@ -112,18 +61,13 @@ impl GraphicsState{
pub fn clear(&mut self){
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{
start_time: std::time::Instant,
manual_mouse_lock:bool,
mouse:physics::MouseState,
user_settings:settings::UserSettings,
graphics:GraphicsState,
physics_thread:worker::CompatWorker<TimedInstruction<InputInstruction>,physics::PhysicsOutputState,Box<dyn FnMut(TimedInstruction<InputInstruction>)->physics::PhysicsOutputState>>,
physics:body::PhysicsState,
}
impl GlobalState{
@ -151,6 +95,77 @@ impl GlobalState{
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)=body::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){
//generate texture view per texture
@ -228,7 +243,7 @@ impl GlobalState{
}else{
Some(ModelGraphicsInstance{
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,
})
}
@ -237,7 +252,7 @@ impl GlobalState{
let id=unique_texture_models.len();
let mut unique_textures=Vec::new();
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){
texture_index
}else{
@ -267,9 +282,9 @@ impl GlobalState{
let mut vertices = Vec::new();
let mut index_from_vertex = std::collections::HashMap::new();//::<IndexedVertex,usize>
let mut entities = Vec::new();
//this mut be combined in a more complex way if the models use different render patterns per group
let mut indices = Vec::new();
//TODO: combine groups using the same render pattern
for group in model.groups {
let mut indices = Vec::new();
for poly in group.polys {
for end_index in 2..poly.vertices.len() {
for &index in &[0, end_index - 1, end_index] {
@ -291,8 +306,8 @@ impl GlobalState{
}
}
}
}
entities.push(indices);
}
models.push(model::ModelSingleTexture{
instances:model.instances,
vertices,
@ -376,7 +391,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;
fn get_instances_buffer_data(instances:&[ModelGraphicsInstance]) -> Vec<f32> {
let mut raw = Vec::with_capacity(MODEL_BUFFER_SIZE*instances.len());
@ -385,12 +400,7 @@ fn get_instances_buffer_data(instances:&[ModelGraphicsInstance]) -> Vec<f32> {
//model transform
raw.extend_from_slice(&AsRef::<[f32; 4*4]>::as_ref(&mi.transform)[..]);
//normal transform
raw.extend_from_slice(AsRef::<[f32; 3]>::as_ref(&mi.normal_transform.x_axis));
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]);
raw.extend_from_slice(&AsRef::<[f32; 4*4]>::as_ref(&mi.normal_transform)[..]);
//color
raw.extend_from_slice(AsRef::<[f32; 4]>::as_ref(&mi.color));
raw.append(&mut v);
@ -398,6 +408,20 @@ fn get_instances_buffer_data(instances:&[ModelGraphicsInstance]) -> Vec<f32> {
raw
}
fn to_uniform_data(camera: &body::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 {
fn optional_features() -> wgpu::Features {
wgpu::Features::TEXTURE_COMPRESSION_ASTC
@ -415,8 +439,6 @@ impl framework::Example for GlobalState {
device: &wgpu::Device,
queue: &wgpu::Queue,
) -> Self {
//wee
let user_settings=settings::read_user_settings();
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.push(primitives::unit_sphere());
@ -560,6 +582,25 @@ impl framework::Example for GlobalState {
source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(include_str!("shader.wgsl"))),
});
let physics = body::PhysicsState {
spawn_point:glam::vec3(0.0,50.0,0.0),
body: 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:body::StyleModifiers::default(),
grounded: false,
contacts: std::collections::HashMap::new(),
intersects: std::collections::HashMap::new(),
models: Vec::new(),
walk: body::WalkState::new(),
camera: body::Camera::from_offset(glam::vec3(0.0,4.5-2.5,0.0),(config.width as f32)/(config.height as f32)),
mouse_interpolation: body::MouseInterpolationState::new(),
controls: 0,
world:body::WorldState{},
game:body::GameMechanicsState::default(),
modes:Vec::new(),
mode_from_mode_id:std::collections::HashMap::new(),
};
//load textures
let device_features = device.features();
@ -754,14 +795,7 @@ impl framework::Example for GlobalState {
multiview: None,
});
let mut physics = physics::PhysicsState::default();
physics.load_user_settings(&user_settings);
let screen_size=glam::uvec2(config.width,config.height);
let camera=GraphicsCamera::new(screen_size,user_settings.calculate_fov(1.0,&screen_size).as_vec2());
let camera_uniforms = camera.to_uniform_data(physics.output().adjust_mouse(&physics.next_mouse));
let camera_uniforms = to_uniform_data(&physics.camera,physics.body.extrapolated_position(0));
let camera_buf = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("Camera"),
contents: bytemuck::cast_slice(&camera_uniforms),
@ -777,7 +811,6 @@ impl framework::Example for GlobalState {
],
label: Some("Camera"),
});
let skybox_texture_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
layout: &skybox_texture_bind_group_layout,
entries: &[
@ -795,7 +828,8 @@ impl framework::Example for GlobalState {
let depth_view = Self::create_depth_texture(config, device);
let mut graphics=GraphicsState {
let graphics=GraphicsState {
screen_size: (config.width,config.height),
pipelines:GraphicsPipelines{
skybox:sky_pipeline,
model:model_pipeline
@ -804,7 +838,6 @@ impl framework::Example for GlobalState {
camera:camera_bind_group,
skybox_texture:skybox_texture_bind_group,
},
camera,
camera_buf,
models: Vec::new(),
depth_view,
@ -814,7 +847,12 @@ impl framework::Example for GlobalState {
temp_squid_texture_view: squid_texture_view,
};
graphics.load_user_settings(&user_settings);
let mut state=GlobalState{
start_time:Instant::now(),
manual_mouse_lock:false,
graphics,
physics,
};
let indexed_model_instances=model::IndexedModelInstances{
textures:Vec::new(),
@ -822,25 +860,7 @@ impl framework::Example for GlobalState {
spawn_point:glam::Vec3::Y*50.0,
modes:Vec::new(),
};
//how to multithread
//1. build
physics.generate_models(&indexed_model_instances);
//2. move
let physics_thread=physics.into_worker();
//3. forget
let mut state=GlobalState{
start_time:Instant::now(),
manual_mouse_lock:false,
mouse:physics::MouseState::default(),
user_settings,
graphics,
physics_thread,
};
state.generate_model_physics(&indexed_model_instances);
state.generate_model_graphics(&device,&queue,indexed_model_instances);
let args:Vec<String>=std::env::args().collect();
@ -864,6 +884,7 @@ impl framework::Example for GlobalState {
//.snf = "SNMF"
//.snf = "SNBF"
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)={
match &first_8[0..4]{
b"<rob"=>{
@ -879,7 +900,7 @@ impl framework::Example for GlobalState {
},
}
},
b"VBSP"=>Some(load_bsp::generate_indexed_models(&mut input)),
//b"VBSP"=>Some(load_bsp::generate_indexed_models(input)),
//b"SNFM"=>Some(sniffer::generate_indexed_models(input)),
//b"SNFB"=>Some(sniffer::load_bot(input)),
other=>{
@ -890,22 +911,21 @@ impl framework::Example for GlobalState {
}{
let spawn_point=indexed_model_instances.spawn_point;
//if generate_indexed_models succeeds, clear the previous ones
self.physics.clear();
self.graphics.clear();
let mut physics=physics::PhysicsState::default();
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.load_user_settings(&self.user_settings);
physics.generate_models(&indexed_model_instances);
self.physics_thread=physics.into_worker();
//graphics.load_user_settings(&self.user_settings);
self.physics.game.stage_id=0;
self.generate_model_physics(&indexed_model_instances);
self.generate_model_graphics(device,queue,indexed_model_instances);
//manual reset
let time=self.physics.time;
instruction::InstructionConsumer::process_instruction(&mut self.physics, instruction::TimedInstruction{
time,
instruction: body::PhysicsInstruction::SetSpawnPosition(spawn_point),
});
instruction::InstructionConsumer::process_instruction(&mut self.physics, instruction::TimedInstruction{
time,
instruction: body::PhysicsInstruction::Input(body::InputInstruction::Reset),
});
}else{
println!("No modeldatas were generated");
}
@ -952,16 +972,6 @@ impl framework::Example for GlobalState {
57=>Some(InputInstruction::Jump(s)),//Space
44=>Some(InputInstruction::Zoom(s)),//Z
19=>if s{Some(InputInstruction::Reset)}else{None},//R
87=>{//F11
if s{
if window.fullscreen().is_some(){
window.set_fullscreen(None);
}else{
window.set_fullscreen(Some(winit::window::Fullscreen::Borderless(None)));
}
}
None
},
01=>{//Esc
if s{
self.manual_mouse_lock=false;
@ -976,7 +986,7 @@ impl framework::Example for GlobalState {
15=>{//Tab
if s{
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.screen_size.0 as f32/2.0, self.graphics.screen_size.1 as f32/2.0)){
Ok(())=>(),
Err(e)=>println!("Could not set cursor position: {:?}",e),
}
@ -1005,17 +1015,18 @@ impl framework::Example for GlobalState {
},
_ => {println!("scancode {}",keycode);None},
}{
self.physics_thread.send(TimedInstruction{
self.physics.run(time);
self.physics.process_instruction(TimedInstruction{
time,
instruction:input_instruction,
}).unwrap();
instruction:PhysicsInstruction::Input(input_instruction),
})
}
},
winit::event::DeviceEvent::MouseMotion {
delta,//these (f64,f64) are integers on my machine
} => {
if self.manual_mouse_lock{
match window.set_cursor_position(winit::dpi::PhysicalPosition::new(self.graphics.camera.screen_size.x as f32/2.0, self.graphics.camera.screen_size.y as f32/2.0)){
match 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)){
Ok(())=>(),
Err(e)=>println!("Could not set cursor position: {:?}",e),
}
@ -1023,22 +1034,21 @@ impl framework::Example for GlobalState {
//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
//which is fine because they run all the time.
let delta=glam::ivec2(delta.0 as i32,delta.1 as i32);
self.mouse.pos+=delta;
self.physics_thread.send(TimedInstruction{
self.physics.process_instruction(TimedInstruction{
time,
instruction:InputInstruction::MoveMouse(self.mouse.pos),
}).unwrap();
instruction:PhysicsInstruction::Input(InputInstruction::MoveMouse(glam::ivec2(delta.0 as i32,delta.1 as i32))),
})
},
winit::event::DeviceEvent::MouseWheel {
delta,
} => {
println!("mousewheel {:?}",delta);
if false{//self.physics.style.use_scroll{
self.physics_thread.send(TimedInstruction{
self.physics.run(time);
self.physics.process_instruction(TimedInstruction{
time,
instruction:InputInstruction::Jump(true),//activates the immediate jump path, but the style modifier prevents controls&CONTROL_JUMP bit from being set to auto jump
}).unwrap();
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
})
}
}
_=>(),
@ -1052,8 +1062,8 @@ impl framework::Example for GlobalState {
_queue: &wgpu::Queue,
) {
self.graphics.depth_view = Self::create_depth_texture(config, device);
self.graphics.camera.screen_size=glam::uvec2(config.width, config.height);
self.graphics.load_user_settings(&self.user_settings);
self.graphics.screen_size = (config.width, config.height);
self.physics.camera.set_fov_aspect(1.0,(config.width as f32)/(config.height as f32));
}
fn render(
@ -1063,20 +1073,15 @@ impl framework::Example for GlobalState {
queue: &wgpu::Queue,
_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;
self.physics_thread.send(TimedInstruction{
time,
instruction:InputInstruction::Idle,
}).unwrap();
//update time lol
self.mouse.time=time;
self.physics.run(time);
let mut encoder =
device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None });
// update rotation
let camera_uniforms = self.graphics.camera.to_uniform_data(self.physics_thread.grab_clone().adjust_mouse(&self.mouse));
let camera_uniforms = to_uniform_data(&self.physics.camera,self.physics.body.extrapolated_position(time));
self.graphics.staging_belt
.write_buffer(
&mut encoder,
@ -1087,7 +1092,6 @@ impl framework::Example for GlobalState {
)
.copy_from_slice(bytemuck::cast_slice(&camera_uniforms));
//This code only needs to run when the uniforms change
/*
for model in self.graphics.models.iter() {
let model_uniforms = get_instances_buffer_data(&model.instances);
self.graphics.staging_belt
@ -1100,7 +1104,6 @@ impl framework::Example for GlobalState {
)
.copy_from_slice(bytemuck::cast_slice(&model_uniforms));
}
*/
self.graphics.staging_belt.finish();
{

@ -52,7 +52,7 @@ pub struct ModelSingleTexture{
#[derive(Clone)]
pub struct ModelGraphicsInstance{
pub transform:glam::Mat4,
pub normal_transform:glam::Mat3,
pub normal_transform:glam::Mat4,
pub color:glam::Vec4,
}
pub struct ModelInstance{
@ -104,6 +104,7 @@ impl ModeDescription{
}
}
}
#[derive(Debug)]
pub enum TempIndexedAttributes{
Start{
mode_id:u32,

@ -107,9 +107,8 @@ local cornerWedgeVerticies = {
*/
#[derive(Hash,PartialEq,Eq)]
pub enum CornerWedgeFace{
Top,
Right,
TopBack,
TopLeft,
Bottom,
Front,
}
@ -163,8 +162,7 @@ pub type CornerWedgeFaceDescription=std::collections::HashMap::<CornerWedgeFace,
pub fn unit_cornerwedge()->crate::model::IndexedModel{
let mut t=CornerWedgeFaceDescription::new();
t.insert(CornerWedgeFace::Right,FaceDescription::default());
t.insert(CornerWedgeFace::TopBack,FaceDescription::default());
t.insert(CornerWedgeFace::TopLeft,FaceDescription::default());
t.insert(CornerWedgeFace::Top,FaceDescription::default());
t.insert(CornerWedgeFace::Bottom,FaceDescription::default());
t.insert(CornerWedgeFace::Front,FaceDescription::default());
generate_partial_unit_cornerwedge(t)
@ -458,10 +456,9 @@ pub fn generate_partial_unit_cornerwedge(face_descriptions:CornerWedgeFaceDescri
} as u32;
let face_id=match face{
CornerWedgeFace::Right => 0,
CornerWedgeFace::TopBack => 1,
CornerWedgeFace::TopLeft => 2,
CornerWedgeFace::Bottom => 3,
CornerWedgeFace::Front => 4,
CornerWedgeFace::Top => 1,
CornerWedgeFace::Bottom => 2,
CornerWedgeFace::Front => 3,
};
//always push normal
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>,
// from world to camera
view: mat4x4<f32>,
// from camera to world
view_inv: mat4x4<f32>,
// camera position
cam_pos: vec4<f32>,
};
//group 0 is the camera
@ -31,7 +31,8 @@ fn vs_sky(@builtin(vertex_index) vertex_index: u32) -> SkyOutput {
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;
var result: SkyOutput;
@ -42,7 +43,7 @@ fn vs_sky(@builtin(vertex_index) vertex_index: u32) -> SkyOutput {
struct ModelInstance{
transform:mat4x4<f32>,
normal_transform:mat3x3<f32>,
normal_transform:mat4x4<f32>,
color:vec4<f32>,
}
//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 {
var position: vec4<f32> = model_instances[instance].transform * vec4<f32>(pos, 1.0);
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.color = 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;
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 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));
}

@ -6,102 +6,78 @@ 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 physics (target use case) knows when it has not changed the body, so not updating the value is also an option.
pub struct Worker<Task:Send,Value:Clone> {
sender: mpsc::Sender<Task>,
value:Arc<Mutex<Value>>,
struct Worker<Task:Send,Value:Clone> {
sender: mpsc::Sender<Task>,
value:Arc<Mutex<Value>>,
}
impl<Task:Send+'static,Value:Clone+Send+'static> Worker<Task,Value> {
pub fn new<F:FnMut(Task)->Value+Send+'static>(value:Value,mut f:F) -> Self {
let (sender, receiver) = mpsc::channel::<Task>();
let ret=Self {
sender,
value:Arc::new(Mutex::new(value)),
};
let value=ret.value.clone();
thread::spawn(move || {
loop {
match receiver.recv() {
Ok(task) => {
let v=f(task);//make sure function is evaluated before lock is acquired
*value.lock()=v;
}
Err(_) => {
println!("Worker stopping.",);
break;
}
}
}
});
ret
}
fn new<F:Fn(Task)->Value+Send+'static>(value:Value,f:F) -> Self {
let (sender, receiver) = mpsc::channel::<Task>();
let ret=Self {
sender,
value:Arc::new(Mutex::new(value)),
};
let value=ret.value.clone();
thread::spawn(move || {
loop {
match receiver.recv() {
Ok(task) => {
println!("Worker got a task");
// Process the task
*value.lock()=f(task);
}
Err(_) => {
println!("Worker stopping.",);
break;
}
}
}
});
ret
}
pub fn send(&self,task:Task)->Result<(), mpsc::SendError<Task>>{
self.sender.send(task)
}
fn send(&self,task:Task)->Result<(), mpsc::SendError<Task>>{
self.sender.send(task)
}
pub fn grab_clone(&self)->Value{
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()
}
fn grab_clone(&self)->Value{
self.value.lock().clone()
}
}
#[test]//How to run this test with printing: cargo test --release -- --nocapture
fn test_worker() {
println!("hiiiii");
// Create the worker thread
let worker = Worker::new(crate::physics::Body::with_pva(glam::Vec3::ZERO,glam::Vec3::ZERO,glam::Vec3::ZERO),
|_|crate::physics::Body::with_pva(glam::Vec3::ONE,glam::Vec3::ONE,glam::Vec3::ONE)
);
println!("hiiiii");
// Create the worker thread
let worker = Worker::new(crate::body::Body::with_pva(glam::Vec3::ZERO,glam::Vec3::ZERO,glam::Vec3::ZERO),
|_|crate::body::Body::with_pva(glam::Vec3::ONE,glam::Vec3::ONE,glam::Vec3::ONE)
);
// Send tasks to the worker
for i in 0..5 {
let task = crate::instruction::TimedInstruction{
time:0,
instruction:crate::physics::PhysicsInstruction::StrafeTick,
};
worker.send(task).unwrap();
}
// Send tasks to the worker
for i in 0..5 {
let task = crate::instruction::TimedInstruction{
time:0,
instruction:crate::body::PhysicsInstruction::StrafeTick,
};
worker.send(task).unwrap();
}
// Optional: Signal the worker to stop (in a real-world scenario)
// sender.send("STOP".to_string()).unwrap();
// Optional: Signal the worker to stop (in a real-world scenario)
// sender.send("STOP".to_string()).unwrap();
// Sleep to allow the worker thread to finish processing
thread::sleep(std::time::Duration::from_secs(2));
// Sleep to allow the worker thread to finish processing
thread::sleep(std::time::Duration::from_secs(2));
// Send a new task
let task = crate::instruction::TimedInstruction{
time:0,
instruction:crate::physics::PhysicsInstruction::StrafeTick,
};
worker.send(task).unwrap();
// Send a new task
let task = crate::instruction::TimedInstruction{
time:0,
instruction:crate::body::PhysicsInstruction::StrafeTick,
};
worker.send(task).unwrap();
println!("value={:?}",worker.grab_clone());
println!("value={:?}",worker.grab_clone());
// wait long enough to see print from final task
thread::sleep(std::time::Duration::from_secs(1));
// wait long enough to see print from final task
thread::sleep(std::time::Duration::from_secs(1));
}