Compare commits

..

3 Commits

Author SHA1 Message Date
1cdaa5d53a fake IBSP 2023-10-02 22:29:57 -07:00
55a1ef0d14 load_bsp module 2023-10-02 15:29:32 -07:00
03a97bfa3e add bsp dep 2023-10-02 15:29:04 -07:00
9 changed files with 316 additions and 871 deletions

91
Cargo.lock generated
View File

@@ -92,6 +92,15 @@ version = "0.3.7"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6b4930d2cb77ce62f89ee5d5289b4ac049559b1c45539271f5ed4fdc7db34545" checksum = "6b4930d2cb77ce62f89ee5d5289b4ac049559b1c45539271f5ed4fdc7db34545"
[[package]]
name = "arrayvec"
version = "0.4.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cd9fd44efafa8690358b7408d253adf110036b88f55672a933f01d616ad9b1b9"
dependencies = [
"nodrop",
]
[[package]] [[package]]
name = "arrayvec" name = "arrayvec"
version = "0.7.4" version = "0.7.4"
@@ -197,7 +206,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "199c42ab6972d92c9f8995f086273d25c42fc0f7b2a1fcefba465c1352d25ba5" checksum = "199c42ab6972d92c9f8995f086273d25c42fc0f7b2a1fcefba465c1352d25ba5"
dependencies = [ dependencies = [
"arrayref", "arrayref",
"arrayvec", "arrayvec 0.7.4",
"cc", "cc",
"cfg-if", "cfg-if",
"constant_time_eq", "constant_time_eq",
@@ -238,12 +247,33 @@ dependencies = [
"objc2-encode", "objc2-encode",
] ]
[[package]]
name = "bsp"
version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b9d6d699bcff31f0c8a5951d29b9a7edfe3270218c20f6c3509f90ae7e1c46e7"
dependencies = [
"arrayvec 0.4.12",
"bitflags 1.3.2",
"bv",
"byteorder 0.5.3",
]
[[package]] [[package]]
name = "bumpalo" name = "bumpalo"
version = "3.13.0" version = "3.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a3e2c3daef883ecc1b5d58c15adae93470a91d425f3532ba1695849656af3fc1" 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]] [[package]]
name = "bytemuck" name = "bytemuck"
version = "1.13.1" version = "1.13.1"
@@ -264,6 +294,12 @@ dependencies = [
"syn 2.0.29", "syn 2.0.29",
] ]
[[package]]
name = "byteorder"
version = "0.5.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0fc10e8cc6b2580fda3f36eb6dc5316657f812a3df879a44a66fc9f0fdbc4855"
[[package]] [[package]]
name = "byteorder" name = "byteorder"
version = "1.4.3" version = "1.4.3"
@@ -423,7 +459,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "594ecd967c2f40db5dde8da4c356975fc1fe030e951c7c3962f6dc2e80042e87" checksum = "594ecd967c2f40db5dde8da4c356975fc1fe030e951c7c3962f6dc2e80042e87"
dependencies = [ dependencies = [
"bitflags 1.3.2", "bitflags 1.3.2",
"byteorder", "byteorder 1.4.3",
"enum_primitive", "enum_primitive",
] ]
@@ -532,6 +568,12 @@ dependencies = [
"simd-adler32", "simd-adler32",
] ]
[[package]]
name = "feature-probe"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "835a3dc7d1ec9e75e2b5fb4ba75396837112d2060b03f7d43bc1897c7f7211da"
[[package]] [[package]]
name = "flate2" name = "flate2"
version = "1.0.27" version = "1.0.27"
@@ -834,29 +876,6 @@ dependencies = [
"pkg-config", "pkg-config",
] ]
[[package]]
name = "lazy-regex"
version = "3.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e723bd417b2df60a0f6a2b6825f297ea04b245d4ba52b5a22cb679bdf58b05fa"
dependencies = [
"lazy-regex-proc_macros",
"once_cell",
"regex",
]
[[package]]
name = "lazy-regex-proc_macros"
version = "3.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0f0a1d9139f0ee2e862e08a9c5d0ba0470f2aa21cd1e1aa1b1562f83116c725f"
dependencies = [
"proc-macro2",
"quote",
"regex",
"syn 2.0.29",
]
[[package]] [[package]]
name = "lazy_static" name = "lazy_static"
version = "1.4.0" version = "1.4.0"
@@ -1081,6 +1100,12 @@ dependencies = [
"memoffset", "memoffset",
] ]
[[package]]
name = "nodrop"
version = "0.1.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72ef4a56884ca558e5ddb05a1d1e7e1bfd9a68d9ed024c21704cc98872dae1bb"
[[package]] [[package]]
name = "nom" name = "nom"
version = "7.1.3" version = "7.1.3"
@@ -1529,7 +1554,7 @@ version = "0.8.12"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f9860a6cc38ed1da53456442089b4dfa35e7cedaa326df63017af88385e6b20" checksum = "7f9860a6cc38ed1da53456442089b4dfa35e7cedaa326df63017af88385e6b20"
dependencies = [ dependencies = [
"byteorder", "byteorder 1.4.3",
"num-traits 0.2.16", "num-traits 0.2.16",
"paste", "paste",
] ]
@@ -1540,7 +1565,7 @@ version = "1.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bffea85eea980d8a74453e5d02a8d93028f3c34725de143085a844ebe953258a" checksum = "bffea85eea980d8a74453e5d02a8d93028f3c34725de143085a844ebe953258a"
dependencies = [ dependencies = [
"byteorder", "byteorder 1.4.3",
"rmp", "rmp",
"serde", "serde",
] ]
@@ -1685,19 +1710,19 @@ name = "strafe-client"
version = "0.7.0" version = "0.7.0"
dependencies = [ dependencies = [
"async-executor", "async-executor",
"bsp",
"bytemuck", "bytemuck",
"ddsfile", "ddsfile",
"env_logger", "env_logger",
"glam", "glam",
"lazy-regex",
"log", "log",
"obj", "obj",
"parking_lot",
"pollster", "pollster",
"rbx_binary", "rbx_binary",
"rbx_dom_weak", "rbx_dom_weak",
"rbx_reflection_database", "rbx_reflection_database",
"rbx_xml", "rbx_xml",
"regex",
"wgpu", "wgpu",
"winit", "winit",
] ]
@@ -1772,7 +1797,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "df8493a203431061e901613751931f047d1971337153f96d0e5e363d6dbf6a67" checksum = "df8493a203431061e901613751931f047d1971337153f96d0e5e363d6dbf6a67"
dependencies = [ dependencies = [
"arrayref", "arrayref",
"arrayvec", "arrayvec 0.7.4",
"bytemuck", "bytemuck",
"cfg-if", "cfg-if",
"png", "png",
@@ -2016,7 +2041,7 @@ version = "0.17.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7472f3b69449a8ae073f6ec41d05b6f846902d92a6c45313c50cb25857b736ce" checksum = "7472f3b69449a8ae073f6ec41d05b6f846902d92a6c45313c50cb25857b736ce"
dependencies = [ dependencies = [
"arrayvec", "arrayvec 0.7.4",
"cfg-if", "cfg-if",
"js-sys", "js-sys",
"log", "log",
@@ -2040,7 +2065,7 @@ version = "0.17.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ecf7454d9386f602f7399225c92dd2fbdcde52c519bc8fb0bd6fbeb388075dc2" checksum = "ecf7454d9386f602f7399225c92dd2fbdcde52c519bc8fb0bd6fbeb388075dc2"
dependencies = [ dependencies = [
"arrayvec", "arrayvec 0.7.4",
"bit-vec", "bit-vec",
"bitflags 2.4.0", "bitflags 2.4.0",
"codespan-reporting", "codespan-reporting",
@@ -2064,7 +2089,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6654a13885a17f475e8324efb46dc6986d7aaaa98353330f8de2077b153d0101" checksum = "6654a13885a17f475e8324efb46dc6986d7aaaa98353330f8de2077b153d0101"
dependencies = [ dependencies = [
"android_system_properties", "android_system_properties",
"arrayvec", "arrayvec 0.7.4",
"ash", "ash",
"bit-set", "bit-set",
"bitflags 2.4.0", "bitflags 2.4.0",

View File

@@ -7,19 +7,19 @@ edition = "2021"
[dependencies] [dependencies]
async-executor = "1.5.1" async-executor = "1.5.1"
bsp = "0.1.2"
bytemuck = { version = "1.13.1", features = ["derive"] } bytemuck = { version = "1.13.1", features = ["derive"] }
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"
lazy-regex = "3.0.2"
log = "0.4.20" log = "0.4.20"
obj = "0.10.2" obj = "0.10.2"
parking_lot = "0.12.1"
pollster = "0.3.0" pollster = "0.3.0"
rbx_binary = "0.7.1" rbx_binary = "0.7.1"
rbx_dom_weak = "2.5.0" rbx_dom_weak = "2.5.0"
rbx_reflection_database = "0.2.7" rbx_reflection_database = "0.2.7"
rbx_xml = "0.13.1" rbx_xml = "0.13.1"
regex = "1.9.5"
wgpu = "0.17.0" wgpu = "0.17.0"
winit = "0.28.6" winit = "0.28.6"

View File

@@ -34,7 +34,7 @@ pub enum InputInstruction {
//for interpolation / networking / playback reasons, most playback heads will always want //for interpolation / networking / playback reasons, most playback heads will always want
//to be 1 instruction ahead to generate the next state for interpolation. //to be 1 instruction ahead to generate the next state for interpolation.
} }
#[derive(Clone,Debug)]
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
@@ -45,20 +45,20 @@ trait MyHash{
fn hash(&self) -> u64; fn hash(&self) -> u64;
} }
impl MyHash for Body { impl MyHash for Body {
fn hash(&self) -> u64 { fn hash(&self) -> u64 {
let mut hasher=std::collections::hash_map::DefaultHasher::new(); let mut hasher=std::collections::hash_map::DefaultHasher::new();
for &el in self.position.as_ref().iter() { for &el in self.position.as_ref().iter() {
std::hash::Hasher::write(&mut hasher, el.to_ne_bytes().as_slice()); std::hash::Hasher::write(&mut hasher, el.to_ne_bytes().as_slice());
} }
for &el in self.velocity.as_ref().iter() { for &el in self.velocity.as_ref().iter() {
std::hash::Hasher::write(&mut hasher, el.to_ne_bytes().as_slice()); std::hash::Hasher::write(&mut hasher, el.to_ne_bytes().as_slice());
} }
for &el in self.acceleration.as_ref().iter() { for &el in self.acceleration.as_ref().iter() {
std::hash::Hasher::write(&mut hasher, el.to_ne_bytes().as_slice()); std::hash::Hasher::write(&mut hasher, el.to_ne_bytes().as_slice());
} }
std::hash::Hasher::write(&mut hasher, self.time.to_ne_bytes().as_slice()); std::hash::Hasher::write(&mut hasher, self.time.to_ne_bytes().as_slice());
return std::hash::Hasher::finish(&hasher);//hash check to see if walk target is valid return std::hash::Hasher::finish(&hasher);//hash check to see if walk target is valid
} }
} }
pub enum MoveRestriction { pub enum MoveRestriction {
@@ -80,9 +80,9 @@ impl InputState {
} }
impl crate::instruction::InstructionEmitter<InputInstruction> for InputState{ impl crate::instruction::InstructionEmitter<InputInstruction> for InputState{
fn next_instruction(&self, time_limit:crate::body::TIME) -> Option<TimedInstruction<InputInstruction>> { fn next_instruction(&self, time_limit:crate::body::TIME) -> Option<TimedInstruction<InputInstruction>> {
//this is polled by PhysicsState for actions like Jump //this is polled by PhysicsState for actions like Jump
//no, it has to be the other way around. physics is run up until the jump instruction, and then the jump instruction is pushed. //no, it has to be the other way around. physics is run up until the jump instruction, and then the jump instruction is pushed.
self.queue.get(0) self.queue.get(0)
} }
} }
impl crate::instruction::InstructionConsumer<InputInstruction> for InputState{ impl crate::instruction::InstructionConsumer<InputInstruction> for InputState{
@@ -97,8 +97,6 @@ enum MouseInterpolation {
First,//just checks the last value First,//just checks the last value
Lerp,//lerps between Lerp,//lerps between
} }
//hey dumbass just use a delta
pub struct MouseInterpolationState { pub struct MouseInterpolationState {
interpolation: MouseInterpolation, interpolation: MouseInterpolation,
time0: TIME, time0: TIME,
@@ -171,12 +169,12 @@ pub struct Camera {
#[inline] #[inline]
fn mat3_from_rotation_y_f64(angle: f64) -> glam::Mat3 { fn mat3_from_rotation_y_f64(angle: f64) -> glam::Mat3 {
let (sina, cosa) = angle.sin_cos(); let (sina, cosa) = angle.sin_cos();
glam::Mat3::from_cols( glam::Mat3::from_cols(
glam::Vec3::new(cosa as f32, 0.0, -sina as f32), glam::Vec3::new(cosa as f32, 0.0, -sina as f32),
glam::Vec3::Y, glam::Vec3::Y,
glam::Vec3::new(sina as f32, 0.0, cosa as f32), glam::Vec3::new(sina as f32, 0.0, cosa as f32),
) )
} }
#[inline] #[inline]
fn perspective_rh(fov_x_slope: f32, fov_y_slope: f32, z_near: f32, z_far: f32) -> glam::Mat4 { fn perspective_rh(fov_x_slope: f32, fov_y_slope: f32, z_near: f32, z_far: f32) -> glam::Mat4 {
@@ -192,11 +190,11 @@ fn perspective_rh(fov_x_slope: f32, fov_y_slope: f32, z_near: f32, z_far: f32) -
impl Camera { impl Camera {
pub fn from_offset(offset:glam::Vec3,aspect:f32) -> Self { pub fn from_offset(offset:glam::Vec3,aspect:f32) -> Self {
Self{ Self{
offset, offset,
angles: glam::DVec2::ZERO, angles: glam::DVec2::ZERO,
fov: glam::vec2(aspect,1.0), fov: glam::vec2(aspect,1.0),
sensitivity: glam::dvec2(1.0/16384.0,1.0/16384.0), sensitivity: glam::dvec2(1.0/6144.0,1.0/6144.0),
time: 0, time: 0,
} }
} }
fn simulate_move_angles(&self, delta: glam::IVec2) -> glam::DVec2 { fn simulate_move_angles(&self, delta: glam::IVec2) -> glam::DVec2 {
@@ -220,120 +218,65 @@ impl Camera {
} }
} }
pub struct GameMechanicsState{ const CONTROL_MOVEFORWARD:u32 = 0b00000001;
pub stage_id:u32, const CONTROL_MOVEBACK:u32 = 0b00000010;
//jump_counts:HashMap<u32,u32>, const CONTROL_MOVERIGHT:u32 = 0b00000100;
} const CONTROL_MOVELEFT:u32 = 0b00001000;
impl std::default::Default for GameMechanicsState{ const CONTROL_MOVEUP:u32 = 0b00010000;
fn default() -> Self { const CONTROL_MOVEDOWN:u32 = 0b00100000;
Self{ const CONTROL_JUMP:u32 = 0b01000000;
stage_id:0, const CONTROL_ZOOM:u32 = 0b10000000;
}
const FORWARD_DIR:glam::Vec3 = glam::Vec3::new(0.0,0.0,-1.0);
const RIGHT_DIR:glam::Vec3 = glam::Vec3::new(1.0,0.0,0.0);
const UP_DIR:glam::Vec3 = glam::Vec3::new(0.0,1.0,0.0);
fn get_control_dir(controls: u32) -> glam::Vec3{
//don't get fancy just do it
let mut control_dir:glam::Vec3 = glam::Vec3::new(0.0,0.0,0.0);
if controls & CONTROL_MOVEFORWARD == CONTROL_MOVEFORWARD {
control_dir+=FORWARD_DIR;
} }
} if controls & CONTROL_MOVEBACK == CONTROL_MOVEBACK {
control_dir+=-FORWARD_DIR;
pub struct WorldState{}
pub struct StyleModifiers{
pub controls_mask:u32,//controls which are unable to be activated
pub controls_held:u32,//controls which must be active to be able to strafe
pub mv:f32,
pub walkspeed:f32,
pub friction:f32,
pub walk_accel:f32,
pub gravity:glam::Vec3,
pub strafe_tick_num:TIME,
pub strafe_tick_den:TIME,
pub hitbox_halfsize:glam::Vec3,
}
impl std::default::Default for StyleModifiers{
fn default() -> Self {
Self{
controls_mask: !0,//&!(Self::CONTROL_MOVEUP|Self::CONTROL_MOVEDOWN),
controls_held: 0,
strafe_tick_num: 100,//100t
strafe_tick_den: 1_000_000_000,
gravity: glam::vec3(0.0,-100.0,0.0),
friction: 1.2,
walk_accel: 90.0,
mv: 2.7,
walkspeed: 18.0,
hitbox_halfsize: glam::vec3(1.0,2.5,1.0),
}
} }
} if controls & CONTROL_MOVELEFT == CONTROL_MOVELEFT {
impl StyleModifiers{ control_dir+=-RIGHT_DIR;
const CONTROL_MOVEFORWARD:u32 = 0b00000001;
const CONTROL_MOVEBACK:u32 = 0b00000010;
const CONTROL_MOVERIGHT:u32 = 0b00000100;
const CONTROL_MOVELEFT:u32 = 0b00001000;
const CONTROL_MOVEUP:u32 = 0b00010000;
const CONTROL_MOVEDOWN:u32 = 0b00100000;
const CONTROL_JUMP:u32 = 0b01000000;
const CONTROL_ZOOM:u32 = 0b10000000;
const FORWARD_DIR:glam::Vec3 = glam::Vec3::NEG_Z;
const RIGHT_DIR:glam::Vec3 = glam::Vec3::X;
const UP_DIR:glam::Vec3 = glam::Vec3::Y;
fn get_control(&self,control:u32,controls:u32)->bool{
controls&self.controls_mask&control!=0
} }
if controls & CONTROL_MOVERIGHT == CONTROL_MOVERIGHT {
fn get_control_dir(&self,controls:u32)->glam::Vec3{ control_dir+=RIGHT_DIR;
//don't get fancy just do it
let mut control_dir:glam::Vec3 = glam::Vec3::ZERO;
//Disallow strafing if held controls are not held
if controls&self.controls_held!=self.controls_held{
return control_dir;
}
//Apply mask after held check so you can require non-allowed keys to be held for some reason
let controls=controls&self.controls_mask;
if controls & Self::CONTROL_MOVEFORWARD == Self::CONTROL_MOVEFORWARD {
control_dir+=Self::FORWARD_DIR;
}
if controls & Self::CONTROL_MOVEBACK == Self::CONTROL_MOVEBACK {
control_dir+=-Self::FORWARD_DIR;
}
if controls & Self::CONTROL_MOVELEFT == Self::CONTROL_MOVELEFT {
control_dir+=-Self::RIGHT_DIR;
}
if controls & Self::CONTROL_MOVERIGHT == Self::CONTROL_MOVERIGHT {
control_dir+=Self::RIGHT_DIR;
}
if controls & Self::CONTROL_MOVEUP == Self::CONTROL_MOVEUP {
control_dir+=Self::UP_DIR;
}
if controls & Self::CONTROL_MOVEDOWN == Self::CONTROL_MOVEDOWN {
control_dir+=-Self::UP_DIR;
}
return control_dir
} }
if controls & CONTROL_MOVEUP == CONTROL_MOVEUP {
control_dir+=UP_DIR;
}
if controls & CONTROL_MOVEDOWN == CONTROL_MOVEDOWN {
control_dir+=-UP_DIR;
}
return control_dir
} }
pub struct PhysicsState{ pub struct PhysicsState {
pub time:TIME, pub body: Body,
pub body:Body, pub hitbox_halfsize: glam::Vec3,
pub world:WorldState,//currently there is only one state the world can be in pub contacts: std::collections::HashSet::<RelativeCollision>,
pub game:GameMechanicsState,
pub style:StyleModifiers,
pub contacts:std::collections::HashMap::<u32,RelativeCollision>,
pub intersects:std::collections::HashMap::<u32,RelativeCollision>,
//pub intersections: Vec<ModelId>, //pub intersections: Vec<ModelId>,
pub models: Vec<ModelPhysics>,
//camera must exist in state because wormholes modify the camera, also camera punch //camera must exist in state because wormholes modify the camera, also camera punch
pub camera:Camera, pub camera: Camera,
pub mouse_interpolation:MouseInterpolationState, pub mouse_interpolation: MouseInterpolationState,
pub controls:u32, pub controls: u32,
pub walk:WalkState, pub time: TIME,
pub grounded:bool, pub strafe_tick_num: TIME,
//all models pub strafe_tick_den: TIME,
pub models:Vec<ModelPhysics>, pub tick: u32,
pub mv: f32,
pub modes:Vec<crate::model::ModeDescription>, pub walk: WalkState,
pub mode_from_mode_id:std::collections::HashMap::<u32,usize>, pub walkspeed: f32,
//the spawn point is where you spawn when you load into the map. pub friction: f32,
//This is not the same as Reset which teleports you to Spawn0 pub walk_accel: f32,
pub spawn_point:glam::Vec3, pub gravity: glam::Vec3,
pub grounded: bool,
pub spawn_point: glam::Vec3,
} }
#[derive(Debug,Clone,Copy,Hash,Eq,PartialEq)] #[derive(Debug,Clone,Copy,Hash,Eq,PartialEq)]
@@ -445,42 +388,20 @@ impl Aabb {
type TreyMeshFace = AabbFace; type TreyMeshFace = AabbFace;
type TreyMesh = Aabb; type TreyMesh = Aabb;
enum PhysicsCollisionAttributes{
Contact{//track whether you are contacting the object
contacting:crate::model::ContactingAttributes,
general:crate::model::GameMechanicAttributes,
},
Intersect{//track whether you are intersecting the object
intersecting:crate::model::IntersectingAttributes,
general:crate::model::GameMechanicAttributes,
},
}
pub struct ModelPhysics { pub struct ModelPhysics {
//A model is a thing that has a hitbox. can be represented by a list of TreyMesh-es //A model is a thing that has a hitbox. can be represented by a list of TreyMesh-es
//in this iteration, all it needs is extents. //in this iteration, all it needs is extents.
mesh: TreyMesh, mesh: TreyMesh,
transform:glam::Affine3A,
attributes:PhysicsCollisionAttributes,
} }
impl ModelPhysics { impl ModelPhysics {
fn from_model_transform_attributes(model:&crate::model::IndexedModel,transform:&glam::Affine3A,attributes:PhysicsCollisionAttributes)->Self{ pub fn from_model(model:&crate::model::IndexedModel,model_transform:glam::Affine3A) -> Self {
let mut aabb=Aabb::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(model_transform.transform_point3(glam::Vec3::from_array(model.unique_pos[indexed_vertex.pos as usize])));
} }
Self{ Self{
mesh:aabb, mesh:aabb,
attributes,
transform:transform.clone(),
}
}
pub fn from_model(model:&crate::model::IndexedModel,instance:&crate::model::ModelInstance) -> Option<Self> {
match &instance.attributes{
crate::model::CollisionAttributes::Contact{contacting,general}=>Some(ModelPhysics::from_model_transform_attributes(model,&instance.transform,PhysicsCollisionAttributes::Contact{contacting:contacting.clone(),general:general.clone()})),
crate::model::CollisionAttributes::Intersect{intersecting,general}=>Some(ModelPhysics::from_model_transform_attributes(model,&instance.transform,PhysicsCollisionAttributes::Intersect{intersecting:intersecting.clone(),general:general.clone()})),
crate::model::CollisionAttributes::Decoration=>None,
} }
} }
pub fn unit_vertices(&self) -> [glam::Vec3;8] { pub fn unit_vertices(&self) -> [glam::Vec3;8] {
@@ -519,14 +440,11 @@ pub struct RelativeCollision {
} }
impl RelativeCollision { impl RelativeCollision {
pub fn model<'a>(&self,models:&'a Vec<ModelPhysics>)->Option<&'a ModelPhysics>{
models.get(self.model as usize)
}
pub fn mesh(&self,models:&Vec<ModelPhysics>) -> TreyMesh { pub fn mesh(&self,models:&Vec<ModelPhysics>) -> TreyMesh {
return self.model(models).unwrap().face_mesh(self.face).clone() return models.get(self.model as usize).unwrap().face_mesh(self.face).clone()
} }
pub fn normal(&self,models:&Vec<ModelPhysics>) -> glam::Vec3 { pub fn normal(&self,models:&Vec<ModelPhysics>) -> glam::Vec3 {
return self.model(models).unwrap().face_normal(self.face) return models.get(self.model as usize).unwrap().face_normal(self.face)
} }
} }
@@ -557,19 +475,6 @@ impl Body {
} }
impl PhysicsState { impl PhysicsState {
pub fn clear(&mut self){
self.models.clear();
self.modes.clear();
self.contacts.clear();
self.intersects.clear();
}
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)
}else{
None
}
}
//tickless gaming //tickless gaming
pub fn run(&mut self, time_limit:TIME){ pub fn run(&mut self, time_limit:TIME){
//prepare is ommitted - everything is done via instructions. //prepare is ommitted - everything is done via instructions.
@@ -596,7 +501,7 @@ impl PhysicsState {
} }
fn contact_constrain_velocity(&self,velocity:&mut glam::Vec3){ fn contact_constrain_velocity(&self,velocity:&mut glam::Vec3){
for (_,contact) in &self.contacts { for contact in self.contacts.iter() {
let n=contact.normal(&self.models); let n=contact.normal(&self.models);
let d=velocity.dot(n); let d=velocity.dot(n);
if d<0f32{ if d<0f32{
@@ -605,7 +510,7 @@ impl PhysicsState {
} }
} }
fn contact_constrain_acceleration(&self,acceleration:&mut glam::Vec3){ fn contact_constrain_acceleration(&self,acceleration:&mut glam::Vec3){
for (_,contact) in &self.contacts { for contact in self.contacts.iter() {
let n=contact.normal(&self.models); let n=contact.normal(&self.models);
let d=acceleration.dot(n); let d=acceleration.dot(n);
if d<0f32{ if d<0f32{
@@ -615,7 +520,7 @@ impl PhysicsState {
} }
fn next_strafe_instruction(&self) -> Option<TimedInstruction<PhysicsInstruction>> { fn next_strafe_instruction(&self) -> Option<TimedInstruction<PhysicsInstruction>> {
return Some(TimedInstruction{ return Some(TimedInstruction{
time:(self.time*self.style.strafe_tick_num/self.style.strafe_tick_den+1)*self.style.strafe_tick_den/self.style.strafe_tick_num, time:(self.time*self.strafe_tick_num/self.strafe_tick_den+1)*self.strafe_tick_den/self.strafe_tick_num,
//only poll the physics if there is a before and after mouse event //only poll the physics if there is a before and after mouse event
instruction:PhysicsInstruction::StrafeTick instruction:PhysicsInstruction::StrafeTick
}); });
@@ -665,7 +570,7 @@ impl PhysicsState {
self.body.acceleration=a; self.body.acceleration=a;
self.walk.state=WalkEnum::Reached; self.walk.state=WalkEnum::Reached;
}else{ }else{
let accel=self.style.walk_accel.min(self.style.gravity.length()*self.style.friction); let accel=self.walk_accel.min(self.gravity.length()*self.friction);
let time_delta=target_diff.length()/accel; let time_delta=target_diff.length()/accel;
let mut a=target_diff/time_delta; let mut a=target_diff/time_delta;
self.contact_constrain_acceleration(&mut a); self.contact_constrain_acceleration(&mut a);
@@ -694,7 +599,7 @@ impl PhysicsState {
fn mesh(&self) -> TreyMesh { fn mesh(&self) -> TreyMesh {
let mut aabb=Aabb::new(); let mut aabb=Aabb::new();
for vertex in Aabb::unit_vertices(){ for vertex in Aabb::unit_vertices(){
aabb.grow(self.body.position+self.style.hitbox_halfsize*vertex); aabb.grow(self.body.position+self.hitbox_halfsize*vertex);
} }
aabb aabb
} }
@@ -978,19 +883,12 @@ impl crate::instruction::InstructionEmitter<PhysicsInstruction> for PhysicsState
//JUST POLLING!!! NO MUTATION //JUST POLLING!!! NO MUTATION
let mut collector = crate::instruction::InstructionCollector::new(time_limit); let mut collector = crate::instruction::InstructionCollector::new(time_limit);
//check for collision stop instructions with curent contacts //check for collision stop instructions with curent contacts
for (_,collision_data) in &self.contacts { for collision_data in self.contacts.iter() {
collector.collect(self.predict_collision_end(self.time,time_limit,collision_data)); collector.collect(self.predict_collision_end(self.time,time_limit,collision_data));
} }
// for collision_data in &self.intersects{
// 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!!)
for i in 0..self.models.len() { for i in 0..self.models.len() {
let i=i as u32; collector.collect(self.predict_collision_start(self.time,time_limit,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 { if self.grounded {
//walk maintenance //walk maintenance
@@ -1006,116 +904,63 @@ impl crate::instruction::InstructionEmitter<PhysicsInstruction> for PhysicsState
impl crate::instruction::InstructionConsumer<PhysicsInstruction> for PhysicsState { impl crate::instruction::InstructionConsumer<PhysicsInstruction> for PhysicsState {
fn process_instruction(&mut self, ins:TimedInstruction<PhysicsInstruction>) { fn process_instruction(&mut self, ins:TimedInstruction<PhysicsInstruction>) {
match &ins.instruction { match &ins.instruction {
PhysicsInstruction::StrafeTick => (), PhysicsInstruction::StrafeTick => (),
PhysicsInstruction::Input(InputInstruction::MoveMouse(_)) => (), PhysicsInstruction::Input(InputInstruction::MoveMouse(_)) => (),
_=>println!("{:?}",ins), _=>println!("{:?}",ins),
} }
//selectively update body //selectively update body
match &ins.instruction { match &ins.instruction {
PhysicsInstruction::Input(InputInstruction::MoveMouse(_)) => (),//dodge time for mouse movement PhysicsInstruction::Input(InputInstruction::MoveMouse(_)) => (),//dodge time for mouse movement
PhysicsInstruction::Input(_) PhysicsInstruction::Input(_)
|PhysicsInstruction::SetSpawnPosition(_) |PhysicsInstruction::SetSpawnPosition(_)
|PhysicsInstruction::ReachWalkTargetVelocity |PhysicsInstruction::ReachWalkTargetVelocity
|PhysicsInstruction::CollisionStart(_) |PhysicsInstruction::CollisionStart(_)
|PhysicsInstruction::CollisionEnd(_) |PhysicsInstruction::CollisionEnd(_)
|PhysicsInstruction::StrafeTick => self.advance_time(ins.time), |PhysicsInstruction::StrafeTick => self.advance_time(ins.time),
} }
match ins.instruction { match ins.instruction {
PhysicsInstruction::SetSpawnPosition(position)=>{ PhysicsInstruction::SetSpawnPosition(position)=>{
self.spawn_point=position; self.spawn_point=position;
} }
PhysicsInstruction::CollisionStart(c) => { PhysicsInstruction::CollisionStart(c) => {
let model=c.model(&self.models).unwrap(); //check ground
match &model.attributes{ match &c.face {
PhysicsCollisionAttributes::Contact{contacting,general}=>{ AabbFace::Top => {
match &contacting.surf{ //ground
Some(surf)=>println!("I'm surfing!"), self.grounded=true;
None=>match &c.face { },
AabbFace::Top => { _ => (),
//ground }
self.grounded=true; self.contacts.insert(c);
}, //flatten v
_ => (), let mut v=self.body.velocity;
}, self.contact_constrain_velocity(&mut v);
} self.body.velocity=v;
match &general.booster{ if self.grounded&&self.controls&CONTROL_JUMP!=0{
Some(booster)=>self.body.velocity+=booster.velocity, self.jump();
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();
}
self.refresh_walk_target();
},
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);
},
} }
self.refresh_walk_target();
}, },
PhysicsInstruction::CollisionEnd(c) => { PhysicsInstruction::CollisionEnd(c) => {
let model=c.model(&self.models).unwrap(); self.contacts.remove(&c);//remove contact before calling contact_constrain_acceleration
match &model.attributes{ let mut a=self.gravity;
PhysicsCollisionAttributes::Contact{contacting,general}=>{ self.contact_constrain_acceleration(&mut a);
self.contacts.remove(&c.model);//remove contact before calling contact_constrain_acceleration self.body.acceleration=a;
let mut a=self.style.gravity; //check ground
self.contact_constrain_acceleration(&mut a); match &c.face {
self.body.acceleration=a; AabbFace::Top => {
//check ground self.grounded=false;
match &c.face { },
AabbFace::Top => { _ => (),
self.grounded=false; }
}, self.refresh_walk_target();
_ => (),
}
self.refresh_walk_target();
},
PhysicsCollisionAttributes::Intersect{intersecting,general}=>{
self.intersects.remove(&c.model);
},
}
}, },
PhysicsInstruction::StrafeTick => { PhysicsInstruction::StrafeTick => {
let camera_mat=self.camera.simulate_move_rotation_y(self.mouse_interpolation.interpolated_position(self.time).x-self.mouse_interpolation.mouse0.x); let camera_mat=self.camera.simulate_move_rotation_y(self.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 control_dir=camera_mat*get_control_dir(self.controls);
let d=self.body.velocity.dot(control_dir); let d=self.body.velocity.dot(control_dir);
if d<self.style.mv { if d<self.mv {
let mut v=self.body.velocity+(self.style.mv-d)*control_dir; let mut v=self.body.velocity+(self.mv-d)*control_dir;
self.contact_constrain_velocity(&mut v); self.contact_constrain_velocity(&mut v);
self.body.velocity=v; self.body.velocity=v;
} }
@@ -1138,21 +983,21 @@ impl crate::instruction::InstructionConsumer<PhysicsInstruction> for PhysicsStat
self.camera.angles=self.camera.simulate_move_angles(self.mouse_interpolation.mouse1-self.mouse_interpolation.mouse0); self.camera.angles=self.camera.simulate_move_angles(self.mouse_interpolation.mouse1-self.mouse_interpolation.mouse0);
self.mouse_interpolation.move_mouse(self.time,m); self.mouse_interpolation.move_mouse(self.time,m);
}, },
InputInstruction::MoveForward(s) => self.set_control(StyleModifiers::CONTROL_MOVEFORWARD,s), InputInstruction::MoveForward(s) => self.set_control(CONTROL_MOVEFORWARD,s),
InputInstruction::MoveLeft(s) => self.set_control(StyleModifiers::CONTROL_MOVELEFT,s), InputInstruction::MoveLeft(s) => self.set_control(CONTROL_MOVELEFT,s),
InputInstruction::MoveBack(s) => self.set_control(StyleModifiers::CONTROL_MOVEBACK,s), InputInstruction::MoveBack(s) => self.set_control(CONTROL_MOVEBACK,s),
InputInstruction::MoveRight(s) => self.set_control(StyleModifiers::CONTROL_MOVERIGHT,s), InputInstruction::MoveRight(s) => self.set_control(CONTROL_MOVERIGHT,s),
InputInstruction::MoveUp(s) => self.set_control(StyleModifiers::CONTROL_MOVEUP,s), InputInstruction::MoveUp(s) => self.set_control(CONTROL_MOVEUP,s),
InputInstruction::MoveDown(s) => self.set_control(StyleModifiers::CONTROL_MOVEDOWN,s), InputInstruction::MoveDown(s) => self.set_control(CONTROL_MOVEDOWN,s),
InputInstruction::Jump(s) => { InputInstruction::Jump(s) => {
self.set_control(StyleModifiers::CONTROL_JUMP,s); self.set_control(CONTROL_JUMP,s);
if self.grounded{ if self.grounded{
self.jump(); self.jump();
} }
refresh_walk_target_velocity=false; refresh_walk_target_velocity=false;
}, },
InputInstruction::Zoom(s) => { InputInstruction::Zoom(s) => {
self.set_control(StyleModifiers::CONTROL_ZOOM,s); self.set_control(CONTROL_ZOOM,s);
refresh_walk_target=false; refresh_walk_target=false;
}, },
InputInstruction::Reset => { InputInstruction::Reset => {
@@ -1161,7 +1006,7 @@ impl crate::instruction::InstructionConsumer<PhysicsInstruction> for PhysicsStat
self.body.velocity=glam::Vec3::ZERO; self.body.velocity=glam::Vec3::ZERO;
//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.body.acceleration=self.style.gravity; self.body.acceleration=self.gravity;
self.walk.state=WalkEnum::Reached; self.walk.state=WalkEnum::Reached;
self.grounded=false; self.grounded=false;
refresh_walk_target=false; refresh_walk_target=false;
@@ -1172,8 +1017,8 @@ impl crate::instruction::InstructionConsumer<PhysicsInstruction> for PhysicsStat
//calculate walk target velocity //calculate walk target velocity
if refresh_walk_target_velocity{ if refresh_walk_target_velocity{
let camera_mat=self.camera.simulate_move_rotation_y(self.mouse_interpolation.interpolated_position(self.time).x-self.mouse_interpolation.mouse0.x); let camera_mat=self.camera.simulate_move_rotation_y(self.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 control_dir=camera_mat*get_control_dir(self.controls);
self.walk.target_velocity=self.style.walkspeed*control_dir; self.walk.target_velocity=self.walkspeed*control_dir;
} }
self.refresh_walk_target(); self.refresh_walk_target();
} }

16
src/load_bsp.rs Normal file
View File

@@ -0,0 +1,16 @@
pub fn generate_indexed_models<R:std::io::Read+std::io::Seek>(input:R) -> crate::model::IndexedModelInstances{
let mut spawn_point=glam::Vec3::ZERO;
let mut indexed_models=Vec::new();
match bsp::Bsp::read(input){
Ok(guac)=>println!("we got the guac {:?}", guac),
Err(e)=>println!("rotten {:?}",e),
}
crate::model::IndexedModelInstances{
textures:Vec::new(),
models:indexed_models,
spawn_point,
}
}

View File

@@ -30,89 +30,13 @@ fn get_texture_refs(dom:&rbx_dom_weak::WeakDom) -> Vec<rbx_dom_weak::types::Ref>
//next class //next class
objects objects
} }
fn get_attributes(name:&str,can_collide:bool,velocity:glam::Vec3,force_intersecting:bool)->crate::model::CollisionAttributes{
let mut general=crate::model::GameMechanicAttributes::default();
let mut intersecting=crate::model::IntersectingAttributes::default();
let mut contacting=crate::model::ContactingAttributes::default();
match name{
//"Water"=>intersecting.water=Some(crate::model::IntersectingWater{density:1.0,drag:1.0}),
"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,
force:false,
behaviour:crate::model::StageElementBehaviour::Platform,
}),
other=>{
if let Some(captures)=lazy_regex::regex!(r"^(Force)?(Spawn|SpawnAt|Trigger|Teleport|Platform)(\d+)$")
.captures(other){
general.stage_element=Some(crate::model::GameMechanicStageElement{
mode_id:0,
stage_id:captures[3].parse::<u32>().unwrap(),
force:match captures.get(1){
Some(m)=>m.as_str()=="Force",
None=>false,
},
behaviour:match &captures[2]{
"Spawn"|"SpawnAt"=>crate::model::StageElementBehaviour::SpawnAt,
"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){
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}),
_=>panic!("regex2[1] messed up bad"),
}
}
}
}
//need some way to skip this
if velocity!=glam::Vec3::ZERO{
general.booster=Some(crate::model::GameMechanicBooster{velocity});
}
match can_collide{
true=>{
match name{
//"Bounce"=>(),
"Surf"=>contacting.surf=Some(crate::model::ContactingSurf{}),
"Ladder"=>contacting.ladder=Some(crate::model::ContactingLadder{sticky:true}),
other=>{
//REGEX!!!!
//Jump#
//WormholeIn#
}
}
crate::model::CollisionAttributes::Contact{contacting,general}
},
false=>if force_intersecting
||general.jump_limit.is_some()
||general.booster.is_some()
||general.zone.is_some()
||general.stage_element.is_some()
||general.wormhole.is_some()
||intersecting.water.is_some()
||intersecting.accelerator.is_some()
{
crate::model::CollisionAttributes::Intersect{intersecting,general}
}else{
crate::model::CollisionAttributes::Decoration
},
}
}
struct RobloxAssetId(u64); struct RobloxAssetId(u64);
struct RobloxAssetIdParseErr; struct RobloxAssetIdParseErr;
impl std::str::FromStr for RobloxAssetId { impl std::str::FromStr for RobloxAssetId {
type Err=RobloxAssetIdParseErr; type Err=RobloxAssetIdParseErr;
fn from_str(s: &str) -> Result<Self, Self::Err>{ fn from_str(s: &str) -> Result<Self, Self::Err>{
let regman=lazy_regex::regex!(r"(\d+)$"); let regman=regex::Regex::new(r"(\d+)$").unwrap();
if let Some(captures) = regman.captures(s) { if let Some(captures) = regman.captures(s) {
if captures.len()==2{//captures[0] is all captures concatenated, and then each individual capture if captures.len()==2{//captures[0] is all captures concatenated, and then each individual capture
if let Ok(id) = captures[0].parse::<u64>() { if let Ok(id) = captures[0].parse::<u64>() {
@@ -203,17 +127,13 @@ pub fn generate_indexed_models(dom:rbx_dom_weak::WeakDom) -> crate::model::Index
if let ( if let (
Some(rbx_dom_weak::types::Variant::CFrame(cf)), Some(rbx_dom_weak::types::Variant::CFrame(cf)),
Some(rbx_dom_weak::types::Variant::Vector3(size)), Some(rbx_dom_weak::types::Variant::Vector3(size)),
Some(rbx_dom_weak::types::Variant::Vector3(velocity)),
Some(rbx_dom_weak::types::Variant::Float32(transparency)), Some(rbx_dom_weak::types::Variant::Float32(transparency)),
Some(rbx_dom_weak::types::Variant::Color3uint8(color3)), Some(rbx_dom_weak::types::Variant::Color3uint8(color3)),
Some(rbx_dom_weak::types::Variant::Bool(can_collide)),
) = ( ) = (
object.properties.get("CFrame"), object.properties.get("CFrame"),
object.properties.get("Size"), object.properties.get("Size"),
object.properties.get("Velocity"),
object.properties.get("Transparency"), object.properties.get("Transparency"),
object.properties.get("Color"), object.properties.get("Color"),
object.properties.get("CanCollide"),
) )
{ {
let model_transform=glam::Affine3A::from_translation( let model_transform=glam::Affine3A::from_translation(
@@ -229,32 +149,12 @@ pub fn generate_indexed_models(dom:rbx_dom_weak::WeakDom) -> crate::model::Index
* glam::Affine3A::from_scale( * glam::Affine3A::from_scale(
glam::Vec3::new(size.x,size.y,size.z)/2.0 glam::Vec3::new(size.x,size.y,size.z)/2.0
); );
if object.name=="MapStart"{
//push TempIndexedAttributes spawn_point=model_transform.transform_point3(glam::Vec3::Y)+glam::vec3(0.0,2.5,0.0);
let mut force_intersecting=false; println!("Found MapStart{:?}",spawn_point);
let mut temp_indexing_attributes=Vec::new(); }
if let Some(attr)=match &object.name[..]{ if *transparency==1.0 {
"MapStart"=>{ continue;
spawn_point=model_transform.transform_point3(glam::Vec3::ZERO)+glam::vec3(0.0,2.5,0.0);
Some(crate::model::TempIndexedAttributes::Start{mode_id:0})
},
"UnorderedCheckpoint"=>Some(crate::model::TempIndexedAttributes::UnorderedCheckpoint{mode_id:0}),
other=>{
let regman=lazy_regex::regex!(r"^(BonusStart|Spawn|ForceSpawn|OrderedCheckpoint)(\d+)$");
if let Some(captures) = regman.captures(other) {
match &captures[1]{
"BonusStart"=>Some(crate::model::TempIndexedAttributes::Start{mode_id:captures[2].parse::<u32>().unwrap()}),
"Spawn"|"ForceSpawn"=>Some(crate::model::TempIndexedAttributes::Spawn{mode_id:0,stage_id:captures[2].parse::<u32>().unwrap()}),
"OrderedCheckpoint"=>Some(crate::model::TempIndexedAttributes::OrderedCheckpoint{mode_id:0,checkpoint_id:captures[2].parse::<u32>().unwrap()}),
_=>None,
}
}else{
None
}
}
}{
force_intersecting=true;
temp_indexing_attributes.push(attr);
} }
//TODO: also detect "CylinderMesh" etc here //TODO: also detect "CylinderMesh" etc here
@@ -354,32 +254,14 @@ pub fn generate_indexed_models(dom:rbx_dom_weak::WeakDom) -> crate::model::Index
} }
} }
//obscure rust syntax "slice pattern" //obscure rust syntax "slice pattern"
let [ let [f0,f1,f2,f3,f4,f5]=part_texture_description;
f0,//Cube::Right
f1,//Cube::Top
f2,//Cube::Back
f3,//Cube::Left
f4,//Cube::Bottom
f5,//Cube::Front
]=part_texture_description;
let basepart_texture_description=match shape{ let basepart_texture_description=match shape{
primitives::Primitives::Sphere=>RobloxBasePartDescription::Sphere, primitives::Primitives::Sphere=>RobloxBasePartDescription::Sphere,
primitives::Primitives::Cube=>RobloxBasePartDescription::Part([f0,f1,f2,f3,f4,f5]), primitives::Primitives::Cube=>RobloxBasePartDescription::Part([f0,f1,f2,f3,f4,f5]),
primitives::Primitives::Cylinder=>RobloxBasePartDescription::Cylinder, primitives::Primitives::Cylinder=>RobloxBasePartDescription::Cylinder,
//use front face texture first and use top face texture as a fallback //use front face texture first and use top face texture as a fallback
primitives::Primitives::Wedge=>RobloxBasePartDescription::Wedge([ primitives::Primitives::Wedge=>RobloxBasePartDescription::Wedge([f0,if f2.is_some(){f2}else{f1},f3,f4,f5]),
f0,//Cube::Right->Wedge::Right primitives::Primitives::CornerWedge=>RobloxBasePartDescription::CornerWedge([f1,f3,f4,f5]),
if f5.is_some(){f5}else{f1},//Cube::Front|Cube::Top->Wedge::TopFront
f2,//Cube::Back->Wedge::Back
f3,//Cube::Left->Wedge::Left
f4,//Cube::Bottom->Wedge::Bottom
]),
primitives::Primitives::CornerWedge=>RobloxBasePartDescription::CornerWedge([
f0,//Cube::Right->CornerWedge::Right
f1,//Cube::Top->CornerWedge::Top
f4,//Cube::Bottom->CornerWedge::Bottom
f5,//Cube::Front->CornerWedge::Front
]),
}; };
//make new model if unit cube has not been created before //make new model if unit cube has not been created before
let model_id=if let Some(&model_id)=model_id_from_description.get(&basepart_texture_description){ let model_id=if let Some(&model_id)=model_id_from_description.get(&basepart_texture_description){
@@ -454,8 +336,6 @@ pub fn generate_indexed_models(dom:rbx_dom_weak::WeakDom) -> crate::model::Index
indexed_models[model_id].instances.push(crate::model::ModelInstance { indexed_models[model_id].instances.push(crate::model::ModelInstance {
transform:model_transform, transform:model_transform,
color:glam::vec4(color3.r as f32/255f32, color3.g as f32/255f32, color3.b as f32/255f32, 1.0-*transparency), color:glam::vec4(color3.r as f32/255f32, color3.g as f32/255f32, color3.b as f32/255f32, 1.0-*transparency),
attributes:get_attributes(&object.name,*can_collide,glam::vec3(velocity.x,velocity.y,velocity.z),force_intersecting),
temp_indexing:temp_indexing_attributes,
}); });
} }
} }
@@ -464,6 +344,5 @@ pub fn generate_indexed_models(dom:rbx_dom_weak::WeakDom) -> crate::model::Index
textures:asset_id_from_texture_id.iter().map(|t|t.to_string()).collect(), textures:asset_id_from_texture_id.iter().map(|t|t.to_string()).collect(),
models:indexed_models, models:indexed_models,
spawn_point, spawn_point,
modes:Vec::new(),
} }
} }

View File

@@ -10,8 +10,8 @@ mod zeroes;
mod framework; mod framework;
mod primitives; mod primitives;
mod instruction; mod instruction;
mod load_bsp;
mod load_roblox; mod load_roblox;
mod worker;
struct Entity { struct Entity {
index_count: u32, index_count: u32,
@@ -39,13 +39,16 @@ pub struct GraphicsBindGroups {
skybox_texture: wgpu::BindGroup, skybox_texture: wgpu::BindGroup,
} }
pub struct GraphicsPipelines{ pub struct GraphicsPipelines {
skybox: wgpu::RenderPipeline, skybox: wgpu::RenderPipeline,
model: wgpu::RenderPipeline, model: wgpu::RenderPipeline,
} }
pub struct GraphicsState{ pub struct GraphicsData {
start_time: std::time::Instant,
screen_size: (u32, u32), screen_size: (u32, u32),
manual_mouse_lock:bool,
physics: body::PhysicsState,
pipelines: GraphicsPipelines, pipelines: GraphicsPipelines,
bind_groups: GraphicsBindGroups, bind_groups: GraphicsBindGroups,
bind_group_layouts: GraphicsBindGroupLayouts, bind_group_layouts: GraphicsBindGroupLayouts,
@@ -57,20 +60,7 @@ pub struct GraphicsState{
staging_belt: wgpu::util::StagingBelt, staging_belt: wgpu::util::StagingBelt,
} }
impl GraphicsState{ impl GraphicsData {
pub fn clear(&mut self){
self.models.clear();
}
}
pub struct GlobalState{
start_time: std::time::Instant,
manual_mouse_lock:bool,
graphics:GraphicsState,
physics:body::PhysicsState,
}
impl GlobalState{
const DEPTH_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Depth24Plus; const DEPTH_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Depth24Plus;
fn create_depth_texture( fn create_depth_texture(
@@ -96,77 +86,15 @@ impl GlobalState{
} }
fn generate_model_physics(&mut self,indexed_models:&model::IndexedModelInstances){ 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{ for model in &indexed_models.models{
//make aabb and run vertices to get realistic bounds //make aabb and run vertices to get realistic bounds
for model_instance in &model.instances{ for model_instance in &model.instances{
if let Some(model_physics)=body::ModelPhysics::from_model(model,model_instance){ self.physics.models.push(body::ModelPhysics::from_model(&model,model_instance.transform));
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()); println!("Physics Objects: {}",self.physics.models.len());
} }
fn generate_model_graphics(&mut self,device:&wgpu::Device,queue:&wgpu::Queue,indexed_models:model::IndexedModelInstances){ fn generate_model_graphics(&mut self,device:&wgpu::Device,queue:&wgpu::Queue,mut indexed_models:model::IndexedModelInstances){
//generate texture view per texture //generate texture view per texture
//idk how to do this gooder lol //idk how to do this gooder lol
@@ -235,23 +163,19 @@ impl GlobalState{
//the models received here are supposed to be tightly packed, i.e. no code needs to check if two models are using the same groups. //the models received here are supposed to be tightly packed, i.e. no code needs to check if two models are using the same groups.
let indexed_models_len=indexed_models.models.len(); let indexed_models_len=indexed_models.models.len();
let mut unique_texture_models=Vec::with_capacity(indexed_models_len); let mut unique_texture_models=Vec::with_capacity(indexed_models_len);
for model in indexed_models.models.into_iter(){ for mut model in indexed_models.models.into_iter(){
//convert ModelInstance into ModelGraphicsInstance //convert ModelInstance into ModelGraphicsInstance
let instances:Vec<ModelGraphicsInstance>=model.instances.into_iter().filter_map(|instance|{ let instances:Vec<ModelGraphicsInstance>=model.instances.iter().map(|instance|{
if instance.color.w==0.0{ ModelGraphicsInstance{
None transform: glam::Mat4::from(instance.transform),
}else{ normal_transform: glam::Mat4::from(instance.transform.inverse()).transpose(),
Some(ModelGraphicsInstance{ color: instance.color,
transform: glam::Mat4::from(instance.transform),
normal_transform: glam::Mat4::from(instance.transform.inverse()).transpose(),
color: instance.color,
})
} }
}).collect(); }).collect();
//check each group, if it's using a new texture then make a new clone of the model //check each group, if it's using a new texture then make a new clone of the model
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.drain(..){
//ignore zero coppy 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
@@ -315,12 +239,12 @@ impl GlobalState{
texture:model.texture, texture:model.texture,
}); });
} }
//.into_iter() the modeldata vec so entities can be /moved/ to models.entities //drain the modeldata vec so entities can be /moved/ to models.entities
let mut model_count=0; let mut model_count=0;
let mut instance_count=0; let mut instance_count=0;
let uniform_buffer_binding_size=<GlobalState as framework::Example>::required_limits().max_uniform_buffer_binding_size as usize; let uniform_buffer_binding_size=<GraphicsData as framework::Example>::required_limits().max_uniform_buffer_binding_size as usize;
let chunk_size=uniform_buffer_binding_size/MODEL_BUFFER_SIZE_BYTES; let chunk_size=uniform_buffer_binding_size/MODEL_BUFFER_SIZE_BYTES;
self.graphics.models.reserve(models.len()); self.models.reserve(models.len());
for model in models.into_iter() { for model in models.into_iter() {
instance_count+=model.instances.len(); instance_count+=model.instances.len();
for instances_chunk in model.instances.rchunks(chunk_size){ for instances_chunk in model.instances.rchunks(chunk_size){
@@ -335,13 +259,13 @@ impl GlobalState{
Some(texture_id)=>{ Some(texture_id)=>{
match double_map.get(&texture_id){ match double_map.get(&texture_id){
Some(&mapped_texture_id)=>&texture_views[mapped_texture_id as usize], Some(&mapped_texture_id)=>&texture_views[mapped_texture_id as usize],
None=>&self.graphics.temp_squid_texture_view, None=>&self.temp_squid_texture_view,
} }
}, },
None=>&self.graphics.temp_squid_texture_view, None=>&self.temp_squid_texture_view,
}; };
let model_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { let model_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
layout: &self.graphics.bind_group_layouts.model, layout: &self.bind_group_layouts.model,
entries: &[ entries: &[
wgpu::BindGroupEntry { wgpu::BindGroupEntry {
binding: 0, binding: 0,
@@ -353,7 +277,7 @@ impl GlobalState{
}, },
wgpu::BindGroupEntry { wgpu::BindGroupEntry {
binding: 2, binding: 2,
resource: wgpu::BindingResource::Sampler(&self.graphics.samplers.repeat), resource: wgpu::BindingResource::Sampler(&self.samplers.repeat),
}, },
], ],
label: Some(format!("Model{} Bind Group",model_count).as_str()), label: Some(format!("Model{} Bind Group",model_count).as_str()),
@@ -364,7 +288,7 @@ impl GlobalState{
usage: wgpu::BufferUsages::VERTEX, usage: wgpu::BufferUsages::VERTEX,
}); });
//all of these are being moved here //all of these are being moved here
self.graphics.models.push(ModelGraphics{ self.models.push(ModelGraphics{
instances:instances_chunk.to_vec(), instances:instances_chunk.to_vec(),
vertex_buf, vertex_buf,
entities: model.entities.iter().map(|indices|{ entities: model.entities.iter().map(|indices|{
@@ -386,7 +310,7 @@ impl GlobalState{
println!("Texture References={}",num_textures); println!("Texture References={}",num_textures);
println!("Textures Loaded={}",texture_views.len()); println!("Textures Loaded={}",texture_views.len());
println!("Indexed Models={}",indexed_models_len); println!("Indexed Models={}",indexed_models_len);
println!("Graphics Objects: {}",self.graphics.models.len()); println!("Graphics Objects: {}",self.models.len());
println!("Graphics Instances: {}",instance_count); println!("Graphics Instances: {}",instance_count);
} }
} }
@@ -422,7 +346,7 @@ fn to_uniform_data(camera: &body::Camera, pos: glam::Vec3) -> [f32; 16 * 3 + 4]
raw raw
} }
impl framework::Example for GlobalState { impl framework::Example for GraphicsData {
fn optional_features() -> wgpu::Features { fn optional_features() -> wgpu::Features {
wgpu::Features::TEXTURE_COMPRESSION_ASTC wgpu::Features::TEXTURE_COMPRESSION_ASTC
| wgpu::Features::TEXTURE_COMPRESSION_ETC2 | wgpu::Features::TEXTURE_COMPRESSION_ETC2
@@ -447,44 +371,34 @@ impl framework::Example for GlobalState {
println!("models.len = {:?}", indexed_models.len()); println!("models.len = {:?}", indexed_models.len());
indexed_models[0].instances.push(ModelInstance{ indexed_models[0].instances.push(ModelInstance{
transform:glam::Affine3A::from_translation(glam::vec3(10.,0.,-10.)), transform:glam::Affine3A::from_translation(glam::vec3(10.,0.,-10.)),
..Default::default() color:glam::Vec4::ONE,
}); });
//quad monkeys //quad monkeys
indexed_models[1].instances.push(ModelInstance{ indexed_models[1].instances.push(ModelInstance{
transform:glam::Affine3A::from_translation(glam::vec3(10.,5.,10.)), transform:glam::Affine3A::from_translation(glam::vec3(10.,5.,10.)),
..Default::default() color:glam::Vec4::ONE,
}); });
indexed_models[1].instances.push(ModelInstance{ indexed_models[1].instances.push(ModelInstance{
transform:glam::Affine3A::from_translation(glam::vec3(20.,5.,10.)), transform:glam::Affine3A::from_translation(glam::vec3(20.,5.,10.)),
color:glam::vec4(1.0,0.0,0.0,1.0), color:glam::vec4(1.0,0.0,0.0,1.0),
..Default::default()
}); });
indexed_models[1].instances.push(ModelInstance{ indexed_models[1].instances.push(ModelInstance{
transform:glam::Affine3A::from_translation(glam::vec3(10.,5.,20.)), transform:glam::Affine3A::from_translation(glam::vec3(10.,5.,20.)),
color:glam::vec4(0.0,1.0,0.0,1.0), color:glam::vec4(0.0,1.0,0.0,1.0),
..Default::default()
}); });
indexed_models[1].instances.push(ModelInstance{ indexed_models[1].instances.push(ModelInstance{
transform:glam::Affine3A::from_translation(glam::vec3(20.,5.,20.)), transform:glam::Affine3A::from_translation(glam::vec3(20.,5.,20.)),
color:glam::vec4(0.0,0.0,1.0,1.0), color:glam::vec4(0.0,0.0,1.0,1.0),
..Default::default()
});
//decorative monkey
indexed_models[1].instances.push(ModelInstance{
transform:glam::Affine3A::from_translation(glam::vec3(15.,10.,15.)),
color:glam::vec4(0.5,0.5,0.5,0.5),
attributes:model::CollisionAttributes::Decoration,
..Default::default()
}); });
//teapot //teapot
indexed_models[2].instances.push(ModelInstance{ indexed_models[2].instances.push(ModelInstance{
transform:glam::Affine3A::from_scale_rotation_translation(glam::vec3(0.5, 1.0, 0.2),glam::quat(-0.22248298016985793,-0.839457167990537,-0.05603504040830783,-0.49261857546227916),glam::vec3(-10.,7.,10.)), transform:glam::Affine3A::from_scale_rotation_translation(glam::vec3(0.5, 1.0, 0.2),glam::quat(-0.22248298016985793,-0.839457167990537,-0.05603504040830783,-0.49261857546227916),glam::vec3(-10.,7.,10.)),
..Default::default() color:glam::Vec4::ONE,
}); });
//ground //ground
indexed_models[3].instances.push(ModelInstance{ indexed_models[3].instances.push(ModelInstance{
transform:glam::Affine3A::from_translation(glam::vec3(0.,0.,0.))*glam::Affine3A::from_scale(glam::vec3(160.0, 1.0, 160.0)), transform:glam::Affine3A::from_translation(glam::vec3(0.,0.,0.))*glam::Affine3A::from_scale(glam::vec3(160.0, 1.0, 160.0)),
..Default::default() color:glam::Vec4::ONE,
}); });
let camera_bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { let camera_bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
@@ -586,19 +500,22 @@ impl framework::Example for GlobalState {
spawn_point:glam::vec3(0.0,50.0,0.0), 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)), 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, time: 0,
style:body::StyleModifiers::default(), tick: 0,
strafe_tick_num: 100,//100t
strafe_tick_den: 1_000_000_000,
gravity: glam::vec3(0.0,-100.0,0.0),
friction: 1.2,
walk_accel: 90.0,
mv: 2.7,
grounded: false, grounded: false,
contacts: std::collections::HashMap::new(), walkspeed: 18.0,
intersects: std::collections::HashMap::new(), contacts: std::collections::HashSet::new(),
models: Vec::new(), models: Vec::new(),
walk: body::WalkState::new(), walk: body::WalkState::new(),
hitbox_halfsize: glam::vec3(1.0,2.5,1.0),
camera: body::Camera::from_offset(glam::vec3(0.0,4.5-2.5,0.0),(config.width as f32)/(config.height as f32)), 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(), mouse_interpolation: body::MouseInterpolationState::new(),
controls: 0, controls: 0,
world:body::WorldState{},
game:body::GameMechanicsState::default(),
modes:Vec::new(),
mode_from_mode_id:std::collections::HashMap::new(),
}; };
//load textures //load textures
@@ -828,8 +745,11 @@ impl framework::Example for GlobalState {
let depth_view = Self::create_depth_texture(config, device); let depth_view = Self::create_depth_texture(config, device);
let graphics=GraphicsState { let mut graphics=GraphicsData {
manual_mouse_lock:false,
start_time: Instant::now(),
screen_size: (config.width,config.height), screen_size: (config.width,config.height),
physics,
pipelines:GraphicsPipelines{ pipelines:GraphicsPipelines{
skybox:sky_pipeline, skybox:sky_pipeline,
model:model_pipeline model:model_pipeline
@@ -847,28 +767,20 @@ impl framework::Example for GlobalState {
temp_squid_texture_view: squid_texture_view, temp_squid_texture_view: squid_texture_view,
}; };
let mut state=GlobalState{
start_time:Instant::now(),
manual_mouse_lock:false,
graphics,
physics,
};
let indexed_model_instances=model::IndexedModelInstances{ let indexed_model_instances=model::IndexedModelInstances{
textures:Vec::new(), textures:Vec::new(),
models:indexed_models, models:indexed_models,
spawn_point:glam::Vec3::Y*50.0, spawn_point:glam::Vec3::Y*50.0,
modes:Vec::new(),
}; };
state.generate_model_physics(&indexed_model_instances); graphics.generate_model_physics(&indexed_model_instances);
state.generate_model_graphics(&device,&queue,indexed_model_instances); graphics.generate_model_graphics(&device,&queue,indexed_model_instances);
let args:Vec<String>=std::env::args().collect(); let args:Vec<String>=std::env::args().collect();
if args.len()==2{ if args.len()==2{
state.load_file(std::path::PathBuf::from(&args[1]), device, queue); graphics.load_file(std::path::PathBuf::from(&args[1]), device, queue);
} }
return state; return graphics;
} }
fn load_file(&mut self,path: std::path::PathBuf, device: &wgpu::Device, queue: &wgpu::Queue){ fn load_file(&mut self,path: std::path::PathBuf, device: &wgpu::Device, queue: &wgpu::Queue){
@@ -900,7 +812,21 @@ impl framework::Example for GlobalState {
}, },
} }
}, },
//b"VBSP"=>Some(load_bsp::generate_indexed_models(input)), b"VBSP"=>{
let mut entire_file=Vec::new();
match std::io::Read::read_to_end(&mut input, &mut entire_file){
Ok(_)=>{
//haha yes this is a quake file what do you mean
entire_file[0]=b'I';
entire_file[4..8].copy_from_slice(&0x2ei32.to_le_bytes());
Some(load_bsp::generate_indexed_models(&mut std::io::Cursor::new(entire_file)))
},
Err(e)=>{
println!("Error loading \"valve\" file:{:?}",e);
None
},
}
},
//b"SNFM"=>Some(sniffer::generate_indexed_models(input)), //b"SNFM"=>Some(sniffer::generate_indexed_models(input)),
//b"SNFB"=>Some(sniffer::load_bot(input)), //b"SNFB"=>Some(sniffer::load_bot(input)),
other=>{ other=>{
@@ -911,9 +837,8 @@ impl framework::Example for GlobalState {
}{ }{
let spawn_point=indexed_model_instances.spawn_point; let spawn_point=indexed_model_instances.spawn_point;
//if generate_indexed_models succeeds, clear the previous ones //if generate_indexed_models succeeds, clear the previous ones
self.physics.clear(); self.models.clear();
self.graphics.clear(); self.physics.models.clear();
self.physics.game.stage_id=0;
self.generate_model_physics(&indexed_model_instances); self.generate_model_physics(&indexed_model_instances);
self.generate_model_graphics(device,queue,indexed_model_instances); self.generate_model_graphics(device,queue,indexed_model_instances);
//manual reset //manual reset
@@ -986,7 +911,7 @@ impl framework::Example for GlobalState {
15=>{//Tab 15=>{//Tab
if s{ if s{
self.manual_mouse_lock=false; self.manual_mouse_lock=false;
match window.set_cursor_position(winit::dpi::PhysicalPosition::new(self.graphics.screen_size.0 as f32/2.0, self.graphics.screen_size.1 as f32/2.0)){ match window.set_cursor_position(winit::dpi::PhysicalPosition::new(self.screen_size.0 as f32/2.0, self.screen_size.1 as f32/2.0)){
Ok(())=>(), Ok(())=>(),
Err(e)=>println!("Could not set cursor position: {:?}",e), Err(e)=>println!("Could not set cursor position: {:?}",e),
} }
@@ -1026,7 +951,7 @@ impl framework::Example for GlobalState {
delta,//these (f64,f64) are integers on my machine delta,//these (f64,f64) are integers on my machine
} => { } => {
if self.manual_mouse_lock{ if self.manual_mouse_lock{
match window.set_cursor_position(winit::dpi::PhysicalPosition::new(self.graphics.screen_size.0 as f32/2.0, self.graphics.screen_size.1 as f32/2.0)){ match window.set_cursor_position(winit::dpi::PhysicalPosition::new(self.screen_size.0 as f32/2.0, self.screen_size.1 as f32/2.0)){
Ok(())=>(), Ok(())=>(),
Err(e)=>println!("Could not set cursor position: {:?}",e), Err(e)=>println!("Could not set cursor position: {:?}",e),
} }
@@ -1061,8 +986,8 @@ impl framework::Example for GlobalState {
device: &wgpu::Device, device: &wgpu::Device,
_queue: &wgpu::Queue, _queue: &wgpu::Queue,
) { ) {
self.graphics.depth_view = Self::create_depth_texture(config, device); self.depth_view = Self::create_depth_texture(config, device);
self.graphics.screen_size = (config.width, config.height); self.screen_size = (config.width, config.height);
self.physics.camera.set_fov_aspect(1.0,(config.width as f32)/(config.height as f32)); self.physics.camera.set_fov_aspect(1.0,(config.width as f32)/(config.height as f32));
} }
@@ -1082,19 +1007,19 @@ impl framework::Example for GlobalState {
// update rotation // update rotation
let camera_uniforms = to_uniform_data(&self.physics.camera,self.physics.body.extrapolated_position(time)); let camera_uniforms = to_uniform_data(&self.physics.camera,self.physics.body.extrapolated_position(time));
self.graphics.staging_belt self.staging_belt
.write_buffer( .write_buffer(
&mut encoder, &mut encoder,
&self.graphics.camera_buf, &self.camera_buf,
0, 0,
wgpu::BufferSize::new((camera_uniforms.len() * 4) as wgpu::BufferAddress).unwrap(), wgpu::BufferSize::new((camera_uniforms.len() * 4) as wgpu::BufferAddress).unwrap(),
device, device,
) )
.copy_from_slice(bytemuck::cast_slice(&camera_uniforms)); .copy_from_slice(bytemuck::cast_slice(&camera_uniforms));
//This code only needs to run when the uniforms change //This code only needs to run when the uniforms change
for model in self.graphics.models.iter() { for model in self.models.iter() {
let model_uniforms = get_instances_buffer_data(&model.instances); let model_uniforms = get_instances_buffer_data(&model.instances);
self.graphics.staging_belt self.staging_belt
.write_buffer( .write_buffer(
&mut encoder, &mut encoder,
&model.model_buf,//description of where data will be written when command is executed &model.model_buf,//description of where data will be written when command is executed
@@ -1104,7 +1029,7 @@ impl framework::Example for GlobalState {
) )
.copy_from_slice(bytemuck::cast_slice(&model_uniforms)); .copy_from_slice(bytemuck::cast_slice(&model_uniforms));
} }
self.graphics.staging_belt.finish(); self.staging_belt.finish();
{ {
let mut rpass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { let mut rpass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
@@ -1123,7 +1048,7 @@ impl framework::Example for GlobalState {
}, },
})], })],
depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment { depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
view: &self.graphics.depth_view, view: &self.depth_view,
depth_ops: Some(wgpu::Operations { depth_ops: Some(wgpu::Operations {
load: wgpu::LoadOp::Clear(1.0), load: wgpu::LoadOp::Clear(1.0),
store: false, store: false,
@@ -1132,11 +1057,11 @@ impl framework::Example for GlobalState {
}), }),
}); });
rpass.set_bind_group(0, &self.graphics.bind_groups.camera, &[]); rpass.set_bind_group(0, &self.bind_groups.camera, &[]);
rpass.set_bind_group(1, &self.graphics.bind_groups.skybox_texture, &[]); rpass.set_bind_group(1, &self.bind_groups.skybox_texture, &[]);
rpass.set_pipeline(&self.graphics.pipelines.model); rpass.set_pipeline(&self.pipelines.model);
for model in self.graphics.models.iter() { for model in self.models.iter() {
rpass.set_bind_group(2, &model.bind_group, &[]); rpass.set_bind_group(2, &model.bind_group, &[]);
rpass.set_vertex_buffer(0, model.vertex_buf.slice(..)); rpass.set_vertex_buffer(0, model.vertex_buf.slice(..));
@@ -1146,18 +1071,18 @@ impl framework::Example for GlobalState {
} }
} }
rpass.set_pipeline(&self.graphics.pipelines.skybox); rpass.set_pipeline(&self.pipelines.skybox);
rpass.draw(0..3, 0..1); rpass.draw(0..3, 0..1);
} }
queue.submit(std::iter::once(encoder.finish())); queue.submit(std::iter::once(encoder.finish()));
self.graphics.staging_belt.recall(); self.staging_belt.recall();
} }
} }
fn main() { fn main() {
framework::run::<GlobalState>( framework::run::<GraphicsData>(
format!("Strafe Client v{}", format!("Strafe Client v{}",
env!("CARGO_PKG_VERSION") env!("CARGO_PKG_VERSION")
).as_str() ).as_str()

View File

@@ -56,177 +56,15 @@ pub struct ModelGraphicsInstance{
pub color:glam::Vec4, pub color:glam::Vec4,
} }
pub struct ModelInstance{ pub struct ModelInstance{
//pub id:u64,//this does not actually help with map fixes resimulating bots, they must always be resimulated
pub transform:glam::Affine3A, pub transform:glam::Affine3A,
pub color:glam::Vec4,//transparency is in here pub color:glam::Vec4,
pub attributes:CollisionAttributes,
pub temp_indexing:Vec<TempIndexedAttributes>,
}
impl std::default::Default for ModelInstance{
fn default() -> Self {
Self{
color:glam::Vec4::ONE,
transform:Default::default(),
attributes:Default::default(),
temp_indexing:Default::default(),
}
}
} }
pub struct IndexedModelInstances{ pub struct IndexedModelInstances{
pub textures:Vec<String>,//RenderPattern pub textures:Vec<String>,//RenderPattern
pub models:Vec<IndexedModel>, pub models:Vec<IndexedModel>,
//may make this into an object later. //object_index for spawns, triggers etc?
pub modes:Vec<ModeDescription>,
pub spawn_point:glam::Vec3, pub spawn_point:glam::Vec3,
} }
//stage description referencing flattened ids is spooky, but the map loading is meant to be deterministic.
pub struct ModeDescription{
pub start:u32,//start=model_id
pub spawns:Vec<u32>,//spawns[spawn_id]=model_id
pub ordered_checkpoints:Vec<u32>,//ordered_checkpoints[checkpoint_id]=model_id
pub unordered_checkpoints:Vec<u32>,//unordered_checkpoints[checkpoint_id]=model_id
pub spawn_from_stage_id:std::collections::HashMap::<u32,usize>,
pub ordered_checkpoint_from_checkpoint_id:std::collections::HashMap::<u32,usize>,
}
impl ModeDescription{
pub fn get_spawn_model_id(&self,stage_id:u32)->Option<&u32>{
if let Some(&spawn)=self.spawn_from_stage_id.get(&stage_id){
self.spawns.get(spawn)
}else{
None
}
}
pub fn get_ordered_checkpoint_model_id(&self,checkpoint_id:u32)->Option<&u32>{
if let Some(&checkpoint)=self.ordered_checkpoint_from_checkpoint_id.get(&checkpoint_id){
self.ordered_checkpoints.get(checkpoint)
}else{
None
}
}
}
#[derive(Debug)]
pub enum TempIndexedAttributes{
Start{
mode_id:u32,
},
Spawn{
mode_id:u32,
stage_id:u32,
},
OrderedCheckpoint{
mode_id:u32,
checkpoint_id:u32,
},
UnorderedCheckpoint{
mode_id:u32,
},
}
//you have this effect while in contact
#[derive(Clone)]
pub struct ContactingSurf{}
#[derive(Clone)]
pub struct ContactingLadder{
pub sticky:bool
}
//you have this effect while intersecting
#[derive(Clone)]
pub struct IntersectingWater{
pub viscosity:i64,
pub density:i64,
pub current:glam::Vec3,
}
#[derive(Clone)]
pub struct IntersectingAccelerator{
pub acceleration:glam::Vec3
}
//All models can be given these attributes
#[derive(Clone)]
pub struct GameMechanicJumpLimit{
pub count:u32,
}
#[derive(Clone)]
pub struct GameMechanicBooster{
pub velocity:glam::Vec3,
}
#[derive(Clone)]
pub enum ZoneBehaviour{
//Start is indexed
//Checkpoints are indexed
Finish,
Anitcheat,
}
#[derive(Clone)]
pub struct GameMechanicZone{
pub mode_id:u32,
pub behaviour:ZoneBehaviour,
}
// enum TrapCondition{
// FasterThan(i64),
// SlowerThan(i64),
// InRange(i64,i64),
// OutsideRange(i64,i64),
// }
#[derive(Clone)]
pub enum StageElementBehaviour{
//Spawn,//The behaviour of stepping on a spawn setting the spawnid
SpawnAt,
Trigger,
Teleport,
Platform,
//Speedtrap(TrapCondition),//Acts as a trigger with a speed condition
}
#[derive(Clone)]
pub struct GameMechanicStageElement{
pub mode_id:u32,
pub stage_id:u32,//which spawn to send to
pub force:bool,//allow setting to lower spawn id i.e. 7->3
pub behaviour:StageElementBehaviour
}
#[derive(Clone)]
pub struct GameMechanicWormhole{//(position,angles)*=origin.transform.inverse()*destination.transform
pub model_id:u32,
}
#[derive(Default,Clone)]
pub struct GameMechanicAttributes{
pub jump_limit:Option<GameMechanicJumpLimit>,
pub booster:Option<GameMechanicBooster>,
pub zone:Option<GameMechanicZone>,
pub stage_element:Option<GameMechanicStageElement>,
pub wormhole:Option<GameMechanicWormhole>,//stage_element and wormhole are in conflict
}
#[derive(Default,Clone)]
pub struct ContactingAttributes{
pub elasticity:Option<u32>,//[1/2^32,1] 0=None (elasticity+1)/2^32
//friction?
pub surf:Option<ContactingSurf>,
pub ladder:Option<ContactingLadder>,
}
#[derive(Default,Clone)]
pub struct IntersectingAttributes{
pub water:Option<IntersectingWater>,
pub accelerator:Option<IntersectingAccelerator>,
}
//Spawn(u32) NO! spawns are indexed in the map header instead of marked with attibutes
pub enum CollisionAttributes{
Decoration,//visual only
Contact{//track whether you are contacting the object
contacting:ContactingAttributes,
general:GameMechanicAttributes,
},
Intersect{//track whether you are intersecting the object
intersecting:IntersectingAttributes,
general:GameMechanicAttributes,
},
}
impl std::default::Default for CollisionAttributes{
fn default() -> Self {
Self::Contact{
contacting:ContactingAttributes::default(),
general:GameMechanicAttributes::default()
}
}
}
pub fn generate_indexed_model_list_from_obj(data:obj::ObjData,color:[f32;4]) -> Vec<IndexedModel>{ pub fn generate_indexed_model_list_from_obj(data:obj::ObjData,color:[f32;4]) -> Vec<IndexedModel>{
let mut unique_vertex_index = std::collections::HashMap::<obj::IndexTuple,u32>::new(); let mut unique_vertex_index = std::collections::HashMap::<obj::IndexTuple,u32>::new();

View File

@@ -113,11 +113,11 @@ pub enum CornerWedgeFace{
Front, Front,
} }
const CORNERWEDGE_DEFAULT_NORMALS:[[f32;3];5]=[ const CORNERWEDGE_DEFAULT_NORMALS:[[f32;3];5]=[
[ 1., 0., 0.],//CornerWedge::Right [ 1., 0., 0.],//Wedge::Right
[ 0., 1., 1.],//CornerWedge::BackTop [ 0., 1., 1.],//Wedge::BackTop
[-1., 1., 0.],//CornerWedge::LeftTop [-1., 1., 0.],//Wedge::LeftTop
[ 0.,-1., 0.],//CornerWedge::Bottom [ 0.,-1., 0.],//Wedge::Bottom
[ 0., 0.,-1.],//CornerWedge::Front [ 0., 0.,-1.],//Wedge::Front
]; ];
//HashMap fits this use case perfectly but feels like using a sledgehammer to drive a nail //HashMap fits this use case perfectly but feels like using a sledgehammer to drive a nail
pub fn unit_sphere()->crate::model::IndexedModel{ pub fn unit_sphere()->crate::model::IndexedModel{

View File

@@ -1,83 +0,0 @@
use std::thread;
use std::sync::{mpsc,Arc};
use parking_lot::Mutex;
//The goal here is to have a worker thread that parks itself when it runs out of work.
//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.
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> {
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
}
fn send(&self,task:Task)->Result<(), mpsc::SendError<Task>>{
self.sender.send(task)
}
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::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::body::PhysicsInstruction::StrafeTick,
};
worker.send(task).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));
// 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());
// wait long enough to see print from final task
thread::sleep(std::time::Duration::from_secs(1));
}