Compare commits

..

4 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
9 changed files with 677 additions and 1892 deletions

27
Cargo.lock generated

@ -834,29 +834,6 @@ dependencies = [
"pkg-config", "pkg-config",
] ]
[[package]]
name = "lazy-regex"
version = "3.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e723bd417b2df60a0f6a2b6825f297ea04b245d4ba52b5a22cb679bdf58b05fa"
dependencies = [
"lazy-regex-proc_macros",
"once_cell",
"regex",
]
[[package]]
name = "lazy-regex-proc_macros"
version = "3.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0f0a1d9139f0ee2e862e08a9c5d0ba0470f2aa21cd1e1aa1b1562f83116c725f"
dependencies = [
"proc-macro2",
"quote",
"regex",
"syn 2.0.29",
]
[[package]] [[package]]
name = "lazy_static" name = "lazy_static"
version = "1.4.0" version = "1.4.0"
@ -1682,14 +1659,13 @@ checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"
[[package]] [[package]]
name = "strafe-client" name = "strafe-client"
version = "0.7.0" version = "0.5.0"
dependencies = [ dependencies = [
"async-executor", "async-executor",
"bytemuck", "bytemuck",
"ddsfile", "ddsfile",
"env_logger", "env_logger",
"glam", "glam",
"lazy-regex",
"log", "log",
"obj", "obj",
"pollster", "pollster",
@ -1697,6 +1673,7 @@ dependencies = [
"rbx_dom_weak", "rbx_dom_weak",
"rbx_reflection_database", "rbx_reflection_database",
"rbx_xml", "rbx_xml",
"regex",
"wgpu", "wgpu",
"winit", "winit",
] ]

@ -1,6 +1,6 @@
[package] [package]
name = "strafe-client" name = "strafe-client"
version = "0.7.0" version = "0.5.0"
edition = "2021" edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
@ -11,7 +11,6 @@ bytemuck = { version = "1.13.1", features = ["derive"] }
ddsfile = "0.5.1" ddsfile = "0.5.1"
env_logger = "0.10.0" env_logger = "0.10.0"
glam = "0.24.1" glam = "0.24.1"
lazy-regex = "3.0.2"
log = "0.4.20" log = "0.4.20"
obj = "0.10.2" obj = "0.10.2"
pollster = "0.3.0" pollster = "0.3.0"
@ -19,6 +18,7 @@ rbx_binary = "0.7.1"
rbx_dom_weak = "2.5.0" rbx_dom_weak = "2.5.0"
rbx_reflection_database = "0.2.7" rbx_reflection_database = "0.2.7"
rbx_xml = "0.13.1" rbx_xml = "0.13.1"
regex = "1.9.5"
wgpu = "0.17.0" wgpu = "0.17.0"
winit = "0.28.6" winit = "0.28.6"

@ -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(
@ -12,27 +16,8 @@ pub enum PhysicsInstruction {
// bool,//true = Trigger; false = teleport // bool,//true = Trigger; false = teleport
// bool,//true = Force // bool,//true = Force
// ) // )
//InputInstructions conditionally activate RefreshWalkTarget (by doing what SetWalkTargetVelocity used to do and then flagging it)
Input(InputInstruction),
//temp //temp
SetSpawnPosition(glam::Vec3), SetPosition(glam::Vec3),
}
#[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,
Idle,
//Idle: there were no input events, but the simulation is safe to advance to this timestep
//for interpolation / networking / playback reasons, most playback heads will always want
//to be 1 instruction ahead to generate the next state for interpolation.
} }
pub struct Body { pub struct Body {
@ -68,37 +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
} }
//hey dumbass just use a delta 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,
@ -108,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 {
@ -142,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,
@ -153,174 +127,34 @@ 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 PhysicsState {
pub struct Camera { pub body: Body,
offset: glam::Vec3, pub hitbox_halfsize: glam::Vec3,
angles: glam::DVec2,//YAW AND THEN PITCH pub contacts: std::collections::HashSet::<RelativeCollision>,
//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/6144.0,1.0/6144.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::FRAC_PI_2, std::f64::consts::FRAC_PI_2);
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, 2000.0)
}
pub fn view(&self,pos:glam::Vec3)->glam::Mat4{
//f32 good enough for view matrix
glam::Mat4::from_translation(pos+self.offset) * glam::Mat4::from_euler(glam::EulerRot::YXZ, self.angles.x as f32, self.angles.y as f32, 0f32)
}
pub fn set_fov_aspect(&mut self,fov:f32,aspect:f32){
self.fov.x=fov*aspect;
self.fov.y=fov;
}
}
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 GameMechanicsState{
pub spawn_id:u32,
//jump_counts:HashMap<u32,u32>,
}
impl std::default::Default for GameMechanicsState{
fn default() -> Self {
Self{
spawn_id:0,
}
}
}
pub struct WorldState{}
pub struct StyleModifiers{
pub constrols_mask:u32,//constrols which are unable to be activated
pub constrols_held:u32,//constrols which must be active to be able to strafe
pub mv:f32,
pub walkspeed:f32,
pub friction:f32,
pub walk_accel:f32,
pub gravity:glam::Vec3,
pub strafe_tick_num:TIME,
pub strafe_tick_den:TIME,
pub hitbox_halfsize:glam::Vec3,
}
impl std::default::Default for StyleModifiers{
fn default() -> Self {
Self{
constrols_mask: !0&!(CONTROL_MOVEUP|CONTROL_MOVEDOWN),
constrols_held: 0,
strafe_tick_num: 100,//100t
strafe_tick_den: 1_000_000_000,
gravity: glam::vec3(0.0,-100.0,0.0),
friction: 1.2,
walk_accel: 90.0,
mv: 2.7,
walkspeed: 18.0,
hitbox_halfsize: glam::vec3(1.0,2.5,1.0),
}
}
}
pub struct PhysicsState{
pub time:TIME,
pub body:Body,
pub world:WorldState,//currently there is only one state the world can be in
pub game:GameMechanicsState,
pub style:StyleModifiers,
pub contacts:std::collections::HashSet::<RelativeCollision>,
//pub intersections: Vec<ModelId>, //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 //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 walk:WalkState, pub strafe_tick_num: TIME,
pub grounded:bool, pub strafe_tick_den: TIME,
//all models pub tick: u32,
pub models:Vec<ModelPhysics>, pub mv: f32,
pub walk: WalkState,
pub stages:Vec<crate::model::StageDescription>, pub walkspeed: f32,
//the spawn point is where you spawn when you load into the map. pub friction: f32,
//This is not the same as Reset which teleports you to Spawn0 pub walk_accel: f32,
pub spawn_point:glam::Vec3, pub gravity: glam::Vec3,
pub grounded: bool,
pub jump_trying: bool,
} }
#[derive(Debug,Clone,Copy,Hash,Eq,PartialEq)] #[derive(Debug,Clone,Copy,Hash,Eq,PartialEq)]
@ -332,7 +166,7 @@ pub enum AabbFace{
Bottom, Bottom,
Front, Front,
} }
#[derive(Clone)]
pub struct Aabb { pub struct Aabb {
min: glam::Vec3, min: glam::Vec3,
max: glam::Vec3, max: glam::Vec3,
@ -432,53 +266,31 @@ impl Aabb {
type TreyMeshFace = AabbFace; type TreyMeshFace = AabbFace;
type TreyMesh = Aabb; type TreyMesh = Aabb;
enum PhysicsCollisionAttributes{
Contact{//track whether you are contacting the object
contacting:crate::model::ContactingAttributes,
general:crate::model::GameMechanicAttributes,
},
Intersect{//track whether you are intersecting the object
intersecting:crate::model::IntersectingAttributes,
general:crate::model::GameMechanicAttributes,
},
}
pub struct ModelPhysics { pub struct ModelPhysics {
//A model is a thing that has a hitbox. can be represented by a list of TreyMesh-es //A model is a thing that has a hitbox. can be represented by a list of TreyMesh-es
//in this iteration, all it needs is extents. //in this iteration, all it needs is extents.
mesh: TreyMesh, transform: glam::Mat4,
attributes:PhysicsCollisionAttributes,
} }
impl ModelPhysics { impl ModelPhysics {
fn from_model_transform_attributes(model:&crate::model::IndexedModel,transform:&glam::Affine3A,attributes:PhysicsCollisionAttributes)->Self{ pub fn new(transform:glam::Mat4) -> Self {
let mut aabb=Aabb::new(); Self{transform}
for indexed_vertex in &model.unique_vertices {
aabb.grow(transform.transform_point3(glam::Vec3::from_array(model.unique_pos[indexed_vertex.pos as usize])));
}
Self{
mesh:aabb,
attributes,
}
}
pub fn from_model(model:&crate::model::IndexedModel,instance:&crate::model::ModelInstance) -> Option<Self> {
match &instance.attributes{
crate::model::CollisionAttributes::Decoration=>None,
crate::model::CollisionAttributes::Contact{contacting,general}=>Some(ModelPhysics::from_model_transform_attributes(model,&instance.transform,PhysicsCollisionAttributes::Contact{contacting:contacting.clone(),general:general.clone()})),
crate::model::CollisionAttributes::Intersect{intersecting,general}=>None,//Some(ModelPhysics::from_model_transform_attributes(model,&instance.transform,PhysicsCollisionAttributes::Intersecting{intersecting,general})),
}
} }
pub fn unit_vertices(&self) -> [glam::Vec3;8] { pub fn unit_vertices(&self) -> [glam::Vec3;8] {
Aabb::unit_vertices() Aabb::unit_vertices()
} }
pub fn mesh(&self) -> &TreyMesh { pub fn mesh(&self) -> TreyMesh {
return &self.mesh; let mut aabb=Aabb::new();
for &vertex in self.unit_vertices().iter() {
aabb.grow(glam::Vec4Swizzles::xyz(self.transform*vertex.extend(1.0)));
}
return aabb;
} }
pub fn unit_face_vertices(&self,face:TreyMeshFace) -> [glam::Vec3;4] { pub fn unit_face_vertices(&self,face:TreyMeshFace) -> [glam::Vec3;4] {
Aabb::unit_face_vertices(face) Aabb::unit_face_vertices(face)
} }
pub fn face_mesh(&self,face:TreyMeshFace) -> TreyMesh { pub fn face_mesh(&self,face:TreyMeshFace) -> TreyMesh {
let mut aabb=self.mesh.clone(); let mut aabb=self.mesh();
//in this implementation face = worldspace aabb face //in this implementation face = worldspace aabb face
match face { match face {
AabbFace::Right => aabb.min.x=aabb.max.x, AabbFace::Right => aabb.min.x=aabb.max.x,
@ -491,7 +303,7 @@ impl ModelPhysics {
return aabb; return aabb;
} }
pub fn face_normal(&self,face:TreyMeshFace) -> glam::Vec3 { pub fn face_normal(&self,face:TreyMeshFace) -> glam::Vec3 {
Aabb::normal(face)//this is wrong for scale glam::Vec4Swizzles::xyz(Aabb::normal(face).extend(0.0))//this is wrong for scale
} }
} }
@ -505,7 +317,7 @@ pub struct RelativeCollision {
impl RelativeCollision { impl RelativeCollision {
pub fn mesh(&self,models:&Vec<ModelPhysics>) -> TreyMesh { pub fn mesh(&self,models:&Vec<ModelPhysics>) -> TreyMesh {
return models.get(self.model as usize).unwrap().face_mesh(self.face).clone() return models.get(self.model as usize).unwrap().face_mesh(self.face)
} }
pub fn normal(&self,models:&Vec<ModelPhysics>) -> glam::Vec3 { pub fn normal(&self,models:&Vec<ModelPhysics>) -> glam::Vec3 {
return models.get(self.model as usize).unwrap().face_normal(self.face) return models.get(self.model as usize).unwrap().face_normal(self.face)
@ -543,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
@ -554,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);
@ -582,9 +386,10 @@ impl PhysicsState {
} }
} }
} }
fn next_strafe_instruction(&self) -> Option<TimedInstruction<PhysicsInstruction>> { fn next_strafe_instruction(&self) -> Option<TimedInstruction<PhysicsInstruction>> {
return Some(TimedInstruction{ return Some(TimedInstruction{
time:(self.time*self.style.strafe_tick_num/self.style.strafe_tick_den+1)*self.style.strafe_tick_den/self.style.strafe_tick_num, time:(self.time*self.strafe_tick_num/self.strafe_tick_den+1)*self.strafe_tick_den/self.strafe_tick_num,
//only poll the physics if there is a before and after mouse event //only poll the physics if there is a before and after mouse event
instruction:PhysicsInstruction::StrafeTick instruction:PhysicsInstruction::StrafeTick
}); });
@ -621,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.style.walk_accel.min(self.style.gravity.length()*self.style.friction);
let time_delta=target_diff.length()/accel;
let mut a=target_diff/time_delta;
self.contact_constrain_acceleration(&mut a);
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{
@ -654,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{
@ -663,7 +447,7 @@ impl PhysicsState {
fn mesh(&self) -> TreyMesh { fn mesh(&self) -> TreyMesh {
let mut aabb=Aabb::new(); let mut aabb=Aabb::new();
for vertex in Aabb::unit_vertices(){ for vertex in Aabb::unit_vertices(){
aabb.grow(self.body.position+self.style.hitbox_halfsize*vertex); aabb.grow(self.body.position+self.hitbox_halfsize*vertex);
} }
aabb aabb
} }
@ -969,22 +753,29 @@ 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::Input(_) |PhysicsInstruction::SetPosition(_)
|PhysicsInstruction::SetSpawnPosition(_) |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::SetSpawnPosition(position)=>{ PhysicsInstruction::SetPosition(position)=>{
self.spawn_point=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) => { PhysicsInstruction::CollisionStart(c) => {
//check ground //check ground
@ -1000,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.style.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 => {
@ -1017,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.style.mv { let mut v=self.body.velocity+(self.mv-d)*self.temp_control_dir;
let mut v=self.body.velocity+(self.style.mv-d)*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;
@ -1039,54 +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=true; //calculate acceleration yada yada
let mut refresh_walk_target_velocity=true; if self.grounded{
match input_instruction{ let mut v=self.walk.target_velocity;
InputInstruction::MoveMouse(m) => { self.contact_constrain_velocity(&mut v);
self.camera.angles=self.camera.simulate_move_angles(self.mouse_interpolation.mouse1-self.mouse_interpolation.mouse0); let mut target_diff=v-self.body.velocity;
self.mouse_interpolation.move_mouse(self.time,m); target_diff.y=0f32;
}, if target_diff==glam::Vec3::ZERO{
InputInstruction::MoveForward(s) => self.set_control(CONTROL_MOVEFORWARD,s), let mut a=glam::Vec3::ZERO;
InputInstruction::MoveLeft(s) => self.set_control(CONTROL_MOVELEFT,s), self.contact_constrain_acceleration(&mut a);
InputInstruction::MoveBack(s) => self.set_control(CONTROL_MOVEBACK,s), self.body.acceleration=a;
InputInstruction::MoveRight(s) => self.set_control(CONTROL_MOVERIGHT,s),
InputInstruction::MoveUp(s) => self.set_control(CONTROL_MOVEUP,s),
InputInstruction::MoveDown(s) => self.set_control(CONTROL_MOVEDOWN,s),
InputInstruction::Jump(s) => {
self.set_control(CONTROL_JUMP,s);
if self.grounded{
self.jump();
}
refresh_walk_target_velocity=false;
},
InputInstruction::Zoom(s) => {
self.set_control(CONTROL_ZOOM,s);
refresh_walk_target=false;
},
InputInstruction::Reset => {
//temp
self.body.position=self.spawn_point;
self.body.velocity=glam::Vec3::ZERO;
//manual clear //for c in self.contacts{process_instruction(CollisionEnd(c))}
self.contacts.clear();
self.body.acceleration=self.style.gravity;
self.walk.state=WalkEnum::Reached; self.walk.state=WalkEnum::Reached;
self.grounded=false; }else{
refresh_walk_target=false; let accel=self.walk_accel.min(self.gravity.length()*self.friction);
}, let time_delta=target_diff.length()/accel;
InputInstruction::Idle => {refresh_walk_target=false;},//literally idle! let mut a=target_diff/time_delta;
} self.contact_constrain_acceleration(&mut a);
if refresh_walk_target{ self.body.acceleration=a;
//calculate walk target velocity self.walk.target_time=self.body.time+((time_delta as f64)*1_000_000_000f64) as TIME;
if refresh_walk_target_velocity{ self.walk.state=WalkEnum::Transient;
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);
self.walk.target_velocity=self.style.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,9 +53,8 @@ pub trait Example: 'static + Sized {
device: &wgpu::Device, device: &wgpu::Device,
queue: &wgpu::Queue, queue: &wgpu::Queue,
); );
fn update(&mut self, window: &winit::window::Window, device: &wgpu::Device, queue: &wgpu::Queue, event: WindowEvent); fn update(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, event: WindowEvent);
fn device_event(&mut self, window: &winit::window::Window, event: DeviceEvent); fn move_mouse(&mut self, delta: (f64,f64));
fn load_file(&mut self, path:std::path::PathBuf, device: &wgpu::Device, queue: &wgpu::Queue);
fn render( fn render(
&mut self, &mut self,
view: &wgpu::TextureView, view: &wgpu::TextureView,
@ -359,7 +360,7 @@ fn start<E: Example>(
WindowEvent::KeyboardInput { WindowEvent::KeyboardInput {
input: input:
event::KeyboardInput { event::KeyboardInput {
virtual_keycode: Some(event::VirtualKeyCode::Scroll), virtual_keycode: Some(event::VirtualKeyCode::R),
state: event::ElementState::Pressed, state: event::ElementState::Pressed,
.. ..
}, },
@ -368,14 +369,17 @@ fn start<E: Example>(
println!("{:#?}", instance.generate_report()); println!("{:#?}", instance.generate_report());
} }
_ => { _ => {
example.update(&window,&device,&queue,event); example.update(&device,&queue,event);
} }
}, },
event::Event::DeviceEvent { event::Event::DeviceEvent {
event, event:
winit::event::DeviceEvent::MouseMotion {
delta,
},
.. ..
} => { } => {
example.device_event(&window,event); example.move_mouse(delta);
}, },
event::Event::RedrawRequested(_) => { event::Event::RedrawRequested(_) => {

@ -1,3 +1,7 @@
use std::todo;
use crate::model::{ModelData,ModelInstance};
use crate::primitives; use crate::primitives;
fn class_is_a(class: &str, superclass: &str) -> bool { fn class_is_a(class: &str, superclass: &str) -> bool {
@ -30,382 +34,107 @@ fn get_texture_refs(dom:&rbx_dom_weak::WeakDom) -> Vec<rbx_dom_weak::types::Ref>
//next class //next class
objects objects
} }
fn get_attributes(name:&str,can_collide:bool,velocity:glam::Vec3)->crate::model::CollisionAttributes{
let mut general=crate::model::GameMechanicAttributes::default();
let mut intersecting=crate::model::IntersectingAttributes::default();
let mut contacting=crate::model::ContactingAttributes::default();
match name{
// "Water"=>intersecting.water=Some(crate::model::IntersectingWater::default()),
// "Accelerator"=>(),
// "MapFinish"=>(),
// "MapAnticheat"=>(),
"Platform"=>general.stage_element=Some(crate::model::GameMechanicStageElement{
mode_id:0,
stage_id:0,
force:false,
behaviour:crate::model::StageElementBehaviour::Platform,
}),
other=>{
let regman=lazy_regex::regex!(r"^(Force)?(SpawnAt|Trigger|Teleport|Platform)(\d+)$");
if let Some(captures) = regman.captures(other) {
general.stage_element=Some(crate::model::GameMechanicStageElement{
mode_id:0,
stage_id:captures[3].parse::<u32>().unwrap(),
force:match captures.get(1){
Some(m)=>m.as_str()=="Force",
None=>false,
},
behaviour:match &captures[2]{
"SpawnAt"=>crate::model::StageElementBehaviour::SpawnAt,
"Trigger"=>crate::model::StageElementBehaviour::Trigger,
"Teleport"=>crate::model::StageElementBehaviour::Teleport,
"Platform"=>crate::model::StageElementBehaviour::Platform,
_=>panic!("regex[2] messed up bad"),
}
})
}
}
}
//need some way to skip this
if velocity!=glam::Vec3::ZERO{
general.booster=Some(crate::model::GameMechanicBooster{velocity});
}
match can_collide{
true=>{
match name{
//"Bounce"=>(),
"Surf"=>contacting.surf=Some(crate::model::ContactingSurf{}),
"Ladder"=>contacting.ladder=Some(crate::model::ContactingLadder{sticky:true}),
other=>{
//REGEX!!!!
//Jump#
//WormholeIn#
}
}
return crate::model::CollisionAttributes::Contact{contacting,general};
},
false=>return crate::model::CollisionAttributes::Decoration,
}
}
struct RobloxAssetId(u64); struct RobloxAssetId(u64);
struct RobloxAssetIdParseErr; struct RobloxAssetIdParseErr;
impl std::str::FromStr for RobloxAssetId { impl std::str::FromStr for RobloxAssetId {
type Err=RobloxAssetIdParseErr; type Err=RobloxAssetIdParseErr;
fn from_str(s: &str) -> Result<Self, Self::Err>{ fn from_str(s: &str) -> Result<Self, Self::Err>{
let regman=lazy_regex::regex!(r"(\d+)$"); let regman=regex::Regex::new(r"(\d+)$").unwrap();
if let Some(captures) = regman.captures(s) { if let Some(captures) = regman.captures(s) {
if captures.len()==2{//captures[0] is all captures concatenated, and then each individual capture if captures.len()==2{//captures[0] is all captures concatenated, and then each individual capture
if let Ok(id) = captures[0].parse::<u64>() { if let Ok(id) = captures[0].parse::<u64>() {
return Ok(Self(id)); return Ok(Self(id));
} }
} }
}
Err(RobloxAssetIdParseErr)
}
}
#[derive(Clone,Copy,PartialEq)]
struct RobloxTextureTransform{
offset_u:f32,
offset_v:f32,
scale_u:f32,
scale_v:f32,
}
impl std::cmp::Eq for RobloxTextureTransform{}//????
impl std::default::Default for RobloxTextureTransform{
fn default() -> Self {
Self{offset_u:0.0,offset_v:0.0,scale_u:1.0,scale_v:1.0}
}
}
impl std::hash::Hash for RobloxTextureTransform {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.offset_u.to_ne_bytes().hash(state);
self.offset_v.to_ne_bytes().hash(state);
self.scale_u.to_ne_bytes().hash(state);
self.scale_v.to_ne_bytes().hash(state);
}
}
#[derive(Clone,PartialEq)]
struct RobloxFaceTextureDescription{
texture:u32,
color:glam::Vec4,
transform:RobloxTextureTransform,
}
impl std::cmp::Eq for RobloxFaceTextureDescription{}//????
impl std::hash::Hash for RobloxFaceTextureDescription {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.texture.hash(state);
self.transform.hash(state);
for &el in self.color.as_ref().iter() {
el.to_ne_bytes().hash(state);
} }
Err(RobloxAssetIdParseErr)
} }
} }
impl RobloxFaceTextureDescription{ pub fn generate_modeldatas_roblox(dom:rbx_dom_weak::WeakDom) -> Result<(Vec<ModelData>,Vec<String>,glam::Vec3), Box<dyn std::error::Error>>{
fn to_face_description(&self)->primitives::FaceDescription{ //ModelData includes texture dds
primitives::FaceDescription{
texture:Some(self.texture),
transform:glam::Affine2::from_translation(
glam::vec2(self.transform.offset_u,self.transform.offset_v)
)
*glam::Affine2::from_scale(
glam::vec2(self.transform.scale_u,self.transform.scale_v)
),
color:self.color,
}
}
}
type RobloxPartDescription=[Option<RobloxFaceTextureDescription>;6];
type RobloxWedgeDescription=[Option<RobloxFaceTextureDescription>;5];
type RobloxCornerWedgeDescription=[Option<RobloxFaceTextureDescription>;4];
#[derive(Clone,Eq,Hash,PartialEq)]
enum RobloxBasePartDescription{
Sphere,
Part(RobloxPartDescription),
Cylinder,
Wedge(RobloxWedgeDescription),
CornerWedge(RobloxCornerWedgeDescription),
}
pub fn generate_indexed_models(dom:rbx_dom_weak::WeakDom) -> crate::model::IndexedModelInstances{
//IndexedModelInstances includes textures
let mut spawn_point=glam::Vec3::ZERO; let mut spawn_point=glam::Vec3::ZERO;
let mut stages=Vec::new(); //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 mut indexed_models=Vec::new(); let unit_cube_modeldata=modeldatas[0].clone();
let mut model_id_from_description=std::collections::HashMap::<RobloxBasePartDescription,usize>::new();
let mut texture_id_from_asset_id=std::collections::HashMap::<u64,u32>::new(); let mut texture_id_from_asset_id=std::collections::HashMap::<u64,u32>::new();
let mut asset_id_from_texture_id=Vec::new(); let mut asset_id_from_texture_id=Vec::new();
let mut object_refs=Vec::new(); let mut object_refs = std::vec::Vec::new();
let mut temp_objects=Vec::new(); let mut temp_objects = std::vec::Vec::new();
recursive_collect_superclass(&mut object_refs, &dom, dom.root(),"BasePart"); recursive_collect_superclass(&mut object_refs, &dom, dom.root(),"BasePart");
for object_ref in object_refs { for object_ref in object_refs {
if let Some(object)=dom.get_by_ref(object_ref){ if let Some(object)=dom.get_by_ref(object_ref){
if let ( if let (
Some(rbx_dom_weak::types::Variant::CFrame(cf)), Some(rbx_dom_weak::types::Variant::CFrame(cf)),
Some(rbx_dom_weak::types::Variant::Vector3(size)), Some(rbx_dom_weak::types::Variant::Vector3(size)),
Some(rbx_dom_weak::types::Variant::Vector3(velocity)),
Some(rbx_dom_weak::types::Variant::Float32(transparency)), Some(rbx_dom_weak::types::Variant::Float32(transparency)),
Some(rbx_dom_weak::types::Variant::Color3uint8(color3)), Some(rbx_dom_weak::types::Variant::Color3uint8(color3)),
Some(rbx_dom_weak::types::Variant::Bool(can_collide)), Some(rbx_dom_weak::types::Variant::Enum(shape)),
) = ( ) = (
object.properties.get("CFrame"), object.properties.get("CFrame"),
object.properties.get("Size"), object.properties.get("Size"),
object.properties.get("Velocity"),
object.properties.get("Transparency"), object.properties.get("Transparency"),
object.properties.get("Color"), object.properties.get("Color"),
object.properties.get("CanCollide"), object.properties.get("Shape"),//this will also skip unions
) )
{ {
let model_transform=glam::Affine3A::from_translation( let model_instance=ModelInstance {
glam::Vec3::new(cf.position.x,cf.position.y,cf.position.z) transform:glam::Mat4::from_translation(
) glam::Vec3::new(cf.position.x,cf.position.y,cf.position.z)
* glam::Affine3A::from_mat3( )
glam::Mat3::from_cols( * glam::Mat4::from_mat3(
glam::Vec3::new(cf.orientation.x.x,cf.orientation.y.x,cf.orientation.z.x), glam::Mat3::from_cols(
glam::Vec3::new(cf.orientation.x.y,cf.orientation.y.y,cf.orientation.z.y), glam::Vec3::new(cf.orientation.x.x,cf.orientation.y.x,cf.orientation.z.x),
glam::Vec3::new(cf.orientation.x.z,cf.orientation.y.z,cf.orientation.z.z), 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::Affine3A::from_scale( )
glam::Vec3::new(size.x,size.y,size.z)/2.0 * 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"{ if object.name=="MapStart"{
spawn_point=model_transform.transform_point3(-glam::Vec3::Y)+glam::vec3(0.0,2.5+0.1,0.0); 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); println!("Found MapStart{:?}",spawn_point);
} }
if *transparency==1.0||shape.to_u32()!=1 {
//TODO: also detect "CylinderMesh" etc here continue;
let shape=match &object.class[..]{ }
"Part"=>{
if let Some(rbx_dom_weak::types::Variant::Enum(shape))=object.properties.get("Shape"){
match shape.to_u32(){
0=>primitives::Primitives::Sphere,
1=>primitives::Primitives::Cube,
2=>primitives::Primitives::Cylinder,
3=>primitives::Primitives::Wedge,
4=>primitives::Primitives::CornerWedge,
_=>panic!("Funky roblox PartType={};",shape.to_u32()),
}
}else{
panic!("Part has no Shape!");
}
},
"WedgePart"=>primitives::Primitives::Wedge,
"CornerWedgePart"=>primitives::Primitives::CornerWedge,
_=>{
println!("Unsupported BasePart ClassName={}; defaulting to cube",object.class);
primitives::Primitives::Cube
}
};
//use the biggest one and cut it down later...
let mut part_texture_description:RobloxPartDescription=[None,None,None,None,None,None];
temp_objects.clear(); temp_objects.clear();
recursive_collect_superclass(&mut temp_objects, &dom, object,"Decal"); 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{ for &decal_ref in &temp_objects{
if let Some(decal)=dom.get_by_ref(decal_ref){ if let Some(decal)=dom.get_by_ref(decal_ref){
if let ( if let Some(rbx_dom_weak::types::Variant::Content(content)) = decal.properties.get("Texture") {
Some(rbx_dom_weak::types::Variant::Content(content)),
Some(rbx_dom_weak::types::Variant::Enum(normalid)),
Some(rbx_dom_weak::types::Variant::Color3(decal_color3)),
Some(rbx_dom_weak::types::Variant::Float32(decal_transparency)),
) = (
decal.properties.get("Texture"),
decal.properties.get("Face"),
decal.properties.get("Color3"),
decal.properties.get("Transparency"),
) {
if let Ok(asset_id)=content.clone().into_string().parse::<RobloxAssetId>(){ if let Ok(asset_id)=content.clone().into_string().parse::<RobloxAssetId>(){
let texture_id=if let Some(&texture_id)=texture_id_from_asset_id.get(&asset_id.0){ if let Some(&texture_id)=texture_id_from_asset_id.get(&asset_id.0){
texture_id i_can_only_load_one_texture_per_model=Some(texture_id);
}else{ }else{
let texture_id=asset_id_from_texture_id.len() as u32; let texture_id=asset_id_from_texture_id.len();
texture_id_from_asset_id.insert(asset_id.0,texture_id); texture_id_from_asset_id.insert(asset_id.0,texture_id as u32);
asset_id_from_texture_id.push(asset_id.0); asset_id_from_texture_id.push(asset_id.0);
texture_id //make new model
}; let mut unit_cube_texture=unit_cube_modeldata.clone();
let normal_id=normalid.to_u32(); unit_cube_texture.texture=Some(texture_id as u32);
if normal_id<6{ modeldatas.push(unit_cube_texture);
let mut roblox_texture_transform=RobloxTextureTransform::default();
let mut roblox_texture_color=glam::Vec4::ONE;
if decal.class=="Texture"{
//generate tranform
if let (
Some(rbx_dom_weak::types::Variant::Float32(ox)),
Some(rbx_dom_weak::types::Variant::Float32(oy)),
Some(rbx_dom_weak::types::Variant::Float32(sx)),
Some(rbx_dom_weak::types::Variant::Float32(sy)),
) = (
decal.properties.get("OffsetStudsU"),
decal.properties.get("OffsetStudsV"),
decal.properties.get("StudsPerTileU"),
decal.properties.get("StudsPerTileV"),
)
{
let (size_u,size_v)=match normal_id{
0=>(size.z,size.y),//right
1=>(size.x,size.z),//top
2=>(size.x,size.y),//back
3=>(size.z,size.y),//left
4=>(size.x,size.z),//bottom
5=>(size.x,size.y),//front
_=>panic!("unreachable"),
};
roblox_texture_transform=RobloxTextureTransform{
offset_u:*ox/(*sx),offset_v:*oy/(*sy),
scale_u:size_u/(*sx),scale_v:size_v/(*sy),
};
roblox_texture_color=glam::vec4(decal_color3.r,decal_color3.g,decal_color3.b,1.0-*decal_transparency);
}
}
part_texture_description[normal_id as usize]=Some(RobloxFaceTextureDescription{
texture:texture_id,
color:roblox_texture_color,
transform:roblox_texture_transform,
});
}else{
println!("NormalId={} unsupported for shape={:?}",normal_id,shape);
} }
} }
} }
} }
} }
//obscure rust syntax "slice pattern" match i_can_only_load_one_texture_per_model{
let [f0,f1,f2,f3,f4,f5]=part_texture_description;
let basepart_texture_description=match shape{
primitives::Primitives::Sphere=>RobloxBasePartDescription::Sphere,
primitives::Primitives::Cube=>RobloxBasePartDescription::Part([f0,f1,f2,f3,f4,f5]),
primitives::Primitives::Cylinder=>RobloxBasePartDescription::Cylinder,
//use front face texture first and use top face texture as a fallback
primitives::Primitives::Wedge=>RobloxBasePartDescription::Wedge([f0,if f2.is_some(){f2}else{f1},f3,f4,f5]),
primitives::Primitives::CornerWedge=>RobloxBasePartDescription::CornerWedge([f1,f3,f4,f5]),
};
//make new model if unit cube has not been created before
let model_id=if let Some(&model_id)=model_id_from_description.get(&basepart_texture_description){
//push to existing texture model //push to existing texture model
model_id Some(texture_id)=>modeldatas[(texture_id+1) as usize].instances.push(model_instance),
}else{ //push instance to big unit cube in the sky
let model_id=indexed_models.len(); None=>modeldatas[0].instances.push(model_instance),
model_id_from_description.insert(basepart_texture_description.clone(),model_id);//borrow checker going crazy }
indexed_models.push(match basepart_texture_description{
RobloxBasePartDescription::Sphere=>primitives::unit_sphere(),
RobloxBasePartDescription::Part(part_texture_description)=>{
let mut cube_face_description=primitives::CubeFaceDescription::new();
for (face_id,roblox_face_description) in part_texture_description.iter().enumerate(){
cube_face_description.insert(
match face_id{
0=>primitives::CubeFace::Right,
1=>primitives::CubeFace::Top,
2=>primitives::CubeFace::Back,
3=>primitives::CubeFace::Left,
4=>primitives::CubeFace::Bottom,
5=>primitives::CubeFace::Front,
_=>panic!("unreachable"),
},
match roblox_face_description{
Some(roblox_texture_transform)=>roblox_texture_transform.to_face_description(),
None=>primitives::FaceDescription::default(),
});
}
primitives::generate_partial_unit_cube(cube_face_description)
},
RobloxBasePartDescription::Cylinder=>primitives::unit_cylinder(),
RobloxBasePartDescription::Wedge(wedge_texture_description)=>{
let mut wedge_face_description=primitives::WedgeFaceDescription::new();
for (face_id,roblox_face_description) in wedge_texture_description.iter().enumerate(){
wedge_face_description.insert(
match face_id{
0=>primitives::WedgeFace::Right,
1=>primitives::WedgeFace::TopFront,
2=>primitives::WedgeFace::Back,
3=>primitives::WedgeFace::Left,
4=>primitives::WedgeFace::Bottom,
_=>panic!("unreachable"),
},
match roblox_face_description{
Some(roblox_texture_transform)=>roblox_texture_transform.to_face_description(),
None=>primitives::FaceDescription::default(),
});
}
primitives::generate_partial_unit_wedge(wedge_face_description)
},
RobloxBasePartDescription::CornerWedge(cornerwedge_texture_description)=>{
let mut cornerwedge_face_description=primitives::CornerWedgeFaceDescription::new();
for (face_id,roblox_face_description) in cornerwedge_texture_description.iter().enumerate(){
cornerwedge_face_description.insert(
match face_id{
0=>primitives::CornerWedgeFace::Top,
1=>primitives::CornerWedgeFace::Right,
2=>primitives::CornerWedgeFace::Bottom,
3=>primitives::CornerWedgeFace::Front,
_=>panic!("unreachable"),
},
match roblox_face_description{
Some(roblox_texture_transform)=>roblox_texture_transform.to_face_description(),
None=>primitives::FaceDescription::default(),
});
}
primitives::generate_partial_unit_cornerwedge(cornerwedge_face_description)
},
});
model_id
};
indexed_models[model_id].instances.push(crate::model::ModelInstance {
transform:model_transform,
color:glam::vec4(color3.r as f32/255f32, color3.g as f32/255f32, color3.b as f32/255f32, 1.0-*transparency),
attributes:get_attributes(&object.name,*can_collide,glam::vec3(velocity.x,velocity.y,velocity.z)),
});
} }
} }
} }
crate::model::IndexedModelInstances{ Ok((modeldatas,asset_id_from_texture_id.iter().map(|t|t.to_string()).collect(),spawn_point))
textures:asset_id_from_texture_id.iter().map(|t|t.to_string()).collect(),
models:indexed_models,
spawn_point,
stages,
}
} }

@ -1,8 +1,6 @@
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,ModelInstance,ModelGraphicsInstance}; use model::{Vertex,ModelData,ModelInstance};
use body::{InputInstruction, PhysicsInstruction};
use instruction::{TimedInstruction, InstructionConsumer};
mod body; mod body;
mod model; mod model;
@ -18,13 +16,93 @@ struct Entity {
} }
struct ModelGraphics { struct ModelGraphics {
instances: Vec<ModelGraphicsInstance>, instances: Vec<ModelInstance>,
vertex_buf: wgpu::Buffer, vertex_buf: wgpu::Buffer,
entities: Vec<Entity>, entities: Vec<Entity>,
bind_group: wgpu::BindGroup, bind_group: wgpu::BindGroup,
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,
} }
@ -45,8 +123,7 @@ 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,
manual_mouse_lock:bool,
physics: body::PhysicsState, physics: body::PhysicsState,
pipelines: GraphicsPipelines, pipelines: GraphicsPipelines,
bind_groups: GraphicsBindGroups, bind_groups: GraphicsBindGroups,
@ -84,183 +161,71 @@ impl GraphicsData {
depth_texture.create_view(&wgpu::TextureViewDescriptor::default()) depth_texture.create_view(&wgpu::TextureViewDescriptor::default())
} }
fn generate_model_physics(&mut self,indexed_models:&model::IndexedModelInstances){ fn generate_model_physics(&mut self,modeldatas:&Vec<ModelData>){
for model in &indexed_models.models{ 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
for model_instance in &model.instances{ m.instances.iter().map(|t|body::ModelPhysics::new(t.transform))
if let Some(model_physics)=body::ModelPhysics::from_model(model,model_instance){ ).flatten().collect());
self.physics.models.push(model_physics);
}
}
}
println!("Physics Objects: {}",self.physics.models.len()); println!("Physics Objects: {}",self.physics.models.len());
} }
fn generate_model_graphics(&mut self,device:&wgpu::Device,queue:&wgpu::Queue,indexed_models:model::IndexedModelInstances){ fn generate_model_graphics(&mut self,device:&wgpu::Device,queue:&wgpu::Queue,mut modeldatas:Vec<ModelData>,textures:Vec<String>){
//generate texture view per texture //generate texture view per texture
//idk how to do this gooder lol //idk how to do this gooder lol
let mut double_map=std::collections::HashMap::<u32,u32>::new(); let mut double_map=std::collections::HashMap::<u32,u32>::new();
let mut texture_loading_threads=Vec::new(); let mut texture_views:Vec<wgpu::TextureView>=Vec::with_capacity(textures.len());
let num_textures=indexed_models.textures.len(); for (i,t) in textures.iter().enumerate(){
for (i,texture_id) in indexed_models.textures.into_iter().enumerate(){ if let Ok(mut file) = std::fs::File::open(std::path::Path::new(&format!("textures/{}.dds",t))){
if let Ok(mut file) = std::fs::File::open(std::path::Path::new(&format!("textures/{}.dds",texture_id))){ let image = ddsfile::Dds::read(&mut file).unwrap();
double_map.insert(i as u32, texture_loading_threads.len() as u32);
texture_loading_threads.push((texture_id,std::thread::spawn(move ||{
ddsfile::Dds::read(&mut file).unwrap()
})));
}
}
let texture_views:Vec<wgpu::TextureView>=texture_loading_threads.into_iter().map(|(texture_id,thread)|{ let size = wgpu::Extent3d {
let image=thread.join().unwrap(); width: image.get_width()/4*4,//floor(w,4), should be ceil(w,4)
height: image.get_height()/4*4,
let (mut width,mut height)=(image.get_width(),image.get_height()); depth_or_array_layers: 1,
let format=match image.header10.unwrap().dxgi_format{
ddsfile::DxgiFormat::R8G8B8A8_UNorm_sRGB => wgpu::TextureFormat::Rgba8UnormSrgb,
ddsfile::DxgiFormat::BC7_UNorm_sRGB => {
//floor(w,4), should be ceil(w,4)
width=width/4*4;
height=height/4*4;
wgpu::TextureFormat::Bc7RgbaUnormSrgb
},
other=>panic!("unsupported format {:?}",other),
};
let size = wgpu::Extent3d {
width,
height,
depth_or_array_layers: 1,
};
let layer_size = wgpu::Extent3d {
depth_or_array_layers: 1,
..size
};
let max_mips = layer_size.max_mips(wgpu::TextureDimension::D2);
let texture = device.create_texture_with_data(
queue,
&wgpu::TextureDescriptor {
size,
mip_level_count: max_mips,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
label: Some(format!("Texture{}",texture_id).as_str()),
view_formats: &[],
},
&image.data,
);
texture.create_view(&wgpu::TextureViewDescriptor {
label: Some(format!("Texture{} View",texture_id).as_str()),
dimension: Some(wgpu::TextureViewDimension::D2),
..wgpu::TextureViewDescriptor::default()
})
}).collect();
//split groups with different textures into separate models
//the models received here are supposed to be tightly packed, i.e. no code needs to check if two models are using the same groups.
let indexed_models_len=indexed_models.models.len();
let mut unique_texture_models=Vec::with_capacity(indexed_models_len);
for mut model in indexed_models.models.into_iter(){
//convert ModelInstance into ModelGraphicsInstance
let instances:Vec<ModelGraphicsInstance>=model.instances.into_iter().filter_map(|instance|{
if instance.color.w==0.0{
None
}else{
Some(ModelGraphicsInstance{
transform: glam::Mat4::from(instance.transform),
normal_transform: glam::Mat4::from(instance.transform.inverse()).transpose(),
color: instance.color,
})
}
}).collect();
//check each group, if it's using a new texture then make a new clone of the model
let id=unique_texture_models.len();
let mut unique_textures=Vec::new();
for group in model.groups.into_iter(){
//ignore zero coppy optimization for now
let texture_index=if let Some(texture_index)=unique_textures.iter().position(|&texture|texture==group.texture){
texture_index
}else{
//create new texture_index
let texture_index=unique_textures.len();
unique_textures.push(group.texture);
unique_texture_models.push(model::IndexedModelSingleTexture{
unique_pos:model.unique_pos.clone(),
unique_tex:model.unique_tex.clone(),
unique_normal:model.unique_normal.clone(),
unique_color:model.unique_color.clone(),
unique_vertices:model.unique_vertices.clone(),
texture:group.texture,
groups:Vec::new(),
instances:instances.clone(),
});
texture_index
}; };
unique_texture_models[id+texture_index].groups.push(model::IndexedGroupFixedTexture{
polys:group.polys, 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()
}));
} }
} }
//de-index models //drain the modeldata vec so entities can be /moved/ to models.entities
let mut models=Vec::with_capacity(unique_texture_models.len());
for model in unique_texture_models.into_iter(){
let mut vertices = Vec::new();
let mut index_from_vertex = std::collections::HashMap::new();//::<IndexedVertex,usize>
let mut entities = Vec::new();
//TODO: combine groups using the same render pattern
for group in model.groups {
let mut indices = Vec::new();
for poly in group.polys {
for end_index in 2..poly.vertices.len() {
for &index in &[0, end_index - 1, end_index] {
let vertex_index = poly.vertices[index];
if let Some(&i)=index_from_vertex.get(&vertex_index){
indices.push(i);
}else{
let i=vertices.len() as u16;
let vertex=&model.unique_vertices[vertex_index as usize];
vertices.push(Vertex {
pos: model.unique_pos[vertex.pos as usize],
tex: model.unique_tex[vertex.tex as usize],
normal: model.unique_normal[vertex.normal as usize],
color:model.unique_color[vertex.color as usize],
});
index_from_vertex.insert(vertex_index,i);
indices.push(i);
}
}
}
}
entities.push(indices);
}
models.push(model::ModelSingleTexture{
instances:model.instances,
vertices,
entities,
texture:model.texture,
});
}
//.into_iter() the modeldata vec so entities can be /moved/ to models.entities
let mut model_count=0;
let mut instance_count=0; let mut instance_count=0;
let uniform_buffer_binding_size=<GraphicsData as framework::Example>::required_limits().max_uniform_buffer_binding_size as usize; self.models.reserve(modeldatas.len());
let chunk_size=uniform_buffer_binding_size/MODEL_BUFFER_SIZE_BYTES; for (i,modeldata) in modeldatas.drain(..).enumerate() {
self.models.reserve(models.len()); let n_instances=modeldata.instances.len();
for model in models.into_iter() { if 0<n_instances{
instance_count+=model.instances.len(); let model_uniforms = get_instances_buffer_data(&modeldata.instances);
for instances_chunk in model.instances.rchunks(chunk_size){
model_count+=1;
let model_uniforms = get_instances_buffer_data(instances_chunk);
let model_buf = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { let model_buf = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some(format!("Model{} Buf",model_count).as_str()), label: Some(format!("Model{} Buf",i).as_str()),
contents: bytemuck::cast_slice(&model_uniforms), contents: bytemuck::cast_slice(&model_uniforms),
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
}); });
let texture_view=match model.texture{ let texture_view=match modeldata.texture{
Some(texture_id)=>{ Some(texture_id)=>{
match double_map.get(&texture_id){ match double_map.get(&texture_id){
Some(&mapped_texture_id)=>&texture_views[mapped_texture_id as usize], Some(&mapped_texture_id)=>&texture_views[mapped_texture_id as usize],
@ -285,18 +250,19 @@ impl GraphicsData {
resource: wgpu::BindingResource::Sampler(&self.samplers.repeat), resource: wgpu::BindingResource::Sampler(&self.samplers.repeat),
}, },
], ],
label: Some(format!("Model{} Bind Group",model_count).as_str()), label: Some(format!("Model{} Bind Group",i).as_str()),
}); });
let vertex_buf = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { let vertex_buf = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("Vertex"), label: Some("Vertex"),
contents: bytemuck::cast_slice(&model.vertices), contents: bytemuck::cast_slice(&modeldata.vertices),
usage: wgpu::BufferUsages::VERTEX, usage: wgpu::BufferUsages::VERTEX,
}); });
//all of these are being moved here //all of these are being moved here
instance_count+=n_instances;
self.models.push(ModelGraphics{ self.models.push(ModelGraphics{
instances:instances_chunk.to_vec(), instances:modeldata.instances,
vertex_buf, vertex_buf,
entities: model.entities.iter().map(|indices|{ entities: modeldata.entities.iter().map(|indices|{
let index_buf = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { let index_buf = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("Index"), label: Some("Index"),
contents: bytemuck::cast_slice(&indices), contents: bytemuck::cast_slice(&indices),
@ -310,54 +276,32 @@ impl GraphicsData {
bind_group: model_bind_group, bind_group: model_bind_group,
model_buf, model_buf,
}); });
}else{
println!("WARNING: Model{} has 0 instances",i);
} }
} }
println!("Texture References={}",num_textures);
println!("Textures Loaded={}",texture_views.len());
println!("Indexed Models={}",indexed_models_len);
println!("Graphics Objects: {}",self.models.len()); println!("Graphics Objects: {}",self.models.len());
println!("Graphics Instances: {}",instance_count); println!("Graphics Instances: {}",instance_count);
} }
} }
const MODEL_BUFFER_SIZE:usize=4*4 + 4*4 + 4;//let size=std::mem::size_of::<ModelInstance>(); fn get_instances_buffer_data(instances:&Vec<ModelInstance>) -> Vec<f32> {
const MODEL_BUFFER_SIZE_BYTES:usize=MODEL_BUFFER_SIZE*4; const SIZE: usize=4*4+4;//let size=std::mem::size_of::<ModelInstance>();
fn get_instances_buffer_data(instances:&[ModelGraphicsInstance]) -> Vec<f32> { let mut raw = Vec::with_capacity(SIZE*instances.len());
let mut raw = Vec::with_capacity(MODEL_BUFFER_SIZE*instances.len());
for (i,mi) in instances.iter().enumerate(){ for (i,mi) in instances.iter().enumerate(){
let mut v = raw.split_off(MODEL_BUFFER_SIZE*i); let mut v = raw.split_off(SIZE*i);
//model transform
raw.extend_from_slice(&AsRef::<[f32; 4*4]>::as_ref(&mi.transform)[..]); raw.extend_from_slice(&AsRef::<[f32; 4*4]>::as_ref(&mi.transform)[..]);
//normal transform
raw.extend_from_slice(&AsRef::<[f32; 4*4]>::as_ref(&mi.normal_transform)[..]);
//color
raw.extend_from_slice(AsRef::<[f32; 4]>::as_ref(&mi.color)); raw.extend_from_slice(AsRef::<[f32; 4]>::as_ref(&mi.color));
raw.append(&mut v); raw.append(&mut v);
} }
raw raw
} }
fn to_uniform_data(camera: &body::Camera, pos: glam::Vec3) -> [f32; 16 * 3 + 4] {
let proj=camera.proj();
let proj_inv = proj.inverse();
let view=camera.view(pos);
let view_inv = view.inverse();
let mut raw = [0f32; 16 * 3 + 4];
raw[..16].copy_from_slice(&AsRef::<[f32; 16]>::as_ref(&proj)[..]);
raw[16..32].copy_from_slice(&AsRef::<[f32; 16]>::as_ref(&proj_inv)[..]);
raw[32..48].copy_from_slice(&AsRef::<[f32; 16]>::as_ref(&view_inv)[..]);
raw[48..52].copy_from_slice(AsRef::<[f32; 4]>::as_ref(&view.col(3)));
raw
}
impl framework::Example for GraphicsData { impl framework::Example for GraphicsData {
fn optional_features() -> wgpu::Features { fn optional_features() -> wgpu::Features {
wgpu::Features::TEXTURE_COMPRESSION_ASTC wgpu::Features::TEXTURE_COMPRESSION_ASTC
| wgpu::Features::TEXTURE_COMPRESSION_ETC2 | wgpu::Features::TEXTURE_COMPRESSION_ETC2
} | wgpu::Features::TEXTURE_COMPRESSION_BC
fn required_features() -> wgpu::Features {
wgpu::Features::TEXTURE_COMPRESSION_BC
} }
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
@ -368,55 +312,43 @@ impl framework::Example for GraphicsData {
device: &wgpu::Device, device: &wgpu::Device,
queue: &wgpu::Queue, queue: &wgpu::Queue,
) -> Self { ) -> Self {
let mut indexed_models = Vec::new(); let unit_cube=primitives::the_unit_cube_lol();
indexed_models.append(&mut model::generate_indexed_model_list_from_obj(obj::ObjData::load_buf(&include_bytes!("../models/teslacyberv3.0.obj")[..]).unwrap(),*glam::Vec4::ONE.as_ref())); let mut modeldatas = Vec::<ModelData>::new();
indexed_models.push(primitives::unit_sphere()); modeldatas.append(&mut model::generate_modeldatas(obj::ObjData::load_buf(&include_bytes!("../models/teslacyberv3.0.obj")[..]).unwrap(),ModelData::COLOR_FLOATS_WHITE));
indexed_models.push(primitives::unit_cylinder()); modeldatas.append(&mut model::generate_modeldatas(obj::ObjData::load_buf(&include_bytes!("../models/suzanne.obj")[..]).unwrap(),ModelData::COLOR_FLOATS_WHITE));
indexed_models.push(primitives::unit_cube()); modeldatas.append(&mut model::generate_modeldatas(obj::ObjData::load_buf(&include_bytes!("../models/teapot.obj")[..]).unwrap(),ModelData::COLOR_FLOATS_WHITE));
println!("models.len = {:?}", indexed_models.len()); modeldatas.append(&mut model::generate_modeldatas(unit_cube.clone(),ModelData::COLOR_FLOATS_WHITE));
indexed_models[0].instances.push(ModelInstance{ println!("models.len = {:?}", modeldatas.len());
transform:glam::Affine3A::from_translation(glam::vec3(10.,0.,-10.)), modeldatas[0].instances.push(ModelInstance{
color:glam::Vec4::ONE, transform:glam::Mat4::from_translation(glam::vec3(10.,0.,-10.)),
attributes:model::CollisionAttributes::contact(), color:ModelData::COLOR_VEC4_WHITE,
}); });
//quad monkeys //quad monkeys
indexed_models[1].instances.push(ModelInstance{ modeldatas[1].instances.push(ModelInstance{
transform:glam::Affine3A::from_translation(glam::vec3(10.,5.,10.)), transform:glam::Mat4::from_translation(glam::vec3(10.,5.,10.)),
color:glam::Vec4::ONE, color:ModelData::COLOR_VEC4_WHITE,
attributes:model::CollisionAttributes::contact(),
}); });
indexed_models[1].instances.push(ModelInstance{ modeldatas[1].instances.push(ModelInstance{
transform:glam::Affine3A::from_translation(glam::vec3(20.,5.,10.)), transform:glam::Mat4::from_translation(glam::vec3(20.,5.,10.)),
color:glam::vec4(1.0,0.0,0.0,1.0), color:glam::vec4(1.0,0.0,0.0,1.0),
attributes:model::CollisionAttributes::contact(),
}); });
indexed_models[1].instances.push(ModelInstance{ modeldatas[1].instances.push(ModelInstance{
transform:glam::Affine3A::from_translation(glam::vec3(10.,5.,20.)), transform:glam::Mat4::from_translation(glam::vec3(10.,5.,20.)),
color:glam::vec4(0.0,1.0,0.0,1.0), color:glam::vec4(0.0,1.0,0.0,1.0),
attributes:model::CollisionAttributes::contact(),
}); });
indexed_models[1].instances.push(ModelInstance{ modeldatas[1].instances.push(ModelInstance{
transform:glam::Affine3A::from_translation(glam::vec3(20.,5.,20.)), transform:glam::Mat4::from_translation(glam::vec3(20.,5.,20.)),
color:glam::vec4(0.0,0.0,1.0,1.0), color:glam::vec4(0.0,0.0,1.0,1.0),
attributes:model::CollisionAttributes::contact(),
});
//decorative monkey
indexed_models[1].instances.push(ModelInstance{
transform:glam::Affine3A::from_translation(glam::vec3(15.,10.,15.)),
color:glam::vec4(0.5,0.5,0.5,0.5),
attributes:model::CollisionAttributes::Decoration,
}); });
//teapot //teapot
indexed_models[2].instances.push(ModelInstance{ modeldatas[2].instances.push(ModelInstance{
transform:glam::Affine3A::from_scale_rotation_translation(glam::vec3(0.5, 1.0, 0.2),glam::quat(-0.22248298016985793,-0.839457167990537,-0.05603504040830783,-0.49261857546227916),glam::vec3(-10.,7.,10.)), transform:glam::Mat4::from_translation(glam::vec3(-10.,5.,10.)),
color:glam::Vec4::ONE, color:ModelData::COLOR_VEC4_WHITE,
attributes:model::CollisionAttributes::contact(),
}); });
//ground //ground
indexed_models[3].instances.push(ModelInstance{ modeldatas[3].instances.push(ModelInstance{
transform:glam::Affine3A::from_translation(glam::vec3(0.,0.,0.))*glam::Affine3A::from_scale(glam::vec3(160.0, 1.0, 160.0)), transform:glam::Mat4::from_translation(glam::vec3(0.,0.,0.))*glam::Mat4::from_scale(glam::vec3(160.0, 1.0, 160.0)),
color:glam::Vec4::ONE, color:ModelData::COLOR_VEC4_WHITE,
attributes:model::CollisionAttributes::contact(),
}); });
let camera_bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { let camera_bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
@ -514,21 +446,32 @@ impl 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 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 = body::PhysicsState { let physics = body::PhysicsState {
spawn_point:glam::vec3(0.0,50.0,0.0),
body: body::Body::with_pva(glam::vec3(0.0,50.0,0.0),glam::vec3(0.0,0.0,0.0),glam::vec3(0.0,-100.0,0.0)), body: body::Body::with_pva(glam::vec3(0.0,50.0,0.0),glam::vec3(0.0,0.0,0.0),glam::vec3(0.0,-100.0,0.0)),
time: 0, time: 0,
style:body::StyleModifiers::default(), tick: 0,
strafe_tick_num: 100,//100t
strafe_tick_den: 1_000_000_000,
gravity: glam::vec3(0.0,-100.0,0.0),
friction: 1.2,
walk_accel: 90.0,
mv: 2.7,
grounded: false, grounded: false,
jump_trying: false,
temp_control_dir: glam::Vec3::ZERO,
walkspeed: 18.0,
contacts: std::collections::HashSet::new(), contacts: std::collections::HashSet::new(),
models: Vec::new(), models: Vec::new(),
walk: body::WalkState::new(), walk: body::WalkState::new(),
camera: body::Camera::from_offset(glam::vec3(0.0,4.5-2.5,0.0),(config.width as f32)/(config.height as f32)), hitbox_halfsize: glam::vec3(1.0,2.5,1.0),
mouse_interpolation: body::MouseInterpolationState::new(),
controls: 0,
world:body::WorldState{},
game:body::GameMechanicsState::default(),
stages:Vec::new(),
}; };
//load textures //load textures
@ -647,19 +590,11 @@ impl framework::Example for GraphicsData {
}) })
}; };
let model_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: None, label: None,
bind_group_layouts: &[ bind_group_layouts: &[
&camera_bind_group_layout, &camera_bind_group_layout,
&skybox_texture_bind_group_layout,
&model_bind_group_layout, &model_bind_group_layout,
],
push_constant_ranges: &[],
});
let sky_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: None,
bind_group_layouts: &[
&camera_bind_group_layout,
&skybox_texture_bind_group_layout, &skybox_texture_bind_group_layout,
], ],
push_constant_ranges: &[], push_constant_ranges: &[],
@ -668,7 +603,7 @@ impl framework::Example for GraphicsData {
// Create the render pipelines // Create the render pipelines
let sky_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { let sky_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("Sky Pipeline"), label: Some("Sky Pipeline"),
layout: Some(&sky_pipeline_layout), layout: Some(&pipeline_layout),
vertex: wgpu::VertexState { vertex: wgpu::VertexState {
module: &shader, module: &shader,
entry_point: "vs_sky", entry_point: "vs_sky",
@ -695,7 +630,7 @@ impl framework::Example for GraphicsData {
}); });
let model_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { let model_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("Model Pipeline"), label: Some("Model Pipeline"),
layout: Some(&model_pipeline_layout), layout: Some(&pipeline_layout),
vertex: wgpu::VertexState { vertex: wgpu::VertexState {
module: &shader, module: &shader,
entry_point: "vs_entity_texture", entry_point: "vs_entity_texture",
@ -725,7 +660,7 @@ impl 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),
@ -759,9 +694,8 @@ impl 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 {
manual_mouse_lock:false,
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,
@ -780,204 +714,122 @@ impl framework::Example for GraphicsData {
temp_squid_texture_view: squid_texture_view, temp_squid_texture_view: squid_texture_view,
}; };
let indexed_model_instances=model::IndexedModelInstances{ graphics.generate_model_physics(&modeldatas);
textures:Vec::new(), graphics.generate_model_graphics(&device,&queue,modeldatas,Vec::new());
models:indexed_models,
spawn_point:glam::Vec3::Y*50.0,
stages:Vec::new(),
};
graphics.generate_model_physics(&indexed_model_instances);
graphics.generate_model_graphics(&device,&queue,indexed_model_instances);
let args:Vec<String>=std::env::args().collect();
if args.len()==2{
graphics.load_file(std::path::PathBuf::from(&args[1]), device, queue);
}
return graphics; return graphics;
} }
fn load_file(&mut self,path: std::path::PathBuf, device: &wgpu::Device, queue: &wgpu::Queue){
println!("Loading file: {:?}", &path);
//oh boy! let's load the map!
if let Ok(file)=std::fs::File::open(path){
let mut input = std::io::BufReader::new(file);
let mut first_8=[0u8;8];
//.rbxm roblox binary = "<roblox!"
//.rbxmx roblox xml = "<roblox "
//.bsp = "VBSP"
//.vmf =
//.snf = "SNMF"
//.snf = "SNBF"
if let (Ok(()),Ok(()))=(std::io::Read::read_exact(&mut input, &mut first_8),std::io::Seek::rewind(&mut input)){
//
if let Some(indexed_model_instances)={
match &first_8[0..4]{
b"<rob"=>{
match match &first_8[4..8]{
b"lox!"=>rbx_binary::from_reader(input).map_err(|e|format!("{:?}",e)),
b"lox "=>rbx_xml::from_reader(input,rbx_xml::DecodeOptions::default()).map_err(|e|format!("{:?}",e)),
other=>Err(format!("Unknown Roblox file type {:?}",other)),
}{
Ok(dom)=>Some(load_roblox::generate_indexed_models(dom)),
Err(e)=>{
println!("Error loading roblox file:{:?}",e);
None
},
}
},
//b"VBSP"=>Some(load_bsp::generate_indexed_models(input)),
//b"SNFM"=>Some(sniffer::generate_indexed_models(input)),
//b"SNFB"=>Some(sniffer::load_bot(input)),
other=>{
println!("loser file {:?}",other);
None
},
}
}{
let spawn_point=indexed_model_instances.spawn_point;
//if generate_indexed_models succeeds, clear the previous ones
self.models.clear();
self.physics.models.clear();
self.generate_model_physics(&indexed_model_instances);
self.generate_model_graphics(device,queue,indexed_model_instances);
//manual reset
let time=self.physics.time;
instruction::InstructionConsumer::process_instruction(&mut self.physics, instruction::TimedInstruction{
time,
instruction: body::PhysicsInstruction::SetSpawnPosition(spawn_point),
});
instruction::InstructionConsumer::process_instruction(&mut self.physics, instruction::TimedInstruction{
time,
instruction: body::PhysicsInstruction::Input(body::InputInstruction::Reset),
});
}else{
println!("No modeldatas were generated");
}
}else{
println!("Failed to read first 8 bytes and seek back to beginning of file.");
}
}else{
println!("Could not open file");
}
}
#[allow(clippy::single_match)] #[allow(clippy::single_match)]
fn update(&mut self, window: &winit::window::Window, device: &wgpu::Device, queue: &wgpu::Queue, 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) => self.load_file(path,device,queue), winit::event::WindowEvent::DroppedFile(path) => {
winit::event::WindowEvent::Focused(state)=>{ println!("opening file: {:?}", &path);
//pause unpause //oh boy! let's load the map!
//recalculate pressed keys on focus if let Ok(file)=std::fs::File::open(path){
let mut input = std::io::BufReader::new(file);
let mut first_8=[0u8;8];
//.rbxm roblox binary = "<roblox!"
//.rbxmx roblox xml = "<roblox "
//.bsp = "VBSP"
//.vmf =
//.snf = "SNMF"
//.snf = "SNBF"
if let (Ok(()),Ok(()))=(std::io::Read::read_exact(&mut input, &mut first_8),std::io::Seek::rewind(&mut input)){
//
if let Some(Ok((modeldatas,textures,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{
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, window: &winit::window::Window, 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
01=>{//Esc
if s{
self.manual_mouse_lock=false;
match window.set_cursor_grab(winit::window::CursorGrabMode::None){
Ok(())=>(),
Err(e)=>println!("Could not release cursor: {:?}",e),
}
window.set_cursor_visible(true);
}
None
},
15=>{//Tab
if s{
self.manual_mouse_lock=false;
match window.set_cursor_position(winit::dpi::PhysicalPosition::new(self.screen_size.0 as f32/2.0, self.screen_size.1 as f32/2.0)){
Ok(())=>(),
Err(e)=>println!("Could not set cursor position: {:?}",e),
}
match window.set_cursor_grab(winit::window::CursorGrabMode::None){
Ok(())=>(),
Err(e)=>println!("Could not release cursor: {:?}",e),
}
}else{
//if cursor is outside window don't lock but apparently there's no get pos function
//let pos=window.get_cursor_pos();
match window.set_cursor_grab(winit::window::CursorGrabMode::Locked){
Ok(())=>(),
Err(_)=>{
match window.set_cursor_grab(winit::window::CursorGrabMode::Confined){
Ok(())=>(),
Err(e)=>{
self.manual_mouse_lock=true;
println!("Could not confine cursor: {:?}",e)
},
}
}
}
}
window.set_cursor_visible(s);
None
},
_ => {println!("scancode {}",keycode);None},
}{
self.physics.run(time);
self.physics.process_instruction(TimedInstruction{
time,
instruction:PhysicsInstruction::Input(input_instruction),
})
}
},
winit::event::DeviceEvent::MouseMotion {
delta,//these (f64,f64) are integers on my machine
} => {
if self.manual_mouse_lock{
match window.set_cursor_position(winit::dpi::PhysicalPosition::new(self.screen_size.0 as f32/2.0, self.screen_size.1 as f32/2.0)){
Ok(())=>(),
Err(e)=>println!("Could not set cursor position: {:?}",e),
}
}
//do not step the physics because the mouse polling rate is higher than the physics can run.
//essentially the previous input will be overwritten until a true step runs
//which is fine because they run all the time.
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 false{//self.physics.style.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(
@ -987,8 +839,7 @@ impl 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(
@ -998,15 +849,45 @@ impl framework::Example for GraphicsData {
queue: &wgpu::Queue, queue: &wgpu::Queue,
_spawner: &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,
@ -1058,11 +939,11 @@ impl framework::Example for GraphicsData {
}); });
rpass.set_bind_group(0, &self.bind_groups.camera, &[]); rpass.set_bind_group(0, &self.bind_groups.camera, &[]);
rpass.set_bind_group(1, &self.bind_groups.skybox_texture, &[]); rpass.set_bind_group(2, &self.bind_groups.skybox_texture, &[]);
rpass.set_pipeline(&self.pipelines.model); rpass.set_pipeline(&self.pipelines.model);
for model in self.models.iter() { for model in self.models.iter() {
rpass.set_bind_group(2, &model.bind_group, &[]); rpass.set_bind_group(1, &model.bind_group, &[]);
rpass.set_vertex_buffer(0, model.vertex_buf.slice(..)); rpass.set_vertex_buffer(0, model.vertex_buf.slice(..));
for entity in model.entities.iter() { for entity in model.entities.iter() {

@ -3,222 +3,68 @@ use bytemuck::{Pod, Zeroable};
#[repr(C)] #[repr(C)]
pub struct Vertex { pub struct Vertex {
pub pos: [f32; 3], pub pos: [f32; 3],
pub tex: [f32; 2], pub texture: [f32; 2],
pub normal: [f32; 3], pub normal: [f32; 3],
pub color: [f32; 4], pub color: [f32; 4],
} }
#[derive(Clone,Hash,PartialEq,Eq)]
pub struct IndexedVertex{ #[derive(Clone)]
pub pos:u32, pub struct ModelInstance {
pub tex:u32, pub transform: glam::Mat4,
pub normal:u32, pub color: glam::Vec4,
pub color:u32,
} }
pub struct IndexedPolygon{
pub vertices:Vec<u32>, #[derive(Clone)]
} pub struct ModelData {
pub struct IndexedGroup{ pub instances: Vec<ModelInstance>,
pub texture:Option<u32>,//RenderPattern? material/texture/shader/flat color
pub polys:Vec<IndexedPolygon>,
}
pub struct IndexedModel{
pub unique_pos:Vec<[f32; 3]>,
pub unique_tex:Vec<[f32; 2]>,
pub unique_normal:Vec<[f32; 3]>,
pub unique_color:Vec<[f32; 4]>,
pub unique_vertices:Vec<IndexedVertex>,
pub groups: Vec<IndexedGroup>,
pub instances:Vec<ModelInstance>,
}
pub struct IndexedGroupFixedTexture{
pub polys:Vec<IndexedPolygon>,
}
pub struct IndexedModelSingleTexture{
pub unique_pos:Vec<[f32; 3]>,
pub unique_tex:Vec<[f32; 2]>,
pub unique_normal:Vec<[f32; 3]>,
pub unique_color:Vec<[f32; 4]>,
pub unique_vertices:Vec<IndexedVertex>,
pub texture:Option<u32>,//RenderPattern? material/texture/shader/flat color
pub groups: Vec<IndexedGroupFixedTexture>,
pub instances:Vec<ModelGraphicsInstance>,
}
pub struct ModelSingleTexture{
pub instances: Vec<ModelGraphicsInstance>,
pub vertices: Vec<Vertex>, pub vertices: Vec<Vertex>,
pub entities: Vec<Vec<u16>>, pub entities: Vec<Vec<u16>>,
pub texture: Option<u32>, pub texture: Option<u32>,
} }
#[derive(Clone)]
pub struct ModelGraphicsInstance{ impl ModelData {
pub transform:glam::Mat4, pub const COLOR_FLOATS_WHITE: [f32;4] = [1.0,1.0,1.0,1.0];
pub normal_transform:glam::Mat4, pub const COLOR_VEC4_WHITE: glam::Vec4 = glam::vec4(1.0,1.0,1.0,1.0);
pub color:glam::Vec4,
}
pub struct ModelInstance{
//pub id:u64,//this does not actually help with map fixes resimulating bots, they must always be resimulated
pub transform:glam::Affine3A,
pub color:glam::Vec4,//transparency is in here
pub attributes:CollisionAttributes,
}
pub struct IndexedModelInstances{
pub textures:Vec<String>,//RenderPattern
pub models:Vec<IndexedModel>,
//may make this into an object later.
pub stages:Vec<StageDescription>,
pub spawn_point:glam::Vec3,
}
//stage description referencing flattened ids is spooky, but the map loading is meant to be deterministic.
pub struct StageDescription{
pub start:u32,//start=model_id
pub spawns:Vec<u32>,//spawns[spawn_id]=model_id
pub ordered_checkpoints:Vec<u32>,//ordered_checkpoints[checkpoint_id]=model_id
pub unordered_checkpoints:Vec<u32>,//unordered_checkpoints[checkpoint_id]=model_id
} }
//you have this effect while in contact pub fn generate_modeldatas(data:obj::ObjData,color:[f32;4]) -> Vec<ModelData>{
#[derive(Clone)] let mut modeldatas=Vec::new();
pub struct ContactingSurf{} let mut vertices = Vec::new();
#[derive(Clone)] let mut vertex_index = std::collections::HashMap::<obj::IndexTuple,u16>::new();
pub struct ContactingLadder{ for object in data.objects {
pub sticky:bool vertices.clear();
} vertex_index.clear();
//you have this effect while intersecting let mut entities = Vec::new();
#[derive(Clone)] for group in object.groups {
pub struct IntersectingWater{ let mut indices = Vec::new();
pub viscosity:i64, for poly in group.polys {
pub density:i64, for end_index in 2..poly.0.len() {
pub current:glam::Vec3, for &index in &[0, end_index - 1, end_index] {
} let vert = poly.0[index];
#[derive(Clone)] if let Some(&i)=vertex_index.get(&vert){
pub struct IntersectingAccelerator{ indices.push(i);
pub acceleration:glam::Vec3 }else{
} let i=vertices.len() as u16;
//All models can be given these attributes vertices.push(Vertex {
#[derive(Clone)] pos: data.position[vert.0],
pub struct GameMechanicJumpLimit{ texture: data.texture[vert.1.unwrap()],
pub count:u32, normal: data.normal[vert.2.unwrap()],
} color,
#[derive(Clone)] });
pub struct GameMechanicBooster{ vertex_index.insert(vert,i);
pub velocity:glam::Vec3, indices.push(i);
} }
#[derive(Clone)]
pub enum ZoneBehaviour{
//Start is indexed
//Checkpoints are indexed
Finish,
Anitcheat,
}
#[derive(Clone)]
pub struct GameMechanicZone{
pub mode_id:u32,
pub behaviour:ZoneBehaviour,
}
// enum TrapCondition{
// FasterThan(i64),
// SlowerThan(i64),
// InRange(i64,i64),
// OutsideRange(i64,i64),
// }
#[derive(Clone)]
pub enum StageElementBehaviour{
//Spawn,//The behaviour of stepping on a spawn setting the spawnid
SpawnAt,
Trigger,
Teleport,
Platform,
//Speedtrap(TrapCondition),//Acts as a trigger with a speed condition
}
#[derive(Clone)]
pub struct GameMechanicStageElement{
pub mode_id:u32,
pub stage_id:u32,//which spawn to send to
pub force:bool,//allow setting to lower spawn id i.e. 7->3
pub behaviour:StageElementBehaviour
}
#[derive(Clone)]
pub struct GameMechanicWormhole{//(position,angles)*=origin.transform.inverse()*destination.transform
pub model_id:u32,
}
#[derive(Default,Clone)]
pub struct GameMechanicAttributes{
pub jump_limit:Option<GameMechanicJumpLimit>,
pub booster:Option<GameMechanicBooster>,
pub zone:Option<GameMechanicZone>,
pub stage_element:Option<GameMechanicStageElement>,
pub wormhole:Option<GameMechanicWormhole>,//stage_element and wormhole are in conflict
}
#[derive(Default,Clone)]
pub struct ContactingAttributes{
pub elasticity:Option<u32>,//[1/2^32,1] 0=None (elasticity+1)/2^32
//friction?
pub surf:Option<ContactingSurf>,
pub ladder:Option<ContactingLadder>,
}
#[derive(Default,Clone)]
pub struct IntersectingAttributes{
pub water:Option<IntersectingWater>,
pub accelerator:Option<IntersectingAccelerator>,
}
//Spawn(u32) NO! spawns are indexed in the map header instead of marked with attibutes
pub enum CollisionAttributes{
Decoration,//visual only
Contact{//track whether you are contacting the object
contacting:ContactingAttributes,
general:GameMechanicAttributes,
},
Intersect{//track whether you are intersecting the object
intersecting:IntersectingAttributes,
general:GameMechanicAttributes,
},
}
impl CollisionAttributes{
pub fn contact() -> Self {
Self::Contact{
contacting:ContactingAttributes::default(),
general:GameMechanicAttributes::default()
}
}
}
pub fn generate_indexed_model_list_from_obj(data:obj::ObjData,color:[f32;4]) -> Vec<IndexedModel>{
let mut unique_vertex_index = std::collections::HashMap::<obj::IndexTuple,u32>::new();
return data.objects.iter().map(|object|{
unique_vertex_index.clear();
let mut unique_vertices = Vec::new();
let groups = object.groups.iter().map(|group|{
IndexedGroup{
texture:None,
polys:group.polys.iter().map(|poly|{
IndexedPolygon{
vertices:poly.0.iter().map(|&tup|{
if let Some(&i)=unique_vertex_index.get(&tup){
i
}else{
let i=unique_vertices.len() as u32;
unique_vertices.push(IndexedVertex{
pos: tup.0 as u32,
tex: tup.1.unwrap() as u32,
normal: tup.2.unwrap() as u32,
color: 0,
});
unique_vertex_index.insert(tup,i);
i
}
}).collect()
} }
}).collect() }
} }
}).collect(); entities.push(indices);
IndexedModel{
unique_pos: data.position.clone(),
unique_tex: data.texture.clone(),
unique_normal: data.normal.clone(),
unique_color: vec![color],
unique_vertices,
groups,
instances:Vec::new(),
} }
}).collect() modeldatas.push(ModelData {
} instances: Vec::new(),
vertices:vertices.clone(),
entities,
texture: None,
});
}
modeldatas
}

@ -1,503 +1,76 @@
use crate::model::{IndexedModel, IndexedPolygon, IndexedGroup, IndexedVertex}; pub fn the_unit_cube_lol() -> obj::ObjData{
obj::ObjData{
#[derive(Debug)] position: vec![
pub enum Primitives{ [-1.,-1., 1.],//left bottom back
Sphere, [ 1.,-1., 1.],//right bottom back
Cube, [ 1., 1., 1.],//right top back
Cylinder, [-1., 1., 1.],//left top back
Wedge, [-1., 1.,-1.],//left top front
CornerWedge, [ 1., 1.,-1.],//right top front
} [ 1.,-1.,-1.],//right bottom front
#[derive(Hash,PartialEq,Eq)] [-1.,-1.,-1.],//left bottom front
pub enum CubeFace{
Right,
Top,
Back,
Left,
Bottom,
Front,
}
const CUBE_DEFAULT_TEXTURE_COORDS:[[f32;2];4]=[[0.0,0.0],[1.0,0.0],[1.0,1.0],[0.0,1.0]];
const CUBE_DEFAULT_VERTICES:[[f32;3];8]=[
[-1.,-1., 1.],//0 left bottom back
[ 1.,-1., 1.],//1 right bottom back
[ 1., 1., 1.],//2 right top back
[-1., 1., 1.],//3 left top back
[-1., 1.,-1.],//4 left top front
[ 1., 1.,-1.],//5 right top front
[ 1.,-1.,-1.],//6 right bottom front
[-1.,-1.,-1.],//7 left bottom front
];
const CUBE_DEFAULT_NORMALS:[[f32;3];6]=[
[ 1., 0., 0.],//CubeFace::Right
[ 0., 1., 0.],//CubeFace::Top
[ 0., 0., 1.],//CubeFace::Back
[-1., 0., 0.],//CubeFace::Left
[ 0.,-1., 0.],//CubeFace::Bottom
[ 0., 0.,-1.],//CubeFace::Front
];
const CUBE_DEFAULT_POLYS:[[[u32;3];4];6]=[
// right (1, 0, 0)
[
[6,2,0],//[vertex,tex,norm]
[5,1,0],
[2,0,0],
[1,3,0],
],
// top (0, 1, 0)
[
[5,3,1],
[4,2,1],
[3,1,1],
[2,0,1],
],
// back (0, 0, 1)
[
[0,3,2],
[1,2,2],
[2,1,2],
[3,0,2],
],
// left (-1, 0, 0)
[
[0,2,3],
[3,1,3],
[4,0,3],
[7,3,3],
],
// bottom (0,-1, 0)
[
[1,1,4],
[0,0,4],
[7,3,4],
[6,2,4],
],
// front (0, 0,-1)
[
[4,1,5],
[5,0,5],
[6,3,5],
[7,2,5],
],
];
#[derive(Hash,PartialEq,Eq)]
pub enum WedgeFace{
Right,
TopFront,
Back,
Left,
Bottom,
}
const WEDGE_DEFAULT_NORMALS:[[f32;3];5]=[
[ 1., 0., 0.],//Wedge::Right
[ 0., 1.,-1.],//Wedge::TopFront
[ 0., 0., 1.],//Wedge::Back
[-1., 0., 0.],//Wedge::Left
[ 0.,-1., 0.],//Wedge::Bottom
];
/*
local cornerWedgeVerticies = {
Vector3.new(-1/2,-1/2,-1/2),7
Vector3.new(-1/2,-1/2, 1/2),0
Vector3.new( 1/2,-1/2,-1/2),6
Vector3.new( 1/2,-1/2, 1/2),1
Vector3.new( 1/2, 1/2,-1/2),5
}
*/
#[derive(Hash,PartialEq,Eq)]
pub enum CornerWedgeFace{
Top,
Right,
Bottom,
Front,
}
const CORNERWEDGE_DEFAULT_NORMALS:[[f32;3];5]=[
[ 1., 0., 0.],//Wedge::Right
[ 0., 1., 1.],//Wedge::BackTop
[-1., 1., 0.],//Wedge::LeftTop
[ 0.,-1., 0.],//Wedge::Bottom
[ 0., 0.,-1.],//Wedge::Front
];
//HashMap fits this use case perfectly but feels like using a sledgehammer to drive a nail
pub fn unit_sphere()->crate::model::IndexedModel{
let mut indexed_model=crate::model::generate_indexed_model_list_from_obj(obj::ObjData::load_buf(&include_bytes!("../models/suzanne.obj")[..]).unwrap(),*glam::Vec4::ONE.as_ref()).remove(0);
for pos in indexed_model.unique_pos.iter_mut(){
pos[0]=pos[0]*0.5;
pos[1]=pos[1]*0.5;
pos[2]=pos[2]*0.5;
}
indexed_model
}
pub type CubeFaceDescription=std::collections::HashMap::<CubeFace,FaceDescription>;
pub fn unit_cube()->crate::model::IndexedModel{
let mut t=CubeFaceDescription::new();
t.insert(CubeFace::Right,FaceDescription::default());
t.insert(CubeFace::Top,FaceDescription::default());
t.insert(CubeFace::Back,FaceDescription::default());
t.insert(CubeFace::Left,FaceDescription::default());
t.insert(CubeFace::Bottom,FaceDescription::default());
t.insert(CubeFace::Front,FaceDescription::default());
generate_partial_unit_cube(t)
}
const TEAPOT_TRANSFORM:glam::Mat3=glam::mat3(glam::vec3(0.0,0.1,0.0),glam::vec3(-0.1,0.0,0.0),glam::vec3(0.0,0.0,0.1));
pub fn unit_cylinder()->crate::model::IndexedModel{
let mut indexed_model=crate::model::generate_indexed_model_list_from_obj(obj::ObjData::load_buf(&include_bytes!("../models/teapot.obj")[..]).unwrap(),*glam::Vec4::ONE.as_ref()).remove(0);
for pos in indexed_model.unique_pos.iter_mut(){
[pos[0],pos[1],pos[2]]=*(TEAPOT_TRANSFORM*glam::Vec3::from_array(*pos)).as_ref();
}
indexed_model
}
pub type WedgeFaceDescription=std::collections::HashMap::<WedgeFace,FaceDescription>;
pub fn unit_wedge()->crate::model::IndexedModel{
let mut t=WedgeFaceDescription::new();
t.insert(WedgeFace::Right,FaceDescription::default());
t.insert(WedgeFace::TopFront,FaceDescription::default());
t.insert(WedgeFace::Back,FaceDescription::default());
t.insert(WedgeFace::Left,FaceDescription::default());
t.insert(WedgeFace::Bottom,FaceDescription::default());
generate_partial_unit_wedge(t)
}
pub type CornerWedgeFaceDescription=std::collections::HashMap::<CornerWedgeFace,FaceDescription>;
pub fn unit_cornerwedge()->crate::model::IndexedModel{
let mut t=CornerWedgeFaceDescription::new();
t.insert(CornerWedgeFace::Right,FaceDescription::default());
t.insert(CornerWedgeFace::Top,FaceDescription::default());
t.insert(CornerWedgeFace::Bottom,FaceDescription::default());
t.insert(CornerWedgeFace::Front,FaceDescription::default());
generate_partial_unit_cornerwedge(t)
}
#[derive(Copy,Clone)]
pub struct FaceDescription{
pub texture:Option<u32>,
pub transform:glam::Affine2,
pub color:glam::Vec4,
}
impl std::default::Default for FaceDescription{
fn default()->Self {
Self{
texture:None,
transform:glam::Affine2::IDENTITY,
color:glam::vec4(1.0,1.0,1.0,0.0),//zero alpha to hide the default texture
}
}
}
impl FaceDescription{
pub fn new(texture:u32,transform:glam::Affine2,color:glam::Vec4)->Self{
Self{texture:Some(texture),transform,color}
}
pub fn from_texture(texture:u32)->Self{
Self{
texture:Some(texture),
transform:glam::Affine2::IDENTITY,
color:glam::Vec4::ONE,
}
}
}
//TODO: it's probably better to use a shared vertex buffer between all primitives and use indexed rendering instead of generating a unique vertex buffer for each primitive.
//implementation: put all roblox primitives into one model.groups <- this won't work but I forget why
pub fn generate_partial_unit_cube(face_descriptions:CubeFaceDescription)->crate::model::IndexedModel{
let mut generated_pos=Vec::<[f32;3]>::new();
let mut generated_tex=Vec::new();
let mut generated_normal=Vec::new();
let mut generated_color=Vec::new();
let mut generated_vertices=Vec::new();
let mut groups=Vec::new();
let mut transforms=Vec::new();
//note that on a cube every vertex is guaranteed to be unique, so there's no need to hash them against existing vertices.
for (face,face_description) in face_descriptions.into_iter(){
//assume that scanning short lists is faster than hashing.
let transform_index=if let Some(transform_index)=transforms.iter().position(|&transform|transform==face_description.transform){
transform_index
}else{
//create new transform_index
let transform_index=transforms.len();
transforms.push(face_description.transform);
for tex in CUBE_DEFAULT_TEXTURE_COORDS{
generated_tex.push(*face_description.transform.transform_point2(glam::Vec2::from_array(tex)).as_ref());
}
transform_index
} as u32;
let color_index=if let Some(color_index)=generated_color.iter().position(|color|color==face_description.color.as_ref()){
color_index
}else{
//create new color_index
let color_index=generated_color.len();
generated_color.push(*face_description.color.as_ref());
color_index
} as u32;
let face_id=match face{
CubeFace::Right => 0,
CubeFace::Top => 1,
CubeFace::Back => 2,
CubeFace::Left => 3,
CubeFace::Bottom => 4,
CubeFace::Front => 5,
};
//always push normal
let normal_index=generated_normal.len() as u32;
generated_normal.push(CUBE_DEFAULT_NORMALS[face_id]);
//push vertices as they are needed
groups.push(IndexedGroup{
texture:face_description.texture,
polys:vec![IndexedPolygon{
vertices:CUBE_DEFAULT_POLYS[face_id].map(|tup|{
let pos=CUBE_DEFAULT_VERTICES[tup[0] as usize];
let pos_index=if let Some(pos_index)=generated_pos.iter().position(|&p|p==pos){
pos_index
}else{
//create new pos_index
let pos_index=generated_pos.len();
generated_pos.push(pos);
pos_index
} as u32;
//always push vertex
let vertex=IndexedVertex{
pos:pos_index,
tex:tup[1]+4*transform_index,
normal:normal_index,
color:color_index,
};
let vert_index=generated_vertices.len();
generated_vertices.push(vertex);
vert_index as u32
}).to_vec(),
}],
});
}
IndexedModel{
unique_pos:generated_pos,
unique_tex:generated_tex,
unique_normal:generated_normal,
unique_color:generated_color,
unique_vertices:generated_vertices,
groups,
instances:Vec::new(),
}
}
//don't think too hard about the copy paste because this is all going into the map tool eventually...
pub fn generate_partial_unit_wedge(face_descriptions:WedgeFaceDescription)->crate::model::IndexedModel{
let wedge_default_polys=vec![
// right (1, 0, 0)
vec![
[6,2,0],//[vertex,tex,norm]
[2,0,0],
[1,3,0],
], ],
// FrontTop (0, 1, -1) texture: vec![[0.0,0.0],[1.0,0.0],[1.0,1.0],[0.0,1.0]],
vec![ normal: vec![
[3,1,1], [1.,0.,0.],//AabbFace::Right
[2,0,1], [0.,1.,0.],//AabbFace::Top
[6,3,1], [0.,0.,1.],//AabbFace::Back
[7,2,1], [-1.,0.,0.],//AabbFace::Left
[0.,-1.,0.],//AabbFace::Bottom
[0.,0.,-1.],//AabbFace::Front
], ],
// back (0, 0, 1) objects: vec![obj::Object{
vec![ name: "Unit Cube".to_owned(),
[0,3,2], groups: vec![obj::Group{
[1,2,2], name: "Cube Vertices".to_owned(),
[2,1,2], index: 0,
[3,0,2], material: None,
], polys: vec![
// left (-1, 0, 0) // back (0, 0, 1)
vec![ obj::SimplePolygon(vec![
[0,2,3], obj::IndexTuple(0,Some(0),Some(2)),
[3,1,3], obj::IndexTuple(1,Some(1),Some(2)),
[7,3,3], obj::IndexTuple(2,Some(2),Some(2)),
], obj::IndexTuple(3,Some(3),Some(2)),
// bottom (0,-1, 0) ]),
vec![ // front (0, 0,-1)
[1,1,4], obj::SimplePolygon(vec![
[0,0,4], obj::IndexTuple(4,Some(0),Some(5)),
[7,3,4], obj::IndexTuple(5,Some(1),Some(5)),
[6,2,4], obj::IndexTuple(6,Some(2),Some(5)),
], obj::IndexTuple(7,Some(3),Some(5)),
]; ]),
let mut generated_pos=Vec::<[f32;3]>::new(); // right (1, 0, 0)
let mut generated_tex=Vec::new(); obj::SimplePolygon(vec![
let mut generated_normal=Vec::new(); obj::IndexTuple(6,Some(0),Some(0)),
let mut generated_color=Vec::new(); obj::IndexTuple(5,Some(1),Some(0)),
let mut generated_vertices=Vec::new(); obj::IndexTuple(2,Some(2),Some(0)),
let mut groups=Vec::new(); obj::IndexTuple(1,Some(3),Some(0)),
let mut transforms=Vec::new(); ]),
//note that on a cube every vertex is guaranteed to be unique, so there's no need to hash them against existing vertices. // left (-1, 0, 0)
for (face,face_description) in face_descriptions.into_iter(){ obj::SimplePolygon(vec![
//assume that scanning short lists is faster than hashing. obj::IndexTuple(0,Some(0),Some(3)),
let transform_index=if let Some(transform_index)=transforms.iter().position(|&transform|transform==face_description.transform){ obj::IndexTuple(3,Some(1),Some(3)),
transform_index obj::IndexTuple(4,Some(2),Some(3)),
}else{ obj::IndexTuple(7,Some(3),Some(3)),
//create new transform_index ]),
let transform_index=transforms.len(); // top (0, 1, 0)
transforms.push(face_description.transform); obj::SimplePolygon(vec![
for tex in CUBE_DEFAULT_TEXTURE_COORDS{ obj::IndexTuple(5,Some(1),Some(1)),
generated_tex.push(*face_description.transform.transform_point2(glam::Vec2::from_array(tex)).as_ref()); obj::IndexTuple(4,Some(0),Some(1)),
} obj::IndexTuple(3,Some(3),Some(1)),
transform_index obj::IndexTuple(2,Some(2),Some(1)),
} as u32; ]),
let color_index=if let Some(color_index)=generated_color.iter().position(|color|color==face_description.color.as_ref()){ // bottom (0,-1, 0)
color_index obj::SimplePolygon(vec![
}else{ obj::IndexTuple(1,Some(1),Some(4)),
//create new color_index obj::IndexTuple(0,Some(0),Some(4)),
let color_index=generated_color.len(); obj::IndexTuple(7,Some(3),Some(4)),
generated_color.push(*face_description.color.as_ref()); obj::IndexTuple(6,Some(2),Some(4)),
color_index ]),
} as u32; ],
let face_id=match face{ }]
WedgeFace::Right => 0, }],
WedgeFace::TopFront => 1, material_libs: Vec::new(),
WedgeFace::Back => 2,
WedgeFace::Left => 3,
WedgeFace::Bottom => 4,
};
//always push normal
let normal_index=generated_normal.len() as u32;
generated_normal.push(WEDGE_DEFAULT_NORMALS[face_id]);
//push vertices as they are needed
groups.push(IndexedGroup{
texture:face_description.texture,
polys:vec![IndexedPolygon{
vertices:wedge_default_polys[face_id].iter().map(|tup|{
let pos=CUBE_DEFAULT_VERTICES[tup[0] as usize];
let pos_index=if let Some(pos_index)=generated_pos.iter().position(|&p|p==pos){
pos_index
}else{
//create new pos_index
let pos_index=generated_pos.len();
generated_pos.push(pos);
pos_index
} as u32;
//always push vertex
let vertex=IndexedVertex{
pos:pos_index,
tex:tup[1]+4*transform_index,
normal:normal_index,
color:color_index,
};
let vert_index=generated_vertices.len();
generated_vertices.push(vertex);
vert_index as u32
}).collect(),
}],
});
} }
IndexedModel{ }
unique_pos:generated_pos,
unique_tex:generated_tex,
unique_normal:generated_normal,
unique_color:generated_color,
unique_vertices:generated_vertices,
groups,
instances:Vec::new(),
}
}
pub fn generate_partial_unit_cornerwedge(face_descriptions:CornerWedgeFaceDescription)->crate::model::IndexedModel{
let cornerwedge_default_polys=vec![
// right (1, 0, 0)
vec![
[6,2,0],//[vertex,tex,norm]
[5,1,0],
[1,3,0],
],
// BackTop (0, 1, 1)
vec![
[5,3,1],
[0,1,1],
[1,0,1],
],
// LeftTop (-1, 1, 0)
vec![
[5,3,2],
[7,2,2],
[0,1,2],
],
// bottom (0,-1, 0)
vec![
[1,1,3],
[0,0,3],
[7,3,3],
[6,2,3],
],
// front (0, 0,-1)
vec![
[5,0,4],
[6,3,4],
[7,2,4],
],
];
let mut generated_pos=Vec::<[f32;3]>::new();
let mut generated_tex=Vec::new();
let mut generated_normal=Vec::new();
let mut generated_color=Vec::new();
let mut generated_vertices=Vec::new();
let mut groups=Vec::new();
let mut transforms=Vec::new();
//note that on a cube every vertex is guaranteed to be unique, so there's no need to hash them against existing vertices.
for (face,face_description) in face_descriptions.into_iter(){
//assume that scanning short lists is faster than hashing.
let transform_index=if let Some(transform_index)=transforms.iter().position(|&transform|transform==face_description.transform){
transform_index
}else{
//create new transform_index
let transform_index=transforms.len();
transforms.push(face_description.transform);
for tex in CUBE_DEFAULT_TEXTURE_COORDS{
generated_tex.push(*face_description.transform.transform_point2(glam::Vec2::from_array(tex)).as_ref());
}
transform_index
} as u32;
let color_index=if let Some(color_index)=generated_color.iter().position(|color|color==face_description.color.as_ref()){
color_index
}else{
//create new color_index
let color_index=generated_color.len();
generated_color.push(*face_description.color.as_ref());
color_index
} as u32;
let face_id=match face{
CornerWedgeFace::Right => 0,
CornerWedgeFace::Top => 1,
CornerWedgeFace::Bottom => 2,
CornerWedgeFace::Front => 3,
};
//always push normal
let normal_index=generated_normal.len() as u32;
generated_normal.push(CORNERWEDGE_DEFAULT_NORMALS[face_id]);
//push vertices as they are needed
groups.push(IndexedGroup{
texture:face_description.texture,
polys:vec![IndexedPolygon{
vertices:cornerwedge_default_polys[face_id].iter().map(|tup|{
let pos=CUBE_DEFAULT_VERTICES[tup[0] as usize];
let pos_index=if let Some(pos_index)=generated_pos.iter().position(|&p|p==pos){
pos_index
}else{
//create new pos_index
let pos_index=generated_pos.len();
generated_pos.push(pos);
pos_index
} as u32;
//always push vertex
let vertex=IndexedVertex{
pos:pos_index,
tex:tup[1]+4*transform_index,
normal:normal_index,
color:color_index,
};
let vert_index=generated_vertices.len();
generated_vertices.push(vertex);
vert_index as u32
}).collect(),
}],
});
}
IndexedModel{
unique_pos:generated_pos,
unique_tex:generated_tex,
unique_normal:generated_normal,
unique_color:generated_color,
unique_vertices:generated_vertices,
groups,
instances:Vec::new(),
}
}

@ -43,20 +43,20 @@ fn vs_sky(@builtin(vertex_index) vertex_index: u32) -> SkyOutput {
struct ModelInstance{ struct ModelInstance{
transform:mat4x4<f32>, transform:mat4x4<f32>,
normal_transform:mat4x4<f32>, //texture_transform:mat3x3<f32>,
color:vec4<f32>, color:vec4<f32>,
} }
//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; const MAX_MODEL_INSTANCES=4096;
@group(2) @group(1)
@binding(0) @binding(0)
var<uniform> model_instances: array<ModelInstance, MAX_MODEL_INSTANCES>; var<uniform> model_instances: array<ModelInstance, MAX_MODEL_INSTANCES>;
@group(2) @group(1)
@binding(1) @binding(1)
var model_texture: texture_2d<f32>; var model_texture: texture_2d<f32>;
@group(2) @group(1)
@binding(2) @binding(2)
var model_sampler: sampler; var model_sampler: sampler;
@ -66,7 +66,6 @@ struct EntityOutputTexture {
@location(2) normal: vec3<f32>, @location(2) normal: vec3<f32>,
@location(3) view: vec3<f32>, @location(3) view: vec3<f32>,
@location(4) color: vec4<f32>, @location(4) color: vec4<f32>,
@location(5) @interpolate(flat) model_color: vec4<f32>,
}; };
@vertex @vertex
fn vs_entity_texture( fn vs_entity_texture(
@ -78,26 +77,25 @@ fn vs_entity_texture(
) -> EntityOutputTexture { ) -> EntityOutputTexture {
var position: vec4<f32> = model_instances[instance].transform * vec4<f32>(pos, 1.0); var position: vec4<f32> = model_instances[instance].transform * vec4<f32>(pos, 1.0);
var result: EntityOutputTexture; var result: EntityOutputTexture;
result.normal = (model_instances[instance].normal_transform * vec4<f32>(normal, 1.0)).xyz; result.normal = (model_instances[instance].transform * vec4<f32>(normal, 0.0)).xyz;
result.texture = texture; result.texture=texture;//(model_instances[instance].texture_transform * vec3<f32>(texture, 1.0)).xy;
result.color = color; result.color=model_instances[instance].color * color;
result.model_color = model_instances[instance].color;
result.view = position.xyz - camera.cam_pos.xyz; result.view = position.xyz - camera.cam_pos.xyz;
result.position = camera.proj * camera.view * position; result.position = camera.proj * camera.view * position;
return result; return result;
} }
//group 2 is the skybox texture //group 2 is the skybox texture
@group(1) @group(2)
@binding(0) @binding(0)
var cube_texture: texture_cube<f32>; var cube_texture: texture_cube<f32>;
@group(1) @group(2)
@binding(1) @binding(1)
var cube_sampler: sampler; var cube_sampler: sampler;
@fragment @fragment
fn fs_sky(vertex: SkyOutput) -> @location(0) vec4<f32> { fn fs_sky(vertex: SkyOutput) -> @location(0) vec4<f32> {
return textureSample(cube_texture, cube_sampler, vertex.sampledir); return textureSample(cube_texture, model_sampler, vertex.sampledir);
} }
@fragment @fragment
@ -109,5 +107,5 @@ fn fs_entity_texture(vertex: EntityOutputTexture) -> @location(0) vec4<f32> {
let fragment_color = textureSample(model_texture, model_sampler, vertex.texture)*vertex.color; let fragment_color = textureSample(model_texture, model_sampler, vertex.texture)*vertex.color;
let reflected_color = textureSample(cube_texture, cube_sampler, reflected).rgb; let reflected_color = textureSample(cube_texture, cube_sampler, reflected).rgb;
return mix(vec4<f32>(vec3<f32>(0.05) + 0.2 * reflected_color,1.0),mix(vertex.model_color,vec4<f32>(fragment_color.rgb,1.0),fragment_color.a),1.0-pow(1.0-abs(d),2.0)); return mix(vec4<f32>(vec3<f32>(0.1) + 0.5 * reflected_color,1.0),fragment_color,1.0-pow(1.0-abs(d),2.0));
} }