Compare commits

..

17 Commits

Author SHA1 Message Date
382ecfa713 its working look at this 2023-09-26 15:54:04 -07:00
28cad39b10 TEMP: teleport to spawn point 2023-09-26 14:36:56 -07:00
2af43480f1 wip 2023-09-26 14:36:08 -07:00
bb7ccd97bb wip 2023-09-26 14:32:33 -07:00
ff7b12e90e add regex dep for load_roblox 2023-09-26 14:31:00 -07:00
e70dc9ad0f keep textures out of git 2023-09-26 14:30:39 -07:00
c5deef8753 support rbxmx 2023-09-26 14:27:00 -07:00
7c2666fdf5 file loader multiplexer, pass dom to load_roblox 2023-09-26 14:26:53 -07:00
6da4c81826 rank device types and ignore user preference 2023-09-25 20:27:14 -07:00
c868a91a06 revert storage buffers: no igpus support 2023-09-25 20:27:14 -07:00
b513e4037d pick adapter better lole 2023-09-25 12:38:53 -07:00
a803ada0e4 zeroes2 inline maybe 2023-09-22 19:42:15 -07:00
eafcbae677 add model.rs 2023-09-22 19:42:15 -07:00
2e786b090f no need for hardcoded image size 2023-09-22 15:20:41 -07:00
70e8f7a0ad delete stupid lib file 2023-09-22 15:19:44 -07:00
48091fc15d print loaded object count for physics and graphics 2023-09-22 02:24:31 -07:00
23857d38d9 no reason to double reference 2023-09-21 20:56:24 -07:00
12 changed files with 811 additions and 673 deletions

1
.gitignore vendored

@ -1 +1,2 @@
/target /target
/textures

24
Cargo.lock generated

