Compare commits

...

7 Commits

3 changed files with 378 additions and 287 deletions

View File

@ -4,11 +4,7 @@ use crate::{instruction::{InstructionEmitter, InstructionConsumer, TimedInstruct
pub enum PhysicsInstruction {
CollisionStart(RelativeCollision),
CollisionEnd(RelativeCollision),
SetControlDir(glam::Vec3),
StrafeTick,
Jump,
SetWalkTargetVelocity(glam::Vec3),
RefreshWalkTarget,
ReachWalkTargetVelocity,
// Water,
// Spawn(
@ -16,6 +12,23 @@ pub enum PhysicsInstruction {
// bool,//true = Trigger; false = teleport
// bool,//true = Force
// )
//temp
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 {
@ -51,34 +64,35 @@ pub enum MoveRestriction {
Ladder,//multiple ladders how
}
enum MouseInterpolation {
First,//just checks the last value
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"),
}
}
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 {
First,//just checks the last value
Lerp,//lerps between
}
pub struct MouseInterpolationState {
interpolation: MouseInterpolation,
time0: TIME,
@ -88,11 +102,20 @@ pub struct MouseInterpolationState {
}
impl MouseInterpolationState {
pub fn move_mouse(&mut self,time:TIME,pos:glam::IVec2){
pub fn new() -> Self {
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.mouse0=self.mouse1;
self.time1=time;
self.mouse1=pos;
self.mouse1=self.mouse1+delta;
}
pub fn interpolated_position(&self,time:TIME) -> glam::IVec2 {
match self.interpolation {
@ -113,7 +136,6 @@ impl MouseInterpolationState {
pub enum WalkEnum{
Reached,
Transient,
Invalid,
}
pub struct WalkState {
pub target_velocity: glam::Vec3,
@ -125,22 +147,120 @@ impl WalkState {
Self{
target_velocity:glam::Vec3::ZERO,
target_time:0,
state:WalkEnum::Invalid,
state:WalkEnum::Reached,
}
}
}
// 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 body: Body,
pub hitbox_halfsize: glam::Vec3,
pub contacts: std::collections::HashSet::<RelativeCollision>,
//pub intersections: Vec<ModelId>,
pub models: Vec<ModelPhysics>,
//temp
pub temp_control_dir: glam::Vec3,
//camera must exist in state because wormholes modify the camera, also camera punch
//pub camera: Camera,
//pub mouse_interpolation: MouseInterpolationState,
pub camera: Camera,
pub mouse_interpolation: MouseInterpolationState,
pub controls: u32,
pub time: TIME,
pub strafe_tick_num: TIME,
pub strafe_tick_den: TIME,
@ -152,7 +272,6 @@ pub struct PhysicsState {
pub walk_accel: f32,
pub gravity: glam::Vec3,
pub grounded: bool,
pub jump_trying: bool,
}
#[derive(Debug,Clone,Copy,Hash,Eq,PartialEq)]
@ -353,8 +472,6 @@ impl PhysicsState {
pub fn run(&mut self, time_limit:TIME){
//prepare is ommitted - everything is done via instructions.
while let Some(instruction) = self.next_instruction(time_limit) {//collect
//advance
//self.advance_time(instruction.time);
//process
self.process_instruction(instruction);
//write hash lol
@ -366,6 +483,16 @@ impl PhysicsState {
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){
for contact in self.contacts.iter() {
let n=contact.normal(&self.models);
@ -384,7 +511,6 @@ 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,
@ -424,6 +550,31 @@ 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>> {
//check if you have a valid walk state and create an instruction
if self.grounded{
@ -432,10 +583,6 @@ impl PhysicsState {
time:self.walk.target_time,
instruction:PhysicsInstruction::ReachWalkTargetVelocity
}),
WalkEnum::Invalid=>Some(TimedInstruction{
time:self.time,
instruction:PhysicsInstruction::RefreshWalkTarget,
}),
WalkEnum::Reached=>None,
}
}else{
@ -751,20 +898,29 @@ impl crate::instruction::InstructionConsumer<PhysicsInstruction> for PhysicsStat
fn process_instruction(&mut self, ins:TimedInstruction<PhysicsInstruction>) {
match &ins.instruction {
PhysicsInstruction::StrafeTick => (),
PhysicsInstruction::Input(InputInstruction::MoveMouse(_)) => (),
_=>println!("{:?}",ins),
}
//selectively update body
match &ins.instruction {
PhysicsInstruction::SetWalkTargetVelocity(_)
|PhysicsInstruction::SetControlDir(_) => self.time=ins.time,//TODO: queue instructions
PhysicsInstruction::RefreshWalkTarget
PhysicsInstruction::Input(InputInstruction::MoveMouse(_)) => (),//dodge time for mouse movement
PhysicsInstruction::SetPosition(_) => self.time=ins.time,//TODO: queue instructions
PhysicsInstruction::Input(_)
|PhysicsInstruction::ReachWalkTargetVelocity
|PhysicsInstruction::CollisionStart(_)
|PhysicsInstruction::CollisionEnd(_)
|PhysicsInstruction::StrafeTick
|PhysicsInstruction::Jump => self.advance_time(ins.time),
|PhysicsInstruction::StrafeTick => self.advance_time(ins.time),
}
match ins.instruction {
PhysicsInstruction::SetPosition(position)=>{
//temp
self.body.position=position;
//manual clear //for c in self.contacts{process_instruction(CollisionEnd(c))}
self.contacts.clear();
self.body.acceleration=self.gravity;
self.walk.state=WalkEnum::Reached;
self.grounded=false;
}
PhysicsInstruction::CollisionStart(c) => {
//check ground
match &c.face {
@ -779,14 +935,16 @@ impl crate::instruction::InstructionConsumer<PhysicsInstruction> for PhysicsStat
let mut v=self.body.velocity;
self.contact_constrain_velocity(&mut v);
self.body.velocity=v;
self.walk.state=WalkEnum::Invalid;
if self.grounded&&self.controls&CONTROL_JUMP!=0{
self.jump();
}
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;
self.walk.state=WalkEnum::Invalid;
//check ground
match &c.face {
AabbFace::Top => {
@ -794,27 +952,18 @@ impl crate::instruction::InstructionConsumer<PhysicsInstruction> for PhysicsStat
},
_ => (),
}
},
PhysicsInstruction::SetControlDir(control_dir)=>{
self.temp_control_dir=control_dir;
self.walk.state=WalkEnum::Invalid;
self.refresh_walk_target();
},
PhysicsInstruction::StrafeTick => {
//let control_dir=self.get_control_dir();//this should respect your mouse interpolation settings
let d=self.body.velocity.dot(self.temp_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);
let d=self.body.velocity.dot(control_dir);
if d<self.mv {
let mut v=self.body.velocity+(self.mv-d)*self.temp_control_dir;
let mut v=self.body.velocity+(self.mv-d)*control_dir;
self.contact_constrain_velocity(&mut 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 => {
//precisely set velocity
let mut a=glam::Vec3::ZERO;
@ -825,32 +974,58 @@ impl crate::instruction::InstructionConsumer<PhysicsInstruction> for PhysicsStat
self.body.velocity=v;
self.walk.state=WalkEnum::Reached;
},
PhysicsInstruction::RefreshWalkTarget => {
//calculate acceleration yada yada
PhysicsInstruction::Input(input_instruction) => {
let mut refresh_walk_target=false;
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::Jump(s) => {
self.set_control(CONTROL_JUMP,s);
refresh_walk_target=true;
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;
}
self.jump();
}
},
PhysicsInstruction::SetWalkTargetVelocity(v) => {
self.walk.target_velocity=v;
self.walk.state=WalkEnum::Invalid;
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();
}
},
}
}

View File

@ -1,12 +1,10 @@
use std::future::Future;
#[cfg(target_arch = "wasm32")]
use std::str::FromStr;
#[cfg(not(target_arch = "wasm32"))]
use std::time::Instant;
#[cfg(target_arch = "wasm32")]
use web_sys::{ImageBitmapRenderingContext, OffscreenCanvas};
use winit::{
event::{self, WindowEvent},
event::{self, WindowEvent, DeviceEvent},
event_loop::{ControlFlow, EventLoop},
};
@ -54,7 +52,7 @@ pub trait Example: 'static + Sized {
queue: &wgpu::Queue,
);
fn update(&mut self, device: &wgpu::Device, event: WindowEvent);
fn move_mouse(&mut self, delta: (f64,f64));
fn device_event(&mut self, event: DeviceEvent);
fn render(
&mut self,
view: &wgpu::TextureView,
@ -350,13 +348,10 @@ fn start<E: Example>(
}
},
event::Event::DeviceEvent {
event:
winit::event::DeviceEvent::MouseMotion {
delta,
},
event,
..
} => {
example.move_mouse(delta);
example.device_event(event);
},
event::Event::RedrawRequested(_) => {

View File

@ -1,4 +1,5 @@
use bytemuck::{Pod, Zeroable};
use strafe_client::{instruction::{TimedInstruction, InstructionConsumer},body::{InputInstruction, PhysicsInstruction}};
use std::{borrow::Cow, time::Instant};
use wgpu::{util::DeviceExt, AstcBlock, AstcChannel};
@ -42,86 +43,6 @@ struct ModelGraphics {
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{
repeat: wgpu::Sampler,
}
@ -142,7 +63,7 @@ pub struct GraphicsPipelines {
pub struct GraphicsData {
start_time: std::time::Instant,
camera: Camera,
screen_size: (u32, u32),
physics: strafe_client::body::PhysicsState,
pipelines: GraphicsPipelines,
bind_groups: GraphicsBindGroups,
@ -181,7 +102,8 @@ impl GraphicsData {
depth_texture.create_view(&wgpu::TextureViewDescriptor::default())
}
fn generate_modeldatas_roblox<R: std::io::Read>(&self,input:R) -> Vec<ModelData>{
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)=>{
@ -200,11 +122,7 @@ impl GraphicsData {
object.properties.get("Shape"),//this will also skip unions
)
{
if *transparency==1.0||shape.to_u32()!=1 {
continue;
}
modeldatas[0].instances.push(ModelInstance {
transform:glam::Mat4::from_translation(
let transform=glam::Mat4::from_translation(
glam::Vec3::new(cf.position.x,cf.position.y,cf.position.z)
)
* glam::Mat4::from_mat3(
@ -216,7 +134,16 @@ impl GraphicsData {
)
* 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),
})
}
@ -224,7 +151,7 @@ impl GraphicsData {
},
Err(e) => println!("lmao err {:?}", e),
}
modeldatas
(modeldatas,spawn_point)
}
fn generate_model_physics(&mut self,modeldatas:&Vec<ModelData>){
self.physics.models.append(&mut modeldatas.iter().map(|m|
@ -340,6 +267,21 @@ fn generate_modeldatas(data:obj::ObjData,color:[f32;4]) -> Vec<ModelData>{
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 {
wgpu::Features::TEXTURE_COMPRESSION_ASTC
@ -565,14 +507,6 @@ impl strafe_client::framework::Example for GraphicsData {
source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(include_str!("shader.wgsl"))),
});
let camera = Camera {
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 = strafe_client::body::PhysicsState {
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)),
time: 0,
@ -584,13 +518,14 @@ impl strafe_client::framework::Example for GraphicsData {
walk_accel: 90.0,
mv: 2.7,
grounded: false,
jump_trying: false,
temp_control_dir: glam::Vec3::ZERO,
walkspeed: 18.0,
contacts: std::collections::HashSet::new(),
models: Vec::new(),
walk: strafe_client::body::WalkState::new(),
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
@ -779,7 +714,7 @@ impl strafe_client::framework::Example for GraphicsData {
multiview: None,
});
let camera_uniforms = camera.to_uniform_data(physics.body.extrapolated_position(0));
let camera_uniforms = to_uniform_data(&physics.camera,physics.body.extrapolated_position(0));
let camera_buf = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("Camera"),
contents: bytemuck::cast_slice(&camera_uniforms),
@ -815,7 +750,7 @@ impl strafe_client::framework::Example for GraphicsData {
let mut graphics=GraphicsData {
handy_unit_cube:unit_cube,
start_time: Instant::now(),
camera,
screen_size: (config.width,config.height),
physics,
pipelines:GraphicsPipelines{
skybox:sky_pipeline,
@ -842,75 +777,90 @@ impl strafe_client::framework::Example for GraphicsData {
#[allow(clippy::single_match)]
fn update(&mut self, device: &wgpu::Device, event: winit::event::WindowEvent) {
//nothing atm
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 input = std::io::BufReader::new(file);
let modeldatas=self.generate_modeldatas_roblox(input);
let (modeldatas,spawn_point)=self.generate_modeldatas_roblox(input);
//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,modeldatas);
//manual reset
let time=self.physics.time;
strafe_client::instruction::InstructionConsumer::process_instruction(&mut self.physics, strafe_client::instruction::TimedInstruction{
time,
instruction: strafe_client::body::PhysicsInstruction::SetPosition(spawn_point),
})
}else{
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 move_mouse(&mut self, delta: (f64,f64)) {
self.camera.pitch=(self.camera.pitch as f64+delta.1/-2048.) as f32;
self.camera.yaw=(self.camera.yaw as f64+delta.0/-2048.) as f32;
fn device_event(&mut self, event: winit::event::DeviceEvent) {
//there's no way this is the best way get a timestamp.
let time=self.start_time.elapsed().as_nanos() as i64;
match event {
winit::event::DeviceEvent::Key(winit::event::KeyboardInput {
state,
scancode: keycode,
..
}) => {
let s=match state {
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(
@ -920,7 +870,8 @@ impl strafe_client::framework::Example for GraphicsData {
_queue: &wgpu::Queue,
) {
self.depth_view = Self::create_depth_texture(config, device);
self.camera.screen_size = (config.width, config.height);
self.screen_size = (config.width, config.height);
self.physics.camera.set_fov_aspect(1.0,(config.width as f32)/(config.height as f32));
}
fn render(
@ -930,45 +881,15 @@ impl strafe_client::framework::Example for GraphicsData {
queue: &wgpu::Queue,
_spawner: &strafe_client::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;
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 {
strafe_client::instruction::InstructionConsumer::process_instruction(&mut self.physics, strafe_client::instruction::TimedInstruction{
time,
instruction:strafe_client::body::PhysicsInstruction::SetWalkTargetVelocity(walk_target_velocity)
});
}
if control_dir!=self.physics.temp_control_dir {
strafe_client::instruction::InstructionConsumer::process_instruction(&mut self.physics, strafe_client::instruction::TimedInstruction{
time,
instruction:strafe_client::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
strafe_client::instruction::InstructionConsumer::process_instruction(&mut self.physics, strafe_client::instruction::TimedInstruction{
time,
instruction:strafe_client::body::PhysicsInstruction::Jump
});
}
let mut encoder =
device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None });
// update rotation
let camera_uniforms = self.camera.to_uniform_data(self.physics.body.extrapolated_position(time));
let camera_uniforms = to_uniform_data(&self.physics.camera,self.physics.body.extrapolated_position(time));
self.staging_belt
.write_buffer(
&mut encoder,