Compare commits

...

44 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
f2c71caae3 TEMP(for a long time): implement indexing attributes
this is not very make invalid states unrepresentable of you
2023-10-03 19:47:06 -07:00
c8ec1f05d1 implement more attributes 2023-10-03 19:47:06 -07:00
b102319b33 implement Default for CollisionAttributes 2023-10-03 19:47:06 -07:00
50e9152ee2 separate graphics state from global state 2023-10-03 19:47:06 -07:00
7a8de938af rename stages to modes 2023-10-03 19:47:03 -07:00
696f383aee enable cheats 2023-10-03 17:31:34 -07:00
bfd6f4493f I was just stupid the whole time 2023-10-03 17:31:34 -07:00
ed96572a24 RelativeCollision.model helper 2023-10-03 17:20:35 -07:00
5914db3599 put control stuff in StyleModifiers 2023-10-03 16:53:00 -07:00
f72acaf2d4 implement attributes + stages 2023-10-03 16:53:00 -07:00
734ce661f2 game mechanics enums 2023-10-03 16:53:00 -07:00
bb8c53aee2 check transparency when generating models 2023-10-03 16:37:04 -07:00
de0eb0790a fixups 2023-10-03 16:37:04 -07:00
9e9550885f replace regex with lazy-regex macros 2023-10-03 16:35:45 -07:00
58be446297 reminder 2023-10-02 22:45:48 -07:00
d16404167b tweak map loading 2023-10-02 15:27:41 -07:00
79262ce3b4 styling 2023-10-02 03:08:40 -07:00
c47020c149 implement mouse lock with tab and manual mouse lock fallback 2023-10-02 03:08:40 -07:00
5854171619 typo 2023-10-02 01:58:35 -07:00
616b09a857 panic when roblox data is invalid 2023-10-02 01:58:30 -07:00
6ff2620bbc this code is unnecessary, delete it 2023-10-02 01:58:06 -07:00
d3e4918d3e into_iter is probably better than drain 2023-10-02 01:57:15 -07:00
6c2eb5ff29 this needs timers 2023-10-01 19:29:41 -07:00
02a509868a some bullshit to reduce line count 2023-10-01 19:29:41 -07:00
af750151f7 allow loading map from cli 2023-10-01 17:18:50 -07:00
bf4560193d make load_file function 2023-10-01 17:18:29 -07:00
514c45fc21 disable annoying scroll 2023-10-01 15:55:40 -07:00
95d16271de add cursor grab 2023-10-01 15:55:40 -07:00
355d391ea5 wee opti 2023-10-01 15:21:19 -07:00
d8c6444af3 consume textures + label textures with texture_id + don't pass id through thread 2023-10-01 15:17:10 -07:00
fddd4576bd multi threaded image load 2023-10-01 15:06:24 -07:00
9 changed files with 1094 additions and 436 deletions

26
Cargo.lock generated