@ -1442,6 +1442,20 @@ dependencies = [
"thiserror", "thiserror",
] ]
[[package]]
name = "rbx_xml"
version = "0.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4bc65b70827519fdc4ab47416d1085b912f087fadab9ed415471b6daba635574"
dependencies = [
"base64",
"log",
"rbx_dom_weak",
"rbx_reflection",
"rbx_reflection_database",
"xml-rs",
]
[[package]] [[package]]
name = "redox_syscall" name = "redox_syscall"
version = "0.3.5" version = "0.3.5"
@ -1453,9 +1467,9 @@ dependencies = [
[[package]] [[package]]
name = "regex" name = "regex"
version = "1.9.4" version = "1.9.5"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "12de2eff854e5fa4b1295edd650e227e9d8fb0c9e90b12e7f36d6a6811791a29" checksum = "697061221ea1b4a94a624f67d0ae2bfe4e22b8a17b6a192afb11046542cc8c47"
dependencies = [ dependencies = [
"aho-corasick", "aho-corasick",
"memchr", "memchr",
@ -1465,9 +1479,9 @@ dependencies = [
[[package]] [[package]]
name = "regex-automata" name = "regex-automata"
version = "0.3.7" version = "0.3.8"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "49530408a136e16e5b486e883fbb6ba058e8e4e8ae6621a77b048b314336e629" checksum = "c2f401f4955220693b56f8ec66ee9c78abffd8d1c4f23dc41a23839eb88f0795"
dependencies = [ dependencies = [
"aho-corasick", "aho-corasick",
"memchr", "memchr",
@ -1658,6 +1672,8 @@ dependencies = [
"rbx_binary", "rbx_binary",
"rbx_dom_weak", "rbx_dom_weak",
"rbx_reflection_database", "rbx_reflection_database",
"rbx_xml",
"regex",
"wgpu", "wgpu",
"winit", "winit",
] ]

@ -17,6 +17,8 @@ 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"
regex = "1.9.5"
wgpu = "0.17.0" wgpu = "0.17.0"
winit = "0.28.6" winit = "0.28.6"

@ -4,7 +4,11 @@ use crate::{instruction::{InstructionEmitter, InstructionConsumer, TimedInstruct
pub enum PhysicsInstruction { pub enum PhysicsInstruction {
CollisionStart(RelativeCollision), CollisionStart(RelativeCollision),
CollisionEnd(RelativeCollision), CollisionEnd(RelativeCollision),
SetControlDir(glam::Vec3),
StrafeTick, StrafeTick,
Jump,
SetWalkTargetVelocity(glam::Vec3),
RefreshWalkTarget,
ReachWalkTargetVelocity, ReachWalkTargetVelocity,
// Water, // Water,
// Spawn( // Spawn(
@ -14,21 +18,6 @@ pub enum PhysicsInstruction {
// ) // )
//temp //temp
SetPosition(glam::Vec3), SetPosition(glam::Vec3),
//Both of these conditionally activate RefreshWalkTarget (by doing what SetWalkTargetVelocity used to do and then flagging it)
Input(InputInstruction),
}
#[derive(Debug)]
pub enum InputInstruction {
MoveMouse(glam::IVec2),
MoveForward(bool),
MoveLeft(bool),
MoveBack(bool),
MoveRight(bool),
MoveUp(bool),
MoveDown(bool),
Jump(bool),
Zoom(bool),
Reset,
} }
pub struct Body { pub struct Body {
@ -64,35 +53,34 @@ pub enum MoveRestriction {
Ladder,//multiple ladders how Ladder,//multiple ladders how
} }
/*
enum InputInstruction {
}
struct InputState {
}
impl InputState {
pub fn get_control(&self,control:u32) -> bool {
self.controls&control!=0
}
}
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)
}
}
impl crate::instruction::InstructionConsumer<InputInstruction> for InputState{
fn process_instruction(&mut self,ins:TimedInstruction<InputInstruction>){
//add to queue
self.queue.push(ins);
}
}
*/
enum MouseInterpolation { enum MouseInterpolation {
First,//just checks the last value First,//just checks the last value
Lerp,//lerps between Lerp,//lerps between
} }
enum InputInstruction {
MoveMouse(glam::IVec2),
Jump(bool),
}
struct InputState {
controls: u32,
mouse_interpolation: MouseInterpolation,
time: TIME,
}
impl InputState {
pub fn get_control(&self,control:u32) -> bool {
self.controls&control!=0
}
pub fn process_instruction(&mut self,ins:InputInstruction){
match ins {
InputInstruction::MoveMouse(m) => todo!("set mouse_interpolation"),
InputInstruction::Jump(b) => todo!("how does info about style modifiers get here"),
}
}
}
pub struct MouseInterpolationState { pub struct MouseInterpolationState {
interpolation: MouseInterpolation, interpolation: MouseInterpolation,
time0: TIME, time0: TIME,
@ -102,20 +90,11 @@ pub struct MouseInterpolationState {
} }
impl MouseInterpolationState { impl MouseInterpolationState {
pub fn new() -> Self { pub fn move_mouse(&mut self,time:TIME,pos:glam::IVec2){
Self {
interpolation:MouseInterpolation::First,
time0:0,
time1:1,//ONE NANOSECOND!!!! avoid divide by zero
mouse0:glam::IVec2::ZERO,
mouse1:glam::IVec2::ZERO,
}
}
pub fn move_mouse(&mut self,time:TIME,delta:glam::IVec2){
self.time0=self.time1; self.time0=self.time1;
self.mouse0=self.mouse1; self.mouse0=self.mouse1;
self.time1=time; self.time1=time;
self.mouse1=self.mouse1+delta; self.mouse1=pos;
} }
pub fn interpolated_position(&self,time:TIME) -> glam::IVec2 { pub fn interpolated_position(&self,time:TIME) -> glam::IVec2 {
match self.interpolation { match self.interpolation {
@ -136,6 +115,7 @@ impl MouseInterpolationState {
pub enum WalkEnum{ pub enum WalkEnum{
Reached, Reached,
Transient, Transient,
Invalid,
} }
pub struct WalkState { pub struct WalkState {
pub target_velocity: glam::Vec3, pub target_velocity: glam::Vec3,
@ -147,120 +127,22 @@ impl WalkState {
Self{ Self{
target_velocity:glam::Vec3::ZERO, target_velocity:glam::Vec3::ZERO,
target_time:0, target_time:0,
state:WalkEnum::Reached, state:WalkEnum::Invalid,
} }
} }
} }
// Note: we use the Y=up coordinate space in this example.
pub struct Camera {
offset: glam::Vec3,
angles: glam::DVec2,//YAW AND THEN PITCH
//punch: glam::Vec3,
//punch_velocity: glam::Vec3,
fov: glam::Vec2,//slope
sensitivity: glam::DVec2,
time: TIME,
}
#[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),
)
}
#[inline]
fn perspective_rh(fov_x_slope: f32, fov_y_slope: f32, z_near: f32, z_far: f32) -> glam::Mat4 {
//glam_assert!(z_near > 0.0 && z_far > 0.0);
let r = z_far / (z_near - z_far);
glam::Mat4::from_cols(
glam::Vec4::new(1.0/fov_x_slope, 0.0, 0.0, 0.0),
glam::Vec4::new(0.0, 1.0/fov_y_slope, 0.0, 0.0),
glam::Vec4::new(0.0, 0.0, r, -1.0),
glam::Vec4::new(0.0, 0.0, r * z_near, 0.0),
)
}
impl Camera {
pub fn from_offset(offset:glam::Vec3,aspect:f32) -> Self {
Self{
offset,
angles: glam::DVec2::ZERO,
fov: glam::vec2(aspect,1.0),
sensitivity: glam::dvec2(1.0/2048.0,1.0/2048.0),
time: 0,
}
}
fn simulate_move_angles(&self, delta: glam::IVec2) -> glam::DVec2 {
let mut a=self.angles-self.sensitivity*delta.as_dvec2();
a.y=a.y.clamp(-std::f64::consts::PI, std::f64::consts::PI);
return a
}
fn simulate_move_rotation_y(&self, delta_x: i32) -> glam::Mat3 {
mat3_from_rotation_y_f64(self.angles.x-self.sensitivity.x*(delta_x as f64))
}
pub fn proj(&self)->glam::Mat4{
perspective_rh(self.fov.x, self.fov.y, 0.5, 1000.0)
}
pub fn view(&self,pos:glam::Vec3)->glam::Mat4{
//f32 good enough for view matrix
glam::Mat4::from_translation(pos+self.offset) * glam::Mat4::from_euler(glam::EulerRot::YXZ, self.angles.x as f32, self.angles.y as f32, 0f32)
}
pub fn set_fov_aspect(&mut self,fov:f32,aspect:f32){
self.fov.x=fov*aspect;
self.fov.y=fov;
}
}
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;
}
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 struct PhysicsState {
pub body: Body, pub body: Body,
pub hitbox_halfsize: glam::Vec3, pub hitbox_halfsize: glam::Vec3,
pub contacts: std::collections::HashSet::<RelativeCollision>, pub contacts: std::collections::HashSet::<RelativeCollision>,
//pub intersections: Vec<ModelId>, //pub intersections: Vec<ModelId>,
pub models: Vec<ModelPhysics>, pub models: Vec<ModelPhysics>,
//temp
pub temp_control_dir: glam::Vec3,
//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 time: TIME, pub time: TIME,
pub strafe_tick_num: TIME, pub strafe_tick_num: TIME,
pub strafe_tick_den: TIME, pub strafe_tick_den: TIME,
@ -272,6 +154,7 @@ pub struct PhysicsState {
pub walk_accel: f32, pub walk_accel: f32,
pub gravity: glam::Vec3, pub gravity: glam::Vec3,
pub grounded: bool, pub grounded: bool,
pub jump_trying: bool,
} }
#[derive(Debug,Clone,Copy,Hash,Eq,PartialEq)] #[derive(Debug,Clone,Copy,Hash,Eq,PartialEq)]
@ -472,6 +355,8 @@ impl PhysicsState {
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.
while let Some(instruction) = self.next_instruction(time_limit) {//collect while let Some(instruction) = self.next_instruction(time_limit) {//collect
//advance
//self.advance_time(instruction.time);
//process //process
self.process_instruction(instruction); self.process_instruction(instruction);
//write hash lol //write hash lol
@ -483,16 +368,6 @@ impl PhysicsState {
self.time=time; self.time=time;
} }
fn set_control(&mut self,control:u32,state:bool){
self.controls=if state{self.controls|control}else{self.controls&!control};
}
fn jump(&mut self){
self.grounded=false;//do I need this?
let mut v=self.body.velocity+glam::Vec3::new(0.0,0.715588/2.0*100.0,0.0);
self.contact_constrain_velocity(&mut v);
self.body.velocity=v;
}
fn contact_constrain_velocity(&self,velocity:&mut glam::Vec3){ fn contact_constrain_velocity(&self,velocity:&mut glam::Vec3){
for contact in self.contacts.iter() { for contact in self.contacts.iter() {
let n=contact.normal(&self.models); let n=contact.normal(&self.models);
@ -511,6 +386,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.strafe_tick_num/self.strafe_tick_den+1)*self.strafe_tick_den/self.strafe_tick_num, time:(self.time*self.strafe_tick_num/self.strafe_tick_den+1)*self.strafe_tick_den/self.strafe_tick_num,
@ -550,31 +426,6 @@ impl PhysicsState {
// }); // });
// } // }
fn refresh_walk_target(&mut self){
//calculate acceleration yada yada
if self.grounded{
let mut v=self.walk.target_velocity;
self.contact_constrain_velocity(&mut v);
let mut target_diff=v-self.body.velocity;
target_diff.y=0f32;
if target_diff==glam::Vec3::ZERO{
let mut a=glam::Vec3::ZERO;
self.contact_constrain_acceleration(&mut a);
self.body.acceleration=a;
self.walk.state=WalkEnum::Reached;
}else{
let accel=self.walk_accel.min(self.gravity.length()*self.friction);
let time_delta=target_diff.length()/accel;
let mut a=target_diff/time_delta;
self.contact_constrain_acceleration(&mut a);
self.body.acceleration=a;
self.walk.target_time=self.body.time+((time_delta as f64)*1_000_000_000f64) as TIME;
self.walk.state=WalkEnum::Transient;
}
}else{
self.walk.state=WalkEnum::Reached;//there is no walk target while not grounded
}
}
fn next_walk_instruction(&self) -> Option<TimedInstruction<PhysicsInstruction>> { fn next_walk_instruction(&self) -> Option<TimedInstruction<PhysicsInstruction>> {
//check if you have a valid walk state and create an instruction //check if you have a valid walk state and create an instruction
if self.grounded{ if self.grounded{
@ -583,6 +434,10 @@ impl PhysicsState {
time:self.walk.target_time, time:self.walk.target_time,
instruction:PhysicsInstruction::ReachWalkTargetVelocity instruction:PhysicsInstruction::ReachWalkTargetVelocity
}), }),
WalkEnum::Invalid=>Some(TimedInstruction{
time:self.time,
instruction:PhysicsInstruction::RefreshWalkTarget,
}),
WalkEnum::Reached=>None, WalkEnum::Reached=>None,
} }
}else{ }else{
@ -898,18 +753,19 @@ impl crate::instruction::InstructionConsumer<PhysicsInstruction> for PhysicsStat
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(_)) => (),
_=>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::SetWalkTargetVelocity(_)
PhysicsInstruction::SetPosition(_) => self.time=ins.time,//TODO: queue instructions |PhysicsInstruction::SetPosition(_)
PhysicsInstruction::Input(_) |PhysicsInstruction::SetControlDir(_) => self.time=ins.time,//TODO: queue instructions
PhysicsInstruction::RefreshWalkTarget
|PhysicsInstruction::ReachWalkTargetVelocity |PhysicsInstruction::ReachWalkTargetVelocity
|PhysicsInstruction::CollisionStart(_) |PhysicsInstruction::CollisionStart(_)
|PhysicsInstruction::CollisionEnd(_) |PhysicsInstruction::CollisionEnd(_)
|PhysicsInstruction::StrafeTick => self.advance_time(ins.time), |PhysicsInstruction::StrafeTick
|PhysicsInstruction::Jump => self.advance_time(ins.time),
} }
match ins.instruction { match ins.instruction {
PhysicsInstruction::SetPosition(position)=>{ PhysicsInstruction::SetPosition(position)=>{
@ -935,16 +791,14 @@ impl crate::instruction::InstructionConsumer<PhysicsInstruction> for PhysicsStat
let mut v=self.body.velocity; let mut v=self.body.velocity;
self.contact_constrain_velocity(&mut v); self.contact_constrain_velocity(&mut v);
self.body.velocity=v; self.body.velocity=v;
if self.grounded&&self.controls&CONTROL_JUMP!=0{ self.walk.state=WalkEnum::Invalid;
self.jump();
}
self.refresh_walk_target();
}, },
PhysicsInstruction::CollisionEnd(c) => { PhysicsInstruction::CollisionEnd(c) => {
self.contacts.remove(&c);//remove contact before calling contact_constrain_acceleration self.contacts.remove(&c);//remove contact before calling contact_constrain_acceleration
let mut a=self.gravity; let mut a=self.gravity;
self.contact_constrain_acceleration(&mut a); self.contact_constrain_acceleration(&mut a);
self.body.acceleration=a; self.body.acceleration=a;
self.walk.state=WalkEnum::Invalid;
//check ground //check ground
match &c.face { match &c.face {
AabbFace::Top => { AabbFace::Top => {
@ -952,18 +806,27 @@ impl crate::instruction::InstructionConsumer<PhysicsInstruction> for PhysicsStat
}, },
_ => (), _ => (),
} }
self.refresh_walk_target(); },
PhysicsInstruction::SetControlDir(control_dir)=>{
self.temp_control_dir=control_dir;
self.walk.state=WalkEnum::Invalid;
}, },
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 control_dir=self.get_control_dir();//this should respect your mouse interpolation settings
let control_dir=camera_mat*get_control_dir(self.controls); let d=self.body.velocity.dot(self.temp_control_dir);
let d=self.body.velocity.dot(control_dir);
if d<self.mv { if d<self.mv {
let mut v=self.body.velocity+(self.mv-d)*control_dir; let mut v=self.body.velocity+(self.mv-d)*self.temp_control_dir;
self.contact_constrain_velocity(&mut v); self.contact_constrain_velocity(&mut v);
self.body.velocity=v; self.body.velocity=v;
} }
} }
PhysicsInstruction::Jump => {
self.grounded=false;//do I need this?
let mut v=self.body.velocity+glam::Vec3::new(0.0,0.715588/2.0*100.0,0.0);
self.contact_constrain_velocity(&mut v);
self.body.velocity=v;
self.walk.state=WalkEnum::Invalid;
},
PhysicsInstruction::ReachWalkTargetVelocity => { PhysicsInstruction::ReachWalkTargetVelocity => {
//precisely set velocity //precisely set velocity
let mut a=glam::Vec3::ZERO; let mut a=glam::Vec3::ZERO;
@ -974,59 +837,33 @@ impl crate::instruction::InstructionConsumer<PhysicsInstruction> for PhysicsStat
self.body.velocity=v; self.body.velocity=v;
self.walk.state=WalkEnum::Reached; self.walk.state=WalkEnum::Reached;
}, },
PhysicsInstruction::Input(input_instruction) => { PhysicsInstruction::RefreshWalkTarget => {
let mut refresh_walk_target=false; //calculate acceleration yada yada
match input_instruction{ if self.grounded{
InputInstruction::MoveMouse(m) => { let mut v=self.walk.target_velocity;
self.camera.angles=self.camera.simulate_move_angles(self.mouse_interpolation.mouse1-self.mouse_interpolation.mouse0); self.contact_constrain_velocity(&mut v);
self.mouse_interpolation.move_mouse(self.time,m); let mut target_diff=v-self.body.velocity;
refresh_walk_target=true; target_diff.y=0f32;
}, if target_diff==glam::Vec3::ZERO{
InputInstruction::MoveForward(s) => { let mut a=glam::Vec3::ZERO;
self.set_control(CONTROL_MOVEFORWARD,s); self.contact_constrain_acceleration(&mut a);
refresh_walk_target=true; self.body.acceleration=a;
}, self.walk.state=WalkEnum::Reached;
InputInstruction::MoveLeft(s) => { }else{
self.set_control(CONTROL_MOVELEFT,s); let accel=self.walk_accel.min(self.gravity.length()*self.friction);
refresh_walk_target=true; let time_delta=target_diff.length()/accel;
}, let mut a=target_diff/time_delta;
InputInstruction::MoveBack(s) => { self.contact_constrain_acceleration(&mut a);
self.set_control(CONTROL_MOVEBACK,s); self.body.acceleration=a;
refresh_walk_target=true; self.walk.target_time=self.body.time+((time_delta as f64)*1_000_000_000f64) as TIME;
}, self.walk.state=WalkEnum::Transient;
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::Jump(s) => {
self.set_control(CONTROL_JUMP,s);
refresh_walk_target=true;
if self.grounded{
self.jump();
}
},
InputInstruction::Zoom(s) => {
self.set_control(CONTROL_ZOOM,s);
},
InputInstruction::Reset => println!("reset"),
}
//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;
self.refresh_walk_target();
} }
}, },
PhysicsInstruction::SetWalkTargetVelocity(v) => {
self.walk.target_velocity=v;
self.walk.state=WalkEnum::Invalid;
},
} }
} }
} }

@ -1,10 +1,12 @@
use std::future::Future; use std::future::Future;
#[cfg(target_arch = "wasm32")] #[cfg(target_arch = "wasm32")]
use std::str::FromStr; use std::str::FromStr;
#[cfg(not(target_arch = "wasm32"))]
use std::time::Instant;
#[cfg(target_arch = "wasm32")] #[cfg(target_arch = "wasm32")]
use web_sys::{ImageBitmapRenderingContext, OffscreenCanvas}; use web_sys::{ImageBitmapRenderingContext, OffscreenCanvas};
use winit::{ use winit::{
event::{self, WindowEvent, DeviceEvent}, event::{self, WindowEvent},
event_loop::{ControlFlow, EventLoop}, event_loop::{ControlFlow, EventLoop},
}; };
@ -51,8 +53,8 @@ pub trait Example: 'static + Sized {
device: &wgpu::Device, device: &wgpu::Device,
queue: &wgpu::Queue, queue: &wgpu::Queue,
); );
fn update(&mut self, device: &wgpu::Device, event: WindowEvent); fn update(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, event: WindowEvent);
fn device_event(&mut self, event: DeviceEvent); fn move_mouse(&mut self, delta: (f64,f64));
fn render( fn render(
&mut self, &mut self,
view: &wgpu::TextureView, view: &wgpu::TextureView,
@ -179,9 +181,41 @@ async fn setup<E: Example>(title: &str) -> Setup {
(size, surface) (size, surface)
}; };
let adapter = wgpu::util::initialize_adapter_from_env_or_default(&instance, Some(&surface))
.await let adapter;
.expect("No suitable GPU adapters found on the system!");
let optional_features = E::optional_features();
let required_features = E::required_features();
//no helper function smh gotta write it myself
let adapters = instance.enumerate_adapters(backends);
let mut chosen_adapter = None;
let mut chosen_adapter_score=0;
for adapter in adapters {
if !adapter.is_surface_supported(&surface) {
continue;
}
let score=match adapter.get_info().device_type{
wgpu::DeviceType::IntegratedGpu=>3,
wgpu::DeviceType::DiscreteGpu=>4,
wgpu::DeviceType::VirtualGpu=>2,
wgpu::DeviceType::Other|wgpu::DeviceType::Cpu=>1,
};
let adapter_features = adapter.features();
if chosen_adapter_score<score&&adapter_features.contains(required_features) {
chosen_adapter_score=score;
chosen_adapter=Some(adapter);
}
}
if let Some(maybe_chosen_adapter) = chosen_adapter{
adapter=maybe_chosen_adapter;
}else{
panic!("No suitable GPU adapters found on the system!");
}
#[cfg(not(target_arch = "wasm32"))] #[cfg(not(target_arch = "wasm32"))]
{ {
@ -189,15 +223,6 @@ async fn setup<E: Example>(title: &str) -> Setup {
println!("Using {} ({:?})", adapter_info.name, adapter_info.backend); println!("Using {} ({:?})", adapter_info.name, adapter_info.backend);
} }
let optional_features = E::optional_features();
let required_features = E::required_features();
let adapter_features = adapter.features();
assert!(
adapter_features.contains(required_features),
"Adapter does not support required features for this example: {:?}",
required_features - adapter_features
);
let required_downlevel_capabilities = E::required_downlevel_capabilities(); let required_downlevel_capabilities = E::required_downlevel_capabilities();
let downlevel_capabilities = adapter.get_downlevel_capabilities(); let downlevel_capabilities = adapter.get_downlevel_capabilities();
assert!( assert!(
@ -221,7 +246,7 @@ async fn setup<E: Example>(title: &str) -> Setup {
.request_device( .request_device(
&wgpu::DeviceDescriptor { &wgpu::DeviceDescriptor {
label: None, label: None,
features: (optional_features & adapter_features) | required_features, features: (optional_features & adapter.features()) | required_features,
limits: needed_limits, limits: needed_limits,
}, },
trace_dir.ok().as_ref().map(std::path::Path::new), trace_dir.ok().as_ref().map(std::path::Path::new),
@ -344,14 +369,17 @@ fn start<E: Example>(
println!("{:#?}", instance.generate_report()); println!("{:#?}", instance.generate_report());
} }
_ => { _ => {
example.update(&device,event); example.update(&device,&queue,event);
} }
}, },
event::Event::DeviceEvent { event::Event::DeviceEvent {
event, event:
winit::event::DeviceEvent::MouseMotion {
delta,
},
.. ..
} => { } => {
example.device_event(event); example.move_mouse(delta);
}, },
event::Event::RedrawRequested(_) => { event::Event::RedrawRequested(_) => {

@ -1,5 +0,0 @@
pub mod framework;
pub mod body;
pub mod zeroes;
pub mod instruction;
pub mod load_roblox;

@ -1,3 +1,9 @@
use std::todo;
use crate::model::{ModelData,ModelInstance};
use crate::primitives;
fn class_is_a(class: &str, superclass: &str) -> bool { fn class_is_a(class: &str, superclass: &str) -> bool {
if class==superclass { if class==superclass {
return true return true
@ -10,18 +16,125 @@ fn class_is_a(class: &str, superclass: &str) -> bool {
} }
return false return false
} }
pub fn get_objects<R: std::io::Read>(buf_thing: R, superclass: &str) -> Result<std::vec::Vec<rbx_dom_weak::Instance>, Box<dyn std::error::Error>> { fn recursive_collect_superclass(objects: &mut std::vec::Vec<rbx_dom_weak::types::Ref>,dom: &rbx_dom_weak::WeakDom, instance: &rbx_dom_weak::Instance, superclass: &str){
// Using buffered I/O is recommended with rbx_binary for &referent in instance.children() {
let dom = rbx_binary::from_reader(buf_thing)?; if let Some(c) = dom.get_by_ref(referent) {
if class_is_a(c.class.as_str(), superclass) {
let mut objects = std::vec::Vec::<rbx_dom_weak::Instance>::new(); objects.push(c.referent());//copy ref
//move matching instances into objects }
let (_,mut instances) = dom.into_raw(); recursive_collect_superclass(objects,dom,c,superclass);
for (_,instance) in instances.drain() {
if class_is_a(instance.class.as_str(), superclass) {
objects.push(instance);
} }
} }
}
return Ok(objects) fn get_texture_refs(dom:&rbx_dom_weak::WeakDom) -> Vec<rbx_dom_weak::types::Ref>{
let mut objects = std::vec::Vec::new();
recursive_collect_superclass(&mut objects, dom, dom.root(),"Decal");
//get ids
//clear vec
//next class
objects
}
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();
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>() {
return Ok(Self(id));
}
}
}
Err(RobloxAssetIdParseErr)
}
}
pub fn generate_modeldatas_roblox(dom:rbx_dom_weak::WeakDom) -> Result<(Vec<ModelData>,Vec<String>,glam::Vec3), Box<dyn std::error::Error>>{
//ModelData includes texture dds
let mut spawn_point=glam::Vec3::ZERO;
//TODO: generate unit Block, Wedge, etc. after based on part shape lists
let mut modeldatas=crate::model::generate_modeldatas(primitives::the_unit_cube_lol(),ModelData::COLOR_FLOATS_WHITE);
let unit_cube_modeldata=modeldatas[0].clone();
let mut texture_id_from_asset_id=std::collections::HashMap::<u64,u32>::new();
let mut asset_id_from_texture_id=Vec::new();
let mut object_refs = std::vec::Vec::new();
let mut temp_objects = std::vec::Vec::new();
recursive_collect_superclass(&mut object_refs, &dom, dom.root(),"BasePart");
for object_ref in object_refs {
if let Some(object)=dom.get_by_ref(object_ref){
if let (
Some(rbx_dom_weak::types::Variant::CFrame(cf)),
Some(rbx_dom_weak::types::Variant::Vector3(size)),
Some(rbx_dom_weak::types::Variant::Float32(transparency)),
Some(rbx_dom_weak::types::Variant::Color3uint8(color3)),
Some(rbx_dom_weak::types::Variant::Enum(shape)),
) = (
object.properties.get("CFrame"),
object.properties.get("Size"),
object.properties.get("Transparency"),
object.properties.get("Color"),
object.properties.get("Shape"),//this will also skip unions
)
{
let model_instance=ModelInstance {
transform:glam::Mat4::from_translation(
glam::Vec3::new(cf.position.x,cf.position.y,cf.position.z)
)
* glam::Mat4::from_mat3(
glam::Mat3::from_cols(
glam::Vec3::new(cf.orientation.x.x,cf.orientation.y.x,cf.orientation.z.x),
glam::Vec3::new(cf.orientation.x.y,cf.orientation.y.y,cf.orientation.z.y),
glam::Vec3::new(cf.orientation.x.z,cf.orientation.y.z,cf.orientation.z.z),
),
)
* glam::Mat4::from_scale(
glam::Vec3::new(size.x,size.y,size.z)/2.0
),
color: glam::vec4(color3.r as f32/255f32, color3.g as f32/255f32, color3.b as f32/255f32, 1.0-*transparency),
};
if object.name=="MapStart"{
spawn_point=glam::Vec4Swizzles::xyz(model_instance.transform*glam::Vec3::Y.extend(1.0))+glam::vec3(0.0,2.5,0.0);
println!("Found MapStart{:?}",spawn_point);
}
if *transparency==1.0||shape.to_u32()!=1 {
continue;
}
temp_objects.clear();
recursive_collect_superclass(&mut temp_objects, &dom, object,"Decal");
let mut i_can_only_load_one_texture_per_model=None;
for &decal_ref in &temp_objects{
if let Some(decal)=dom.get_by_ref(decal_ref){
if let Some(rbx_dom_weak::types::Variant::Content(content)) = decal.properties.get("Texture") {
if let Ok(asset_id)=content.clone().into_string().parse::<RobloxAssetId>(){
if let Some(&texture_id)=texture_id_from_asset_id.get(&asset_id.0){
i_can_only_load_one_texture_per_model=Some(texture_id);
}else{
let texture_id=asset_id_from_texture_id.len();
texture_id_from_asset_id.insert(asset_id.0,texture_id as u32);
asset_id_from_texture_id.push(asset_id.0);
//make new model
let mut unit_cube_texture=unit_cube_modeldata.clone();
unit_cube_texture.texture=Some(texture_id as u32);
modeldatas.push(unit_cube_texture);
}
}
}
}
}
match i_can_only_load_one_texture_per_model{
//push to existing texture model
Some(texture_id)=>modeldatas[(texture_id+1) as usize].instances.push(model_instance),
//push instance to big unit cube in the sky
None=>modeldatas[0].instances.push(model_instance),
}
}
}
}
Ok((modeldatas,asset_id_from_texture_id.iter().map(|t|t.to_string()).collect(),spawn_point))
} }

@ -1,40 +1,20 @@
use bytemuck::{Pod, Zeroable};
use strafe_client::{instruction::{TimedInstruction, InstructionConsumer},body::{InputInstruction, PhysicsInstruction}};
use std::{borrow::Cow, time::Instant}; use std::{borrow::Cow, time::Instant};
use wgpu::{util::DeviceExt, AstcBlock, AstcChannel}; use wgpu::{util::DeviceExt, AstcBlock, AstcChannel};
use model::{Vertex,ModelData,ModelInstance};
const IMAGE_SIZE: u32 = 128; mod body;
mod model;
#[derive(Clone, Copy, Pod, Zeroable)] mod zeroes;
#[repr(C)] mod framework;
struct Vertex { mod primitives;
pos: [f32; 3], mod instruction;
texture: [f32; 2], mod load_roblox;
normal: [f32; 3],
color: [f32; 4],
}
struct Entity { struct Entity {
index_count: u32, index_count: u32,
index_buf: wgpu::Buffer, index_buf: wgpu::Buffer,
} }
struct ModelInstance {
transform: glam::Mat4,
color: glam::Vec4,
}
struct ModelData {
instances: Vec<ModelInstance>,
vertices: Vec<Vertex>,
entities: Vec<Vec<u16>>,
}
impl ModelData {
const COLOR_FLOATS_WHITE: [f32;4] = [1.0,1.0,1.0,1.0];
const COLOR_VEC4_WHITE: glam::Vec4 = glam::vec4(1.0,1.0,1.0,1.0);
}
struct ModelGraphics { struct ModelGraphics {
instances: Vec<ModelInstance>, instances: Vec<ModelInstance>,
vertex_buf: wgpu::Buffer, vertex_buf: wgpu::Buffer,
@ -43,6 +23,86 @@ struct ModelGraphics {
model_buf: wgpu::Buffer, model_buf: wgpu::Buffer,
} }
// Note: we use the Y=up coordinate space in this example.
struct Camera {
screen_size: (u32, u32),
offset: glam::Vec3,
fov: f32,
yaw: f32,
pitch: f32,
controls: u32,
}
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;
}
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
}
#[inline]
fn perspective_rh(fov_y_slope: f32, aspect_ratio: f32, z_near: f32, z_far: f32) -> glam::Mat4 {
//glam_assert!(z_near > 0.0 && z_far > 0.0);
let r = z_far / (z_near - z_far);
glam::Mat4::from_cols(
glam::Vec4::new(1.0/(fov_y_slope * aspect_ratio), 0.0, 0.0, 0.0),
glam::Vec4::new(0.0, 1.0/fov_y_slope, 0.0, 0.0),
glam::Vec4::new(0.0, 0.0, r, -1.0),
glam::Vec4::new(0.0, 0.0, r * z_near, 0.0),
)
}
impl Camera {
fn to_uniform_data(&self, pos: glam::Vec3) -> [f32; 16 * 3 + 4] {
let aspect = self.screen_size.0 as f32 / self.screen_size.1 as f32;
let fov = if self.controls&CONTROL_ZOOM==0 {
self.fov
}else{
self.fov/5.0
};
let proj = perspective_rh(fov, aspect, 0.5, 1000.0);
let proj_inv = proj.inverse();
let view = glam::Mat4::from_translation(pos+self.offset) * glam::Mat4::from_euler(glam::EulerRot::YXZ, self.yaw, self.pitch, 0f32);
let view_inv = view.inverse();
let mut raw = [0f32; 16 * 3 + 4];
raw[..16].copy_from_slice(&AsRef::<[f32; 16]>::as_ref(&proj)[..]);
raw[16..32].copy_from_slice(&AsRef::<[f32; 16]>::as_ref(&proj_inv)[..]);
raw[32..48].copy_from_slice(&AsRef::<[f32; 16]>::as_ref(&view_inv)[..]);
raw[48..52].copy_from_slice(AsRef::<[f32; 4]>::as_ref(&view.col(3)));
raw
}
}
pub struct GraphicsSamplers{ pub struct GraphicsSamplers{
repeat: wgpu::Sampler, repeat: wgpu::Sampler,
} }
@ -63,8 +123,8 @@ pub struct GraphicsPipelines {
pub struct GraphicsData { pub struct GraphicsData {
start_time: std::time::Instant, start_time: std::time::Instant,
screen_size: (u32, u32), camera: Camera,
physics: strafe_client::body::PhysicsState, physics: body::PhysicsState,
pipelines: GraphicsPipelines, pipelines: GraphicsPipelines,
bind_groups: GraphicsBindGroups, bind_groups: GraphicsBindGroups,
bind_group_layouts: GraphicsBindGroupLayouts, bind_group_layouts: GraphicsBindGroupLayouts,
@ -74,7 +134,6 @@ pub struct GraphicsData {
models: Vec<ModelGraphics>, models: Vec<ModelGraphics>,
depth_view: wgpu::TextureView, depth_view: wgpu::TextureView,
staging_belt: wgpu::util::StagingBelt, staging_belt: wgpu::util::StagingBelt,
handy_unit_cube: obj::ObjData,
} }
impl GraphicsData { impl GraphicsData {
@ -102,115 +161,127 @@ impl GraphicsData {
depth_texture.create_view(&wgpu::TextureViewDescriptor::default()) depth_texture.create_view(&wgpu::TextureViewDescriptor::default())
} }
fn generate_modeldatas_roblox<R: std::io::Read>(&self,input:R) -> (Vec<ModelData>,glam::Vec3){
let mut spawn_point=glam::Vec3::ZERO;
let mut modeldatas=generate_modeldatas(self.handy_unit_cube.clone(),ModelData::COLOR_FLOATS_WHITE);
match strafe_client::load_roblox::get_objects(input, "BasePart") {
Ok(objects)=>{
for object in objects.iter() {
if let (
Some(rbx_dom_weak::types::Variant::CFrame(cf)),
Some(rbx_dom_weak::types::Variant::Vector3(size)),
Some(rbx_dom_weak::types::Variant::Float32(transparency)),
Some(rbx_dom_weak::types::Variant::Color3uint8(color3)),
Some(rbx_dom_weak::types::Variant::Enum(shape)),
) = (
object.properties.get("CFrame"),
object.properties.get("Size"),
object.properties.get("Transparency"),
object.properties.get("Color"),
object.properties.get("Shape"),//this will also skip unions
)
{
let transform=glam::Mat4::from_translation(
glam::Vec3::new(cf.position.x,cf.position.y,cf.position.z)
)
* glam::Mat4::from_mat3(
glam::Mat3::from_cols(
glam::Vec3::new(cf.orientation.x.x,cf.orientation.y.x,cf.orientation.z.x),
glam::Vec3::new(cf.orientation.x.y,cf.orientation.y.y,cf.orientation.z.y),
glam::Vec3::new(cf.orientation.x.z,cf.orientation.y.z,cf.orientation.z.z),
),
)
* glam::Mat4::from_scale(
glam::Vec3::new(size.x,size.y,size.z)/2.0
);
if object.name=="MapStart"{
spawn_point=glam::Vec4Swizzles::xyz(transform*glam::Vec3::Y.extend(1.0))+glam::vec3(0.0,2.5,0.0);
println!("Found MapStart{:?}",spawn_point);
}
if *transparency==1.0||shape.to_u32()!=1 {
continue;
}
modeldatas[0].instances.push(ModelInstance {
transform,
color: glam::vec4(color3.r as f32/255f32, color3.g as f32/255f32, color3.b as f32/255f32, 1.0-*transparency),
})
}
}
},
Err(e) => println!("lmao err {:?}", e),
}
(modeldatas,spawn_point)
}
fn generate_model_physics(&mut self,modeldatas:&Vec<ModelData>){ fn generate_model_physics(&mut self,modeldatas:&Vec<ModelData>){
self.physics.models.append(&mut modeldatas.iter().map(|m| self.physics.models.append(&mut modeldatas.iter().map(|m|
//make aabb and run vertices to get realistic bounds //make aabb and run vertices to get realistic bounds
m.instances.iter().map(|t|strafe_client::body::ModelPhysics::new(t.transform)) m.instances.iter().map(|t|body::ModelPhysics::new(t.transform))
).flatten().collect()); ).flatten().collect());
println!("Physics Objects: {}",self.physics.models.len());
} }
fn generate_model_graphics(&mut self,device:&wgpu::Device,mut modeldatas:Vec<ModelData>){ fn generate_model_graphics(&mut self,device:&wgpu::Device,queue:&wgpu::Queue,mut modeldatas:Vec<ModelData>,textures:Vec<String>){
//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(textures.len());
for (i,t) in 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 size = wgpu::Extent3d {
width: image.get_width()/4*4,//floor(w,4), should be ceil(w,4)
height: image.get_height()/4*4,
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: wgpu::TextureFormat::Bc7RgbaUnorm,
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()
}));
}
}
//drain 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 instance_count=0;
self.models.reserve(modeldatas.len()); self.models.reserve(modeldatas.len());
for (i,modeldata) in modeldatas.drain(..).enumerate() { for (i,modeldata) in modeldatas.drain(..).enumerate() {
let model_uniforms = get_instances_buffer_data(&modeldata.instances); let n_instances=modeldata.instances.len();
let model_buf = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { if 0<n_instances{
label: Some(format!("ModelGraphics{}",i).as_str()), let model_uniforms = get_instances_buffer_data(&modeldata.instances);
contents: bytemuck::cast_slice(&model_uniforms), let model_buf = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST, label: Some(format!("Model{} Buf",i).as_str()),
}); contents: bytemuck::cast_slice(&model_uniforms),
let model_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
layout: &self.bind_group_layouts.model, });
entries: &[ let texture_view=match modeldata.texture{
wgpu::BindGroupEntry { Some(texture_id)=>{
binding: 0, match double_map.get(&texture_id){
resource: model_buf.as_entire_binding(), Some(&mapped_texture_id)=>&texture_views[mapped_texture_id as usize],
None=>&self.temp_squid_texture_view,
}
}, },
wgpu::BindGroupEntry { None=>&self.temp_squid_texture_view,
binding: 1, };
resource: wgpu::BindingResource::TextureView(&self.temp_squid_texture_view), let model_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
}, layout: &self.bind_group_layouts.model,
wgpu::BindGroupEntry { entries: &[
binding: 2, wgpu::BindGroupEntry {
resource: wgpu::BindingResource::Sampler(&self.samplers.repeat), binding: 0,
}, resource: model_buf.as_entire_binding(),
], },
label: Some(format!("ModelGraphics{}",i).as_str()), wgpu::BindGroupEntry {
}); binding: 1,
let vertex_buf = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { resource: wgpu::BindingResource::TextureView(texture_view),
label: Some("Vertex"), },
contents: bytemuck::cast_slice(&modeldata.vertices), wgpu::BindGroupEntry {
usage: wgpu::BufferUsages::VERTEX, binding: 2,
}); resource: wgpu::BindingResource::Sampler(&self.samplers.repeat),
//all of these are being moved here },
self.models.push(ModelGraphics{ ],
instances:modeldata.instances, label: Some(format!("Model{} Bind Group",i).as_str()),
vertex_buf, });
entities: modeldata.entities.iter().map(|indices|{ let vertex_buf = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
let index_buf = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some("Vertex"),
label: Some("Index"), contents: bytemuck::cast_slice(&modeldata.vertices),
contents: bytemuck::cast_slice(&indices), usage: wgpu::BufferUsages::VERTEX,
usage: wgpu::BufferUsages::INDEX, });
}); //all of these are being moved here
Entity { instance_count+=n_instances;
index_buf, self.models.push(ModelGraphics{
index_count: indices.len() as u32, instances:modeldata.instances,
} vertex_buf,
}).collect(), entities: modeldata.entities.iter().map(|indices|{
bind_group: model_bind_group, let index_buf = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
model_buf, label: Some("Index"),
}) contents: bytemuck::cast_slice(&indices),
usage: wgpu::BufferUsages::INDEX,
});
Entity {
index_buf,
index_count: indices.len() as u32,
}
}).collect(),
bind_group: model_bind_group,
model_buf,
});
}else{
println!("WARNING: Model{} has 0 instances",i);
}
} }
println!("Graphics Objects: {}",self.models.len());
println!("Graphics Instances: {}",instance_count);
} }
} }
@ -226,71 +297,12 @@ fn get_instances_buffer_data(instances:&Vec<ModelInstance>) -> Vec<f32> {
raw raw
} }
fn generate_modeldatas(data:obj::ObjData,color:[f32;4]) -> Vec<ModelData>{ impl framework::Example for GraphicsData {
let mut modeldatas=Vec::new();
let mut vertices = Vec::new();
let mut vertex_index = std::collections::HashMap::<obj::IndexTuple,u16>::new();
for object in data.objects {
vertices.clear();
vertex_index.clear();
let mut entities = Vec::new();
for group in object.groups {
let mut indices = Vec::new();
for poly in group.polys {
for end_index in 2..poly.0.len() {
for &index in &[0, end_index - 1, end_index] {
let vert = poly.0[index];
if let Some(&i)=vertex_index.get(&vert){
indices.push(i);
}else{
let i=vertices.len() as u16;
vertices.push(Vertex {
pos: data.position[vert.0],
texture: data.texture[vert.1.unwrap()],
normal: data.normal[vert.2.unwrap()],
color,
});
vertex_index.insert(vert,i);
indices.push(i);
}
}
}
}
entities.push(indices);
}
modeldatas.push(ModelData {
instances: Vec::new(),
vertices:vertices.clone(),
entities,
});
}
modeldatas
}
fn to_uniform_data(camera: &strafe_client::body::Camera, pos: glam::Vec3) -> [f32; 16 * 3 + 4] {
let proj=camera.proj();
let proj_inv = proj.inverse();
let view=camera.view(pos);
let view_inv = view.inverse();
let mut raw = [0f32; 16 * 3 + 4];
raw[..16].copy_from_slice(&AsRef::<[f32; 16]>::as_ref(&proj)[..]);
raw[16..32].copy_from_slice(&AsRef::<[f32; 16]>::as_ref(&proj_inv)[..]);
raw[32..48].copy_from_slice(&AsRef::<[f32; 16]>::as_ref(&view_inv)[..]);
raw[48..52].copy_from_slice(AsRef::<[f32; 4]>::as_ref(&view.col(3)));
raw
}
impl strafe_client::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
| wgpu::Features::TEXTURE_COMPRESSION_BC | wgpu::Features::TEXTURE_COMPRESSION_BC
} }
fn required_features() -> wgpu::Features {
wgpu::Features::STORAGE_RESOURCE_BINDING_ARRAY
}
fn required_limits() -> wgpu::Limits { fn required_limits() -> wgpu::Limits {
wgpu::Limits::default() //framework.rs was using goofy limits that caused me a multi-day headache wgpu::Limits::default() //framework.rs was using goofy limits that caused me a multi-day headache
} }
@ -300,85 +312,12 @@ impl strafe_client::framework::Example for GraphicsData {
device: &wgpu::Device, device: &wgpu::Device,
queue: &wgpu::Queue, queue: &wgpu::Queue,
) -> Self { ) -> Self {
let unit_cube=obj::ObjData{ let unit_cube=primitives::the_unit_cube_lol();
position: vec![
[-1.,-1., 1.],//left bottom back
[ 1.,-1., 1.],//right bottom back
[ 1., 1., 1.],//right top back
[-1., 1., 1.],//left top back
[-1., 1.,-1.],//left top front
[ 1., 1.,-1.],//right top front
[ 1.,-1.,-1.],//right bottom front
[-1.,-1.,-1.],//left bottom front
],
texture: vec![[0.0,0.0],[1.0,0.0],[1.0,1.0],[0.0,1.0]],
normal: vec![
[1.,0.,0.],//AabbFace::Right
[0.,1.,0.],//AabbFace::Top
[0.,0.,1.],//AabbFace::Back
[-1.,0.,0.],//AabbFace::Left
[0.,-1.,0.],//AabbFace::Bottom
[0.,0.,-1.],//AabbFace::Front
],
objects: vec![obj::Object{
name: "Unit Cube".to_owned(),
groups: vec![obj::Group{
name: "Cube Vertices".to_owned(),
index: 0,
material: None,
polys: vec![
// back (0, 0, 1)
obj::SimplePolygon(vec![
obj::IndexTuple(0,Some(0),Some(2)),
obj::IndexTuple(1,Some(1),Some(2)),
obj::IndexTuple(2,Some(2),Some(2)),
obj::IndexTuple(3,Some(3),Some(2)),
]),
// front (0, 0,-1)
obj::SimplePolygon(vec![
obj::IndexTuple(4,Some(0),Some(5)),
obj::IndexTuple(5,Some(1),Some(5)),
obj::IndexTuple(6,Some(2),Some(5)),
obj::IndexTuple(7,Some(3),Some(5)),
]),
// right (1, 0, 0)
obj::SimplePolygon(vec![
obj::IndexTuple(6,Some(0),Some(0)),
obj::IndexTuple(5,Some(1),Some(0)),
obj::IndexTuple(2,Some(2),Some(0)),
obj::IndexTuple(1,Some(3),Some(0)),
]),
// left (-1, 0, 0)
obj::SimplePolygon(vec![
obj::IndexTuple(0,Some(0),Some(3)),
obj::IndexTuple(3,Some(1),Some(3)),
obj::IndexTuple(4,Some(2),Some(3)),
obj::IndexTuple(7,Some(3),Some(3)),
]),
// top (0, 1, 0)
obj::SimplePolygon(vec![
obj::IndexTuple(5,Some(1),Some(1)),
obj::IndexTuple(4,Some(0),Some(1)),
obj::IndexTuple(3,Some(3),Some(1)),
obj::IndexTuple(2,Some(2),Some(1)),
]),
// bottom (0,-1, 0)
obj::SimplePolygon(vec![
obj::IndexTuple(1,Some(1),Some(4)),
obj::IndexTuple(0,Some(0),Some(4)),
obj::IndexTuple(7,Some(3),Some(4)),
obj::IndexTuple(6,Some(2),Some(4)),
]),
],
}]
}],
material_libs: Vec::new(),
};
let mut modeldatas = Vec::<ModelData>::new(); let mut modeldatas = Vec::<ModelData>::new();
modeldatas.append(&mut generate_modeldatas(obj::ObjData::load_buf(&include_bytes!("../models/teslacyberv3.0.obj")[..]).unwrap(),ModelData::COLOR_FLOATS_WHITE)); modeldatas.append(&mut model::generate_modeldatas(obj::ObjData::load_buf(&include_bytes!("../models/teslacyberv3.0.obj")[..]).unwrap(),ModelData::COLOR_FLOATS_WHITE));
modeldatas.append(&mut generate_modeldatas(obj::ObjData::load_buf(&include_bytes!("../models/suzanne.obj")[..]).unwrap(),ModelData::COLOR_FLOATS_WHITE)); modeldatas.append(&mut model::generate_modeldatas(obj::ObjData::load_buf(&include_bytes!("../models/suzanne.obj")[..]).unwrap(),ModelData::COLOR_FLOATS_WHITE));
modeldatas.append(&mut generate_modeldatas(obj::ObjData::load_buf(&include_bytes!("../models/teapot.obj")[..]).unwrap(),ModelData::COLOR_FLOATS_WHITE)); modeldatas.append(&mut model::generate_modeldatas(obj::ObjData::load_buf(&include_bytes!("../models/teapot.obj")[..]).unwrap(),ModelData::COLOR_FLOATS_WHITE));
modeldatas.append(&mut generate_modeldatas(unit_cube.clone(),ModelData::COLOR_FLOATS_WHITE)); modeldatas.append(&mut model::generate_modeldatas(unit_cube.clone(),ModelData::COLOR_FLOATS_WHITE));
println!("models.len = {:?}", modeldatas.len()); println!("models.len = {:?}", modeldatas.len());
modeldatas[0].instances.push(ModelInstance{ modeldatas[0].instances.push(ModelInstance{
transform:glam::Mat4::from_translation(glam::vec3(10.,0.,-10.)), transform:glam::Mat4::from_translation(glam::vec3(10.,0.,-10.)),
@ -455,7 +394,7 @@ impl strafe_client::framework::Example for GraphicsData {
binding: 0, binding: 0,
visibility: wgpu::ShaderStages::VERTEX, visibility: wgpu::ShaderStages::VERTEX,
ty: wgpu::BindingType::Buffer { ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Storage { read_only: true }, ty: wgpu::BufferBindingType::Uniform,
has_dynamic_offset: false, has_dynamic_offset: false,
min_binding_size: None, min_binding_size: None,
}, },
@ -507,8 +446,16 @@ impl strafe_client::framework::Example for GraphicsData {
source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(include_str!("shader.wgsl"))), source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(include_str!("shader.wgsl"))),
}); });
let physics = strafe_client::body::PhysicsState { let camera = Camera {
body: strafe_client::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)), screen_size: (config.width, config.height),
offset: glam::Vec3::new(0.0,4.5-2.5,0.0),
fov: 1.0, //fov_slope = tan(fov_y/2)
pitch: 0.0,
yaw: 0.0,
controls:0,
};
let physics = body::PhysicsState {
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,
tick: 0, tick: 0,
strafe_tick_num: 100,//100t strafe_tick_num: 100,//100t
@ -518,14 +465,13 @@ impl strafe_client::framework::Example for GraphicsData {
walk_accel: 90.0, walk_accel: 90.0,
mv: 2.7, mv: 2.7,
grounded: false, grounded: false,
jump_trying: false,
temp_control_dir: glam::Vec3::ZERO,
walkspeed: 18.0, walkspeed: 18.0,
contacts: std::collections::HashSet::new(), contacts: std::collections::HashSet::new(),
models: Vec::new(), models: Vec::new(),
walk: strafe_client::body::WalkState::new(), walk: body::WalkState::new(),
hitbox_halfsize: glam::vec3(1.0,2.5,1.0), hitbox_halfsize: glam::vec3(1.0,2.5,1.0),
camera: strafe_client::body::Camera::from_offset(glam::vec3(0.0,4.5-2.5,0.0),(config.width as f32)/(config.height as f32)),
mouse_interpolation: strafe_client::body::MouseInterpolationState::new(),
controls: 0,
}; };
//load textures //load textures
@ -549,9 +495,22 @@ impl strafe_client::framework::Example for GraphicsData {
wgpu::TextureFormat::Bgra8UnormSrgb wgpu::TextureFormat::Bgra8UnormSrgb
}; };
let bytes = match skybox_format {
wgpu::TextureFormat::Astc {
block: AstcBlock::B4x4,
channel: AstcChannel::UnormSrgb,
} => &include_bytes!("../images/astc.dds")[..],
wgpu::TextureFormat::Etc2Rgb8UnormSrgb => &include_bytes!("../images/etc2.dds")[..],
wgpu::TextureFormat::Bc1RgbaUnormSrgb => &include_bytes!("../images/bc1.dds")[..],
wgpu::TextureFormat::Bgra8UnormSrgb => &include_bytes!("../images/bgra.dds")[..],
_ => unreachable!(),
};
let skybox_image = ddsfile::Dds::read(&mut std::io::Cursor::new(bytes)).unwrap();
let size = wgpu::Extent3d { let size = wgpu::Extent3d {
width: IMAGE_SIZE, width: skybox_image.get_width(),
height: IMAGE_SIZE, height: skybox_image.get_height(),
depth_or_array_layers: 6, depth_or_array_layers: 6,
}; };
@ -564,24 +523,11 @@ impl strafe_client::framework::Example for GraphicsData {
log::debug!( log::debug!(
"Copying {:?} skybox images of size {}, {}, 6 with {} mips to gpu", "Copying {:?} skybox images of size {}, {}, 6 with {} mips to gpu",
skybox_format, skybox_format,
IMAGE_SIZE, size.width,
IMAGE_SIZE, size.height,
max_mips, max_mips,
); );
let bytes = match skybox_format {
wgpu::TextureFormat::Astc {
block: AstcBlock::B4x4,
channel: AstcChannel::UnormSrgb,
} => &include_bytes!("../images/astc.dds")[..],
wgpu::TextureFormat::Etc2Rgb8UnormSrgb => &include_bytes!("../images/etc2.dds")[..],
wgpu::TextureFormat::Bc1RgbaUnormSrgb => &include_bytes!("../images/bc1.dds")[..],
wgpu::TextureFormat::Bgra8UnormSrgb => &include_bytes!("../images/bgra.dds")[..],
_ => unreachable!(),
};
let skybox_image = ddsfile::Dds::read(&mut std::io::Cursor::new(&bytes)).unwrap();
let skybox_texture = device.create_texture_with_data( let skybox_texture = device.create_texture_with_data(
queue, queue,
&wgpu::TextureDescriptor { &wgpu::TextureDescriptor {
@ -606,9 +552,9 @@ impl strafe_client::framework::Example for GraphicsData {
//squid //squid
let squid_texture_view={ let squid_texture_view={
let bytes = &include_bytes!("../images/squid.dds")[..]; let bytes = include_bytes!("../images/squid.dds");
let image = ddsfile::Dds::read(&mut std::io::Cursor::new(&bytes)).unwrap(); let image = ddsfile::Dds::read(&mut std::io::Cursor::new(bytes)).unwrap();
let size = wgpu::Extent3d { let size = wgpu::Extent3d {
width: image.get_width(), width: image.get_width(),
@ -714,7 +660,7 @@ impl strafe_client::framework::Example for GraphicsData {
multiview: None, multiview: None,
}); });
let camera_uniforms = to_uniform_data(&physics.camera,physics.body.extrapolated_position(0)); let camera_uniforms = camera.to_uniform_data(physics.body.extrapolated_position(0));
let camera_buf = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { let camera_buf = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("Camera"), label: Some("Camera"),
contents: bytemuck::cast_slice(&camera_uniforms), contents: bytemuck::cast_slice(&camera_uniforms),
@ -748,9 +694,8 @@ impl strafe_client::framework::Example for GraphicsData {
let depth_view = Self::create_depth_texture(config, device); let depth_view = Self::create_depth_texture(config, device);
let mut graphics=GraphicsData { let mut graphics=GraphicsData {
handy_unit_cube:unit_cube,
start_time: Instant::now(), start_time: Instant::now(),
screen_size: (config.width,config.height), camera,
physics, physics,
pipelines:GraphicsPipelines{ pipelines:GraphicsPipelines{
skybox:sky_pipeline, skybox:sky_pipeline,
@ -770,97 +715,121 @@ impl strafe_client::framework::Example for GraphicsData {
}; };
graphics.generate_model_physics(&modeldatas); graphics.generate_model_physics(&modeldatas);
graphics.generate_model_graphics(&device,modeldatas); graphics.generate_model_graphics(&device,&queue,modeldatas,Vec::new());
return graphics; return graphics;
} }
#[allow(clippy::single_match)] #[allow(clippy::single_match)]
fn update(&mut self, device: &wgpu::Device, event: winit::event::WindowEvent) { fn update(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, event: winit::event::WindowEvent) {
//nothing atm
match event { match event {
winit::event::WindowEvent::DroppedFile(path) => { winit::event::WindowEvent::DroppedFile(path) => {
println!("opening file: {:?}", &path); println!("opening file: {:?}", &path);
//oh boy! let's load the map! //oh boy! let's load the map!
if let Ok(file)=std::fs::File::open(path){ if let Ok(file)=std::fs::File::open(path){
let input = std::io::BufReader::new(file); let mut input = std::io::BufReader::new(file);
let (modeldatas,spawn_point)=self.generate_modeldatas_roblox(input); let mut first_8=[0u8;8];
//if generate_modeldatas succeeds, clear the previous ones //.rbxm roblox binary = "<roblox!"
self.models.clear(); //.rbxmx roblox xml = "<roblox "
self.physics.models.clear(); //.bsp = "VBSP"
self.generate_model_physics(&modeldatas); //.vmf =
self.generate_model_graphics(device,modeldatas); //.snf = "SNMF"
//manual reset //.snf = "SNBF"
let time=self.physics.time; if let (Ok(()),Ok(()))=(std::io::Read::read_exact(&mut input, &mut first_8),std::io::Seek::rewind(&mut input)){
strafe_client::instruction::InstructionConsumer::process_instruction(&mut self.physics, strafe_client::instruction::TimedInstruction{ //
time, if let Some(Ok((modeldatas,textures,spawn_point)))={
instruction: strafe_client::body::PhysicsInstruction::SetPosition(spawn_point), if &first_8==b"<roblox!"{
}) if let Ok(dom) = rbx_binary::from_reader(input){
Some(load_roblox::generate_modeldatas_roblox(dom))
}else{
None
}
}else if &first_8==b"<roblox "{
if let Ok(dom) = rbx_xml::from_reader(input,rbx_xml::DecodeOptions::default()){
Some(load_roblox::generate_modeldatas_roblox(dom))
}else{
None
}
//}else if &first_8[0..4]==b"VBSP"{
// self.generate_modeldatas_valve(input)
}else{
None
}
}{
//if generate_modeldatas succeeds, clear the previous ones
self.models.clear();
self.physics.models.clear();
self.generate_model_physics(&modeldatas);
self.generate_model_graphics(device,queue,modeldatas,textures);
//manual reset
let time=self.physics.time;
instruction::InstructionConsumer::process_instruction(&mut self.physics, instruction::TimedInstruction{
time,
instruction: body::PhysicsInstruction::SetPosition(spawn_point),
})
}else{
println!("No modeldatas were generated");
}
}else{
println!("Failed ro read first 8 bytes and seek back to beginning of file.");
}
}else{ }else{
println!("Could not open file"); println!("Could not open file");
} }
}, },
_=>(), winit::event::WindowEvent::KeyboardInput {
input:
winit::event::KeyboardInput {
state,
virtual_keycode: Some(keycode),
..
},
..
} => {
match (state,keycode) {
(k,winit::event::VirtualKeyCode::W) => match k {
winit::event::ElementState::Pressed => self.camera.controls|=CONTROL_MOVEFORWARD,
winit::event::ElementState::Released => self.camera.controls&=!CONTROL_MOVEFORWARD,
}
(k,winit::event::VirtualKeyCode::A) => match k {
winit::event::ElementState::Pressed => self.camera.controls|=CONTROL_MOVELEFT,
winit::event::ElementState::Released => self.camera.controls&=!CONTROL_MOVELEFT,
}
(k,winit::event::VirtualKeyCode::S) => match k {
winit::event::ElementState::Pressed => self.camera.controls|=CONTROL_MOVEBACK,
winit::event::ElementState::Released => self.camera.controls&=!CONTROL_MOVEBACK,
}
(k,winit::event::VirtualKeyCode::D) => match k {
winit::event::ElementState::Pressed => self.camera.controls|=CONTROL_MOVERIGHT,
winit::event::ElementState::Released => self.camera.controls&=!CONTROL_MOVERIGHT,
}
(k,winit::event::VirtualKeyCode::E) => match k {
winit::event::ElementState::Pressed => self.camera.controls|=CONTROL_MOVEUP,
winit::event::ElementState::Released => self.camera.controls&=!CONTROL_MOVEUP,
}
(k,winit::event::VirtualKeyCode::Q) => match k {
winit::event::ElementState::Pressed => self.camera.controls|=CONTROL_MOVEDOWN,
winit::event::ElementState::Released => self.camera.controls&=!CONTROL_MOVEDOWN,
}
(k,winit::event::VirtualKeyCode::Space) => match k {
winit::event::ElementState::Pressed => self.camera.controls|=CONTROL_JUMP,
winit::event::ElementState::Released => self.camera.controls&=!CONTROL_JUMP,
}
(k,winit::event::VirtualKeyCode::Z) => match k {
winit::event::ElementState::Pressed => self.camera.controls|=CONTROL_ZOOM,
winit::event::ElementState::Released => self.camera.controls&=!CONTROL_ZOOM,
}
_ => (),
}
}
_ => {}
} }
} }
fn device_event(&mut self, event: winit::event::DeviceEvent) { fn move_mouse(&mut self, delta: (f64,f64)) {
//there's no way this is the best way get a timestamp. self.camera.pitch=(self.camera.pitch as f64+delta.1/-2048.) as f32;
let time=self.start_time.elapsed().as_nanos() as i64; self.camera.yaw=(self.camera.yaw as f64+delta.0/-2048.) as f32;
match event {
winit::event::DeviceEvent::Key(winit::event::KeyboardInput {
state,
scancode: keycode,
..
}) => {
let s=match state {
winit::event::ElementState::Pressed => true,
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,
}
{
self.physics.run(time);
self.physics.process_instruction(TimedInstruction{
time,
instruction:PhysicsInstruction::Input(input_instruction),
})
}
},
winit::event::DeviceEvent::MouseMotion {
delta,//these (f64,f64) are integers on my machine
} => {
//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.
self.physics.process_instruction(TimedInstruction{
time,
instruction:PhysicsInstruction::Input(InputInstruction::MoveMouse(glam::ivec2(delta.0 as i32,delta.1 as i32))),
})
},
winit::event::DeviceEvent::MouseWheel {
delta,
} => {
println!("mousewheel{:?}",delta);
if true{//self.physics.use_scroll
self.physics.run(time);
self.physics.process_instruction(TimedInstruction{
time,
instruction:PhysicsInstruction::Input(InputInstruction::Jump(true)),//activates the immediate jump path, but the style modifier prevents controls&CONTROL_JUMP bit from being set to auto jump
})
}
}
_=>(),
}
} }
fn resize( fn resize(
@ -870,8 +839,7 @@ impl strafe_client::framework::Example for GraphicsData {
_queue: &wgpu::Queue, _queue: &wgpu::Queue,
) { ) {
self.depth_view = Self::create_depth_texture(config, device); self.depth_view = Self::create_depth_texture(config, device);
self.screen_size = (config.width, config.height); self.camera.screen_size = (config.width, config.height);
self.physics.camera.set_fov_aspect(1.0,(config.width as f32)/(config.height as f32));
} }
fn render( fn render(
@ -879,17 +847,47 @@ impl strafe_client::framework::Example for GraphicsData {
view: &wgpu::TextureView, view: &wgpu::TextureView,
device: &wgpu::Device, device: &wgpu::Device,
queue: &wgpu::Queue, queue: &wgpu::Queue,
_spawner: &strafe_client::framework::Spawner, _spawner: &framework::Spawner,
) { ) {
let camera_mat=glam::Mat3::from_rotation_y(self.camera.yaw);
let control_dir=camera_mat*get_control_dir(self.camera.controls&(CONTROL_MOVELEFT|CONTROL_MOVERIGHT|CONTROL_MOVEFORWARD|CONTROL_MOVEBACK)).normalize_or_zero();
let time=self.start_time.elapsed().as_nanos() as i64; let time=self.start_time.elapsed().as_nanos() as i64;
self.physics.run(time); self.physics.run(time);
//ALL OF THIS IS TOTALLY WRONG!!!
let walk_target_velocity=self.physics.walkspeed*control_dir;
//autohop (already pressing spacebar; the signal to begin trying to jump is different)
if self.physics.grounded&&walk_target_velocity!=self.physics.walk.target_velocity {
instruction::InstructionConsumer::process_instruction(&mut self.physics, instruction::TimedInstruction{
time,
instruction:body::PhysicsInstruction::SetWalkTargetVelocity(walk_target_velocity)
});
}
if control_dir!=self.physics.temp_control_dir {
instruction::InstructionConsumer::process_instruction(&mut self.physics, instruction::TimedInstruction{
time,
instruction:body::PhysicsInstruction::SetControlDir(control_dir)
});
}
self.physics.jump_trying=self.camera.controls&CONTROL_JUMP!=0;
//autohop (already pressing spacebar; the signal to begin trying to jump is different)
if self.physics.grounded&&self.physics.jump_trying {
//scroll will be implemented with InputInstruction::Jump(true) but it blocks setting self.jump_trying=true
instruction::InstructionConsumer::process_instruction(&mut self.physics, instruction::TimedInstruction{
time,
instruction:body::PhysicsInstruction::Jump
});
}
let mut encoder = let mut encoder =
device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None }); device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None });
// update rotation // update rotation
let camera_uniforms = to_uniform_data(&self.physics.camera,self.physics.body.extrapolated_position(time)); let camera_uniforms = self.camera.to_uniform_data(self.physics.body.extrapolated_position(time));
self.staging_belt self.staging_belt
.write_buffer( .write_buffer(
&mut encoder, &mut encoder,
@ -965,7 +963,7 @@ impl strafe_client::framework::Example for GraphicsData {
} }
fn main() { fn main() {
strafe_client::framework::run::<GraphicsData>( framework::run::<GraphicsData>(
format!("Strafe Client v{}", format!("Strafe Client v{}",
env!("CARGO_PKG_VERSION") env!("CARGO_PKG_VERSION")
).as_str() ).as_str()

70
src/model.rs Normal file

@ -0,0 +1,70 @@
use bytemuck::{Pod, Zeroable};
#[derive(Clone, Copy, Pod, Zeroable)]
#[repr(C)]
pub struct Vertex {
pub pos: [f32; 3],
pub texture: [f32; 2],
pub normal: [f32; 3],
pub color: [f32; 4],
}
#[derive(Clone)]
pub struct ModelInstance {
pub transform: glam::Mat4,
pub color: glam::Vec4,
}
#[derive(Clone)]
pub struct ModelData {
pub instances: Vec<ModelInstance>,
pub vertices: Vec<Vertex>,
pub entities: Vec<Vec<u16>>,
pub texture: Option<u32>,
}
impl ModelData {
pub const COLOR_FLOATS_WHITE: [f32;4] = [1.0,1.0,1.0,1.0];
pub const COLOR_VEC4_WHITE: glam::Vec4 = glam::vec4(1.0,1.0,1.0,1.0);
}
pub fn generate_modeldatas(data:obj::ObjData,color:[f32;4]) -> Vec<ModelData>{
let mut modeldatas=Vec::new();
let mut vertices = Vec::new();
let mut vertex_index = std::collections::HashMap::<obj::IndexTuple,u16>::new();
for object in data.objects {
vertices.clear();
vertex_index.clear();
let mut entities = Vec::new();
for group in object.groups {
let mut indices = Vec::new();
for poly in group.polys {
for end_index in 2..poly.0.len() {
for &index in &[0, end_index - 1, end_index] {
let vert = poly.0[index];
if let Some(&i)=vertex_index.get(&vert){
indices.push(i);
}else{
let i=vertices.len() as u16;
vertices.push(Vertex {
pos: data.position[vert.0],
texture: data.texture[vert.1.unwrap()],
normal: data.normal[vert.2.unwrap()],
color,
});
vertex_index.insert(vert,i);
indices.push(i);
}
}
}
}
entities.push(indices);
}
modeldatas.push(ModelData {
instances: Vec::new(),
vertices:vertices.clone(),
entities,
texture: None,
});
}
modeldatas
}

76
src/primitives.rs Normal file

@ -0,0 +1,76 @@
pub fn the_unit_cube_lol() -> obj::ObjData{
obj::ObjData{
position: vec![
[-1.,-1., 1.],//left bottom back
[ 1.,-1., 1.],//right bottom back
[ 1., 1., 1.],//right top back
[-1., 1., 1.],//left top back
[-1., 1.,-1.],//left top front
[ 1., 1.,-1.],//right top front
[ 1.,-1.,-1.],//right bottom front
[-1.,-1.,-1.],//left bottom front
],
texture: vec![[0.0,0.0],[1.0,0.0],[1.0,1.0],[0.0,1.0]],
normal: vec![
[1.,0.,0.],//AabbFace::Right
[0.,1.,0.],//AabbFace::Top
[0.,0.,1.],//AabbFace::Back
[-1.,0.,0.],//AabbFace::Left
[0.,-1.,0.],//AabbFace::Bottom
[0.,0.,-1.],//AabbFace::Front
],
objects: vec![obj::Object{
name: "Unit Cube".to_owned(),
groups: vec![obj::Group{
name: "Cube Vertices".to_owned(),
index: 0,
material: None,
polys: vec![
// back (0, 0, 1)
obj::SimplePolygon(vec![
obj::IndexTuple(0,Some(0),Some(2)),
obj::IndexTuple(1,Some(1),Some(2)),
obj::IndexTuple(2,Some(2),Some(2)),
obj::IndexTuple(3,Some(3),Some(2)),
]),
// front (0, 0,-1)
obj::SimplePolygon(vec![
obj::IndexTuple(4,Some(0),Some(5)),
obj::IndexTuple(5,Some(1),Some(5)),
obj::IndexTuple(6,Some(2),Some(5)),
obj::IndexTuple(7,Some(3),Some(5)),
]),
// right (1, 0, 0)
obj::SimplePolygon(vec![
obj::IndexTuple(6,Some(0),Some(0)),
obj::IndexTuple(5,Some(1),Some(0)),
obj::IndexTuple(2,Some(2),Some(0)),
obj::IndexTuple(1,Some(3),Some(0)),
]),
// left (-1, 0, 0)
obj::SimplePolygon(vec![
obj::IndexTuple(0,Some(0),Some(3)),
obj::IndexTuple(3,Some(1),Some(3)),
obj::IndexTuple(4,Some(2),Some(3)),
obj::IndexTuple(7,Some(3),Some(3)),
]),
// top (0, 1, 0)
obj::SimplePolygon(vec![
obj::IndexTuple(5,Some(1),Some(1)),
obj::IndexTuple(4,Some(0),Some(1)),
obj::IndexTuple(3,Some(3),Some(1)),
obj::IndexTuple(2,Some(2),Some(1)),
]),
// bottom (0,-1, 0)
obj::SimplePolygon(vec![
obj::IndexTuple(1,Some(1),Some(4)),
obj::IndexTuple(0,Some(0),Some(4)),
obj::IndexTuple(7,Some(3),Some(4)),
obj::IndexTuple(6,Some(2),Some(4)),
]),
],
}]
}],
material_libs: Vec::new(),
}
}

@ -49,9 +49,10 @@ struct ModelInstance{
//my fancy idea is to create a megatexture for each model that includes all the textures each intance will need //my fancy idea is to create a megatexture for each model that includes all the textures each intance will need
//the texture transform then maps the texture coordinates to the location of the specific texture //the texture transform then maps the texture coordinates to the location of the specific texture
//group 1 is the model //group 1 is the model
const MAX_MODEL_INSTANCES=4096;
@group(1) @group(1)
@binding(0) @binding(0)
var<storage> model_instances: array<ModelInstance>; var<uniform> model_instances: array<ModelInstance, MAX_MODEL_INSTANCES>;
@group(1) @group(1)
@binding(1) @binding(1)
var model_texture: texture_2d<f32>; var model_texture: texture_2d<f32>;

@ -1,4 +1,5 @@
//find roots of polynomials //find roots of polynomials
#[inline]
pub fn zeroes2(a0:f32,a1:f32,a2:f32) -> Vec<f32>{ pub fn zeroes2(a0:f32,a1:f32,a2:f32) -> Vec<f32>{
if a2==0f32{ if a2==0f32{
return zeroes1(a0, a1); return zeroes1(a0, a1);