Compare commits

...

55 Commits

Author SHA1 Message Date
6f4af1c694 weird empty comment 2023-10-05 19:46:33 -07:00
40af48068a create CompatWorker and move physics back into main thread so it feels good to play
eventually I will work on thread stuff again and make threads for everything and workarounds to latency issues
2023-10-05 19:46:33 -07:00
edd3ca566a forgot camera offset 2023-10-05 19:46:33 -07:00
a1f9a62c89 to fix speen 2023-10-05 19:46:33 -07:00
b5ee40e48d fix mouse interpolation 2023-10-05 19:46:33 -07:00
3c521089cb this adds lag and is unnecessary 2023-10-04 23:52:20 -07:00
77ea099880 use absolute pos 2023-10-04 23:52:20 -07:00
54a21ae00b time must advance! (2 bugs related to this)
global.mouse.time
physics.time
2023-10-04 23:52:20 -07:00
dd61c64ddd move physics to its own thread 2023-10-04 23:51:46 -07:00
8cf66f3446 print less 2023-10-04 23:51:39 -07:00
1cb0d6e586 bro it takes 4 seconds to build now 2023-10-04 23:51:19 -07:00
12a4bf7948 rename body to physics 2023-10-04 23:16:26 -07:00
f2e4286a08 spawn_point is part of building 2023-10-04 15:34:52 -07:00
bd6cd5eacc worker module 2023-10-04 14:32:28 -07:00
f2dfb438d0 add parking_lot dep 2023-10-04 14:16:25 -07:00
7c8bc8d647 reset stage id on map change 2023-10-04 14:16:25 -07:00
4943bc6a7f edit normal mapping comments 2023-10-04 14:16:25 -07:00
55eebba1c5 fiddle with rustings 2023-10-04 14:16:25 -07:00
b8f13539db runtime attributes + implement model intersection (but not collision end) 2023-10-04 14:16:25 -07:00
fb2e2afeb9 hashmap map ids into internal structure ids 2023-10-04 14:13:25 -07:00
f30f246e5f sens TOO DAMN HIGH 2023-10-04 14:07:57 -07:00
0ac49308a0 Spawn & ForceSpawn attributes 2023-10-04 14:07:20 -07:00
30cbbbca1b fix MapStart indexing bug 2023-10-04 14:05:53 -07:00
66fa8fd637 tabs 2023-10-04 14:01:06 -07:00
f2c71caae3 TEMP(for a long time): implement indexing attributes
this is not very make invalid states unrepresentable of you
2023-10-03 19:47:06 -07:00
c8ec1f05d1 implement more attributes 2023-10-03 19:47:06 -07:00
b102319b33 implement Default for CollisionAttributes 2023-10-03 19:47:06 -07:00
50e9152ee2 separate graphics state from global state 2023-10-03 19:47:06 -07:00
7a8de938af rename stages to modes 2023-10-03 19:47:03 -07:00
696f383aee enable cheats 2023-10-03 17:31:34 -07:00
bfd6f4493f I was just stupid the whole time 2023-10-03 17:31:34 -07:00
ed96572a24 RelativeCollision.model helper 2023-10-03 17:20:35 -07:00
5914db3599 put control stuff in StyleModifiers 2023-10-03 16:53:00 -07:00
f72acaf2d4 implement attributes + stages 2023-10-03 16:53:00 -07:00
734ce661f2 game mechanics enums 2023-10-03 16:53:00 -07:00
bb8c53aee2 check transparency when generating models 2023-10-03 16:37:04 -07:00
de0eb0790a fixups 2023-10-03 16:37:04 -07:00
9e9550885f replace regex with lazy-regex macros 2023-10-03 16:35:45 -07:00
58be446297 reminder 2023-10-02 22:45:48 -07:00
d16404167b tweak map loading 2023-10-02 15:27:41 -07:00
79262ce3b4 styling 2023-10-02 03:08:40 -07:00
c47020c149 implement mouse lock with tab and manual mouse lock fallback 2023-10-02 03:08:40 -07:00
5854171619 typo 2023-10-02 01:58:35 -07:00
616b09a857 panic when roblox data is invalid 2023-10-02 01:58:30 -07:00
6ff2620bbc this code is unnecessary, delete it 2023-10-02 01:58:06 -07:00
d3e4918d3e into_iter is probably better than drain 2023-10-02 01:57:15 -07:00
6c2eb5ff29 this needs timers 2023-10-01 19:29:41 -07:00
02a509868a some bullshit to reduce line count 2023-10-01 19:29:41 -07:00
af750151f7 allow loading map from cli 2023-10-01 17:18:50 -07:00
bf4560193d make load_file function 2023-10-01 17:18:29 -07:00
514c45fc21 disable annoying scroll 2023-10-01 15:55:40 -07:00
95d16271de add cursor grab 2023-10-01 15:55:40 -07:00
355d391ea5 wee opti 2023-10-01 15:21:19 -07:00
d8c6444af3 consume textures + label textures with texture_id + don't pass id through thread 2023-10-01 15:17:10 -07:00
fddd4576bd multi threaded image load 2023-10-01 15:06:24 -07:00
10 changed files with 1401 additions and 579 deletions

26
Cargo.lock generated

@ -834,6 +834,29 @@ dependencies = [
"pkg-config",
]
[[package]]
name = "lazy-regex"
version = "3.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e723bd417b2df60a0f6a2b6825f297ea04b245d4ba52b5a22cb679bdf58b05fa"
dependencies = [
"lazy-regex-proc_macros",
"once_cell",
"regex",
]
[[package]]
name = "lazy-regex-proc_macros"
version = "3.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0f0a1d9139f0ee2e862e08a9c5d0ba0470f2aa21cd1e1aa1b1562f83116c725f"
dependencies = [
"proc-macro2",
"quote",
"regex",
"syn 2.0.29",
]
[[package]]
name = "lazy_static"
version = "1.4.0"
@ -1666,14 +1689,15 @@ dependencies = [
"ddsfile",
"env_logger",
"glam",
"lazy-regex",
"log",
"obj",
"parking_lot",
"pollster",
"rbx_binary",
"rbx_dom_weak",
"rbx_reflection_database",
"rbx_xml",
"regex",
"wgpu",
"winit",
]

@ -11,18 +11,19 @@ bytemuck = { version = "1.13.1", features = ["derive"] }
ddsfile = "0.5.1"
env_logger = "0.10.0"
glam = "0.24.1"
lazy-regex = "3.0.2"
log = "0.4.20"
obj = "0.10.2"
parking_lot = "0.12.1"
pollster = "0.3.0"
rbx_binary = "0.7.1"
rbx_dom_weak = "2.5.0"
rbx_reflection_database = "0.2.7"
rbx_xml = "0.13.1"
regex = "1.9.5"
wgpu = "0.17.0"
winit = "0.28.6"
[profile.release]
lto = true
strip = true
codegen-units = 1
#[profile.release]
#lto = true
#strip = true
#codegen-units = 1

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