@ -834,6 +834,29 @@ dependencies = [
"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]]
name = "lazy_static"
version = "1.4.0"
@ -1666,14 +1689,15 @@ dependencies = [
"ddsfile",
"env_logger",
"glam",
"lazy-regex",
"log",
"obj",
"parking_lot",
"pollster",
"rbx_binary",
"rbx_dom_weak",
"rbx_reflection_database",
"rbx_xml",
"regex",
"wgpu",
"winit",
]

@ -11,14 +11,15 @@ bytemuck = { version = "1.13.1", features = ["derive"] }
ddsfile = "0.5.1"
env_logger = "0.10.0"
glam = "0.24.1"
lazy-regex = "3.0.2"
log = "0.4.20"
obj = "0.10.2"
parking_lot = "0.12.1"
pollster = "0.3.0"
rbx_binary = "0.7.1"
rbx_dom_weak = "2.5.0"
rbx_reflection_database = "0.2.7"
rbx_xml = "0.13.1"
regex = "1.9.5"
wgpu = "0.17.0"
winit = "0.28.6"

@ -34,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,Debug)]
pub struct Body {
position: glam::Vec3,//I64 where 2^32 = 1 u
velocity: glam::Vec3,//I64 where 2^32 = 1 u/s
@ -45,20 +45,20 @@ trait MyHash{
fn hash(&self) -> u64;
}
impl MyHash for Body {
fn hash(&self) -> u64 {
fn hash(&self) -> u64 {
let mut hasher=std::collections::hash_map::DefaultHasher::new();
for &el in self.position.as_ref().iter() {
std::hash::Hasher::write(&mut hasher, el.to_ne_bytes().as_slice());
}
for &el in self.velocity.as_ref().iter() {
std::hash::Hasher::write(&mut hasher, el.to_ne_bytes().as_slice());
}
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, self.time.to_ne_bytes().as_slice());
for &el in self.position.as_ref().iter() {
std::hash::Hasher::write(&mut hasher, el.to_ne_bytes().as_slice());
}
for &el in self.velocity.as_ref().iter() {
std::hash::Hasher::write(&mut hasher, el.to_ne_bytes().as_slice());
}
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, self.time.to_ne_bytes().as_slice());
return std::hash::Hasher::finish(&hasher);//hash check to see if walk target is valid
}
}
}
pub enum MoveRestriction {
@ -80,9 +80,9 @@ impl InputState {
}
impl crate::instruction::InstructionEmitter<InputInstruction> for InputState{
fn next_instruction(&self, time_limit:crate::body::TIME) -> Option<TimedInstruction<InputInstruction>> {
//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.
self.queue.get(0)
//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.
self.queue.get(0)
}
}
impl crate::instruction::InstructionConsumer<InputInstruction> for InputState{
@ -97,6 +97,8 @@ enum MouseInterpolation {
First,//just checks the last value
Lerp,//lerps between
}
//hey dumbass just use a delta
pub struct MouseInterpolationState {
interpolation: MouseInterpolation,
time0: TIME,
@ -169,12 +171,12 @@ pub struct Camera {
#[inline]
fn mat3_from_rotation_y_f64(angle: f64) -> glam::Mat3 {
let (sina, cosa) = angle.sin_cos();
glam::Mat3::from_cols(
glam::Vec3::new(cosa as f32, 0.0, -sina as f32),
glam::Vec3::Y,
glam::Vec3::new(sina as f32, 0.0, cosa as f32),
)
let (sina, cosa) = angle.sin_cos();
glam::Mat3::from_cols(
glam::Vec3::new(cosa as f32, 0.0, -sina as f32),
glam::Vec3::Y,
glam::Vec3::new(sina as f32, 0.0, cosa as f32),
)
}
#[inline]
fn perspective_rh(fov_x_slope: f32, fov_y_slope: f32, z_near: f32, z_far: f32) -> glam::Mat4 {
@ -190,11 +192,11 @@ fn perspective_rh(fov_x_slope: f32, fov_y_slope: f32, z_near: f32, z_far: f32) -
impl Camera {
pub fn from_offset(offset:glam::Vec3,aspect:f32) -> Self {
Self{
offset,
angles: glam::DVec2::ZERO,
fov: glam::vec2(aspect,1.0),
sensitivity: glam::dvec2(1.0/6144.0,1.0/6144.0),
time: 0,
offset,
angles: glam::DVec2::ZERO,
fov: glam::vec2(aspect,1.0),
sensitivity: glam::dvec2(1.0/16384.0,1.0/16384.0),
time: 0,
}
}
fn simulate_move_angles(&self, delta: glam::IVec2) -> glam::DVec2 {
@ -218,65 +220,120 @@ impl Camera {
}
}
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::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;
pub struct GameMechanicsState{
pub stage_id:u32,
//jump_counts:HashMap<u32,u32>,
}
impl std::default::Default for GameMechanicsState{
fn default() -> Self {
Self{
stage_id:0,
}
}
if controls & CONTROL_MOVEBACK == CONTROL_MOVEBACK {
control_dir+=-FORWARD_DIR;
}
if controls & CONTROL_MOVELEFT == CONTROL_MOVELEFT {
control_dir+=-RIGHT_DIR;
}
if controls & CONTROL_MOVERIGHT == CONTROL_MOVERIGHT {
control_dir+=RIGHT_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 body: Body,
pub hitbox_halfsize: glam::Vec3,
pub contacts: std::collections::HashSet::<RelativeCollision>,
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),
}
}
}
impl StyleModifiers{
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
}
fn get_control_dir(&self,controls:u32)->glam::Vec3{
//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
}
}
pub struct PhysicsState{
pub time:TIME,
pub body:Body,
pub world:WorldState,//currently there is only one state the world can be in
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 models: Vec<ModelPhysics>,
//camera must exist in state because wormholes modify the camera, also camera punch
pub camera: Camera,
pub mouse_interpolation: MouseInterpolationState,
pub controls: u32,
pub time: TIME,
pub strafe_tick_num: TIME,
pub strafe_tick_den: TIME,
pub tick: u32,
pub mv: f32,
pub walk: WalkState,
pub walkspeed: f32,
pub friction: f32,
pub walk_accel: f32,
pub gravity: glam::Vec3,
pub grounded: bool,
pub spawn_point: glam::Vec3,
pub camera:Camera,
pub mouse_interpolation:MouseInterpolationState,
pub controls:u32,
pub walk:WalkState,
pub grounded:bool,
//all models
pub models:Vec<ModelPhysics>,
pub modes:Vec<crate::model::ModeDescription>,
pub mode_from_mode_id:std::collections::HashMap::<u32,usize>,
//the spawn point is where you spawn when you load into the map.
//This is not the same as Reset which teleports you to Spawn0
pub spawn_point:glam::Vec3,
}
#[derive(Debug,Clone,Copy,Hash,Eq,PartialEq)]
@ -388,20 +445,42 @@ impl Aabb {
type TreyMeshFace = AabbFace;
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 {
//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.
mesh: TreyMesh,
transform:glam::Affine3A,
attributes:PhysicsCollisionAttributes,
}
impl ModelPhysics {
pub fn from_model(model:&crate::model::IndexedModel,model_transform:glam::Affine3A) -> Self {
fn from_model_transform_attributes(model:&crate::model::IndexedModel,transform:&glam::Affine3A,attributes:PhysicsCollisionAttributes)->Self{
let mut aabb=Aabb::new();
for indexed_vertex in &model.unique_vertices {
aabb.grow(model_transform.transform_point3(glam::Vec3::from_array(model.unique_pos[indexed_vertex.pos as usize])));
aabb.grow(transform.transform_point3(glam::Vec3::from_array(model.unique_pos[indexed_vertex.pos as usize])));
}
Self{
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] {
@ -440,11 +519,14 @@ pub struct 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 {
return models.get(self.model as usize).unwrap().face_mesh(self.face).clone()
return self.model(models).unwrap().face_mesh(self.face).clone()
}
pub fn normal(&self,models:&Vec<ModelPhysics>) -> glam::Vec3 {
return models.get(self.model as usize).unwrap().face_normal(self.face)
return self.model(models).unwrap().face_normal(self.face)
}
}
@ -475,6 +557,19 @@ impl Body {
}
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
pub fn run(&mut self, time_limit:TIME){
//prepare is ommitted - everything is done via instructions.
@ -501,7 +596,7 @@ impl PhysicsState {
}
fn contact_constrain_velocity(&self,velocity:&mut glam::Vec3){
for contact in self.contacts.iter() {
for (_,contact) in &self.contacts {
let n=contact.normal(&self.models);
let d=velocity.dot(n);
if d<0f32{
@ -510,7 +605,7 @@ impl PhysicsState {
}
}
fn contact_constrain_acceleration(&self,acceleration:&mut glam::Vec3){
for contact in self.contacts.iter() {
for (_,contact) in &self.contacts {
let n=contact.normal(&self.models);
let d=acceleration.dot(n);
if d<0f32{
@ -520,7 +615,7 @@ impl PhysicsState {
}
fn next_strafe_instruction(&self) -> Option<TimedInstruction<PhysicsInstruction>> {
return Some(TimedInstruction{
time:(self.time*self.strafe_tick_num/self.strafe_tick_den+1)*self.strafe_tick_den/self.strafe_tick_num,
time:(self.time*self.style.strafe_tick_num/self.style.strafe_tick_den+1)*self.style.strafe_tick_den/self.style.strafe_tick_num,
//only poll the physics if there is a before and after mouse event
instruction:PhysicsInstruction::StrafeTick
});
@ -570,7 +665,7 @@ impl PhysicsState {
self.body.acceleration=a;
self.walk.state=WalkEnum::Reached;
}else{
let accel=self.walk_accel.min(self.gravity.length()*self.friction);
let accel=self.style.walk_accel.min(self.style.gravity.length()*self.style.friction);
let time_delta=target_diff.length()/accel;
let mut a=target_diff/time_delta;
self.contact_constrain_acceleration(&mut a);
@ -599,7 +694,7 @@ impl PhysicsState {
fn mesh(&self) -> TreyMesh {
let mut aabb=Aabb::new();
for vertex in Aabb::unit_vertices(){
aabb.grow(self.body.position+self.hitbox_halfsize*vertex);
aabb.grow(self.body.position+self.style.hitbox_halfsize*vertex);
}
aabb
}
@ -883,12 +978,19 @@ impl crate::instruction::InstructionEmitter<PhysicsInstruction> for PhysicsState
//JUST POLLING!!! NO MUTATION
let mut collector = crate::instruction::InstructionCollector::new(time_limit);
//check for collision stop instructions with curent contacts
for collision_data in self.contacts.iter() {
for (_,collision_data) in &self.contacts {
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!!)
for i in 0..self.models.len() {
collector.collect(self.predict_collision_start(self.time,time_limit,i as u32));
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
@ -904,63 +1006,116 @@ 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::StrafeTick => (),
PhysicsInstruction::Input(InputInstruction::MoveMouse(_)) => (),
_=>println!("{:?}",ins),
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(_)
|PhysicsInstruction::SetSpawnPosition(_)
|PhysicsInstruction::ReachWalkTargetVelocity
|PhysicsInstruction::CollisionStart(_)
|PhysicsInstruction::CollisionEnd(_)
|PhysicsInstruction::StrafeTick => self.advance_time(ins.time),
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) => {
//check ground
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;
if self.grounded&&self.controls&CONTROL_JUMP!=0{
self.jump();
let model=c.model(&self.models).unwrap();
match &model.attributes{
PhysicsCollisionAttributes::Contact{contacting,general}=>{
match &contacting.surf{
Some(surf)=>println!("I'm surfing!"),
None=>match &c.face {
AabbFace::Top => {
//ground
self.grounded=true;
},
_ => (),
},
}
match &general.booster{
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();
}
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) => {
self.contacts.remove(&c);//remove contact before calling contact_constrain_acceleration
let mut a=self.gravity;
self.contact_constrain_acceleration(&mut a);
self.body.acceleration=a;
//check ground
match &c.face {
AabbFace::Top => {
self.grounded=false;
},
_ => (),
}
self.refresh_walk_target();
let model=c.model(&self.models).unwrap();
match &model.attributes{
PhysicsCollisionAttributes::Contact{contacting,general}=>{
self.contacts.remove(&c.model);//remove contact before calling contact_constrain_acceleration
let mut a=self.style.gravity;
self.contact_constrain_acceleration(&mut a);
self.body.acceleration=a;
//check ground
match &c.face {
AabbFace::Top => {
self.grounded=false;
},
_ => (),
}
self.refresh_walk_target();
},
PhysicsCollisionAttributes::Intersect{intersecting,general}=>{
self.intersects.remove(&c.model);
},
}
},
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 control_dir=camera_mat*get_control_dir(self.controls);
let control_dir=camera_mat*self.style.get_control_dir(self.controls);
let d=self.body.velocity.dot(control_dir);
if d<self.mv {
let mut v=self.body.velocity+(self.mv-d)*control_dir;
if d<self.style.mv {
let mut v=self.body.velocity+(self.style.mv-d)*control_dir;
self.contact_constrain_velocity(&mut v);
self.body.velocity=v;
}
@ -976,64 +1131,50 @@ impl crate::instruction::InstructionConsumer<PhysicsInstruction> for PhysicsStat
self.walk.state=WalkEnum::Reached;
},
PhysicsInstruction::Input(input_instruction) => {
let mut refresh_walk_target=false;
let mut refresh_walk_target=true;
let mut refresh_walk_target_velocity=true;
match input_instruction{
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);
refresh_walk_target=true;
},
InputInstruction::MoveForward(s) => {
self.set_control(CONTROL_MOVEFORWARD,s);
refresh_walk_target=true;
},
InputInstruction::MoveLeft(s) => {
self.set_control(CONTROL_MOVELEFT,s);
refresh_walk_target=true;
},
InputInstruction::MoveBack(s) => {
self.set_control(CONTROL_MOVEBACK,s);
refresh_walk_target=true;
},
InputInstruction::MoveRight(s) => {
self.set_control(CONTROL_MOVERIGHT,s);
refresh_walk_target=true;
},
InputInstruction::MoveUp(s) => {
self.set_control(CONTROL_MOVEUP,s);
refresh_walk_target=true;
},
InputInstruction::MoveDown(s) => {
self.set_control(CONTROL_MOVEDOWN,s);
refresh_walk_target=true;
},
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(CONTROL_JUMP,s);
refresh_walk_target=true;
self.set_control(StyleModifiers::CONTROL_JUMP,s);
if self.grounded{
self.jump();
}
refresh_walk_target_velocity=false;
},
InputInstruction::Zoom(s) => {
self.set_control(CONTROL_ZOOM,s);
self.set_control(StyleModifiers::CONTROL_ZOOM,s);
refresh_walk_target=false;
},
InputInstruction::Reset => {
//temp
self.body.position=self.spawn_point;
self.body.velocity=glam::Vec3::ZERO;
//manual clear //for c in self.contacts{process_instruction(CollisionEnd(c))}
self.contacts.clear();
self.body.acceleration=self.gravity;
self.body.acceleration=self.style.gravity;
self.walk.state=WalkEnum::Reached;
self.grounded=false;
refresh_walk_target=false;
},
InputInstruction::Idle => (),//literally idle!
InputInstruction::Idle => {refresh_walk_target=false;},//literally idle!
}
//calculate control dir
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*get_control_dir(self.controls);
//calculate walk target velocity
if refresh_walk_target{
self.walk.target_velocity=self.walkspeed*control_dir;
//calculate 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 control_dir=camera_mat*self.style.get_control_dir(self.controls);
self.walk.target_velocity=self.style.walkspeed*control_dir;
}
self.refresh_walk_target();
}
},

@ -51,8 +51,9 @@ pub trait Example: 'static + Sized {
device: &wgpu::Device,
queue: &wgpu::Queue,
);
fn update(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, event: WindowEvent);
fn device_event(&mut self, event: DeviceEvent);
fn update(&mut self, window: &winit::window::Window, device: &wgpu::Device, queue: &wgpu::Queue, event: WindowEvent);
fn device_event(&mut self, window: &winit::window::Window, event: DeviceEvent);
fn load_file(&mut self, path:std::path::PathBuf, device: &wgpu::Device, queue: &wgpu::Queue);
fn render(
&mut self,
view: &wgpu::TextureView,
@ -367,14 +368,14 @@ fn start<E: Example>(
println!("{:#?}", instance.generate_report());
}
_ => {
example.update(&device,&queue,event);
example.update(&window,&device,&queue,event);
}
},
event::Event::DeviceEvent {
event,
..
} => {
example.device_event(event);
example.device_event(&window,event);
},
event::Event::RedrawRequested(_) => {

@ -1,5 +1,3 @@
use crate::model::{IndexedModelInstances,ModelInstance};
use crate::primitives;
fn class_is_a(class: &str, superclass: &str) -> bool {
@ -32,13 +30,89 @@ fn get_texture_refs(dom:&rbx_dom_weak::WeakDom) -> Vec<rbx_dom_weak::types::Ref>
//next class
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 RobloxAssetIdParseErr;
impl std::str::FromStr for RobloxAssetId {
type Err=RobloxAssetIdParseErr;
fn from_str(s: &str) -> Result<Self, Self::Err>{
let regman=regex::Regex::new(r"(\d+)$").unwrap();
let regman=lazy_regex::regex!(r"(\d+)$");
if let Some(captures) = regman.captures(s) {
if captures.len()==2{//captures[0] is all captures concatenated, and then each individual capture
if let Ok(id) = captures[0].parse::<u64>() {
@ -111,7 +185,7 @@ enum RobloxBasePartDescription{
Wedge(RobloxWedgeDescription),
CornerWedge(RobloxCornerWedgeDescription),
}
pub fn generate_indexed_models_roblox(dom:rbx_dom_weak::WeakDom) -> Result<(IndexedModelInstances,glam::Vec3), Box<dyn std::error::Error>>{
pub fn generate_indexed_models(dom:rbx_dom_weak::WeakDom) -> crate::model::IndexedModelInstances{
//IndexedModelInstances includes textures
let mut spawn_point=glam::Vec3::ZERO;
@ -129,13 +203,17 @@ pub fn generate_indexed_models_roblox(dom:rbx_dom_weak::WeakDom) -> Result<(Inde
if let (
Some(rbx_dom_weak::types::Variant::CFrame(cf)),
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::Color3uint8(color3)),
Some(rbx_dom_weak::types::Variant::Bool(can_collide)),
) = (
object.properties.get("CFrame"),
object.properties.get("Size"),
object.properties.get("Velocity"),
object.properties.get("Transparency"),
object.properties.get("Color"),
object.properties.get("CanCollide"),
)
{
let model_transform=glam::Affine3A::from_translation(
@ -151,14 +229,35 @@ pub fn generate_indexed_models_roblox(dom:rbx_dom_weak::WeakDom) -> Result<(Inde
* glam::Affine3A::from_scale(
glam::Vec3::new(size.x,size.y,size.z)/2.0
);
if object.name=="MapStart"{
spawn_point=model_transform.transform_point3(glam::Vec3::Y)+glam::vec3(0.0,2.5,0.0);
println!("Found MapStart{:?}",spawn_point);
}
if *transparency==1.0 {
continue;
//push TempIndexedAttributes
let mut force_intersecting=false;
let mut temp_indexing_attributes=Vec::new();
if let Some(attr)=match &object.name[..]{
"MapStart"=>{
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
let shape=match &object.class[..]{
"Part"=>{
if let Some(rbx_dom_weak::types::Variant::Enum(shape))=object.properties.get("Shape"){
@ -168,14 +267,10 @@ pub fn generate_indexed_models_roblox(dom:rbx_dom_weak::WeakDom) -> Result<(Inde
2=>primitives::Primitives::Cylinder,
3=>primitives::Primitives::Wedge,
4=>primitives::Primitives::CornerWedge,
_=>{
println!("Funky roblox PartType={}; defaulting to cube",shape.to_u32());
primitives::Primitives::Cube
},
_=>panic!("Funky roblox PartType={};",shape.to_u32()),
}
}else{
println!("Part has no Shape! defaulting to cube");
primitives::Primitives::Cube
panic!("Part has no Shape!");
}
},
"WedgePart"=>primitives::Primitives::Wedge,
@ -186,38 +281,6 @@ pub fn generate_indexed_models_roblox(dom:rbx_dom_weak::WeakDom) -> Result<(Inde
}
};
//TODO: also detect "CylinderMesh" etc here
let mut face_map=std::collections::HashMap::new();
match shape{
primitives::Primitives::Cube => {
face_map.insert(0,0);//Right
face_map.insert(1,1);//Top
face_map.insert(2,2);//Back
face_map.insert(3,3);//Left
face_map.insert(4,4);//Bottom
face_map.insert(5,5);//Front
},
primitives::Primitives::Wedge => {
face_map.insert(0,0);//Right
face_map.insert(1,1);//Top -> TopFront (some surf maps put surf textures on the Top face)
face_map.insert(2,1);//Front -> TopFront
face_map.insert(3,2);//Back
face_map.insert(4,3);//Left
face_map.insert(5,4);//Bottom
},
primitives::Primitives::CornerWedge => {
//Right -> None
face_map.insert(1,0);//Top
//Back -> None
face_map.insert(3,1);//Right
face_map.insert(4,2);//Bottom
face_map.insert(5,3);//Front
},
//do not support textured spheres/cylinders imported from roblox
//this can be added later, there are some maps that use it
primitives::Primitives::Sphere
|primitives::Primitives::Cylinder => (),
}
//use the biggest one and cut it down later...
let mut part_texture_description:RobloxPartDescription=[None,None,None,None,None,None];
temp_objects.clear();
@ -245,7 +308,7 @@ pub fn generate_indexed_models_roblox(dom:rbx_dom_weak::WeakDom) -> Result<(Inde
texture_id
};
let normal_id=normalid.to_u32();
if let Some(&face)=face_map.get(&normal_id){
if normal_id<6{
let mut roblox_texture_transform=RobloxTextureTransform::default();
let mut roblox_texture_color=glam::Vec4::ONE;
if decal.class=="Texture"{
@ -269,7 +332,7 @@ pub fn generate_indexed_models_roblox(dom:rbx_dom_weak::WeakDom) -> Result<(Inde
3=>(size.z,size.y),//left
4=>(size.x,size.z),//bottom
5=>(size.x,size.y),//front
_=>(1.,1.),
_=>panic!("unreachable"),
};
roblox_texture_transform=RobloxTextureTransform{
offset_u:*ox/(*sx),offset_v:*oy/(*sy),
@ -278,7 +341,7 @@ pub fn generate_indexed_models_roblox(dom:rbx_dom_weak::WeakDom) -> Result<(Inde
roblox_texture_color=glam::vec4(decal_color3.r,decal_color3.g,decal_color3.b,1.0-*decal_transparency);
}
}
part_texture_description[face]=Some(RobloxFaceTextureDescription{
part_texture_description[normal_id as usize]=Some(RobloxFaceTextureDescription{
texture:texture_id,
color:roblox_texture_color,
transform:roblox_texture_transform,
@ -291,16 +354,34 @@ pub fn generate_indexed_models_roblox(dom:rbx_dom_weak::WeakDom) -> Result<(Inde
}
}
//obscure rust syntax "slice pattern"
let [f0,f1,f2,f3,f4,f5]=part_texture_description;
let [
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{
primitives::Primitives::Sphere=>RobloxBasePartDescription::Sphere,
primitives::Primitives::Cube=>RobloxBasePartDescription::Part([f0,f1,f2,f3,f4,f5]),
primitives::Primitives::Cylinder=>RobloxBasePartDescription::Cylinder,
//HAHAHA
primitives::Primitives::Wedge=>RobloxBasePartDescription::Wedge([f0,f1,f2,f3,f4]),
primitives::Primitives::CornerWedge=>RobloxBasePartDescription::CornerWedge([f0,f1,f2,f3]),
//use front face texture first and use top face texture as a fallback
primitives::Primitives::Wedge=>RobloxBasePartDescription::Wedge([
f0,//Cube::Right->Wedge::Right
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 crated 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){
//push to existing texture model
model_id
@ -370,15 +451,19 @@ pub fn generate_indexed_models_roblox(dom:rbx_dom_weak::WeakDom) -> Result<(Inde
});
model_id
};
indexed_models[model_id].instances.push(ModelInstance {
indexed_models[model_id].instances.push(crate::model::ModelInstance {
transform:model_transform,
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,
});
}
}
}
Ok((IndexedModelInstances{
crate::model::IndexedModelInstances{
textures:asset_id_from_texture_id.iter().map(|t|t.to_string()).collect(),
models:indexed_models,
},spawn_point))
spawn_point,
modes:Vec::new(),
}
}

@ -11,6 +11,7 @@ mod framework;
mod primitives;
mod instruction;
mod load_roblox;
mod worker;
struct Entity {
index_count: u32,
@ -38,15 +39,13 @@ pub struct GraphicsBindGroups {
skybox_texture: wgpu::BindGroup,
}
pub struct GraphicsPipelines {
pub struct GraphicsPipelines{
skybox: wgpu::RenderPipeline,
model: wgpu::RenderPipeline,
}
pub struct GraphicsData {
start_time: std::time::Instant,
pub struct GraphicsState{
screen_size: (u32, u32),
physics: body::PhysicsState,
pipelines: GraphicsPipelines,
bind_groups: GraphicsBindGroups,
bind_group_layouts: GraphicsBindGroupLayouts,
@ -58,7 +57,20 @@ pub struct GraphicsData {
staging_belt: wgpu::util::StagingBelt,
}
impl GraphicsData {
impl GraphicsState{
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;
fn create_depth_texture(
@ -84,89 +96,162 @@ impl GraphicsData {
}
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{
self.physics.models.push(body::ModelPhysics::from_model(&model,model_instance.transform));
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,mut indexed_models:model::IndexedModelInstances){
fn generate_model_graphics(&mut self,device:&wgpu::Device,queue:&wgpu::Queue,indexed_models:model::IndexedModelInstances){
//generate texture view per texture
//idk how to do this gooder lol
let mut double_map=std::collections::HashMap::<u32,u32>::new();
let mut texture_views:Vec<wgpu::TextureView>=Vec::with_capacity(indexed_models.textures.len());
for (i,t) in indexed_models.textures.iter().enumerate(){
if let Ok(mut file) = std::fs::File::open(std::path::Path::new(&format!("textures/{}.dds",t))){
let image = ddsfile::Dds::read(&mut file).unwrap();
let (mut width,mut height)=(image.get_width(),image.get_height());
let format=match image.header10.unwrap().dxgi_format{
ddsfile::DxgiFormat::R8G8B8A8_UNorm_sRGB => wgpu::TextureFormat::Rgba8UnormSrgb,
ddsfile::DxgiFormat::BC7_UNorm_sRGB => {
//floor(w,4), should be ceil(w,4)
width=width/4*4;
height=height/4*4;
wgpu::TextureFormat::Bc7RgbaUnormSrgb
},
other=>panic!("unsupported format {:?}",other),
};
let size = wgpu::Extent3d {
width,
height,
depth_or_array_layers: 1,
};
let layer_size = wgpu::Extent3d {
depth_or_array_layers: 1,
..size
};
let max_mips = layer_size.max_mips(wgpu::TextureDimension::D2);
let texture = device.create_texture_with_data(
queue,
&wgpu::TextureDescriptor {
size,
mip_level_count: max_mips,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
label: Some(format!("Texture{}",i).as_str()),
view_formats: &[],
},
&image.data,
);
double_map.insert(i as u32, texture_views.len() as u32);
texture_views.push(texture.create_view(&wgpu::TextureViewDescriptor {
label: Some(format!("Texture{} View",i).as_str()),
dimension: Some(wgpu::TextureViewDimension::D2),
..wgpu::TextureViewDescriptor::default()
}));
let mut texture_loading_threads=Vec::new();
let num_textures=indexed_models.textures.len();
for (i,texture_id) in indexed_models.textures.into_iter().enumerate(){
if let Ok(mut file) = std::fs::File::open(std::path::Path::new(&format!("textures/{}.dds",texture_id))){
double_map.insert(i as u32, texture_loading_threads.len() as u32);
texture_loading_threads.push((texture_id,std::thread::spawn(move ||{
ddsfile::Dds::read(&mut file).unwrap()
})));
}
}
let indexed_models_len=indexed_models.models.len();
let texture_views:Vec<wgpu::TextureView>=texture_loading_threads.into_iter().map(|(texture_id,thread)|{
let image=thread.join().unwrap();
let (mut width,mut height)=(image.get_width(),image.get_height());
let format=match image.header10.unwrap().dxgi_format{
ddsfile::DxgiFormat::R8G8B8A8_UNorm_sRGB => wgpu::TextureFormat::Rgba8UnormSrgb,
ddsfile::DxgiFormat::BC7_UNorm_sRGB => {
//floor(w,4), should be ceil(w,4)
width=width/4*4;
height=height/4*4;
wgpu::TextureFormat::Bc7RgbaUnormSrgb
},
other=>panic!("unsupported format {:?}",other),
};
let size = wgpu::Extent3d {
width,
height,
depth_or_array_layers: 1,
};
let layer_size = wgpu::Extent3d {
depth_or_array_layers: 1,
..size
};
let max_mips = layer_size.max_mips(wgpu::TextureDimension::D2);
let texture = device.create_texture_with_data(
queue,
&wgpu::TextureDescriptor {
size,
mip_level_count: max_mips,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
label: Some(format!("Texture{}",texture_id).as_str()),
view_formats: &[],
},
&image.data,
);
texture.create_view(&wgpu::TextureViewDescriptor {
label: Some(format!("Texture{} View",texture_id).as_str()),
dimension: Some(wgpu::TextureViewDimension::D2),
..wgpu::TextureViewDescriptor::default()
})
}).collect();
//split groups with different textures into separate models
//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 mut unique_texture_models=Vec::with_capacity(indexed_models.models.len());
for mut model in indexed_models.models.drain(..){
let indexed_models_len=indexed_models.models.len();
let mut unique_texture_models=Vec::with_capacity(indexed_models_len);
for model in indexed_models.models.into_iter(){
//convert ModelInstance into ModelGraphicsInstance
let instances:Vec<ModelGraphicsInstance>=model.instances.iter().map(|instance|{
ModelGraphicsInstance{
transform: glam::Mat4::from(instance.transform),
normal_transform: glam::Mat4::from(instance.transform.inverse()).transpose(),
color: instance.color,
let instances:Vec<ModelGraphicsInstance>=model.instances.into_iter().filter_map(|instance|{
if instance.color.w==0.0{
None
}else{
Some(ModelGraphicsInstance{
transform: glam::Mat4::from(instance.transform),
normal_transform: glam::Mat4::from(instance.transform.inverse()).transpose(),
color: instance.color,
})
}
}).collect();
//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 mut unique_textures=Vec::new();
for group in model.groups.drain(..){
for group in model.groups.into_iter(){
//ignore zero coppy optimization for now
let texture_index=if let Some(texture_index)=unique_textures.iter().position(|&texture|texture==group.texture){
texture_index
@ -193,7 +278,7 @@ impl GraphicsData {
}
//de-index models
let mut models=Vec::with_capacity(unique_texture_models.len());
for model in unique_texture_models.drain(..){
for model in unique_texture_models.into_iter(){
let mut vertices = Vec::new();
let mut index_from_vertex = std::collections::HashMap::new();//::<IndexedVertex,usize>
let mut entities = Vec::new();
@ -230,13 +315,13 @@ impl GraphicsData {
texture:model.texture,
});
}
//drain the modeldata vec so entities can be /moved/ to models.entities
//.into_iter() the modeldata vec so entities can be /moved/ to models.entities
let mut model_count=0;
let mut instance_count=0;
let uniform_buffer_binding_size=<GraphicsData as framework::Example>::required_limits().max_uniform_buffer_binding_size as usize;
let uniform_buffer_binding_size=<GlobalState as framework::Example>::required_limits().max_uniform_buffer_binding_size as usize;
let chunk_size=uniform_buffer_binding_size/MODEL_BUFFER_SIZE_BYTES;
self.models.reserve(models.len());
for model in models.drain(..) {
self.graphics.models.reserve(models.len());
for model in models.into_iter() {
instance_count+=model.instances.len();
for instances_chunk in model.instances.rchunks(chunk_size){
model_count+=1;
@ -250,13 +335,13 @@ impl GraphicsData {
Some(texture_id)=>{
match double_map.get(&texture_id){
Some(&mapped_texture_id)=>&texture_views[mapped_texture_id as usize],
None=>&self.temp_squid_texture_view,
None=>&self.graphics.temp_squid_texture_view,
}
},
None=>&self.temp_squid_texture_view,
None=>&self.graphics.temp_squid_texture_view,
};
let model_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
layout: &self.bind_group_layouts.model,
layout: &self.graphics.bind_group_layouts.model,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
@ -268,7 +353,7 @@ impl GraphicsData {
},
wgpu::BindGroupEntry {
binding: 2,
resource: wgpu::BindingResource::Sampler(&self.samplers.repeat),
resource: wgpu::BindingResource::Sampler(&self.graphics.samplers.repeat),
},
],
label: Some(format!("Model{} Bind Group",model_count).as_str()),
@ -279,7 +364,7 @@ impl GraphicsData {
usage: wgpu::BufferUsages::VERTEX,
});
//all of these are being moved here
self.models.push(ModelGraphics{
self.graphics.models.push(ModelGraphics{
instances:instances_chunk.to_vec(),
vertex_buf,
entities: model.entities.iter().map(|indices|{
@ -298,10 +383,10 @@ impl GraphicsData {
});
}
}
println!("Texture References={}",indexed_models.textures.len());
println!("Texture References={}",num_textures);
println!("Textures Loaded={}",texture_views.len());
println!("Indexed Models={}",indexed_models_len);
println!("Graphics Objects: {}",self.models.len());
println!("Graphics Objects: {}",self.graphics.models.len());
println!("Graphics Instances: {}",instance_count);
}
}
@ -337,7 +422,7 @@ fn to_uniform_data(camera: &body::Camera, pos: glam::Vec3) -> [f32; 16 * 3 + 4]
raw
}
impl framework::Example for GraphicsData {
impl framework::Example for GlobalState {
fn optional_features() -> wgpu::Features {
wgpu::Features::TEXTURE_COMPRESSION_ASTC
| wgpu::Features::TEXTURE_COMPRESSION_ETC2
@ -362,34 +447,44 @@ impl framework::Example for GraphicsData {
println!("models.len = {:?}", indexed_models.len());
indexed_models[0].instances.push(ModelInstance{
transform:glam::Affine3A::from_translation(glam::vec3(10.,0.,-10.)),
color:glam::Vec4::ONE,
..Default::default()
});
//quad monkeys
indexed_models[1].instances.push(ModelInstance{
transform:glam::Affine3A::from_translation(glam::vec3(10.,5.,10.)),
color:glam::Vec4::ONE,
..Default::default()
});
indexed_models[1].instances.push(ModelInstance{
transform:glam::Affine3A::from_translation(glam::vec3(20.,5.,10.)),
color:glam::vec4(1.0,0.0,0.0,1.0),
..Default::default()
});
indexed_models[1].instances.push(ModelInstance{
transform:glam::Affine3A::from_translation(glam::vec3(10.,5.,20.)),
color:glam::vec4(0.0,1.0,0.0,1.0),
..Default::default()
});
indexed_models[1].instances.push(ModelInstance{
transform:glam::Affine3A::from_translation(glam::vec3(20.,5.,20.)),
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
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.)),
color:glam::Vec4::ONE,
..Default::default()
});
//ground
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)),
color:glam::Vec4::ONE,
..Default::default()
});
let camera_bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
@ -491,22 +586,19 @@ impl framework::Example for GraphicsData {
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,
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,
style:body::StyleModifiers::default(),
grounded: false,
walkspeed: 18.0,
contacts: std::collections::HashSet::new(),
contacts: std::collections::HashMap::new(),
intersects: std::collections::HashMap::new(),
models: Vec::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)),
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
@ -736,10 +828,8 @@ impl framework::Example for GraphicsData {
let depth_view = Self::create_depth_texture(config, device);
let mut graphics=GraphicsData {
start_time: Instant::now(),
let graphics=GraphicsState {
screen_size: (config.width,config.height),
physics,
pipelines:GraphicsPipelines{
skybox:sky_pipeline,
model:model_pipeline
@ -757,85 +847,109 @@ impl framework::Example for GraphicsData {
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{
textures:Vec::new(),
models:indexed_models,
spawn_point:glam::Vec3::Y*50.0,
modes:Vec::new(),
};
graphics.generate_model_physics(&indexed_model_instances);
graphics.generate_model_graphics(&device,&queue,indexed_model_instances);
state.generate_model_physics(&indexed_model_instances);
state.generate_model_graphics(&device,&queue,indexed_model_instances);
return graphics;
let args:Vec<String>=std::env::args().collect();
if args.len()==2{
state.load_file(std::path::PathBuf::from(&args[1]), device, queue);
}
return state;
}
fn load_file(&mut self,path: std::path::PathBuf, device: &wgpu::Device, queue: &wgpu::Queue){
println!("Loading file: {:?}", &path);
//oh boy! let's load the map!
if let Ok(file)=std::fs::File::open(path){
let mut input = std::io::BufReader::new(file);
let mut first_8=[0u8;8];
//.rbxm roblox binary = "<roblox!"
//.rbxmx roblox xml = "<roblox "
//.bsp = "VBSP"
//.vmf =
//.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"=>{
match match &first_8[4..8]{
b"lox!"=>rbx_binary::from_reader(input).map_err(|e|format!("{:?}",e)),
b"lox "=>rbx_xml::from_reader(input,rbx_xml::DecodeOptions::default()).map_err(|e|format!("{:?}",e)),
other=>Err(format!("Unknown Roblox file type {:?}",other)),
}{
Ok(dom)=>Some(load_roblox::generate_indexed_models(dom)),
Err(e)=>{
println!("Error loading roblox file:{:?}",e);
None
},
}
},
//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=>{
println!("loser file {:?}",other);
None
},
}
}{
let spawn_point=indexed_model_instances.spawn_point;
//if generate_indexed_models succeeds, clear the previous ones
self.physics.clear();
self.graphics.clear();
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");
}
}else{
println!("Failed to read first 8 bytes and seek back to beginning of file.");
}
}else{
println!("Could not open file");
}
}
#[allow(clippy::single_match)]
fn update(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, event: winit::event::WindowEvent) {
//nothing atm
fn update(&mut self, window: &winit::window::Window, device: &wgpu::Device, queue: &wgpu::Queue, event: winit::event::WindowEvent) {
match event {
winit::event::WindowEvent::DroppedFile(path) => {
println!("opening file: {:?}", &path);
//oh boy! let's load the map!
if let Ok(file)=std::fs::File::open(path){
let mut input = std::io::BufReader::new(file);
let mut first_8=[0u8;8];
//.rbxm roblox binary = "<roblox!"
//.rbxmx roblox xml = "<roblox "
//.bsp = "VBSP"
//.vmf =
//.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(Ok((indexed_model_instances,spawn_point)))={
match &first_8[0..4]{
b"<rob"=>{
match match &first_8[4..8]{
b"lox!"=>rbx_binary::from_reader(input).map_err(|e|format!("{:?}",e)),
b"lox "=>rbx_xml::from_reader(input,rbx_xml::DecodeOptions::default()).map_err(|e|format!("{:?}",e)),
other=>Err(format!("Unknown Roblox file type {:?}",other)),
}{
Ok(dom)=>Some(load_roblox::generate_indexed_models_roblox(dom)),
Err(e)=>{
println!("Error loading roblox file:{:?}",e);
None
},
}
},
//b"VBSP"=>load_valve::generate_indexed_models_valve(input),
//b"SNFM"=>sniffer::generate_indexed_models(input),
//b"SNFB"=>sniffer::load_bot(input),
_=>None,
}
}{
//if generate_indexed_models succeeds, clear the previous ones
self.models.clear();
self.physics.models.clear();
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");
}
}else{
println!("Failed to read first 8 bytes and seek back to beginning of file.");
}
}else{
println!("Could not open file");
}
},
winit::event::WindowEvent::DroppedFile(path) => self.load_file(path,device,queue),
winit::event::WindowEvent::Focused(state)=>{
//pause unpause
//recalculate pressed keys on focus
}
_=>(),
}
}
fn device_event(&mut self, event: winit::event::DeviceEvent) {
fn device_event(&mut self, window: &winit::window::Window, event: winit::event::DeviceEvent) {
//there's no way this is the best way get a timestamp.
let time=self.start_time.elapsed().as_nanos() as i64;
match event {
@ -849,18 +963,58 @@ impl framework::Example for GraphicsData {
winit::event::ElementState::Released => false,
};
if let Some(input_instruction)=match keycode {
17 => Some(InputInstruction::MoveForward(s)),//W
30 => Some(InputInstruction::MoveLeft(s)),//A
31 => Some(InputInstruction::MoveBack(s)),//S
32 => Some(InputInstruction::MoveRight(s)),//D
18 => Some(InputInstruction::MoveUp(s)),//E
16 => Some(InputInstruction::MoveDown(s)),//Q
57 => Some(InputInstruction::Jump(s)),//Space
44 => Some(InputInstruction::Zoom(s)),//Z
19 => if s{Some(InputInstruction::Reset)}else{None},//R
_ => None,
}
{
17=>Some(InputInstruction::MoveForward(s)),//W
30=>Some(InputInstruction::MoveLeft(s)),//A
31=>Some(InputInstruction::MoveBack(s)),//S
32=>Some(InputInstruction::MoveRight(s)),//D
18=>Some(InputInstruction::MoveUp(s)),//E
16=>Some(InputInstruction::MoveDown(s)),//Q
57=>Some(InputInstruction::Jump(s)),//Space
44=>Some(InputInstruction::Zoom(s)),//Z
19=>if s{Some(InputInstruction::Reset)}else{None},//R
01=>{//Esc
if s{
self.manual_mouse_lock=false;
match window.set_cursor_grab(winit::window::CursorGrabMode::None){
Ok(())=>(),
Err(e)=>println!("Could not release cursor: {:?}",e),
}
window.set_cursor_visible(true);
}
None
},
15=>{//Tab
if s{
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)){
Ok(())=>(),
Err(e)=>println!("Could not set cursor position: {:?}",e),
}
match window.set_cursor_grab(winit::window::CursorGrabMode::None){
Ok(())=>(),
Err(e)=>println!("Could not release cursor: {:?}",e),
}
}else{
//if cursor is outside window don't lock but apparently there's no get pos function
//let pos=window.get_cursor_pos();
match window.set_cursor_grab(winit::window::CursorGrabMode::Locked){
Ok(())=>(),
Err(_)=>{
match window.set_cursor_grab(winit::window::CursorGrabMode::Confined){
Ok(())=>(),
Err(e)=>{
self.manual_mouse_lock=true;
println!("Could not confine cursor: {:?}",e)
},
}
}
}
}
window.set_cursor_visible(s);
None
},
_ => {println!("scancode {}",keycode);None},
}{
self.physics.run(time);
self.physics.process_instruction(TimedInstruction{
time,
@ -871,6 +1025,12 @@ impl framework::Example for GraphicsData {
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.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),
}
}
//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.
@ -882,8 +1042,8 @@ impl framework::Example for GraphicsData {
winit::event::DeviceEvent::MouseWheel {
delta,
} => {
println!("mousewheel{:?}",delta);
if true{//self.physics.use_scroll
println!("mousewheel {:?}",delta);
if false{//self.physics.style.use_scroll{
self.physics.run(time);
self.physics.process_instruction(TimedInstruction{
time,
@ -901,8 +1061,8 @@ impl framework::Example for GraphicsData {
device: &wgpu::Device,
_queue: &wgpu::Queue,
) {
self.depth_view = Self::create_depth_texture(config, device);
self.screen_size = (config.width, config.height);
self.graphics.depth_view = Self::create_depth_texture(config, device);
self.graphics.screen_size = (config.width, config.height);
self.physics.camera.set_fov_aspect(1.0,(config.width as f32)/(config.height as f32));
}
@ -922,19 +1082,19 @@ impl framework::Example for GraphicsData {
// update rotation
let camera_uniforms = to_uniform_data(&self.physics.camera,self.physics.body.extrapolated_position(time));
self.staging_belt
self.graphics.staging_belt
.write_buffer(
&mut encoder,
&self.camera_buf,
&self.graphics.camera_buf,
0,
wgpu::BufferSize::new((camera_uniforms.len() * 4) as wgpu::BufferAddress).unwrap(),
device,
)
.copy_from_slice(bytemuck::cast_slice(&camera_uniforms));
//This code only needs to run when the uniforms change
for model in self.models.iter() {
for model in self.graphics.models.iter() {
let model_uniforms = get_instances_buffer_data(&model.instances);
self.staging_belt
self.graphics.staging_belt
.write_buffer(
&mut encoder,
&model.model_buf,//description of where data will be written when command is executed
@ -944,7 +1104,7 @@ impl framework::Example for GraphicsData {
)
.copy_from_slice(bytemuck::cast_slice(&model_uniforms));
}
self.staging_belt.finish();
self.graphics.staging_belt.finish();
{
let mut rpass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
@ -963,7 +1123,7 @@ impl framework::Example for GraphicsData {
},
})],
depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
view: &self.depth_view,
view: &self.graphics.depth_view,
depth_ops: Some(wgpu::Operations {
load: wgpu::LoadOp::Clear(1.0),
store: false,
@ -972,11 +1132,11 @@ impl framework::Example for GraphicsData {
}),
});
rpass.set_bind_group(0, &self.bind_groups.camera, &[]);
rpass.set_bind_group(1, &self.bind_groups.skybox_texture, &[]);
rpass.set_bind_group(0, &self.graphics.bind_groups.camera, &[]);
rpass.set_bind_group(1, &self.graphics.bind_groups.skybox_texture, &[]);
rpass.set_pipeline(&self.pipelines.model);
for model in self.models.iter() {
rpass.set_pipeline(&self.graphics.pipelines.model);
for model in self.graphics.models.iter() {
rpass.set_bind_group(2, &model.bind_group, &[]);
rpass.set_vertex_buffer(0, model.vertex_buf.slice(..));
@ -986,18 +1146,18 @@ impl framework::Example for GraphicsData {
}
}
rpass.set_pipeline(&self.pipelines.skybox);
rpass.set_pipeline(&self.graphics.pipelines.skybox);
rpass.draw(0..3, 0..1);
}
queue.submit(std::iter::once(encoder.finish()));
self.staging_belt.recall();
self.graphics.staging_belt.recall();
}
}
fn main() {
framework::run::<GraphicsData>(
framework::run::<GlobalState>(
format!("Strafe Client v{}",
env!("CARGO_PKG_VERSION")
).as_str()

@ -56,13 +56,176 @@ pub struct ModelGraphicsInstance{
pub color:glam::Vec4,
}
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 color:glam::Vec4,
pub color:glam::Vec4,//transparency is in here
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 textures:Vec<String>,//RenderPattern
pub models:Vec<IndexedModel>,
//object_index for spawns, triggers etc?
//may make this into an object later.
pub modes:Vec<ModeDescription>,
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>{

@ -113,11 +113,11 @@ pub enum CornerWedgeFace{
Front,
}
const CORNERWEDGE_DEFAULT_NORMALS:[[f32;3];5]=[
[ 1., 0., 0.],//Wedge::Right
[ 0., 1., 1.],//Wedge::BackTop
[-1., 1., 0.],//Wedge::LeftTop
[ 0.,-1., 0.],//Wedge::Bottom
[ 0., 0.,-1.],//Wedge::Front
[ 1., 0., 0.],//CornerWedge::Right
[ 0., 1., 1.],//CornerWedge::BackTop
[-1., 1., 0.],//CornerWedge::LeftTop
[ 0.,-1., 0.],//CornerWedge::Bottom
[ 0., 0.,-1.],//CornerWedge::Front
];
//HashMap fits this use case perfectly but feels like using a sledgehammer to drive a nail
pub fn unit_sphere()->crate::model::IndexedModel{
@ -206,7 +206,7 @@ pub fn generate_partial_unit_cube(face_descriptions:CubeFaceDescription)->crate:
let mut groups=Vec::new();
let mut transforms=Vec::new();
//note that on a cube every vertex is guaranteed to be unique, so there's no need to hash them against existing vertices.
for (face,face_description) in face_descriptions.iter(){
for (face,face_description) in face_descriptions.into_iter(){
//assume that scanning short lists is faster than hashing.
let transform_index=if let Some(transform_index)=transforms.iter().position(|&transform|transform==face_description.transform){
transform_index
@ -321,7 +321,7 @@ pub fn generate_partial_unit_wedge(face_descriptions:WedgeFaceDescription)->crat
let mut groups=Vec::new();
let mut transforms=Vec::new();
//note that on a cube every vertex is guaranteed to be unique, so there's no need to hash them against existing vertices.
for (face,face_description) in face_descriptions.iter(){
for (face,face_description) in face_descriptions.into_iter(){
//assume that scanning short lists is faster than hashing.
let transform_index=if let Some(transform_index)=transforms.iter().position(|&transform|transform==face_description.transform){
transform_index
@ -433,7 +433,7 @@ pub fn generate_partial_unit_cornerwedge(face_descriptions:CornerWedgeFaceDescri
let mut groups=Vec::new();
let mut transforms=Vec::new();
//note that on a cube every vertex is guaranteed to be unique, so there's no need to hash them against existing vertices.
for (face,face_description) in face_descriptions.iter(){
for (face,face_description) in face_descriptions.into_iter(){
//assume that scanning short lists is faster than hashing.
let transform_index=if let Some(transform_index)=transforms.iter().position(|&transform|transform==face_description.transform){
transform_index

83
src/worker.rs Normal file

@ -0,0 +1,83 @@
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));
}