@ -1,11 +1,11 @@
#[derive(Debug)]
pub struct TimedInstruction<I> {
pub time: crate::body::TIME,
pub time: crate::physics::TIME,
pub instruction: I,
}
pub trait InstructionEmitter<I> {
fn next_instruction(&self, time_limit:crate::body::TIME) -> Option<TimedInstruction<I>>;
fn next_instruction(&self, time_limit:crate::physics::TIME) -> Option<TimedInstruction<I>>;
}
pub trait InstructionConsumer<I> {
fn process_instruction(&mut self, instruction:TimedInstruction<I>);
@ -13,11 +13,11 @@ pub trait InstructionConsumer<I> {
//PROPER PRIVATE FIELDS!!!
pub struct InstructionCollector<I> {
time: crate::body::TIME,
time: crate::physics::TIME,
instruction: Option<I>,
}
impl<I> InstructionCollector<I> {
pub fn new(time:crate::body::TIME) -> Self {
pub fn new(time:crate::physics::TIME) -> Self {
Self{
time,
instruction:None

@ -1,5 +1,3 @@
use crate::model::{IndexedModelInstances,ModelInstance};
use crate::primitives;
fn class_is_a(class: &str, superclass: &str) -> bool {
@ -32,13 +30,89 @@ fn get_texture_refs(dom:&rbx_dom_weak::WeakDom) -> Vec<rbx_dom_weak::types::Ref>
//next class
objects
}
fn get_attributes(name:&str,can_collide:bool,velocity:glam::Vec3,force_intersecting:bool)->crate::model::CollisionAttributes{
let mut general=crate::model::GameMechanicAttributes::default();
let mut intersecting=crate::model::IntersectingAttributes::default();
let mut contacting=crate::model::ContactingAttributes::default();
match name{
//"Water"=>intersecting.water=Some(crate::model::IntersectingWater{density:1.0,drag:1.0}),
"Accelerator"=>intersecting.accelerator=Some(crate::model::IntersectingAccelerator{acceleration:velocity}),
"MapFinish"=>general.zone=Some(crate::model::GameMechanicZone{mode_id:0,behaviour:crate::model::ZoneBehaviour::Finish}),
"MapAnticheat"=>general.zone=Some(crate::model::GameMechanicZone{mode_id:0,behaviour:crate::model::ZoneBehaviour::Anitcheat}),
"Platform"=>general.stage_element=Some(crate::model::GameMechanicStageElement{
mode_id:0,
stage_id:0,
force:false,
behaviour:crate::model::StageElementBehaviour::Platform,
}),
other=>{
if let Some(captures)=lazy_regex::regex!(r"^(Force)?(Spawn|SpawnAt|Trigger|Teleport|Platform)(\d+)$")
.captures(other){
general.stage_element=Some(crate::model::GameMechanicStageElement{
mode_id:0,
stage_id:captures[3].parse::<u32>().unwrap(),
force:match captures.get(1){
Some(m)=>m.as_str()=="Force",
None=>false,
},
behaviour:match &captures[2]{
"Spawn"|"SpawnAt"=>crate::model::StageElementBehaviour::SpawnAt,
"Trigger"=>crate::model::StageElementBehaviour::Trigger,
"Teleport"=>crate::model::StageElementBehaviour::Teleport,
"Platform"=>crate::model::StageElementBehaviour::Platform,
_=>panic!("regex1[2] messed up bad"),
}
})
}else if let Some(captures)=lazy_regex::regex!(r"^Bonus(Finish|Anticheat)(\d+)$")
.captures(other){
match &captures[1]{
"Finish"=>general.zone=Some(crate::model::GameMechanicZone{mode_id:captures[2].parse::<u32>().unwrap(),behaviour:crate::model::ZoneBehaviour::Finish}),
"Anticheat"=>general.zone=Some(crate::model::GameMechanicZone{mode_id:captures[2].parse::<u32>().unwrap(),behaviour:crate::model::ZoneBehaviour::Anitcheat}),
_=>panic!("regex2[1] messed up bad"),
}
}
}
}
//need some way to skip this
if velocity!=glam::Vec3::ZERO{
general.booster=Some(crate::model::GameMechanicBooster{velocity});
}
match can_collide{
true=>{
match name{
//"Bounce"=>(),
"Surf"=>contacting.surf=Some(crate::model::ContactingSurf{}),
"Ladder"=>contacting.ladder=Some(crate::model::ContactingLadder{sticky:true}),
other=>{
//REGEX!!!!
//Jump#
//WormholeIn#
}
}
crate::model::CollisionAttributes::Contact{contacting,general}
},
false=>if force_intersecting
||general.jump_limit.is_some()
||general.booster.is_some()
||general.zone.is_some()
||general.stage_element.is_some()
||general.wormhole.is_some()
||intersecting.water.is_some()
||intersecting.accelerator.is_some()
{
crate::model::CollisionAttributes::Intersect{intersecting,general}
}else{
crate::model::CollisionAttributes::Decoration
},
}
}
struct RobloxAssetId(u64);
struct RobloxAssetIdParseErr;
impl std::str::FromStr for RobloxAssetId {
type Err=RobloxAssetIdParseErr;
fn from_str(s: &str) -> Result<Self, Self::Err>{
let regman=regex::Regex::new(r"(\d+)$").unwrap();
let regman=lazy_regex::regex!(r"(\d+)$");
if let Some(captures) = regman.captures(s) {
if captures.len()==2{//captures[0] is all captures concatenated, and then each individual capture
if let Ok(id) = captures[0].parse::<u64>() {
@ -111,7 +185,7 @@ enum RobloxBasePartDescription{
Wedge(RobloxWedgeDescription),
CornerWedge(RobloxCornerWedgeDescription),
}
pub fn generate_indexed_models_roblox(dom:rbx_dom_weak::WeakDom) -> Result<(IndexedModelInstances,glam::Vec3), Box<dyn std::error::Error>>{
pub fn generate_indexed_models(dom:rbx_dom_weak::WeakDom) -> crate::model::IndexedModelInstances{
//IndexedModelInstances includes textures
let mut spawn_point=glam::Vec3::ZERO;
@ -129,13 +203,17 @@ pub fn generate_indexed_models_roblox(dom:rbx_dom_weak::WeakDom) -> Result<(Inde
if let (
Some(rbx_dom_weak::types::Variant::CFrame(cf)),
Some(rbx_dom_weak::types::Variant::Vector3(size)),
Some(rbx_dom_weak::types::Variant::Vector3(velocity)),
Some(rbx_dom_weak::types::Variant::Float32(transparency)),
Some(rbx_dom_weak::types::Variant::Color3uint8(color3)),
Some(rbx_dom_weak::types::Variant::Bool(can_collide)),
) = (
object.properties.get("CFrame"),
object.properties.get("Size"),
object.properties.get("Velocity"),
object.properties.get("Transparency"),
object.properties.get("Color"),
object.properties.get("CanCollide"),
)
{
let model_transform=glam::Affine3A::from_translation(
@ -151,14 +229,35 @@ pub fn generate_indexed_models_roblox(dom:rbx_dom_weak::WeakDom) -> Result<(Inde
* glam::Affine3A::from_scale(
glam::Vec3::new(size.x,size.y,size.z)/2.0
);
if object.name=="MapStart"{
spawn_point=model_transform.transform_point3(glam::Vec3::Y)+glam::vec3(0.0,2.5,0.0);
println!("Found MapStart{:?}",spawn_point);
}
if *transparency==1.0 {
continue;
//push TempIndexedAttributes
let mut force_intersecting=false;
let mut temp_indexing_attributes=Vec::new();
if let Some(attr)=match &object.name[..]{
"MapStart"=>{
spawn_point=model_transform.transform_point3(glam::Vec3::ZERO)+glam::vec3(0.0,2.5,0.0);
Some(crate::model::TempIndexedAttributes::Start{mode_id:0})
},
"UnorderedCheckpoint"=>Some(crate::model::TempIndexedAttributes::UnorderedCheckpoint{mode_id:0}),
other=>{
let regman=lazy_regex::regex!(r"^(BonusStart|Spawn|ForceSpawn|OrderedCheckpoint)(\d+)$");
if let Some(captures) = regman.captures(other) {
match &captures[1]{
"BonusStart"=>Some(crate::model::TempIndexedAttributes::Start{mode_id:captures[2].parse::<u32>().unwrap()}),
"Spawn"|"ForceSpawn"=>Some(crate::model::TempIndexedAttributes::Spawn{mode_id:0,stage_id:captures[2].parse::<u32>().unwrap()}),
"OrderedCheckpoint"=>Some(crate::model::TempIndexedAttributes::OrderedCheckpoint{mode_id:0,checkpoint_id:captures[2].parse::<u32>().unwrap()}),
_=>None,
}
}else{
None
}
}
}{
force_intersecting=true;
temp_indexing_attributes.push(attr);
}
//TODO: also detect "CylinderMesh" etc here
let shape=match &object.class[..]{
"Part"=>{
if let Some(rbx_dom_weak::types::Variant::Enum(shape))=object.properties.get("Shape"){
@ -168,14 +267,10 @@ pub fn generate_indexed_models_roblox(dom:rbx_dom_weak::WeakDom) -> Result<(Inde
2=>primitives::Primitives::Cylinder,
3=>primitives::Primitives::Wedge,
4=>primitives::Primitives::CornerWedge,
_=>{
println!("Funky roblox PartType={}; defaulting to cube",shape.to_u32());
primitives::Primitives::Cube
},
_=>panic!("Funky roblox PartType={};",shape.to_u32()),
}
}else{
println!("Part has no Shape! defaulting to cube");
primitives::Primitives::Cube
panic!("Part has no Shape!");
}
},
"WedgePart"=>primitives::Primitives::Wedge,
@ -186,38 +281,6 @@ pub fn generate_indexed_models_roblox(dom:rbx_dom_weak::WeakDom) -> Result<(Inde
}
};
//TODO: also detect "CylinderMesh" etc here
let mut face_map=std::collections::HashMap::new();
match shape{
primitives::Primitives::Cube => {
face_map.insert(0,0);//Right
face_map.insert(1,1);//Top
face_map.insert(2,2);//Back
face_map.insert(3,3);//Left
face_map.insert(4,4);//Bottom
face_map.insert(5,5);//Front
},
primitives::Primitives::Wedge => {
face_map.insert(0,0);//Right
face_map.insert(1,1);//Top -> TopFront (some surf maps put surf textures on the Top face)
face_map.insert(2,1);//Front -> TopFront
face_map.insert(3,2);//Back
face_map.insert(4,3);//Left
face_map.insert(5,4);//Bottom
},
primitives::Primitives::CornerWedge => {
//Right -> None
face_map.insert(1,0);//Top
//Back -> None
face_map.insert(3,1);//Right
face_map.insert(4,2);//Bottom
face_map.insert(5,3);//Front
},
//do not support textured spheres/cylinders imported from roblox
//this can be added later, there are some maps that use it
primitives::Primitives::Sphere
|primitives::Primitives::Cylinder => (),
}
//use the biggest one and cut it down later...
let mut part_texture_description:RobloxPartDescription=[None,None,None,None,None,None];
temp_objects.clear();
@ -245,7 +308,7 @@ pub fn generate_indexed_models_roblox(dom:rbx_dom_weak::WeakDom) -> Result<(Inde
texture_id
};
let normal_id=normalid.to_u32();
if let Some(&face)=face_map.get(&normal_id){
if normal_id<6{
let mut roblox_texture_transform=RobloxTextureTransform::default();
let mut roblox_texture_color=glam::Vec4::ONE;
if decal.class=="Texture"{
@ -269,7 +332,7 @@ pub fn generate_indexed_models_roblox(dom:rbx_dom_weak::WeakDom) -> Result<(Inde
3=>(size.z,size.y),//left
4=>(size.x,size.z),//bottom
5=>(size.x,size.y),//front
_=>(1.,1.),
_=>panic!("unreachable"),
};
roblox_texture_transform=RobloxTextureTransform{
offset_u:*ox/(*sx),offset_v:*oy/(*sy),
@ -278,7 +341,7 @@ pub fn generate_indexed_models_roblox(dom:rbx_dom_weak::WeakDom) -> Result<(Inde
roblox_texture_color=glam::vec4(decal_color3.r,decal_color3.g,decal_color3.b,1.0-*decal_transparency);
}
}
part_texture_description[face]=Some(RobloxFaceTextureDescription{
part_texture_description[normal_id as usize]=Some(RobloxFaceTextureDescription{
texture:texture_id,
color:roblox_texture_color,
transform:roblox_texture_transform,
@ -291,16 +354,34 @@ pub fn generate_indexed_models_roblox(dom:rbx_dom_weak::WeakDom) -> Result<(Inde
}
}
//obscure rust syntax "slice pattern"
let [f0,f1,f2,f3,f4,f5]=part_texture_description;
let [
f0,//Cube::Right
f1,//Cube::Top
f2,//Cube::Back
f3,//Cube::Left
f4,//Cube::Bottom
f5,//Cube::Front
]=part_texture_description;
let basepart_texture_description=match shape{
primitives::Primitives::Sphere=>RobloxBasePartDescription::Sphere,
primitives::Primitives::Cube=>RobloxBasePartDescription::Part([f0,f1,f2,f3,f4,f5]),
primitives::Primitives::Cylinder=>RobloxBasePartDescription::Cylinder,
//HAHAHA
primitives::Primitives::Wedge=>RobloxBasePartDescription::Wedge([f0,f1,f2,f3,f4]),
primitives::Primitives::CornerWedge=>RobloxBasePartDescription::CornerWedge([f0,f1,f2,f3]),
//use front face texture first and use top face texture as a fallback
primitives::Primitives::Wedge=>RobloxBasePartDescription::Wedge([
f0,//Cube::Right->Wedge::Right
if f5.is_some(){f5}else{f1},//Cube::Front|Cube::Top->Wedge::TopFront
f2,//Cube::Back->Wedge::Back
f3,//Cube::Left->Wedge::Left
f4,//Cube::Bottom->Wedge::Bottom
]),
primitives::Primitives::CornerWedge=>RobloxBasePartDescription::CornerWedge([
f0,//Cube::Right->CornerWedge::Right
f1,//Cube::Top->CornerWedge::Top
f4,//Cube::Bottom->CornerWedge::Bottom
f5,//Cube::Front->CornerWedge::Front
]),
};
//make new model if unit cube has not been crated before
//make new model if unit cube has not been created before
let model_id=if let Some(&model_id)=model_id_from_description.get(&basepart_texture_description){
//push to existing texture model
model_id
@ -370,15 +451,19 @@ pub fn generate_indexed_models_roblox(dom:rbx_dom_weak::WeakDom) -> Result<(Inde
});
model_id
};
indexed_models[model_id].instances.push(ModelInstance {
indexed_models[model_id].instances.push(crate::model::ModelInstance {
transform:model_transform,
color:glam::vec4(color3.r as f32/255f32, color3.g as f32/255f32, color3.b as f32/255f32, 1.0-*transparency),
attributes:get_attributes(&object.name,*can_collide,glam::vec3(velocity.x,velocity.y,velocity.z),force_intersecting),
temp_indexing:temp_indexing_attributes,
});
}
}
}
Ok((IndexedModelInstances{
crate::model::IndexedModelInstances{
textures:asset_id_from_texture_id.iter().map(|t|t.to_string()).collect(),
models:indexed_models,
},spawn_point))
spawn_point,
modes:Vec::new(),
}
}

@ -1,12 +1,13 @@
use std::{borrow::Cow, time::Instant};
use wgpu::{util::DeviceExt, AstcBlock, AstcChannel};
use model::{Vertex,ModelInstance,ModelGraphicsInstance};
use body::{InputInstruction, PhysicsInstruction};
use physics::{InputInstruction, PhysicsInstruction};
use instruction::{TimedInstruction, InstructionConsumer};
mod body;
mod model;
mod zeroes;
mod worker;
mod physics;
mod framework;
mod primitives;
mod instruction;
@ -38,27 +39,90 @@ pub struct GraphicsBindGroups {
skybox_texture: wgpu::BindGroup,
}
pub struct GraphicsPipelines {
pub struct GraphicsPipelines{
skybox: wgpu::RenderPipeline,
model: wgpu::RenderPipeline,
}
pub struct GraphicsData {
start_time: std::time::Instant,
screen_size: (u32, u32),
physics: body::PhysicsState,
pub struct GraphicsCamera{
screen_size: glam::UVec2,
fov: glam::Vec2,//slope
//camera angles and such are extrapolated and passed in every time
}
#[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 GraphicsCamera{
pub fn new(screen_size:glam::UVec2,fov_y:f32)->Self{
Self{
screen_size,
fov: glam::vec2(fov_y*(screen_size.x as f32)/(screen_size.y as f32),fov_y),
}
}
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,angles:glam::Vec2)->glam::Mat4{
//f32 good enough for view matrix
glam::Mat4::from_translation(pos) * glam::Mat4::from_euler(glam::EulerRot::YXZ, angles.x, angles.y, 0f32)
}
pub fn set_screen_size(&mut self,screen_size:glam::UVec2){
self.screen_size=screen_size;
self.fov.x=self.fov.y*(screen_size.x as f32)/(screen_size.y as f32);
}
pub fn to_uniform_data(&self,(pos,angles): (glam::Vec3,glam::Vec2)) -> [f32; 16 * 3 + 4] {
let proj=self.proj();
let proj_inv = proj.inverse();
let view=self.view(pos,angles);
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 GraphicsState{
pipelines: GraphicsPipelines,
bind_groups: GraphicsBindGroups,
bind_group_layouts: GraphicsBindGroupLayouts,
samplers: GraphicsSamplers,
temp_squid_texture_view: wgpu::TextureView,
camera:GraphicsCamera,
camera_buf: wgpu::Buffer,
temp_squid_texture_view: wgpu::TextureView,
models: Vec<ModelGraphics>,
depth_view: wgpu::TextureView,
staging_belt: wgpu::util::StagingBelt,
}
impl GraphicsData {
impl GraphicsState{
pub fn clear(&mut self){
self.models.clear();
}
}
pub struct GlobalState{
start_time: std::time::Instant,
manual_mouse_lock:bool,
mouse:physics::MouseState,
graphics:GraphicsState,
physics_thread:worker::CompatWorker<TimedInstruction<InputInstruction>,physics::PhysicsOutputState,Box<dyn FnMut(TimedInstruction<InputInstruction>)->physics::PhysicsOutputState>>,
}
impl GlobalState{
const DEPTH_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Depth24Plus;
fn create_depth_texture(
@ -83,90 +147,92 @@ impl GraphicsData {
depth_texture.create_view(&wgpu::TextureViewDescriptor::default())
}
fn generate_model_physics(&mut self,indexed_models:&model::IndexedModelInstances){
for model in &indexed_models.models{
//make aabb and run vertices to get realistic bounds
for model_instance in &model.instances{
self.physics.models.push(body::ModelPhysics::from_model(&model,model_instance.transform));
}
}
println!("Physics Objects: {}",self.physics.models.len());
}
fn generate_model_graphics(&mut self,device:&wgpu::Device,queue:&wgpu::Queue,mut indexed_models:model::IndexedModelInstances){
fn generate_model_graphics(&mut self,device:&wgpu::Device,queue:&wgpu::Queue,indexed_models:model::IndexedModelInstances){
//generate texture view per texture
//idk how to do this gooder lol
let mut double_map=std::collections::HashMap::<u32,u32>::new();
let mut texture_views:Vec<wgpu::TextureView>=Vec::with_capacity(indexed_models.textures.len());
for (i,t) in indexed_models.textures.iter().enumerate(){
if let Ok(mut file) = std::fs::File::open(std::path::Path::new(&format!("textures/{}.dds",t))){
let image = ddsfile::Dds::read(&mut file).unwrap();
let (mut width,mut height)=(image.get_width(),image.get_height());
let format=match image.header10.unwrap().dxgi_format{
ddsfile::DxgiFormat::R8G8B8A8_UNorm_sRGB => wgpu::TextureFormat::Rgba8UnormSrgb,
ddsfile::DxgiFormat::BC7_UNorm_sRGB => {
//floor(w,4), should be ceil(w,4)
width=width/4*4;
height=height/4*4;
wgpu::TextureFormat::Bc7RgbaUnormSrgb
},
other=>panic!("unsupported format {:?}",other),
};
let size = wgpu::Extent3d {
width,
height,
depth_or_array_layers: 1,
};
let layer_size = wgpu::Extent3d {
depth_or_array_layers: 1,
..size
};
let max_mips = layer_size.max_mips(wgpu::TextureDimension::D2);
let texture = device.create_texture_with_data(
queue,
&wgpu::TextureDescriptor {
size,
mip_level_count: max_mips,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
label: Some(format!("Texture{}",i).as_str()),
view_formats: &[],
},
&image.data,
);
double_map.insert(i as u32, texture_views.len() as u32);
texture_views.push(texture.create_view(&wgpu::TextureViewDescriptor {
label: Some(format!("Texture{} View",i).as_str()),
dimension: Some(wgpu::TextureViewDimension::D2),
..wgpu::TextureViewDescriptor::default()
}));
let mut texture_loading_threads=Vec::new();
let num_textures=indexed_models.textures.len();
for (i,texture_id) in indexed_models.textures.into_iter().enumerate(){
if let Ok(mut file) = std::fs::File::open(std::path::Path::new(&format!("textures/{}.dds",texture_id))){
double_map.insert(i as u32, texture_loading_threads.len() as u32);
texture_loading_threads.push((texture_id,std::thread::spawn(move ||{
ddsfile::Dds::read(&mut file).unwrap()
})));
}
}
let indexed_models_len=indexed_models.models.len();
let texture_views:Vec<wgpu::TextureView>=texture_loading_threads.into_iter().map(|(texture_id,thread)|{
let image=thread.join().unwrap();
let (mut width,mut height)=(image.get_width(),image.get_height());
let format=match image.header10.unwrap().dxgi_format{
ddsfile::DxgiFormat::R8G8B8A8_UNorm_sRGB => wgpu::TextureFormat::Rgba8UnormSrgb,
ddsfile::DxgiFormat::BC7_UNorm_sRGB => {
//floor(w,4), should be ceil(w,4)
width=width/4*4;
height=height/4*4;
wgpu::TextureFormat::Bc7RgbaUnormSrgb
},
other=>panic!("unsupported format {:?}",other),
};
let size = wgpu::Extent3d {
width,
height,
depth_or_array_layers: 1,
};
let layer_size = wgpu::Extent3d {
depth_or_array_layers: 1,
..size
};
let max_mips = layer_size.max_mips(wgpu::TextureDimension::D2);
let texture = device.create_texture_with_data(
queue,
&wgpu::TextureDescriptor {
size,
mip_level_count: max_mips,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
label: Some(format!("Texture{}",texture_id).as_str()),
view_formats: &[],
},
&image.data,
);
texture.create_view(&wgpu::TextureViewDescriptor {
label: Some(format!("Texture{} View",texture_id).as_str()),
dimension: Some(wgpu::TextureViewDimension::D2),
..wgpu::TextureViewDescriptor::default()
})
}).collect();
//split groups with different textures into separate models
//the models received here are supposed to be tightly packed, i.e. no code needs to check if two models are using the same groups.
let mut unique_texture_models=Vec::with_capacity(indexed_models.models.len());
for mut model in indexed_models.models.drain(..){
let indexed_models_len=indexed_models.models.len();
let mut unique_texture_models=Vec::with_capacity(indexed_models_len);
for model in indexed_models.models.into_iter(){
//convert ModelInstance into ModelGraphicsInstance
let instances:Vec<ModelGraphicsInstance>=model.instances.iter().map(|instance|{
ModelGraphicsInstance{
transform: glam::Mat4::from(instance.transform),
normal_transform: glam::Mat4::from(instance.transform.inverse()).transpose(),
color: instance.color,
let instances:Vec<ModelGraphicsInstance>=model.instances.into_iter().filter_map(|instance|{
if instance.color.w==0.0{
None
}else{
Some(ModelGraphicsInstance{
transform: glam::Mat4::from(instance.transform),
normal_transform: glam::Mat4::from(instance.transform.inverse()).transpose(),
color: instance.color,
})
}
}).collect();
//check each group, if it's using a new texture then make a new clone of the model
let id=unique_texture_models.len();
let mut unique_textures=Vec::new();
for group in model.groups.drain(..){
for group in model.groups.into_iter(){
//ignore zero coppy optimization for now
let texture_index=if let Some(texture_index)=unique_textures.iter().position(|&texture|texture==group.texture){
texture_index
@ -193,7 +259,7 @@ impl GraphicsData {
}
//de-index models
let mut models=Vec::with_capacity(unique_texture_models.len());
for model in unique_texture_models.drain(..){
for model in unique_texture_models.into_iter(){
let mut vertices = Vec::new();
let mut index_from_vertex = std::collections::HashMap::new();//::<IndexedVertex,usize>
let mut entities = Vec::new();
@ -230,13 +296,13 @@ impl GraphicsData {
texture:model.texture,
});
}
//drain the modeldata vec so entities can be /moved/ to models.entities
//.into_iter() the modeldata vec so entities can be /moved/ to models.entities
let mut model_count=0;
let mut instance_count=0;
let uniform_buffer_binding_size=<GraphicsData as framework::Example>::required_limits().max_uniform_buffer_binding_size as usize;
let uniform_buffer_binding_size=<GlobalState as framework::Example>::required_limits().max_uniform_buffer_binding_size as usize;
let chunk_size=uniform_buffer_binding_size/MODEL_BUFFER_SIZE_BYTES;
self.models.reserve(models.len());
for model in models.drain(..) {
self.graphics.models.reserve(models.len());
for model in models.into_iter() {
instance_count+=model.instances.len();
for instances_chunk in model.instances.rchunks(chunk_size){
model_count+=1;
@ -250,13 +316,13 @@ impl GraphicsData {
Some(texture_id)=>{
match double_map.get(&texture_id){
Some(&mapped_texture_id)=>&texture_views[mapped_texture_id as usize],
None=>&self.temp_squid_texture_view,
None=>&self.graphics.temp_squid_texture_view,
}
},
None=>&self.temp_squid_texture_view,
None=>&self.graphics.temp_squid_texture_view,
};
let model_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
layout: &self.bind_group_layouts.model,
layout: &self.graphics.bind_group_layouts.model,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
@ -268,7 +334,7 @@ impl GraphicsData {
},
wgpu::BindGroupEntry {
binding: 2,
resource: wgpu::BindingResource::Sampler(&self.samplers.repeat),
resource: wgpu::BindingResource::Sampler(&self.graphics.samplers.repeat),
},
],
label: Some(format!("Model{} Bind Group",model_count).as_str()),
@ -279,7 +345,7 @@ impl GraphicsData {
usage: wgpu::BufferUsages::VERTEX,
});
//all of these are being moved here
self.models.push(ModelGraphics{
self.graphics.models.push(ModelGraphics{
instances:instances_chunk.to_vec(),
vertex_buf,
entities: model.entities.iter().map(|indices|{
@ -298,10 +364,10 @@ impl GraphicsData {
});
}
}
println!("Texture References={}",indexed_models.textures.len());
println!("Texture References={}",num_textures);
println!("Textures Loaded={}",texture_views.len());
println!("Indexed Models={}",indexed_models_len);
println!("Graphics Objects: {}",self.models.len());
println!("Graphics Objects: {}",self.graphics.models.len());
println!("Graphics Instances: {}",instance_count);
}
}
@ -323,21 +389,7 @@ fn get_instances_buffer_data(instances:&[ModelGraphicsInstance]) -> Vec<f32> {
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 GlobalState {
fn optional_features() -> wgpu::Features {
wgpu::Features::TEXTURE_COMPRESSION_ASTC
| wgpu::Features::TEXTURE_COMPRESSION_ETC2
@ -362,34 +414,44 @@ impl framework::Example for GraphicsData {
println!("models.len = {:?}", indexed_models.len());
indexed_models[0].instances.push(ModelInstance{
transform:glam::Affine3A::from_translation(glam::vec3(10.,0.,-10.)),
color:glam::Vec4::ONE,
..Default::default()
});
//quad monkeys
indexed_models[1].instances.push(ModelInstance{
transform:glam::Affine3A::from_translation(glam::vec3(10.,5.,10.)),
color:glam::Vec4::ONE,
..Default::default()
});
indexed_models[1].instances.push(ModelInstance{
transform:glam::Affine3A::from_translation(glam::vec3(20.,5.,10.)),
color:glam::vec4(1.0,0.0,0.0,1.0),
..Default::default()
});
indexed_models[1].instances.push(ModelInstance{
transform:glam::Affine3A::from_translation(glam::vec3(10.,5.,20.)),
color:glam::vec4(0.0,1.0,0.0,1.0),
..Default::default()
});
indexed_models[1].instances.push(ModelInstance{
transform:glam::Affine3A::from_translation(glam::vec3(20.,5.,20.)),
color:glam::vec4(0.0,0.0,1.0,1.0),
..Default::default()
});
//decorative monkey
indexed_models[1].instances.push(ModelInstance{
transform:glam::Affine3A::from_translation(glam::vec3(15.,10.,15.)),
color:glam::vec4(0.5,0.5,0.5,0.5),
attributes:model::CollisionAttributes::Decoration,
..Default::default()
});
//teapot
indexed_models[2].instances.push(ModelInstance{
transform:glam::Affine3A::from_scale_rotation_translation(glam::vec3(0.5, 1.0, 0.2),glam::quat(-0.22248298016985793,-0.839457167990537,-0.05603504040830783,-0.49261857546227916),glam::vec3(-10.,7.,10.)),
color:glam::Vec4::ONE,
..Default::default()
});
//ground
indexed_models[3].instances.push(ModelInstance{
transform:glam::Affine3A::from_translation(glam::vec3(0.,0.,0.))*glam::Affine3A::from_scale(glam::vec3(160.0, 1.0, 160.0)),
color:glam::Vec4::ONE,
..Default::default()
});
let camera_bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
@ -487,28 +549,6 @@ impl framework::Example for GraphicsData {
source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(include_str!("shader.wgsl"))),
});
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)),
time: 0,
tick: 0,
strafe_tick_num: 100,//100t
strafe_tick_den: 1_000_000_000,
gravity: glam::vec3(0.0,-100.0,0.0),
friction: 1.2,
walk_accel: 90.0,
mv: 2.7,
grounded: false,
walkspeed: 18.0,
contacts: std::collections::HashSet::new(),
models: Vec::new(),
walk: body::WalkState::new(),
hitbox_halfsize: glam::vec3(1.0,2.5,1.0),
camera: body::Camera::from_offset(glam::vec3(0.0,4.5-2.5,0.0),(config.width as f32)/(config.height as f32)),
mouse_interpolation: body::MouseInterpolationState::new(),
controls: 0,
};
//load textures
let device_features = device.features();
@ -703,7 +743,10 @@ impl framework::Example for GraphicsData {
multiview: None,
});
let camera_uniforms = to_uniform_data(&physics.camera,physics.body.extrapolated_position(0));
let mut physics = physics::PhysicsState::default();
let camera=GraphicsCamera::new(glam::uvec2(config.width,config.height), 1.0);
let camera_uniforms = camera.to_uniform_data(physics.output().adjust_mouse(&physics.next_mouse));
let camera_buf = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("Camera"),
contents: bytemuck::cast_slice(&camera_uniforms),
@ -719,6 +762,7 @@ impl framework::Example for GraphicsData {
],
label: Some("Camera"),
});
let skybox_texture_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
layout: &skybox_texture_bind_group_layout,
entries: &[
@ -736,10 +780,7 @@ impl framework::Example for GraphicsData {
let depth_view = Self::create_depth_texture(config, device);
let mut graphics=GraphicsData {
start_time: Instant::now(),
screen_size: (config.width,config.height),
physics,
let graphics=GraphicsState {
pipelines:GraphicsPipelines{
skybox:sky_pipeline,
model:model_pipeline
@ -748,6 +789,7 @@ impl framework::Example for GraphicsData {
camera:camera_bind_group,
skybox_texture:skybox_texture_bind_group,
},
camera,
camera_buf,
models: Vec::new(),
depth_view,
@ -760,82 +802,114 @@ impl framework::Example for GraphicsData {
let indexed_model_instances=model::IndexedModelInstances{
textures:Vec::new(),
models:indexed_models,
spawn_point:glam::Vec3::Y*50.0,
modes:Vec::new(),
};
graphics.generate_model_physics(&indexed_model_instances);
graphics.generate_model_graphics(&device,&queue,indexed_model_instances);
return graphics;
//how to multithread
//1. build
physics.generate_models(&indexed_model_instances);
//2. move
let physics_thread=physics.into_worker();
//3. forget
let mut state=GlobalState{
start_time:Instant::now(),
manual_mouse_lock:false,
mouse:physics::MouseState::default(),
graphics,
physics_thread,
};
state.generate_model_graphics(&device,&queue,indexed_model_instances);
let args:Vec<String>=std::env::args().collect();
if args.len()==2{
state.load_file(std::path::PathBuf::from(&args[1]), device, queue);
}
return state;
}
fn load_file(&mut self,path: std::path::PathBuf, device: &wgpu::Device, queue: &wgpu::Queue){
println!("Loading file: {:?}", &path);
//oh boy! let's load the map!
if let Ok(file)=std::fs::File::open(path){
let mut input = std::io::BufReader::new(file);
let mut first_8=[0u8;8];
//.rbxm roblox binary = "<roblox!"
//.rbxmx roblox xml = "<roblox "
//.bsp = "VBSP"
//.vmf =
//.snf = "SNMF"
//.snf = "SNBF"
if let (Ok(()),Ok(()))=(std::io::Read::read_exact(&mut input, &mut first_8),std::io::Seek::rewind(&mut input)){
if let Some(indexed_model_instances)={
match &first_8[0..4]{
b"<rob"=>{
match match &first_8[4..8]{
b"lox!"=>rbx_binary::from_reader(input).map_err(|e|format!("{:?}",e)),
b"lox "=>rbx_xml::from_reader(input,rbx_xml::DecodeOptions::default()).map_err(|e|format!("{:?}",e)),
other=>Err(format!("Unknown Roblox file type {:?}",other)),
}{
Ok(dom)=>Some(load_roblox::generate_indexed_models(dom)),
Err(e)=>{
println!("Error loading roblox file:{:?}",e);
None
},
}
},
//b"VBSP"=>Some(load_bsp::generate_indexed_models(input)),
//b"SNFM"=>Some(sniffer::generate_indexed_models(input)),
//b"SNFB"=>Some(sniffer::load_bot(input)),
other=>{
println!("loser file {:?}",other);
None
},
}
}{
let spawn_point=indexed_model_instances.spawn_point;
//if generate_indexed_models succeeds, clear the previous ones
self.graphics.clear();
let mut physics=physics::PhysicsState::default();
physics.game.stage_id=0;
physics.spawn_point=spawn_point;
physics.process_instruction(instruction::TimedInstruction{
time:physics.time,
instruction: PhysicsInstruction::Input(physics::PhysicsInputInstruction::Reset),
});
physics.generate_models(&indexed_model_instances);
self.physics_thread=physics.into_worker();
self.generate_model_graphics(device,queue,indexed_model_instances);
//manual reset
}else{
println!("No modeldatas were generated");
}
}else{
println!("Failed to read first 8 bytes and seek back to beginning of file.");
}
}else{
println!("Could not open file");
}
}
#[allow(clippy::single_match)]
fn update(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, event: winit::event::WindowEvent) {
//nothing atm
fn update(&mut self, window: &winit::window::Window, device: &wgpu::Device, queue: &wgpu::Queue, event: winit::event::WindowEvent) {
match event {
winit::event::WindowEvent::DroppedFile(path) => {
println!("opening file: {:?}", &path);
//oh boy! let's load the map!
if let Ok(file)=std::fs::File::open(path){
let mut input = std::io::BufReader::new(file);
let mut first_8=[0u8;8];
//.rbxm roblox binary = "<roblox!"
//.rbxmx roblox xml = "<roblox "
//.bsp = "VBSP"
//.vmf =
//.snf = "SNMF"
//.snf = "SNBF"
if let (Ok(()),Ok(()))=(std::io::Read::read_exact(&mut input, &mut first_8),std::io::Seek::rewind(&mut input)){
//
if let Some(Ok((indexed_model_instances,spawn_point)))={
match &first_8[0..4]{
b"<rob"=>{
match match &first_8[4..8]{
b"lox!"=>rbx_binary::from_reader(input).map_err(|e|format!("{:?}",e)),
b"lox "=>rbx_xml::from_reader(input,rbx_xml::DecodeOptions::default()).map_err(|e|format!("{:?}",e)),
other=>Err(format!("Unknown Roblox file type {:?}",other)),
}{
Ok(dom)=>Some(load_roblox::generate_indexed_models_roblox(dom)),
Err(e)=>{
println!("Error loading roblox file:{:?}",e);
None
},
}
},
//b"VBSP"=>load_valve::generate_indexed_models_valve(input),
//b"SNFM"=>sniffer::generate_indexed_models(input),
//b"SNFB"=>sniffer::load_bot(input),
_=>None,
}
}{
//if generate_indexed_models succeeds, clear the previous ones
self.models.clear();
self.physics.models.clear();
self.generate_model_physics(&indexed_model_instances);
self.generate_model_graphics(device,queue,indexed_model_instances);
//manual reset
let time=self.physics.time;
instruction::InstructionConsumer::process_instruction(&mut self.physics, instruction::TimedInstruction{
time,
instruction: body::PhysicsInstruction::SetSpawnPosition(spawn_point),
});
instruction::InstructionConsumer::process_instruction(&mut self.physics, instruction::TimedInstruction{
time,
instruction: body::PhysicsInstruction::Input(body::InputInstruction::Reset),
});
}else{
println!("No modeldatas were generated");
}
}else{
println!("Failed to read first 8 bytes and seek back to beginning of file.");
}
}else{
println!("Could not open file");
}
},
winit::event::WindowEvent::DroppedFile(path) => self.load_file(path,device,queue),
winit::event::WindowEvent::Focused(state)=>{
//pause unpause
//recalculate pressed keys on focus
}
_=>(),
}
}
fn device_event(&mut self, event: winit::event::DeviceEvent) {
fn device_event(&mut self, window: &winit::window::Window, event: winit::event::DeviceEvent) {
//there's no way this is the best way get a timestamp.
let time=self.start_time.elapsed().as_nanos() as i64;
match event {
@ -849,46 +923,92 @@ impl framework::Example for GraphicsData {
winit::event::ElementState::Released => false,
};
if let Some(input_instruction)=match keycode {
17 => Some(InputInstruction::MoveForward(s)),//W
30 => Some(InputInstruction::MoveLeft(s)),//A
31 => Some(InputInstruction::MoveBack(s)),//S
32 => Some(InputInstruction::MoveRight(s)),//D
18 => Some(InputInstruction::MoveUp(s)),//E
16 => Some(InputInstruction::MoveDown(s)),//Q
57 => Some(InputInstruction::Jump(s)),//Space
44 => Some(InputInstruction::Zoom(s)),//Z
19 => if s{Some(InputInstruction::Reset)}else{None},//R
_ => None,
}
{
self.physics.run(time);
self.physics.process_instruction(TimedInstruction{
17=>Some(InputInstruction::MoveForward(s)),//W
30=>Some(InputInstruction::MoveLeft(s)),//A
31=>Some(InputInstruction::MoveBack(s)),//S
32=>Some(InputInstruction::MoveRight(s)),//D
18=>Some(InputInstruction::MoveUp(s)),//E
16=>Some(InputInstruction::MoveDown(s)),//Q
57=>Some(InputInstruction::Jump(s)),//Space
44=>Some(InputInstruction::Zoom(s)),//Z
19=>if s{Some(InputInstruction::Reset)}else{None},//R
01=>{//Esc
if s{
self.manual_mouse_lock=false;
match window.set_cursor_grab(winit::window::CursorGrabMode::None){
Ok(())=>(),
Err(e)=>println!("Could not release cursor: {:?}",e),
}
window.set_cursor_visible(true);
}
None
},
15=>{//Tab
if s{
self.manual_mouse_lock=false;
match window.set_cursor_position(winit::dpi::PhysicalPosition::new(self.graphics.camera.screen_size.x as f32/2.0, self.graphics.camera.screen_size.y 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_thread.send(TimedInstruction{
time,
instruction:PhysicsInstruction::Input(input_instruction),
})
instruction:input_instruction,
}).unwrap();
}
},
winit::event::DeviceEvent::MouseMotion {
delta,//these (f64,f64) are integers on my machine
} => {
if self.manual_mouse_lock{
match window.set_cursor_position(winit::dpi::PhysicalPosition::new(self.graphics.camera.screen_size.x as f32/2.0, self.graphics.camera.screen_size.y 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{
let delta=glam::ivec2(delta.0 as i32,delta.1 as i32);
self.mouse.pos+=delta;
self.physics_thread.send(TimedInstruction{
time,
instruction:PhysicsInstruction::Input(InputInstruction::MoveMouse(glam::ivec2(delta.0 as i32,delta.1 as i32))),
})
instruction:InputInstruction::MoveMouse(self.mouse.pos),
}).unwrap();
},
winit::event::DeviceEvent::MouseWheel {
delta,
} => {
println!("mousewheel{:?}",delta);
if true{//self.physics.use_scroll
self.physics.run(time);
self.physics.process_instruction(TimedInstruction{
println!("mousewheel {:?}",delta);
if false{//self.physics.style.use_scroll{
self.physics_thread.send(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
})
instruction:InputInstruction::Jump(true),//activates the immediate jump path, but the style modifier prevents controls&CONTROL_JUMP bit from being set to auto jump
}).unwrap();
}
}
_=>(),
@ -901,9 +1021,8 @@ impl framework::Example for GraphicsData {
device: &wgpu::Device,
_queue: &wgpu::Queue,
) {
self.depth_view = Self::create_depth_texture(config, device);
self.screen_size = (config.width, config.height);
self.physics.camera.set_fov_aspect(1.0,(config.width as f32)/(config.height as f32));
self.graphics.depth_view = Self::create_depth_texture(config, device);
self.graphics.camera.set_screen_size(glam::uvec2(config.width, config.height));
}
fn render(
@ -913,28 +1032,34 @@ impl framework::Example for GraphicsData {
queue: &wgpu::Queue,
_spawner: &framework::Spawner,
) {
//ideally this would be scheduled to execute and finish right before the render.
let time=self.start_time.elapsed().as_nanos() as i64;
self.physics.run(time);
self.physics_thread.send(TimedInstruction{
time,
instruction:InputInstruction::Idle,
}).unwrap();
//update time lol
self.mouse.time=time;
let mut encoder =
device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None });
// update rotation
let camera_uniforms = to_uniform_data(&self.physics.camera,self.physics.body.extrapolated_position(time));
self.staging_belt
let camera_uniforms = self.graphics.camera.to_uniform_data(self.physics_thread.grab_clone().adjust_mouse(&self.mouse));
self.graphics.staging_belt
.write_buffer(
&mut encoder,
&self.camera_buf,
&self.graphics.camera_buf,
0,
wgpu::BufferSize::new((camera_uniforms.len() * 4) as wgpu::BufferAddress).unwrap(),
device,
)
.copy_from_slice(bytemuck::cast_slice(&camera_uniforms));
//This code only needs to run when the uniforms change
for model in self.models.iter() {
/*
for model in self.graphics.models.iter() {
let model_uniforms = get_instances_buffer_data(&model.instances);
self.staging_belt
self.graphics.staging_belt
.write_buffer(
&mut encoder,
&model.model_buf,//description of where data will be written when command is executed
@ -944,7 +1069,8 @@ impl framework::Example for GraphicsData {
)
.copy_from_slice(bytemuck::cast_slice(&model_uniforms));
}
self.staging_belt.finish();
*/
self.graphics.staging_belt.finish();
{
let mut rpass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
@ -963,7 +1089,7 @@ impl framework::Example for GraphicsData {
},
})],
depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
view: &self.depth_view,
view: &self.graphics.depth_view,
depth_ops: Some(wgpu::Operations {
load: wgpu::LoadOp::Clear(1.0),
store: false,
@ -972,11 +1098,11 @@ impl framework::Example for GraphicsData {
}),
});
rpass.set_bind_group(0, &self.bind_groups.camera, &[]);
rpass.set_bind_group(1, &self.bind_groups.skybox_texture, &[]);
rpass.set_bind_group(0, &self.graphics.bind_groups.camera, &[]);
rpass.set_bind_group(1, &self.graphics.bind_groups.skybox_texture, &[]);
rpass.set_pipeline(&self.pipelines.model);
for model in self.models.iter() {
rpass.set_pipeline(&self.graphics.pipelines.model);
for model in self.graphics.models.iter() {
rpass.set_bind_group(2, &model.bind_group, &[]);
rpass.set_vertex_buffer(0, model.vertex_buf.slice(..));
@ -986,18 +1112,18 @@ impl framework::Example for GraphicsData {
}
}
rpass.set_pipeline(&self.pipelines.skybox);
rpass.set_pipeline(&self.graphics.pipelines.skybox);
rpass.draw(0..3, 0..1);
}
queue.submit(std::iter::once(encoder.finish()));
self.staging_belt.recall();
self.graphics.staging_belt.recall();
}
}
fn main() {
framework::run::<GraphicsData>(
framework::run::<GlobalState>(
format!("Strafe Client v{}",
env!("CARGO_PKG_VERSION")
).as_str()

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

@ -13,9 +13,22 @@ pub enum PhysicsInstruction {
// bool,//true = Force
// )
//InputInstructions conditionally activate RefreshWalkTarget (by doing what SetWalkTargetVelocity used to do and then flagging it)
Input(InputInstruction),
//temp
SetSpawnPosition(glam::Vec3),
Input(PhysicsInputInstruction),
}
#[derive(Debug)]
pub enum PhysicsInputInstruction {
ReplaceMouse(MouseState,MouseState),
SetNextMouse(MouseState),
SetMoveForward(bool),
SetMoveLeft(bool),
SetMoveBack(bool),
SetMoveRight(bool),
SetMoveUp(bool),
SetMoveDown(bool),
SetJump(bool),
SetZoom(bool),
Reset,
Idle,
}
#[derive(Debug)]
pub enum InputInstruction {
@ -34,7 +47,7 @@ pub enum InputInstruction {
//for interpolation / networking / playback reasons, most playback heads will always want
//to be 1 instruction ahead to generate the next state for interpolation.
}
#[derive(Clone)]
pub struct Body {
position: glam::Vec3,//I64 where 2^32 = 1 u
velocity: glam::Vec3,//I64 where 2^32 = 1 u/s
@ -45,20 +58,20 @@ trait MyHash{
fn hash(&self) -> u64;
}
impl MyHash for Body {
fn hash(&self) -> u64 {
fn hash(&self) -> u64 {
let mut hasher=std::collections::hash_map::DefaultHasher::new();
for &el in self.position.as_ref().iter() {
std::hash::Hasher::write(&mut hasher, el.to_ne_bytes().as_slice());
}
for &el in self.velocity.as_ref().iter() {
std::hash::Hasher::write(&mut hasher, el.to_ne_bytes().as_slice());
}
for &el in self.acceleration.as_ref().iter() {
std::hash::Hasher::write(&mut hasher, el.to_ne_bytes().as_slice());
}
std::hash::Hasher::write(&mut hasher, self.time.to_ne_bytes().as_slice());
for &el in self.position.as_ref().iter() {
std::hash::Hasher::write(&mut hasher, el.to_ne_bytes().as_slice());
}
for &el in self.velocity.as_ref().iter() {
std::hash::Hasher::write(&mut hasher, el.to_ne_bytes().as_slice());
}
for &el in self.acceleration.as_ref().iter() {
std::hash::Hasher::write(&mut hasher, el.to_ne_bytes().as_slice());
}
std::hash::Hasher::write(&mut hasher, self.time.to_ne_bytes().as_slice());
return std::hash::Hasher::finish(&hasher);//hash check to see if walk target is valid
}
}
}
pub enum MoveRestriction {
@ -80,9 +93,9 @@ impl InputState {
}
impl crate::instruction::InstructionEmitter<InputInstruction> for InputState{
fn next_instruction(&self, time_limit:crate::body::TIME) -> Option<TimedInstruction<InputInstruction>> {
//this is polled by PhysicsState for actions like Jump
//no, it has to be the other way around. physics is run up until the jump instruction, and then the jump instruction is pushed.
self.queue.get(0)
//this is polled by PhysicsState for actions like Jump
//no, it has to be the other way around. physics is run up until the jump instruction, and then the jump instruction is pushed.
self.queue.get(0)
}
}
impl crate::instruction::InstructionConsumer<InputInstruction> for InputState{
@ -93,47 +106,30 @@ impl crate::instruction::InstructionConsumer<InputInstruction> for InputState{
}
*/
enum MouseInterpolation {
First,//just checks the last value
Lerp,//lerps between
//hey dumbass just use a delta
#[derive(Clone,Debug)]
pub struct MouseState {
pub pos: glam::IVec2,
pub time: TIME,
}
pub struct MouseInterpolationState {
interpolation: MouseInterpolation,
time0: TIME,
time1: TIME,
mouse0: glam::IVec2,
mouse1: glam::IVec2,
}
impl MouseInterpolationState {
pub fn new() -> Self {
impl Default for MouseState{
fn default() -> Self {
Self {
interpolation:MouseInterpolation::First,
time0:0,
time1:1,//ONE NANOSECOND!!!! avoid divide by zero
mouse0:glam::IVec2::ZERO,
mouse1:glam::IVec2::ZERO,
time:0,
pos:glam::IVec2::ZERO,
}
}
pub fn move_mouse(&mut self,time:TIME,delta:glam::IVec2){
self.time0=self.time1;
self.mouse0=self.mouse1;
self.time1=time;
self.mouse1=self.mouse1+delta;
}
pub fn interpolated_position(&self,time:TIME) -> glam::IVec2 {
match self.interpolation {
MouseInterpolation::First => self.mouse0,
MouseInterpolation::Lerp => {
let m0=self.mouse0.as_i64vec2();
let m1=self.mouse1.as_i64vec2();
//these are deltas
let t1t=(self.time1-time) as i64;
let tt0=(time-self.time0) as i64;
let dt=(self.time1-self.time0) as i64;
((m0*t1t+m1*tt0)/dt).as_ivec2()
}
}
}
impl MouseState {
pub fn lerp(&self,target:&MouseState,time:TIME)->glam::IVec2 {
let m0=self.pos.as_i64vec2();
let m1=target.pos.as_i64vec2();
//these are deltas
//let time=time.clamp(self.time, target.time);
let t1t=(target.time-time) as i64;
let tt0=(time-self.time) as i64;
let dt=(target.time-self.time) as i64;
((m0*t1t+m1*tt0)/dt).as_ivec2()
}
}
@ -156,127 +152,168 @@ impl WalkState {
}
}
// Note: we use the Y=up coordinate space in this example.
pub struct Camera {
#[derive(Clone)]
pub struct PhysicsCamera {
offset: glam::Vec3,
angles: glam::DVec2,//YAW AND THEN PITCH
//punch: glam::Vec3,
//punch_velocity: glam::Vec3,
fov: glam::Vec2,//slope
sensitivity: glam::DVec2,
time: TIME,
mouse:MouseState,
}
#[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),
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),
)
}
impl Camera {
pub fn from_offset(offset:glam::Vec3,aspect:f32) -> Self {
impl PhysicsCamera {
pub fn from_offset(offset:glam::Vec3) -> Self {
Self{
offset,
angles: glam::DVec2::ZERO,
fov: glam::vec2(aspect,1.0),
sensitivity: glam::dvec2(1.0/6144.0,1.0/6144.0),
time: 0,
offset,
angles: glam::DVec2::ZERO,
sensitivity: glam::dvec2(1.0/16384.0,1.0/16384.0),
mouse:MouseState{pos:glam::IVec2::ZERO,time:-1},//escape initialization hell divide by zero
}
}
fn simulate_move_angles(&self, delta: glam::IVec2) -> glam::DVec2 {
let mut a=self.angles-self.sensitivity*delta.as_dvec2();
pub fn simulate_move_angles(&self, mouse_pos: glam::IVec2) -> glam::DVec2 {
let mut a=self.angles-self.sensitivity*(mouse_pos-self.mouse.pos).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;
fn simulate_move_rotation_y(&self, mouse_pos_x: i32) -> glam::Mat3 {
mat3_from_rotation_y_f64(self.angles.x-self.sensitivity.x*((mouse_pos_x-self.mouse.pos.x) as f64))
}
}
const CONTROL_MOVEFORWARD:u32 = 0b00000001;
const CONTROL_MOVEBACK:u32 = 0b00000010;
const CONTROL_MOVERIGHT:u32 = 0b00000100;
const CONTROL_MOVELEFT:u32 = 0b00001000;
const CONTROL_MOVEUP:u32 = 0b00010000;
const CONTROL_MOVEDOWN:u32 = 0b00100000;
const CONTROL_JUMP:u32 = 0b01000000;
const CONTROL_ZOOM:u32 = 0b10000000;
const FORWARD_DIR:glam::Vec3 = glam::Vec3::new(0.0,0.0,-1.0);
const RIGHT_DIR:glam::Vec3 = glam::Vec3::new(1.0,0.0,0.0);
const UP_DIR:glam::Vec3 = glam::Vec3::new(0.0,1.0,0.0);
fn get_control_dir(controls: u32) -> glam::Vec3{
//don't get fancy just do it
let mut control_dir:glam::Vec3 = glam::Vec3::new(0.0,0.0,0.0);
if controls & CONTROL_MOVEFORWARD == CONTROL_MOVEFORWARD {
control_dir+=FORWARD_DIR;
pub struct GameMechanicsState{
pub stage_id:u32,
//jump_counts:HashMap<u32,u32>,
}
impl std::default::Default for GameMechanicsState{
fn default() -> Self {
Self{
stage_id:0,
}
}
if controls & CONTROL_MOVEBACK == CONTROL_MOVEBACK {
control_dir+=-FORWARD_DIR;
}
if controls & CONTROL_MOVELEFT == CONTROL_MOVELEFT {
control_dir+=-RIGHT_DIR;
}
if controls & CONTROL_MOVERIGHT == CONTROL_MOVERIGHT {
control_dir+=RIGHT_DIR;
}
if controls & CONTROL_MOVEUP == CONTROL_MOVEUP {
control_dir+=UP_DIR;
}
if controls & CONTROL_MOVEDOWN == CONTROL_MOVEDOWN {
control_dir+=-UP_DIR;
}
return control_dir
}
pub struct PhysicsState {
pub body: Body,
pub hitbox_halfsize: glam::Vec3,
pub contacts: std::collections::HashSet::<RelativeCollision>,
pub struct WorldState{}
pub struct StyleModifiers{
pub controls_mask:u32,//controls which are unable to be activated
pub controls_held:u32,//controls which must be active to be able to strafe
pub mv:f32,
pub walkspeed:f32,
pub friction:f32,
pub walk_accel:f32,
pub gravity:glam::Vec3,
pub strafe_tick_num:TIME,
pub strafe_tick_den:TIME,
pub hitbox_halfsize:glam::Vec3,
}
impl std::default::Default for StyleModifiers{
fn default() -> Self {
Self{
controls_mask: !0,//&!(Self::CONTROL_MOVEUP|Self::CONTROL_MOVEDOWN),
controls_held: 0,
strafe_tick_num: 100,//100t
strafe_tick_den: 1_000_000_000,
gravity: glam::vec3(0.0,-100.0,0.0),
friction: 1.2,
walk_accel: 90.0,
mv: 2.7,
walkspeed: 18.0,
hitbox_halfsize: glam::vec3(1.0,2.5,1.0),
}
}
}
impl StyleModifiers{
const CONTROL_MOVEFORWARD:u32 = 0b00000001;
const CONTROL_MOVEBACK:u32 = 0b00000010;
const CONTROL_MOVERIGHT:u32 = 0b00000100;
const CONTROL_MOVELEFT:u32 = 0b00001000;
const CONTROL_MOVEUP:u32 = 0b00010000;
const CONTROL_MOVEDOWN:u32 = 0b00100000;
const CONTROL_JUMP:u32 = 0b01000000;
const CONTROL_ZOOM:u32 = 0b10000000;
const FORWARD_DIR:glam::Vec3 = glam::Vec3::NEG_Z;
const RIGHT_DIR:glam::Vec3 = glam::Vec3::X;
const UP_DIR:glam::Vec3 = glam::Vec3::Y;
fn get_control(&self,control:u32,controls:u32)->bool{
controls&self.controls_mask&control==control
}
fn get_control_dir(&self,controls:u32)->glam::Vec3{
//don't get fancy just do it
let mut control_dir:glam::Vec3 = glam::Vec3::ZERO;
//Disallow strafing if held controls are not held
if controls&self.controls_held!=self.controls_held{
return control_dir;
}
//Apply mask after held check so you can require non-allowed keys to be held for some reason
let controls=controls&self.controls_mask;
if controls & Self::CONTROL_MOVEFORWARD == Self::CONTROL_MOVEFORWARD {
control_dir+=Self::FORWARD_DIR;
}
if controls & Self::CONTROL_MOVEBACK == Self::CONTROL_MOVEBACK {
control_dir+=-Self::FORWARD_DIR;
}
if controls & Self::CONTROL_MOVELEFT == Self::CONTROL_MOVELEFT {
control_dir+=-Self::RIGHT_DIR;
}
if controls & Self::CONTROL_MOVERIGHT == Self::CONTROL_MOVERIGHT {
control_dir+=Self::RIGHT_DIR;
}
if controls & Self::CONTROL_MOVEUP == Self::CONTROL_MOVEUP {
control_dir+=Self::UP_DIR;
}
if controls & Self::CONTROL_MOVEDOWN == Self::CONTROL_MOVEDOWN {
control_dir+=-Self::UP_DIR;
}
return control_dir
}
}
pub struct PhysicsState{
pub time:TIME,
pub body:Body,
pub world:WorldState,//currently there is only one state the world can be in
pub game:GameMechanicsState,
pub style:StyleModifiers,
pub contacts:std::collections::HashMap::<u32,RelativeCollision>,
pub intersects:std::collections::HashMap::<u32,RelativeCollision>,
//pub intersections: Vec<ModelId>,
pub models: Vec<ModelPhysics>,
//camera must exist in state because wormholes modify the camera, also camera punch
pub camera: Camera,
pub mouse_interpolation: MouseInterpolationState,
pub controls: u32,
pub time: TIME,
pub strafe_tick_num: TIME,
pub strafe_tick_den: TIME,
pub tick: u32,
pub mv: f32,
pub walk: WalkState,
pub walkspeed: f32,
pub friction: f32,
pub walk_accel: f32,
pub gravity: glam::Vec3,
pub grounded: bool,
pub spawn_point: glam::Vec3,
pub camera:PhysicsCamera,
pub next_mouse:MouseState,//Where is the mouse headed next
pub controls:u32,
pub walk:WalkState,
pub grounded:bool,
//all models
pub models:Vec<ModelPhysics>,
pub modes:Vec<crate::model::ModeDescription>,
pub mode_from_mode_id:std::collections::HashMap::<u32,usize>,
//the spawn point is where you spawn when you load into the map.
//This is not the same as Reset which teleports you to Spawn0
pub spawn_point:glam::Vec3,
}
#[derive(Clone)]
pub struct PhysicsOutputState{
camera:PhysicsCamera,
body:Body,
}
impl PhysicsOutputState{
pub fn adjust_mouse(&self,mouse:&MouseState)->(glam::Vec3,glam::Vec2){
(self.body.extrapolated_position(mouse.time)+self.camera.offset,self.camera.simulate_move_angles(mouse.pos).as_vec2())
}
}
#[derive(Debug,Clone,Copy,Hash,Eq,PartialEq)]
@ -388,20 +425,42 @@ impl Aabb {
type TreyMeshFace = AabbFace;
type TreyMesh = Aabb;
enum PhysicsCollisionAttributes{
Contact{//track whether you are contacting the object
contacting:crate::model::ContactingAttributes,
general:crate::model::GameMechanicAttributes,
},
Intersect{//track whether you are intersecting the object
intersecting:crate::model::IntersectingAttributes,
general:crate::model::GameMechanicAttributes,
},
}
pub struct ModelPhysics {
//A model is a thing that has a hitbox. can be represented by a list of TreyMesh-es
//in this iteration, all it needs is extents.
mesh: TreyMesh,
transform:glam::Affine3A,
attributes:PhysicsCollisionAttributes,
}
impl ModelPhysics {
pub fn from_model(model:&crate::model::IndexedModel,model_transform:glam::Affine3A) -> Self {
fn from_model_transform_attributes(model:&crate::model::IndexedModel,transform:&glam::Affine3A,attributes:PhysicsCollisionAttributes)->Self{
let mut aabb=Aabb::new();
for indexed_vertex in &model.unique_vertices {
aabb.grow(model_transform.transform_point3(glam::Vec3::from_array(model.unique_pos[indexed_vertex.pos as usize])));
aabb.grow(transform.transform_point3(glam::Vec3::from_array(model.unique_pos[indexed_vertex.pos as usize])));
}
Self{
mesh:aabb,
attributes,
transform:transform.clone(),
}
}
pub fn from_model(model:&crate::model::IndexedModel,instance:&crate::model::ModelInstance) -> Option<Self> {
match &instance.attributes{
crate::model::CollisionAttributes::Contact{contacting,general}=>Some(ModelPhysics::from_model_transform_attributes(model,&instance.transform,PhysicsCollisionAttributes::Contact{contacting:contacting.clone(),general:general.clone()})),
crate::model::CollisionAttributes::Intersect{intersecting,general}=>Some(ModelPhysics::from_model_transform_attributes(model,&instance.transform,PhysicsCollisionAttributes::Intersect{intersecting:intersecting.clone(),general:general.clone()})),
crate::model::CollisionAttributes::Decoration=>None,
}
}
pub fn unit_vertices(&self) -> [glam::Vec3;8] {
@ -440,11 +499,14 @@ pub struct RelativeCollision {
}
impl RelativeCollision {
pub fn model<'a>(&self,models:&'a Vec<ModelPhysics>)->Option<&'a ModelPhysics>{
models.get(self.model as usize)
}
pub fn mesh(&self,models:&Vec<ModelPhysics>) -> TreyMesh {
return models.get(self.model as usize).unwrap().face_mesh(self.face).clone()
return self.model(models).unwrap().face_mesh(self.face).clone()
}
pub fn normal(&self,models:&Vec<ModelPhysics>) -> glam::Vec3 {
return models.get(self.model as usize).unwrap().face_normal(self.face)
return self.model(models).unwrap().face_normal(self.face)
}
}
@ -474,7 +536,210 @@ impl Body {
}
}
impl Default for PhysicsState{
fn default() -> Self {
Self{
spawn_point:glam::vec3(0.0,50.0,0.0),
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,
style:StyleModifiers::default(),
grounded: false,
contacts: std::collections::HashMap::new(),
intersects: std::collections::HashMap::new(),
models: Vec::new(),
walk: WalkState::new(),
camera: PhysicsCamera::from_offset(glam::vec3(0.0,4.5-2.5,0.0)),
next_mouse: MouseState::default(),
controls: 0,
world:WorldState{},
game:GameMechanicsState::default(),
modes:Vec::new(),
mode_from_mode_id:std::collections::HashMap::new(),
}
}
}
impl PhysicsState {
pub fn clear(&mut self){
self.models.clear();
self.modes.clear();
self.contacts.clear();
self.intersects.clear();
}
pub fn into_worker(mut self)->crate::worker::CompatWorker<TimedInstruction<InputInstruction>,PhysicsOutputState,Box<dyn FnMut(TimedInstruction<InputInstruction>)->PhysicsOutputState>>{
let mut mouse_blocking=true;
let mut last_mouse_time=self.next_mouse.time;
let mut timeline=std::collections::VecDeque::new();
crate::worker::CompatWorker::new(self.output(),Box::new(move |ins:TimedInstruction<InputInstruction>|{
if if let Some(phys_input)=match ins.instruction{
InputInstruction::MoveMouse(m)=>{
if mouse_blocking{
//tell the game state which is living in the past about its future
timeline.push_front(TimedInstruction{
time:last_mouse_time,
instruction:PhysicsInputInstruction::SetNextMouse(MouseState{time:ins.time,pos:m}),
});
}else{
//mouse has just started moving again after being still for longer than 10ms.
//replace the entire mouse interpolation state to avoid an intermediate state with identical m0.t m1.t timestamps which will divide by zero
timeline.push_front(TimedInstruction{
time:last_mouse_time,
instruction:PhysicsInputInstruction::ReplaceMouse(
MouseState{time:last_mouse_time,pos:self.next_mouse.pos},
MouseState{time:ins.time,pos:m}
),
});
//delay physics execution until we have an interpolation target
mouse_blocking=true;
}
last_mouse_time=ins.time;
None
},
InputInstruction::MoveForward(s)=>Some(PhysicsInputInstruction::SetMoveForward(s)),
InputInstruction::MoveLeft(s)=>Some(PhysicsInputInstruction::SetMoveLeft(s)),
InputInstruction::MoveBack(s)=>Some(PhysicsInputInstruction::SetMoveBack(s)),
InputInstruction::MoveRight(s)=>Some(PhysicsInputInstruction::SetMoveRight(s)),
InputInstruction::MoveUp(s)=>Some(PhysicsInputInstruction::SetMoveUp(s)),
InputInstruction::MoveDown(s)=>Some(PhysicsInputInstruction::SetMoveDown(s)),
InputInstruction::Jump(s)=>Some(PhysicsInputInstruction::SetJump(s)),
InputInstruction::Zoom(s)=>Some(PhysicsInputInstruction::SetZoom(s)),
InputInstruction::Reset=>Some(PhysicsInputInstruction::Reset),
InputInstruction::Idle=>Some(PhysicsInputInstruction::Idle),
}{
//non-mouse event
timeline.push_back(TimedInstruction{
time:ins.time,
instruction:phys_input,
});
if mouse_blocking{
//assume the mouse has stopped moving after 10ms.
//shitty mice are 125Hz which is 8ms so this should cover that.
//setting this to 100us still doesn't print even though it's 10x lower than the polling rate,
//so mouse events are probably not handled separately from drawing and fire right before it :(
if 10_000_000<ins.time-self.next_mouse.time{
//push an event to extrapolate no movement from
timeline.push_front(TimedInstruction{
time:last_mouse_time,
instruction:PhysicsInputInstruction::SetNextMouse(MouseState{time:ins.time,pos:self.next_mouse.pos}),
});
last_mouse_time=ins.time;
//stop blocking. the mouse is not moving so the physics does not need to live in the past and wait for interpolation targets.
mouse_blocking=false;
true
}else{
false
}
}else{
//keep this up to date so that it can be used as a known-timestamp
//that the mouse was not moving when the mouse starts moving again
last_mouse_time=ins.time;
true
}
}else{
//mouse event
true
}{
//empty queue
while let Some(instruction)=timeline.pop_front(){
self.run(instruction.time);
self.process_instruction(TimedInstruction{
time:instruction.time,
instruction:PhysicsInstruction::Input(instruction.instruction),
});
}
}
self.output()
}))
}
pub fn output(&self)->PhysicsOutputState{
PhysicsOutputState{
body:self.body.clone(),
camera:self.camera.clone(),
}
}
pub fn generate_models(&mut self,indexed_models:&crate::model::IndexedModelInstances){
let mut starts=Vec::new();
let mut spawns=Vec::new();
let mut ordered_checkpoints=Vec::new();
let mut unordered_checkpoints=Vec::new();
for model in &indexed_models.models{
//make aabb and run vertices to get realistic bounds
for model_instance in &model.instances{
if let Some(model_physics)=ModelPhysics::from_model(model,model_instance){
let model_id=self.models.len() as u32;
self.models.push(model_physics);
for attr in &model_instance.temp_indexing{
match attr{
crate::model::TempIndexedAttributes::Start{mode_id}=>starts.push((*mode_id,model_id)),
crate::model::TempIndexedAttributes::Spawn{mode_id,stage_id}=>spawns.push((*mode_id,model_id,*stage_id)),
crate::model::TempIndexedAttributes::OrderedCheckpoint{mode_id,checkpoint_id}=>ordered_checkpoints.push((*mode_id,model_id,*checkpoint_id)),
crate::model::TempIndexedAttributes::UnorderedCheckpoint{mode_id}=>unordered_checkpoints.push((*mode_id,model_id)),
}
}
}
}
}
//I don't wanna write structs for temporary structures
//this code builds ModeDescriptions from the unsorted lists at the top of the function
starts.sort_by_key(|tup|tup.0);
let mut eshmep=std::collections::HashMap::new();
let mut modedatas:Vec<(u32,Vec<(u32,u32)>,Vec<(u32,u32)>,Vec<u32>)>=starts.into_iter().enumerate().map(|(i,tup)|{
eshmep.insert(tup.0,i);
(tup.1,Vec::new(),Vec::new(),Vec::new())
}).collect();
for tup in spawns{
if let Some(mode_id)=eshmep.get(&tup.0){
if let Some(modedata)=modedatas.get_mut(*mode_id){
modedata.1.push((tup.2,tup.1));
}
}
}
for tup in ordered_checkpoints{
if let Some(mode_id)=eshmep.get(&tup.0){
if let Some(modedata)=modedatas.get_mut(*mode_id){
modedata.2.push((tup.2,tup.1));
}
}
}
for tup in unordered_checkpoints{
if let Some(mode_id)=eshmep.get(&tup.0){
if let Some(modedata)=modedatas.get_mut(*mode_id){
modedata.3.push(tup.1);
}
}
}
let num_modes=self.modes.len();
for (mode_id,mode) in eshmep{
self.mode_from_mode_id.insert(mode_id,num_modes+mode);
}
self.modes.append(&mut modedatas.into_iter().map(|mut tup|{
tup.1.sort_by_key(|tup|tup.0);
tup.2.sort_by_key(|tup|tup.0);
let mut eshmep1=std::collections::HashMap::new();
let mut eshmep2=std::collections::HashMap::new();
crate::model::ModeDescription{
start:tup.0,
spawns:tup.1.into_iter().enumerate().map(|(i,tup)|{eshmep1.insert(tup.0,i);tup.1}).collect(),
ordered_checkpoints:tup.2.into_iter().enumerate().map(|(i,tup)|{eshmep2.insert(tup.0,i);tup.1}).collect(),
unordered_checkpoints:tup.3,
spawn_from_stage_id:eshmep1,
ordered_checkpoint_from_checkpoint_id:eshmep2,
}
}).collect());
println!("Physics Objects: {}",self.models.len());
}
pub fn get_mode(&self,mode_id:u32)->Option<&crate::model::ModeDescription>{
if let Some(&mode)=self.mode_from_mode_id.get(&mode_id){
self.modes.get(mode)
}else{
None
}
}
//tickless gaming
pub fn run(&mut self, time_limit:TIME){
//prepare is ommitted - everything is done via instructions.
@ -501,7 +766,7 @@ impl PhysicsState {
}
fn contact_constrain_velocity(&self,velocity:&mut glam::Vec3){
for contact in self.contacts.iter() {
for (_,contact) in &self.contacts {
let n=contact.normal(&self.models);
let d=velocity.dot(n);
if d<0f32{
@ -510,7 +775,7 @@ impl PhysicsState {
}
}
fn contact_constrain_acceleration(&self,acceleration:&mut glam::Vec3){
for contact in self.contacts.iter() {
for (_,contact) in &self.contacts {
let n=contact.normal(&self.models);
let d=acceleration.dot(n);
if d<0f32{
@ -520,7 +785,7 @@ impl PhysicsState {
}
fn next_strafe_instruction(&self) -> Option<TimedInstruction<PhysicsInstruction>> {
return Some(TimedInstruction{
time:(self.time*self.strafe_tick_num/self.strafe_tick_den+1)*self.strafe_tick_den/self.strafe_tick_num,
time:(self.time*self.style.strafe_tick_num/self.style.strafe_tick_den+1)*self.style.strafe_tick_den/self.style.strafe_tick_num,
//only poll the physics if there is a before and after mouse event
instruction:PhysicsInstruction::StrafeTick
});
@ -570,7 +835,7 @@ impl PhysicsState {
self.body.acceleration=a;
self.walk.state=WalkEnum::Reached;
}else{
let accel=self.walk_accel.min(self.gravity.length()*self.friction);
let accel=self.style.walk_accel.min(self.style.gravity.length()*self.style.friction);
let time_delta=target_diff.length()/accel;
let mut a=target_diff/time_delta;
self.contact_constrain_acceleration(&mut a);
@ -599,7 +864,7 @@ impl PhysicsState {
fn mesh(&self) -> TreyMesh {
let mut aabb=Aabb::new();
for vertex in Aabb::unit_vertices(){
aabb.grow(self.body.position+self.hitbox_halfsize*vertex);
aabb.grow(self.body.position+self.style.hitbox_halfsize*vertex);
}
aabb
}
@ -883,12 +1148,19 @@ impl crate::instruction::InstructionEmitter<PhysicsInstruction> for PhysicsState
//JUST POLLING!!! NO MUTATION
let mut collector = crate::instruction::InstructionCollector::new(time_limit);
//check for collision stop instructions with curent contacts
for collision_data in self.contacts.iter() {
for (_,collision_data) in &self.contacts {
collector.collect(self.predict_collision_end(self.time,time_limit,collision_data));
}
// for collision_data in &self.intersects{
// collector.collect(self.predict_collision_end2(self.time,time_limit,collision_data));
// }
//check for collision start instructions (against every part in the game with no optimization!!)
for i in 0..self.models.len() {
collector.collect(self.predict_collision_start(self.time,time_limit,i as u32));
let i=i as u32;
if self.contacts.contains_key(&i)||self.intersects.contains_key(&i){
continue;
}
collector.collect(self.predict_collision_start(self.time,time_limit,i));
}
if self.grounded {
//walk maintenance
@ -904,63 +1176,117 @@ impl crate::instruction::InstructionEmitter<PhysicsInstruction> for PhysicsState
impl crate::instruction::InstructionConsumer<PhysicsInstruction> for PhysicsState {
fn process_instruction(&mut self, ins:TimedInstruction<PhysicsInstruction>) {
match &ins.instruction {
PhysicsInstruction::StrafeTick => (),
PhysicsInstruction::Input(InputInstruction::MoveMouse(_)) => (),
_=>println!("{:?}",ins),
PhysicsInstruction::Input(PhysicsInputInstruction::Idle)
|PhysicsInstruction::Input(PhysicsInputInstruction::SetNextMouse(_))
|PhysicsInstruction::Input(PhysicsInputInstruction::ReplaceMouse(_,_))
|PhysicsInstruction::StrafeTick => (),
_=>println!("{}|{:?}",ins.time,ins.instruction),
}
//selectively update body
match &ins.instruction {
PhysicsInstruction::Input(InputInstruction::MoveMouse(_)) => (),//dodge time for mouse movement
PhysicsInstruction::Input(_)
|PhysicsInstruction::SetSpawnPosition(_)
|PhysicsInstruction::ReachWalkTargetVelocity
|PhysicsInstruction::CollisionStart(_)
|PhysicsInstruction::CollisionEnd(_)
|PhysicsInstruction::StrafeTick => self.advance_time(ins.time),
//PhysicsInstruction::Input(InputInstruction::MoveMouse(_)) => (),//dodge time for mouse movement
PhysicsInstruction::Input(_)
|PhysicsInstruction::ReachWalkTargetVelocity
|PhysicsInstruction::CollisionStart(_)
|PhysicsInstruction::CollisionEnd(_)
|PhysicsInstruction::StrafeTick => self.advance_time(ins.time),
}
match ins.instruction {
PhysicsInstruction::SetSpawnPosition(position)=>{
self.spawn_point=position;
}
PhysicsInstruction::CollisionStart(c) => {
//check ground
match &c.face {
AabbFace::Top => {
//ground
self.grounded=true;
},
_ => (),
}
self.contacts.insert(c);
//flatten v
let mut v=self.body.velocity;
self.contact_constrain_velocity(&mut v);
self.body.velocity=v;
if self.grounded&&self.controls&CONTROL_JUMP!=0{
self.jump();
let model=c.model(&self.models).unwrap();
match &model.attributes{
PhysicsCollisionAttributes::Contact{contacting,general}=>{
match &contacting.surf{
Some(surf)=>println!("I'm surfing!"),
None=>match &c.face {
AabbFace::Top => {
//ground
self.grounded=true;
},
_ => (),
},
}
//check ground
self.contacts.insert(c.model,c);
match &general.stage_element{
Some(stage_element)=>{
if stage_element.force||self.game.stage_id<stage_element.stage_id{
self.game.stage_id=stage_element.stage_id;
}
match stage_element.behaviour{
crate::model::StageElementBehaviour::SpawnAt=>(),
crate::model::StageElementBehaviour::Trigger
|crate::model::StageElementBehaviour::Teleport=>{
//TODO make good
if let Some(mode)=self.get_mode(stage_element.mode_id){
if let Some(&spawn)=mode.get_spawn_model_id(self.game.stage_id){
if let Some(model)=self.models.get(spawn as usize){
self.body.position=model.transform.transform_point3(glam::Vec3::Y)+glam::Vec3::Y*(self.style.hitbox_halfsize.y+0.1);
//manual clear //for c in self.contacts{process_instruction(CollisionEnd(c))}
self.contacts.clear();
self.intersects.clear();
self.body.acceleration=self.style.gravity;
self.walk.state=WalkEnum::Reached;
self.grounded=false;
}else{println!("bad1");}
}else{println!("bad2");}
}else{println!("bad3");}
},
crate::model::StageElementBehaviour::Platform=>(),
}
},
None=>(),
}
//flatten v
let mut v=self.body.velocity;
self.contact_constrain_velocity(&mut v);
match &general.booster{
Some(booster)=>{
v+=booster.velocity;
self.contact_constrain_velocity(&mut v);
},
None=>(),
}
self.body.velocity=v;
if self.grounded&&self.style.get_control(StyleModifiers::CONTROL_JUMP,self.controls){
self.jump();
}
self.refresh_walk_target();
},
PhysicsCollisionAttributes::Intersect{intersecting,general}=>{
//I think that setting the velocity to 0 was preventing surface contacts from entering an infinite loop
self.intersects.insert(c.model,c);
},
}
self.refresh_walk_target();
},
PhysicsInstruction::CollisionEnd(c) => {
self.contacts.remove(&c);//remove contact before calling contact_constrain_acceleration
let mut a=self.gravity;
self.contact_constrain_acceleration(&mut a);
self.body.acceleration=a;
//check ground
match &c.face {
AabbFace::Top => {
self.grounded=false;
},
_ => (),
}
self.refresh_walk_target();
let model=c.model(&self.models).unwrap();
match &model.attributes{
PhysicsCollisionAttributes::Contact{contacting,general}=>{
self.contacts.remove(&c.model);//remove contact before calling contact_constrain_acceleration
let mut a=self.style.gravity;
self.contact_constrain_acceleration(&mut a);
self.body.acceleration=a;
//check ground
match &c.face {
AabbFace::Top => {
self.grounded=false;
},
_ => (),
}
self.refresh_walk_target();
},
PhysicsCollisionAttributes::Intersect{intersecting,general}=>{
self.intersects.remove(&c.model);
},
}
},
PhysicsInstruction::StrafeTick => {
let camera_mat=self.camera.simulate_move_rotation_y(self.mouse_interpolation.interpolated_position(self.time).x-self.mouse_interpolation.mouse0.x);
let control_dir=camera_mat*get_control_dir(self.controls);
let camera_mat=self.camera.simulate_move_rotation_y(self.camera.mouse.lerp(&self.next_mouse,self.time).x);
let control_dir=camera_mat*self.style.get_control_dir(self.controls);
let d=self.body.velocity.dot(control_dir);
if d<self.mv {
let mut v=self.body.velocity+(self.mv-d)*control_dir;
if d<self.style.mv {
let mut v=self.body.velocity+(self.style.mv-d)*control_dir;
self.contact_constrain_velocity(&mut v);
self.body.velocity=v;
}
@ -976,64 +1302,54 @@ impl crate::instruction::InstructionConsumer<PhysicsInstruction> for PhysicsStat
self.walk.state=WalkEnum::Reached;
},
PhysicsInstruction::Input(input_instruction) => {
let mut refresh_walk_target=false;
let mut refresh_walk_target=true;
let mut refresh_walk_target_velocity=true;
match input_instruction{
InputInstruction::MoveMouse(m) => {
self.camera.angles=self.camera.simulate_move_angles(self.mouse_interpolation.mouse1-self.mouse_interpolation.mouse0);
self.mouse_interpolation.move_mouse(self.time,m);
refresh_walk_target=true;
PhysicsInputInstruction::SetNextMouse(m) => {
self.camera.angles=self.camera.simulate_move_angles(self.next_mouse.pos);
(self.camera.mouse,self.next_mouse)=(self.next_mouse.clone(),m);
},
InputInstruction::MoveForward(s) => {
self.set_control(CONTROL_MOVEFORWARD,s);
refresh_walk_target=true;
PhysicsInputInstruction::ReplaceMouse(m0,m1) => {
self.camera.angles=self.camera.simulate_move_angles(m0.pos);
(self.camera.mouse,self.next_mouse)=(m0,m1);
},
InputInstruction::MoveLeft(s) => {
self.set_control(CONTROL_MOVELEFT,s);
refresh_walk_target=true;
},
InputInstruction::MoveBack(s) => {
self.set_control(CONTROL_MOVEBACK,s);
refresh_walk_target=true;
},
InputInstruction::MoveRight(s) => {
self.set_control(CONTROL_MOVERIGHT,s);
refresh_walk_target=true;
},
InputInstruction::MoveUp(s) => {
self.set_control(CONTROL_MOVEUP,s);
refresh_walk_target=true;
},
InputInstruction::MoveDown(s) => {
self.set_control(CONTROL_MOVEDOWN,s);
refresh_walk_target=true;
},
InputInstruction::Jump(s) => {
self.set_control(CONTROL_JUMP,s);
refresh_walk_target=true;
PhysicsInputInstruction::SetMoveForward(s) => self.set_control(StyleModifiers::CONTROL_MOVEFORWARD,s),
PhysicsInputInstruction::SetMoveLeft(s) => self.set_control(StyleModifiers::CONTROL_MOVELEFT,s),
PhysicsInputInstruction::SetMoveBack(s) => self.set_control(StyleModifiers::CONTROL_MOVEBACK,s),
PhysicsInputInstruction::SetMoveRight(s) => self.set_control(StyleModifiers::CONTROL_MOVERIGHT,s),
PhysicsInputInstruction::SetMoveUp(s) => self.set_control(StyleModifiers::CONTROL_MOVEUP,s),
PhysicsInputInstruction::SetMoveDown(s) => self.set_control(StyleModifiers::CONTROL_MOVEDOWN,s),
PhysicsInputInstruction::SetJump(s) => {
self.set_control(StyleModifiers::CONTROL_JUMP,s);
if self.grounded{
self.jump();
}
refresh_walk_target_velocity=false;
},
InputInstruction::Zoom(s) => {
self.set_control(CONTROL_ZOOM,s);
PhysicsInputInstruction::SetZoom(s) => {
self.set_control(StyleModifiers::CONTROL_ZOOM,s);
refresh_walk_target=false;
},
InputInstruction::Reset => {
PhysicsInputInstruction::Reset => {
//temp
self.body.position=self.spawn_point;
self.body.velocity=glam::Vec3::ZERO;
//manual clear //for c in self.contacts{process_instruction(CollisionEnd(c))}
self.contacts.clear();
self.body.acceleration=self.gravity;
self.body.acceleration=self.style.gravity;
self.walk.state=WalkEnum::Reached;
self.grounded=false;
refresh_walk_target=false;
},
InputInstruction::Idle => (),//literally idle!
PhysicsInputInstruction::Idle => {refresh_walk_target=false;},//literally idle!
}
//calculate control dir
let camera_mat=self.camera.simulate_move_rotation_y(self.mouse_interpolation.interpolated_position(self.time).x-self.mouse_interpolation.mouse0.x);
let control_dir=camera_mat*get_control_dir(self.controls);
//calculate walk target velocity
if refresh_walk_target{
self.walk.target_velocity=self.walkspeed*control_dir;
//calculate walk target velocity
if refresh_walk_target_velocity{
let camera_mat=self.camera.simulate_move_rotation_y(self.camera.mouse.lerp(&self.next_mouse,self.time).x);
let control_dir=camera_mat*self.style.get_control_dir(self.controls);
self.walk.target_velocity=self.style.walkspeed*control_dir;
}
self.refresh_walk_target();
}
},

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

107
src/worker.rs Normal file

@ -0,0 +1,107 @@
use std::thread;
use std::sync::{mpsc,Arc};
use parking_lot::Mutex;
//The goal here is to have a worker thread that parks itself when it runs out of work.
//The worker thread publishes the result of its work back to the worker object for every item in the work queue.
//The physics (target use case) knows when it has not changed the body, so not updating the value is also an option.
pub struct Worker<Task:Send,Value:Clone> {
sender: mpsc::Sender<Task>,
value:Arc<Mutex<Value>>,
}
impl<Task:Send+'static,Value:Clone+Send+'static> Worker<Task,Value> {
pub fn new<F:FnMut(Task)->Value+Send+'static>(value:Value,mut f:F) -> Self {
let (sender, receiver) = mpsc::channel::<Task>();
let ret=Self {
sender,
value:Arc::new(Mutex::new(value)),
};
let value=ret.value.clone();
thread::spawn(move || {
loop {
match receiver.recv() {
Ok(task) => {
let v=f(task);//make sure function is evaluated before lock is acquired
*value.lock()=v;
}
Err(_) => {
println!("Worker stopping.",);
break;
}
}
}
});
ret
}
pub fn send(&self,task:Task)->Result<(), mpsc::SendError<Task>>{
self.sender.send(task)
}
pub fn grab_clone(&self)->Value{
self.value.lock().clone()
}
}
pub struct CompatWorker<Task,Value:Clone,F>{
data:std::marker::PhantomData<Task>,
f:F,
value:Value,
}
impl<Task,Value:Clone,F:FnMut(Task)->Value> CompatWorker<Task,Value,F> {
pub fn new(value:Value,f:F) -> Self {
Self {
f,
value,
data:std::marker::PhantomData,
}
}
pub fn send(&mut self,task:Task)->Result<(),()>{
self.value=(self.f)(task);
Ok(())
}
pub fn grab_clone(&self)->Value{
self.value.clone()
}
}
#[test]//How to run this test with printing: cargo test --release -- --nocapture
fn test_worker() {
println!("hiiiii");
// Create the worker thread
let worker = Worker::new(crate::physics::Body::with_pva(glam::Vec3::ZERO,glam::Vec3::ZERO,glam::Vec3::ZERO),
|_|crate::physics::Body::with_pva(glam::Vec3::ONE,glam::Vec3::ONE,glam::Vec3::ONE)
);
// Send tasks to the worker
for i in 0..5 {
let task = crate::instruction::TimedInstruction{
time:0,
instruction:crate::physics::PhysicsInstruction::StrafeTick,
};
worker.send(task).unwrap();
}
// Optional: Signal the worker to stop (in a real-world scenario)
// sender.send("STOP".to_string()).unwrap();
// Sleep to allow the worker thread to finish processing
thread::sleep(std::time::Duration::from_secs(2));
// Send a new task
let task = crate::instruction::TimedInstruction{
time:0,
instruction:crate::physics::PhysicsInstruction::StrafeTick,
};
worker.send(task).unwrap();
println!("value={:?}",worker.grab_clone());
// wait long enough to see print from final task
thread::sleep(std::time::Duration::from_secs(1));
}