Compare commits
66 Commits
Author | SHA1 | Date | |
---|---|---|---|
64e1e762a1 | |||
ad862ae8c9 | |||
0ee17ac3d9 | |||
e2af6fc4ed | |||
bdc0dd1b3b | |||
95fb316a23 | |||
9dec53d764 | |||
3552491a9a | |||
dd13a066d0 | |||
f3dd43b171 | |||
82d71df94e | |||
684dbda73a | |||
e398da3aa6 | |||
944393dabe | |||
4adce7acd3 | |||
5b935c32fe | |||
436706bc4d | |||
bde24d35a2 | |||
fc91d644e6 | |||
2b47827383 | |||
a942e10554 | |||
5d1e38c36c | |||
e78cabf0f5 | |||
4e90da2228 | |||
9fa4ea6716 | |||
aedef03e7c | |||
6a9af0441f | |||
8cf66f3446 | |||
1cb0d6e586 | |||
12a4bf7948 | |||
f2e4286a08 | |||
bd6cd5eacc | |||
f2dfb438d0 | |||
7c8bc8d647 | |||
4943bc6a7f | |||
55eebba1c5 | |||
b8f13539db | |||
fb2e2afeb9 | |||
f30f246e5f | |||
0ac49308a0 | |||
30cbbbca1b | |||
66fa8fd637 | |||
f2c71caae3 | |||
c8ec1f05d1 | |||
b102319b33 | |||
50e9152ee2 | |||
7a8de938af | |||
696f383aee | |||
bfd6f4493f | |||
ed96572a24 | |||
5914db3599 | |||
f72acaf2d4 | |||
734ce661f2 | |||
bb8c53aee2 | |||
de0eb0790a | |||
9e9550885f | |||
58be446297 | |||
d16404167b | |||
79262ce3b4 | |||
c47020c149 | |||
5854171619 | |||
616b09a857 | |||
6ff2620bbc | |||
d3e4918d3e | |||
6c2eb5ff29 | |||
02a509868a |
35
Cargo.lock
generated
35
Cargo.lock
generated
@ -331,6 +331,12 @@ dependencies = [
|
||||
"crossbeam-utils",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "configparser"
|
||||
version = "3.0.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5458d9d1a587efaf5091602c59d299696a3877a439c8f6d461a2d3cce11df87a"
|
||||
|
||||
[[package]]
|
||||
name = "constant_time_eq"
|
||||
version = "0.3.0"
|
||||
@ -834,6 +840,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"
|
||||
@ -1659,21 +1688,23 @@ checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"
|
||||
|
||||
[[package]]
|
||||
name = "strafe-client"
|
||||
version = "0.7.0"
|
||||
version = "0.8.0"
|
||||
dependencies = [
|
||||
"async-executor",
|
||||
"bytemuck",
|
||||
"configparser",
|
||||
"ddsfile",
|
||||
"env_logger",
|
||||
"glam",
|
||||
"lazy-regex",
|
||||
"log",
|
||||
"obj",
|
||||
"parking_lot",
|
||||
"pollster",
|
||||
"rbx_binary",
|
||||
"rbx_dom_weak",
|
||||
"rbx_reflection_database",
|
||||
"rbx_xml",
|
||||
"regex",
|
||||
"wgpu",
|
||||
"winit",
|
||||
]
|
||||
|
14
Cargo.toml
14
Cargo.toml
@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "strafe-client"
|
||||
version = "0.7.0"
|
||||
version = "0.8.0"
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
@ -8,21 +8,23 @@ edition = "2021"
|
||||
[dependencies]
|
||||
async-executor = "1.5.1"
|
||||
bytemuck = { version = "1.13.1", features = ["derive"] }
|
||||
configparser = "3.0.2"
|
||||
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
|
||||
|
91
src/aabb.rs
Normal file
91
src/aabb.rs
Normal file
@ -0,0 +1,91 @@
|
||||
#[derive(Debug,Clone,Copy,Hash,Eq,PartialEq)]
|
||||
pub enum AabbFace{
|
||||
Right,//+X
|
||||
Top,
|
||||
Back,
|
||||
Left,
|
||||
Bottom,
|
||||
Front,
|
||||
}
|
||||
#[derive(Clone)]
|
||||
pub struct Aabb {
|
||||
pub min: glam::Vec3,
|
||||
pub max: glam::Vec3,
|
||||
}
|
||||
|
||||
impl Default for Aabb {
|
||||
fn default() -> Self {
|
||||
Aabb::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl Aabb {
|
||||
const VERTEX_DATA: [glam::Vec3; 8] = [
|
||||
glam::vec3(1., -1., -1.),
|
||||
glam::vec3(1., 1., -1.),
|
||||
glam::vec3(1., 1., 1.),
|
||||
glam::vec3(1., -1., 1.),
|
||||
glam::vec3(-1., -1., 1.),
|
||||
glam::vec3(-1., 1., 1.),
|
||||
glam::vec3(-1., 1., -1.),
|
||||
glam::vec3(-1., -1., -1.),
|
||||
];
|
||||
|
||||
pub fn new() -> Self {
|
||||
Self {min: glam::Vec3::INFINITY,max: glam::Vec3::NEG_INFINITY}
|
||||
}
|
||||
|
||||
pub fn grow(&mut self, point:glam::Vec3){
|
||||
self.min=self.min.min(point);
|
||||
self.max=self.max.max(point);
|
||||
}
|
||||
pub fn join(&mut self, aabb:&Aabb){
|
||||
self.min=self.min.min(aabb.min);
|
||||
self.max=self.max.max(aabb.max);
|
||||
}
|
||||
pub fn inflate(&mut self, hs:glam::Vec3){
|
||||
self.min-=hs;
|
||||
self.max+=hs;
|
||||
}
|
||||
pub fn intersects(&self,aabb:&Aabb)->bool{
|
||||
(self.min.cmplt(aabb.max)&aabb.min.cmplt(self.max)).all()
|
||||
}
|
||||
pub fn normal(face:AabbFace) -> glam::Vec3 {
|
||||
match face {
|
||||
AabbFace::Right => glam::vec3(1.,0.,0.),
|
||||
AabbFace::Top => glam::vec3(0.,1.,0.),
|
||||
AabbFace::Back => glam::vec3(0.,0.,1.),
|
||||
AabbFace::Left => glam::vec3(-1.,0.,0.),
|
||||
AabbFace::Bottom => glam::vec3(0.,-1.,0.),
|
||||
AabbFace::Front => glam::vec3(0.,0.,-1.),
|
||||
}
|
||||
}
|
||||
pub fn unit_vertices() -> [glam::Vec3;8] {
|
||||
return Self::VERTEX_DATA;
|
||||
}
|
||||
pub fn face(&self,face:AabbFace) -> Aabb {
|
||||
let mut aabb=self.clone();
|
||||
//in this implementation face = worldspace aabb face
|
||||
match face {
|
||||
AabbFace::Right => aabb.min.x=aabb.max.x,
|
||||
AabbFace::Top => aabb.min.y=aabb.max.y,
|
||||
AabbFace::Back => aabb.min.z=aabb.max.z,
|
||||
AabbFace::Left => aabb.max.x=aabb.min.x,
|
||||
AabbFace::Bottom => aabb.max.y=aabb.min.y,
|
||||
AabbFace::Front => aabb.max.z=aabb.min.z,
|
||||
}
|
||||
return aabb;
|
||||
}
|
||||
pub fn center(&self)->glam::Vec3{
|
||||
return (self.min+self.max)/2.0
|
||||
}
|
||||
//probably use floats for area & volume because we don't care about precision
|
||||
pub fn area_weight(&self)->f32{
|
||||
let d=self.max-self.min;
|
||||
d.x*d.y+d.y*d.z+d.z*d.x
|
||||
}
|
||||
pub fn volume(&self)->f32{
|
||||
let d=self.max-self.min;
|
||||
d.x*d.y*d.z
|
||||
}
|
||||
}
|
1042
src/body.rs
1042
src/body.rs
File diff suppressed because it is too large
Load Diff
107
src/bvh.rs
Normal file
107
src/bvh.rs
Normal file
@ -0,0 +1,107 @@
|
||||
use crate::aabb::Aabb;
|
||||
|
||||
//da algaritum
|
||||
//lista boxens
|
||||
//sort by {minx,maxx,miny,maxy,minz,maxz} (6 lists)
|
||||
//find the sets that minimizes the sum of surface areas
|
||||
//splitting is done when the minimum split sum of surface areas is larger than the node's own surface area
|
||||
|
||||
//start with bisection into octrees because a bad bvh is still 1000x better than no bvh
|
||||
//sort the centerpoints on each axis (3 lists)
|
||||
//bv is put into octant based on whether it is upper or lower in each list
|
||||
#[derive(Default)]
|
||||
pub struct BvhNode{
|
||||
children:Vec<Self>,
|
||||
models:Vec<u32>,
|
||||
aabb:Aabb,
|
||||
}
|
||||
|
||||
impl BvhNode{
|
||||
pub fn the_tester<F:FnMut(u32)>(&self,aabb:&Aabb,f:&mut F){
|
||||
for &model in &self.models{
|
||||
f(model);
|
||||
}
|
||||
for child in &self.children{
|
||||
if aabb.intersects(&child.aabb){
|
||||
child.the_tester(aabb,f);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn generate_bvh(boxen:Vec<Aabb>)->BvhNode{
|
||||
generate_bvh_node(boxen.into_iter().enumerate().collect())
|
||||
}
|
||||
|
||||
fn generate_bvh_node(boxen:Vec<(usize,Aabb)>)->BvhNode{
|
||||
let n=boxen.len();
|
||||
if n<20{
|
||||
let mut aabb=Aabb::new();
|
||||
let models=boxen.into_iter().map(|b|{aabb.join(&b.1);b.0 as u32}).collect();
|
||||
BvhNode{
|
||||
children:Vec::new(),
|
||||
models,
|
||||
aabb,
|
||||
}
|
||||
}else{
|
||||
let mut octant=std::collections::HashMap::with_capacity(n);//this ids which octant the boxen is put in
|
||||
let mut sort_x=Vec::with_capacity(n);
|
||||
let mut sort_y=Vec::with_capacity(n);
|
||||
let mut sort_z=Vec::with_capacity(n);
|
||||
for (i,aabb) in boxen.iter(){
|
||||
let center=aabb.center();
|
||||
octant.insert(*i,0);
|
||||
sort_x.push((*i,center.x));
|
||||
sort_y.push((*i,center.y));
|
||||
sort_z.push((*i,center.z));
|
||||
}
|
||||
sort_x.sort_by(|tup0,tup1|tup0.1.partial_cmp(&tup1.1).unwrap());
|
||||
sort_y.sort_by(|tup0,tup1|tup0.1.partial_cmp(&tup1.1).unwrap());
|
||||
sort_z.sort_by(|tup0,tup1|tup0.1.partial_cmp(&tup1.1).unwrap());
|
||||
let h=n/2;
|
||||
let median_x=sort_x[h].1;
|
||||
let median_y=sort_y[h].1;
|
||||
let median_z=sort_z[h].1;
|
||||
for (i,c) in sort_x{
|
||||
if median_x<c{
|
||||
octant.insert(i,octant[&i]+1<<0);
|
||||
}
|
||||
}
|
||||
for (i,c) in sort_y{
|
||||
if median_y<c{
|
||||
octant.insert(i,octant[&i]+1<<1);
|
||||
}
|
||||
}
|
||||
for (i,c) in sort_z{
|
||||
if median_z<c{
|
||||
octant.insert(i,octant[&i]+1<<2);
|
||||
}
|
||||
}
|
||||
//generate lists for unique octant values
|
||||
let mut list_list=Vec::with_capacity(8);
|
||||
let mut octant_list=Vec::with_capacity(8);
|
||||
for (i,aabb) in boxen.into_iter(){
|
||||
let octant_id=octant[&i];
|
||||
let list_id=if let Some(list_id)=octant_list.iter().position(|&id|id==octant_id){
|
||||
list_id
|
||||
}else{
|
||||
let list_id=list_list.len();
|
||||
octant_list.push(octant_id);
|
||||
list_list.push(Vec::new());
|
||||
list_id
|
||||
};
|
||||
list_list[list_id].push((i,aabb));
|
||||
}
|
||||
let mut aabb=Aabb::new();
|
||||
let children=list_list.into_iter().map(|b|{
|
||||
let node=generate_bvh_node(b);
|
||||
aabb.join(&node.aabb);
|
||||
node
|
||||
}).collect();
|
||||
BvhNode{
|
||||
children,
|
||||
models:Vec::new(),
|
||||
aabb,
|
||||
}
|
||||
}
|
||||
}
|
@ -52,7 +52,7 @@ pub trait Example: 'static + Sized {
|
||||
queue: &wgpu::Queue,
|
||||
);
|
||||
fn update(&mut self, window: &winit::window::Window, device: &wgpu::Device, queue: &wgpu::Queue, event: WindowEvent);
|
||||
fn device_event(&mut self, event: DeviceEvent);
|
||||
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,
|
||||
@ -375,7 +375,7 @@ fn start<E: Example>(
|
||||
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,91 @@ 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();
|
||||
let mut force_can_collide=can_collide;
|
||||
match name{
|
||||
//"Water"=>intersecting.water=Some(crate::model::IntersectingWater{density:1.0,drag:1.0}),
|
||||
"Accelerator"=>{force_can_collide=false;intersecting.accelerator=Some(crate::model::IntersectingAccelerator{acceleration:velocity})},
|
||||
"MapFinish"=>{force_can_collide=false;general.zone=Some(crate::model::GameMechanicZone{mode_id:0,behaviour:crate::model::ZoneBehaviour::Finish})},
|
||||
"MapAnticheat"=>{force_can_collide=false;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"=>{force_can_collide=false;crate::model::StageElementBehaviour::Trigger},
|
||||
"Teleport"=>{force_can_collide=false;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){
|
||||
force_can_collide=false;
|
||||
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 force_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>() {
|
||||
@ -102,7 +178,7 @@ impl RobloxFaceTextureDescription{
|
||||
}
|
||||
type RobloxPartDescription=[Option<RobloxFaceTextureDescription>;6];
|
||||
type RobloxWedgeDescription=[Option<RobloxFaceTextureDescription>;5];
|
||||
type RobloxCornerWedgeDescription=[Option<RobloxFaceTextureDescription>;4];
|
||||
type RobloxCornerWedgeDescription=[Option<RobloxFaceTextureDescription>;5];
|
||||
#[derive(Clone,Eq,Hash,PartialEq)]
|
||||
enum RobloxBasePartDescription{
|
||||
Sphere,
|
||||
@ -111,7 +187,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 +205,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 +231,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 +269,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 +283,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,10 +310,8 @@ 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){
|
||||
let mut roblox_texture_transform=RobloxTextureTransform::default();
|
||||
let mut roblox_texture_color=glam::Vec4::ONE;
|
||||
if decal.class=="Texture"{
|
||||
if normal_id<6{
|
||||
let (roblox_texture_color,roblox_texture_transform)=if decal.class=="Texture"{
|
||||
//generate tranform
|
||||
if let (
|
||||
Some(rbx_dom_weak::types::Variant::Float32(ox)),
|
||||
@ -269,16 +332,22 @@ 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),
|
||||
scale_u:size_u/(*sx),scale_v:size_v/(*sy),
|
||||
};
|
||||
roblox_texture_color=glam::vec4(decal_color3.r,decal_color3.g,decal_color3.b,1.0-*decal_transparency);
|
||||
(
|
||||
glam::vec4(decal_color3.r,decal_color3.g,decal_color3.b,1.0-*decal_transparency),
|
||||
RobloxTextureTransform{
|
||||
offset_u:*ox/(*sx),offset_v:*oy/(*sy),
|
||||
scale_u:size_u/(*sx),scale_v:size_v/(*sy),
|
||||
}
|
||||
)
|
||||
}else{
|
||||
(glam::Vec4::ONE,RobloxTextureTransform::default())
|
||||
}
|
||||
}
|
||||
part_texture_description[face]=Some(RobloxFaceTextureDescription{
|
||||
}else{
|
||||
(glam::Vec4::ONE,RobloxTextureTransform::default())
|
||||
};
|
||||
part_texture_description[normal_id as usize]=Some(RobloxFaceTextureDescription{
|
||||
texture:texture_id,
|
||||
color:roblox_texture_color,
|
||||
transform:roblox_texture_transform,
|
||||
@ -291,16 +360,36 @@ 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
|
||||
]),
|
||||
//TODO: fix Left+Back texture coordinates to match roblox when not overwridden by Top
|
||||
primitives::Primitives::CornerWedge=>RobloxBasePartDescription::CornerWedge([
|
||||
f0,//Cube::Right->CornerWedge::Right
|
||||
if f2.is_some(){f2}else{f1.clone()},//Cube::Back|Cube::Top->CornerWedge::TopBack
|
||||
if f3.is_some(){f3}else{f1},//Cube::Left|Cube::Top->CornerWedge::TopLeft
|
||||
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
|
||||
@ -354,10 +443,11 @@ pub fn generate_indexed_models_roblox(dom:rbx_dom_weak::WeakDom) -> Result<(Inde
|
||||
for (face_id,roblox_face_description) in cornerwedge_texture_description.iter().enumerate(){
|
||||
cornerwedge_face_description.insert(
|
||||
match face_id{
|
||||
0=>primitives::CornerWedgeFace::Top,
|
||||
1=>primitives::CornerWedgeFace::Right,
|
||||
2=>primitives::CornerWedgeFace::Bottom,
|
||||
3=>primitives::CornerWedgeFace::Front,
|
||||
0=>primitives::CornerWedgeFace::Right,
|
||||
1=>primitives::CornerWedgeFace::TopBack,
|
||||
2=>primitives::CornerWedgeFace::TopLeft,
|
||||
3=>primitives::CornerWedgeFace::Bottom,
|
||||
4=>primitives::CornerWedgeFace::Front,
|
||||
_=>panic!("unreachable"),
|
||||
},
|
||||
match roblox_face_description{
|
||||
@ -370,15 +460,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(),
|
||||
}
|
||||
}
|
||||
|
461
src/main.rs
461
src/main.rs
@ -1,12 +1,17 @@
|
||||
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 bvh;
|
||||
mod aabb;
|
||||
mod model;
|
||||
mod timers;
|
||||
mod zeroes;
|
||||
mod worker;
|
||||
mod physics;
|
||||
mod settings;
|
||||
mod framework;
|
||||
mod primitives;
|
||||
mod instruction;
|
||||
@ -38,27 +43,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:glam::Vec2)->Self{
|
||||
Self{
|
||||
screen_size,
|
||||
fov,
|
||||
}
|
||||
}
|
||||
pub fn proj(&self)->glam::Mat4{
|
||||
perspective_rh(self.fov.x, self.fov.y, 0.5, 2000.0)
|
||||
}
|
||||
pub fn world(&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 to_uniform_data(&self,(pos,angles): (glam::Vec3,glam::Vec2)) -> [f32; 16 * 4] {
|
||||
let proj=self.proj();
|
||||
let proj_inv = proj.inverse();
|
||||
let view_inv=self.world(pos,angles);
|
||||
let view=view_inv.inverse();
|
||||
|
||||
let mut raw = [0f32; 16 * 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)[..]);
|
||||
raw[48..64].copy_from_slice(&AsRef::<[f32; 16]>::as_ref(&view_inv)[..]);
|
||||
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 fn load_user_settings(&mut self,user_settings:&settings::UserSettings){
|
||||
self.camera.fov=user_settings.calculate_fov(1.0,&self.camera.screen_size).as_vec2();
|
||||
}
|
||||
}
|
||||
|
||||
pub struct GlobalState{
|
||||
start_time: std::time::Instant,
|
||||
manual_mouse_lock:bool,
|
||||
mouse:physics::MouseState,
|
||||
user_settings:settings::UserSettings,
|
||||
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,16 +151,7 @@ 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
|
||||
@ -161,20 +220,24 @@ impl GraphicsData {
|
||||
//the models received here are supposed to be tightly packed, i.e. no code needs to check if two models are using the same groups.
|
||||
let indexed_models_len=indexed_models.models.len();
|
||||
let mut unique_texture_models=Vec::with_capacity(indexed_models_len);
|
||||
for mut model in indexed_models.models.drain(..){
|
||||
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::Mat3::from(instance.transform.matrix3.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(..){
|
||||
//ignore zero coppy optimization for now
|
||||
for group in model.groups.into_iter(){
|
||||
//ignore zero copy optimization for now
|
||||
let texture_index=if let Some(texture_index)=unique_textures.iter().position(|&texture|texture==group.texture){
|
||||
texture_index
|
||||
}else{
|
||||
@ -200,13 +263,13 @@ 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();
|
||||
//TODO: combine groups using the same render pattern
|
||||
for group in model.groups {
|
||||
//this mut be combined in a more complex way if the models use different render patterns per group
|
||||
let mut indices = Vec::new();
|
||||
for group in model.groups {
|
||||
for poly in group.polys {
|
||||
for end_index in 2..poly.vertices.len() {
|
||||
for &index in &[0, end_index - 1, end_index] {
|
||||
@ -228,8 +291,8 @@ impl GraphicsData {
|
||||
}
|
||||
}
|
||||
}
|
||||
entities.push(indices);
|
||||
}
|
||||
entities.push(indices);
|
||||
models.push(model::ModelSingleTexture{
|
||||
instances:model.instances,
|
||||
vertices,
|
||||
@ -237,13 +300,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;
|
||||
@ -257,13 +320,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,
|
||||
@ -275,7 +338,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()),
|
||||
@ -286,7 +349,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|{
|
||||
@ -308,12 +371,12 @@ impl GraphicsData {
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
const MODEL_BUFFER_SIZE:usize=4*4 + 4*4 + 4;//let size=std::mem::size_of::<ModelInstance>();
|
||||
const MODEL_BUFFER_SIZE:usize=4*4 + 12 + 4;//let size=std::mem::size_of::<ModelInstance>();
|
||||
const MODEL_BUFFER_SIZE_BYTES:usize=MODEL_BUFFER_SIZE*4;
|
||||
fn get_instances_buffer_data(instances:&[ModelGraphicsInstance]) -> Vec<f32> {
|
||||
let mut raw = Vec::with_capacity(MODEL_BUFFER_SIZE*instances.len());
|
||||
@ -322,7 +385,12 @@ fn get_instances_buffer_data(instances:&[ModelGraphicsInstance]) -> Vec<f32> {
|
||||
//model transform
|
||||
raw.extend_from_slice(&AsRef::<[f32; 4*4]>::as_ref(&mi.transform)[..]);
|
||||
//normal transform
|
||||
raw.extend_from_slice(&AsRef::<[f32; 4*4]>::as_ref(&mi.normal_transform)[..]);
|
||||
raw.extend_from_slice(AsRef::<[f32; 3]>::as_ref(&mi.normal_transform.x_axis));
|
||||
raw.extend_from_slice(&[0.0]);
|
||||
raw.extend_from_slice(AsRef::<[f32; 3]>::as_ref(&mi.normal_transform.y_axis));
|
||||
raw.extend_from_slice(&[0.0]);
|
||||
raw.extend_from_slice(AsRef::<[f32; 3]>::as_ref(&mi.normal_transform.z_axis));
|
||||
raw.extend_from_slice(&[0.0]);
|
||||
//color
|
||||
raw.extend_from_slice(AsRef::<[f32; 4]>::as_ref(&mi.color));
|
||||
raw.append(&mut v);
|
||||
@ -330,21 +398,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
|
||||
@ -361,6 +415,8 @@ impl framework::Example for GraphicsData {
|
||||
device: &wgpu::Device,
|
||||
queue: &wgpu::Queue,
|
||||
) -> Self {
|
||||
//wee
|
||||
let user_settings=settings::read_user_settings();
|
||||
let mut indexed_models = Vec::new();
|
||||
indexed_models.append(&mut model::generate_indexed_model_list_from_obj(obj::ObjData::load_buf(&include_bytes!("../models/teslacyberv3.0.obj")[..]).unwrap(),*glam::Vec4::ONE.as_ref()));
|
||||
indexed_models.push(primitives::unit_sphere());
|
||||
@ -369,34 +425,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 {
|
||||
@ -494,28 +560,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();
|
||||
|
||||
@ -710,7 +754,14 @@ 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();
|
||||
|
||||
physics.load_user_settings(&user_settings);
|
||||
|
||||
let screen_size=glam::uvec2(config.width,config.height);
|
||||
|
||||
let camera=GraphicsCamera::new(screen_size,user_settings.calculate_fov(1.0,&screen_size).as_vec2());
|
||||
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),
|
||||
@ -726,6 +777,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: &[
|
||||
@ -743,10 +795,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 mut graphics=GraphicsState {
|
||||
pipelines:GraphicsPipelines{
|
||||
skybox:sky_pipeline,
|
||||
model:model_pipeline
|
||||
@ -755,6 +804,7 @@ impl framework::Example for GraphicsData {
|
||||
camera:camera_bind_group,
|
||||
skybox_texture:skybox_texture_bind_group,
|
||||
},
|
||||
camera,
|
||||
camera_buf,
|
||||
models: Vec::new(),
|
||||
depth_view,
|
||||
@ -764,19 +814,41 @@ impl framework::Example for GraphicsData {
|
||||
temp_squid_texture_view: squid_texture_view,
|
||||
};
|
||||
|
||||
graphics.load_user_settings(&user_settings);
|
||||
|
||||
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);
|
||||
|
||||
//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(),
|
||||
user_settings,
|
||||
graphics,
|
||||
physics_thread,
|
||||
};
|
||||
state.generate_model_graphics(&device,&queue,indexed_model_instances);
|
||||
|
||||
let args:Vec<String>=std::env::args().collect();
|
||||
if args.len()==2{
|
||||
graphics.load_file(std::path::PathBuf::from(&args[1]), device, queue);
|
||||
state.load_file(std::path::PathBuf::from(&args[1]), device, queue);
|
||||
}
|
||||
|
||||
return graphics;
|
||||
return state;
|
||||
}
|
||||
|
||||
fn load_file(&mut self,path: std::path::PathBuf, device: &wgpu::Device, queue: &wgpu::Queue){
|
||||
@ -792,8 +864,7 @@ impl framework::Example for GraphicsData {
|
||||
//.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)))={
|
||||
if let Some(indexed_model_instances)={
|
||||
match &first_8[0..4]{
|
||||
b"<rob"=>{
|
||||
match match &first_8[4..8]{
|
||||
@ -801,34 +872,40 @@ impl framework::Example for GraphicsData {
|
||||
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)),
|
||||
Ok(dom)=>Some(load_roblox::generate_indexed_models(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,
|
||||
//b"VBSP"=>Some(load_bsp::generate_indexed_models(input)),
|
||||
//b"SNFM"=>Some(sniffer::generate_indexed_models(input)),
|
||||
//b"SNFB"=>Some(sniffer::load_bot(input)),
|
||||
other=>{
|
||||
println!("loser file {:?}",other);
|
||||
None
|
||||
},
|
||||
}
|
||||
}{
|
||||
let spawn_point=indexed_model_instances.spawn_point;
|
||||
//if generate_indexed_models succeeds, clear the previous ones
|
||||
self.models.clear();
|
||||
self.physics.models.clear();
|
||||
self.generate_model_physics(&indexed_model_instances);
|
||||
self.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.load_user_settings(&self.user_settings);
|
||||
physics.generate_models(&indexed_model_instances);
|
||||
self.physics_thread=physics.into_worker();
|
||||
|
||||
//graphics.load_user_settings(&self.user_settings);
|
||||
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");
|
||||
}
|
||||
@ -845,6 +922,10 @@ impl framework::Example for GraphicsData {
|
||||
let time=self.start_time.elapsed().as_nanos() as i64;
|
||||
match event {
|
||||
winit::event::WindowEvent::DroppedFile(path) => self.load_file(path,device,queue),
|
||||
winit::event::WindowEvent::Focused(state)=>{
|
||||
//pause unpause
|
||||
//recalculate pressed keys on focus
|
||||
},
|
||||
winit::event::WindowEvent::KeyboardInput {
|
||||
input:winit::event::KeyboardInput{state, virtual_keycode,..},
|
||||
..
|
||||
@ -856,14 +937,51 @@ impl framework::Example for GraphicsData {
|
||||
match virtual_keycode{
|
||||
Some(winit::event::VirtualKeyCode::Tab)=>{
|
||||
if s{
|
||||
if let Ok(())=window.set_cursor_grab(winit::window::CursorGrabMode::None){
|
||||
window.set_cursor_visible(true);
|
||||
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 let Ok(())=window.set_cursor_grab(winit::window::CursorGrabMode::Locked){
|
||||
window.set_cursor_visible(false);
|
||||
//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);
|
||||
},
|
||||
Some(winit::event::VirtualKeyCode::F11)=>{
|
||||
if s{
|
||||
if window.fullscreen().is_some(){
|
||||
window.set_fullscreen(None);
|
||||
}else{
|
||||
window.set_fullscreen(Some(winit::window::Fullscreen::Borderless(None)));
|
||||
}
|
||||
}
|
||||
},
|
||||
Some(winit::event::VirtualKeyCode::Escape)=>{
|
||||
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);
|
||||
}
|
||||
},
|
||||
Some(keycode)=>{
|
||||
if let Some(input_instruction)=match keycode {
|
||||
@ -877,13 +995,11 @@ impl framework::Example for GraphicsData {
|
||||
winit::event::VirtualKeyCode::Z => Some(InputInstruction::Zoom(s)),
|
||||
winit::event::VirtualKeyCode::R => if s{Some(InputInstruction::Reset)}else{None},
|
||||
_ => None,
|
||||
}
|
||||
{
|
||||
self.physics.run(time);
|
||||
self.physics.process_instruction(TimedInstruction{
|
||||
}{
|
||||
self.physics_thread.send(TimedInstruction{
|
||||
time,
|
||||
instruction:PhysicsInstruction::Input(input_instruction),
|
||||
})
|
||||
instruction:input_instruction,
|
||||
}).unwrap();
|
||||
}
|
||||
},
|
||||
_=>(),
|
||||
@ -893,62 +1009,38 @@ impl framework::Example for GraphicsData {
|
||||
}
|
||||
}
|
||||
|
||||
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 {
|
||||
/* use WindowEvent for input for now because DeviceEvent doesn't work on wayland
|
||||
winit::event::DeviceEvent::Key(winit::event::KeyboardInput {
|
||||
state,
|
||||
scancode: keycode,
|
||||
..
|
||||
}) => {
|
||||
let s=match state {
|
||||
winit::event::ElementState::Pressed => true,
|
||||
winit::event::ElementState::Released => false,
|
||||
};
|
||||
if let Some(input_instruction)=match keycode {
|
||||
17 => Some(InputInstruction::MoveForward(s)),//W
|
||||
30 => Some(InputInstruction::MoveLeft(s)),//A
|
||||
31 => Some(InputInstruction::MoveBack(s)),//S
|
||||
32 => Some(InputInstruction::MoveRight(s)),//D
|
||||
18 => Some(InputInstruction::MoveUp(s)),//E
|
||||
16 => Some(InputInstruction::MoveDown(s)),//Q
|
||||
57 => Some(InputInstruction::Jump(s)),//Space
|
||||
44 => Some(InputInstruction::Zoom(s)),//Z
|
||||
19 => if s{Some(InputInstruction::Reset)}else{None},//R
|
||||
_ => None,
|
||||
}
|
||||
{
|
||||
self.physics.run(time);
|
||||
self.physics.process_instruction(TimedInstruction{
|
||||
time,
|
||||
instruction:PhysicsInstruction::Input(input_instruction),
|
||||
})
|
||||
}
|
||||
},
|
||||
*/
|
||||
winit::event::DeviceEvent::MouseMotion {
|
||||
delta,//these (f64,f64) are integers on my machine
|
||||
} => {
|
||||
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);
|
||||
println!("mousewheel {:?}",delta);
|
||||
if false{//self.physics.style.use_scroll{
|
||||
self.physics.run(time);
|
||||
self.physics.process_instruction(TimedInstruction{
|
||||
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();
|
||||
}
|
||||
}
|
||||
_=>(),
|
||||
@ -961,9 +1053,9 @@ 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.screen_size=glam::uvec2(config.width, config.height);
|
||||
self.graphics.load_user_settings(&self.user_settings);
|
||||
}
|
||||
|
||||
fn render(
|
||||
@ -973,28 +1065,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
|
||||
@ -1004,7 +1102,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 {
|
||||
@ -1023,7 +1122,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,
|
||||
@ -1032,11 +1131,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(..));
|
||||
|
||||
@ -1046,18 +1145,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()
|
||||
|
168
src/model.rs
168
src/model.rs
@ -52,17 +52,179 @@ pub struct ModelSingleTexture{
|
||||
#[derive(Clone)]
|
||||
pub struct ModelGraphicsInstance{
|
||||
pub transform:glam::Mat4,
|
||||
pub normal_transform:glam::Mat4,
|
||||
pub normal_transform:glam::Mat3,
|
||||
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>{
|
||||
|
1288
src/physics.rs
Normal file
1288
src/physics.rs
Normal file
File diff suppressed because it is too large
Load Diff
@ -107,17 +107,18 @@ local cornerWedgeVerticies = {
|
||||
*/
|
||||
#[derive(Hash,PartialEq,Eq)]
|
||||
pub enum CornerWedgeFace{
|
||||
Top,
|
||||
Right,
|
||||
TopBack,
|
||||
TopLeft,
|
||||
Bottom,
|
||||
Front,
|
||||
}
|
||||
const CORNERWEDGE_DEFAULT_NORMALS:[[f32;3];5]=[
|
||||
[ 1., 0., 0.],//Wedge::Right
|
||||
[ 0., 1., 1.],//Wedge::BackTop
|
||||
[-1., 1., 0.],//Wedge::LeftTop
|
||||
[ 0.,-1., 0.],//Wedge::Bottom
|
||||
[ 0., 0.,-1.],//Wedge::Front
|
||||
[ 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{
|
||||
@ -162,7 +163,8 @@ pub type CornerWedgeFaceDescription=std::collections::HashMap::<CornerWedgeFace,
|
||||
pub fn unit_cornerwedge()->crate::model::IndexedModel{
|
||||
let mut t=CornerWedgeFaceDescription::new();
|
||||
t.insert(CornerWedgeFace::Right,FaceDescription::default());
|
||||
t.insert(CornerWedgeFace::Top,FaceDescription::default());
|
||||
t.insert(CornerWedgeFace::TopBack,FaceDescription::default());
|
||||
t.insert(CornerWedgeFace::TopLeft,FaceDescription::default());
|
||||
t.insert(CornerWedgeFace::Bottom,FaceDescription::default());
|
||||
t.insert(CornerWedgeFace::Front,FaceDescription::default());
|
||||
generate_partial_unit_cornerwedge(t)
|
||||
@ -206,7 +208,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 +323,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 +435,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
|
||||
@ -456,9 +458,10 @@ pub fn generate_partial_unit_cornerwedge(face_descriptions:CornerWedgeFaceDescri
|
||||
} as u32;
|
||||
let face_id=match face{
|
||||
CornerWedgeFace::Right => 0,
|
||||
CornerWedgeFace::Top => 1,
|
||||
CornerWedgeFace::Bottom => 2,
|
||||
CornerWedgeFace::Front => 3,
|
||||
CornerWedgeFace::TopBack => 1,
|
||||
CornerWedgeFace::TopLeft => 2,
|
||||
CornerWedgeFace::Bottom => 3,
|
||||
CornerWedgeFace::Front => 4,
|
||||
};
|
||||
//always push normal
|
||||
let normal_index=generated_normal.len() as u32;
|
||||
|
123
src/settings.rs
Normal file
123
src/settings.rs
Normal file
@ -0,0 +1,123 @@
|
||||
struct Ratio{
|
||||
ratio:f64,
|
||||
}
|
||||
enum DerivedFov{
|
||||
FromScreenAspect,
|
||||
FromAspect(Ratio),
|
||||
}
|
||||
enum Fov{
|
||||
Exactly{x:f64,y:f64},
|
||||
DeriveX{x:DerivedFov,y:f64},
|
||||
DeriveY{x:f64,y:DerivedFov},
|
||||
}
|
||||
impl Default for Fov{
|
||||
fn default() -> Self {
|
||||
Fov::DeriveX{x:DerivedFov::FromScreenAspect,y:1.0}
|
||||
}
|
||||
}
|
||||
|
||||
enum Sensitivity{
|
||||
Exactly{x:f64,y:f64},
|
||||
DeriveX{x:Ratio,y:f64},
|
||||
DeriveY{x:f64,y:Ratio},
|
||||
}
|
||||
impl Default for Sensitivity{
|
||||
fn default() -> Self {
|
||||
Sensitivity::DeriveY{x:0.001,y:Ratio{ratio:1.0}}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct UserSettings{
|
||||
fov:Fov,
|
||||
sensitivity:Sensitivity,
|
||||
}
|
||||
impl UserSettings{
|
||||
pub fn calculate_fov(&self,zoom:f64,screen_size:&glam::UVec2)->glam::DVec2{
|
||||
zoom*match &self.fov{
|
||||
&Fov::Exactly{x,y}=>glam::dvec2(x,y),
|
||||
Fov::DeriveX{x,y}=>match x{
|
||||
DerivedFov::FromScreenAspect=>glam::dvec2(y*(screen_size.x as f64/screen_size.y as f64),*y),
|
||||
DerivedFov::FromAspect(ratio)=>glam::dvec2(y*ratio.ratio,*y),
|
||||
},
|
||||
Fov::DeriveY{x,y}=>match y{
|
||||
DerivedFov::FromScreenAspect=>glam::dvec2(*x,x*(screen_size.y as f64/screen_size.x as f64)),
|
||||
DerivedFov::FromAspect(ratio)=>glam::dvec2(*x,x*ratio.ratio),
|
||||
},
|
||||
}
|
||||
}
|
||||
pub fn calculate_sensitivity(&self)->glam::DVec2{
|
||||
match &self.sensitivity{
|
||||
&Sensitivity::Exactly{x,y}=>glam::dvec2(x,y),
|
||||
Sensitivity::DeriveX{x,y}=>glam::dvec2(y*x.ratio,*y),
|
||||
Sensitivity::DeriveY{x,y}=>glam::dvec2(*x,x*y.ratio),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
//sensitivity is raw input dots (i.e. dpi = dots per inch) to radians conversion factor
|
||||
sensitivity_x=0.001
|
||||
sensitivity_y_from_x_ratio=1
|
||||
Sensitivity::DeriveY{x:0.0.001,y:DerivedSensitivity{ratio:1.0}}
|
||||
*/
|
||||
|
||||
pub fn read_user_settings()->UserSettings{
|
||||
let mut cfg=configparser::ini::Ini::new();
|
||||
if let Ok(_)=cfg.load("settings.conf"){
|
||||
let (cfg_fov_x,cfg_fov_y)=(cfg.getfloat("camera","fov_x"),cfg.getfloat("camera","fov_y"));
|
||||
let fov=match(cfg_fov_x,cfg_fov_y){
|
||||
(Ok(Some(fov_x)),Ok(Some(fov_y)))=>Fov::Exactly {
|
||||
x:fov_x,
|
||||
y:fov_y
|
||||
},
|
||||
(Ok(Some(fov_x)),Ok(None))=>Fov::DeriveY{
|
||||
x:fov_x,
|
||||
y:if let Ok(Some(fov_y_from_x_ratio))=cfg.getfloat("camera","fov_y_from_x_ratio"){
|
||||
DerivedFov::FromAspect(Ratio{ratio:fov_y_from_x_ratio})
|
||||
}else{
|
||||
DerivedFov::FromScreenAspect
|
||||
}
|
||||
},
|
||||
(Ok(None),Ok(Some(fov_y)))=>Fov::DeriveX{
|
||||
x:if let Ok(Some(fov_x_from_y_ratio))=cfg.getfloat("camera","fov_x_from_y_ratio"){
|
||||
DerivedFov::FromAspect(Ratio{ratio:fov_x_from_y_ratio})
|
||||
}else{
|
||||
DerivedFov::FromScreenAspect
|
||||
},
|
||||
y:fov_y,
|
||||
},
|
||||
_=>{
|
||||
Fov::default()
|
||||
},
|
||||
};
|
||||
let (cfg_sensitivity_x,cfg_sensitivity_y)=(cfg.getfloat("camera","sensitivity_x"),cfg.getfloat("camera","sensitivity_y"));
|
||||
let sensitivity=match(cfg_sensitivity_x,cfg_sensitivity_y){
|
||||
(Ok(Some(sensitivity_x)),Ok(Some(sensitivity_y)))=>Sensitivity::Exactly {
|
||||
x:sensitivity_x,
|
||||
y:sensitivity_y
|
||||
},
|
||||
(Ok(Some(sensitivity_x)),Ok(None))=>Sensitivity::DeriveY{
|
||||
x:sensitivity_x,
|
||||
y:Ratio{
|
||||
ratio:if let Ok(Some(sensitivity_y_from_x_ratio))=cfg.getfloat("camera","sensitivity_y_from_x_ratio"){sensitivity_y_from_x_ratio}else{1.0}
|
||||
}
|
||||
},
|
||||
(Ok(None),Ok(Some(sensitivity_y)))=>Sensitivity::DeriveX{
|
||||
x:Ratio{
|
||||
ratio:if let Ok(Some(sensitivity_x_from_y_ratio))=cfg.getfloat("camera","sensitivity_x_from_y_ratio"){sensitivity_x_from_y_ratio}else{1.0}
|
||||
},
|
||||
y:sensitivity_y,
|
||||
},
|
||||
_=>{
|
||||
Sensitivity::default()
|
||||
},
|
||||
};
|
||||
UserSettings{
|
||||
fov,
|
||||
sensitivity,
|
||||
}
|
||||
}else{
|
||||
UserSettings::default()
|
||||
}
|
||||
}
|
@ -5,8 +5,8 @@ struct Camera {
|
||||
proj_inv: mat4x4<f32>,
|
||||
// from world to camera
|
||||
view: mat4x4<f32>,
|
||||
// camera position
|
||||
cam_pos: vec4<f32>,
|
||||
// from camera to world
|
||||
view_inv: mat4x4<f32>,
|
||||
};
|
||||
|
||||
//group 0 is the camera
|
||||
@ -31,8 +31,7 @@ fn vs_sky(@builtin(vertex_index) vertex_index: u32) -> SkyOutput {
|
||||
1.0
|
||||
);
|
||||
|
||||
// transposition = inversion for this orthonormal matrix
|
||||
let inv_model_view = transpose(mat3x3<f32>(camera.view[0].xyz, camera.view[1].xyz, camera.view[2].xyz));
|
||||
let inv_model_view = mat3x3<f32>(camera.view_inv[0].xyz, camera.view_inv[1].xyz, camera.view_inv[2].xyz);
|
||||
let unprojected = camera.proj_inv * pos;
|
||||
|
||||
var result: SkyOutput;
|
||||
@ -43,7 +42,7 @@ fn vs_sky(@builtin(vertex_index) vertex_index: u32) -> SkyOutput {
|
||||
|
||||
struct ModelInstance{
|
||||
transform:mat4x4<f32>,
|
||||
normal_transform:mat4x4<f32>,
|
||||
normal_transform:mat3x3<f32>,
|
||||
color:vec4<f32>,
|
||||
}
|
||||
//my fancy idea is to create a megatexture for each model that includes all the textures each intance will need
|
||||
@ -78,11 +77,11 @@ fn vs_entity_texture(
|
||||
) -> EntityOutputTexture {
|
||||
var position: vec4<f32> = model_instances[instance].transform * vec4<f32>(pos, 1.0);
|
||||
var result: EntityOutputTexture;
|
||||
result.normal = (model_instances[instance].normal_transform * vec4<f32>(normal, 1.0)).xyz;
|
||||
result.normal = model_instances[instance].normal_transform * normal;
|
||||
result.texture = texture;
|
||||
result.color = color;
|
||||
result.model_color = model_instances[instance].color;
|
||||
result.view = position.xyz - camera.cam_pos.xyz;
|
||||
result.view = position.xyz - camera.view_inv[3].xyz;//col(3)
|
||||
result.position = camera.proj * camera.view * position;
|
||||
return result;
|
||||
}
|
||||
@ -109,5 +108,5 @@ fn fs_entity_texture(vertex: EntityOutputTexture) -> @location(0) vec4<f32> {
|
||||
|
||||
let fragment_color = textureSample(model_texture, model_sampler, vertex.texture)*vertex.color;
|
||||
let reflected_color = textureSample(cube_texture, cube_sampler, reflected).rgb;
|
||||
return mix(vec4<f32>(vec3<f32>(0.05) + 0.2 * reflected_color,1.0),mix(vertex.model_color,vec4<f32>(fragment_color.rgb,1.0),fragment_color.a),1.0-pow(1.0-abs(d),2.0));
|
||||
return mix(vec4<f32>(vec3<f32>(0.05) + 0.2 * reflected_color,1.0),mix(vertex.model_color,vec4<f32>(fragment_color.rgb,1.0),fragment_color.a),0.5+0.5*abs(d));
|
||||
}
|
||||
|
237
src/timers.rs
Normal file
237
src/timers.rs
Normal file
@ -0,0 +1,237 @@
|
||||
type TIME=crate::physics::TIME;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct Timescale{
|
||||
num:i64,
|
||||
den:std::num::NonZeroU64,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct Paused{}
|
||||
#[derive(Clone)]
|
||||
pub struct Unpaused{}
|
||||
#[derive(Clone)]
|
||||
pub struct PausedScaled{scale:Timescale}
|
||||
#[derive(Clone)]
|
||||
pub struct UnpausedScaled{scale:Timescale}
|
||||
|
||||
pub trait TimerState{}
|
||||
impl TimerState for Paused{}
|
||||
impl TimerState for Unpaused{}
|
||||
impl TimerState for PausedScaled{}
|
||||
impl TimerState for UnpausedScaled{}
|
||||
|
||||
pub trait IsPaused{}
|
||||
impl IsPaused for Paused{}
|
||||
impl IsPaused for PausedScaled{}
|
||||
|
||||
pub trait IsUnpaused{}
|
||||
impl IsUnpaused for Unpaused{}
|
||||
impl IsUnpaused for UnpausedScaled{}
|
||||
|
||||
pub trait IsScaled{}
|
||||
impl IsScaled for PausedScaled{}
|
||||
impl IsScaled for UnpausedScaled{}
|
||||
|
||||
pub trait IsUnscaled{}
|
||||
impl IsUnscaled for Paused{}
|
||||
impl IsUnscaled for Unpaused{}
|
||||
|
||||
//scaled timer wrapper
|
||||
enum Scaled{
|
||||
Paused(Timer<PausedScaled>),
|
||||
Unpaused(Timer<UnpausedScaled>),
|
||||
}
|
||||
pub struct ScaledTimer{
|
||||
timer:Scaled,
|
||||
}
|
||||
impl ScaledTimer{
|
||||
pub fn unpaused()->Self{
|
||||
Self{
|
||||
timer:Scaled::Unpaused(unpaused_scaled(Timescale{num:1,den:std::num::NonZeroU64::new(1).unwrap()}))
|
||||
}
|
||||
}
|
||||
pub fn time(&self,time:TIME)->TIME{
|
||||
match &self.timer{
|
||||
Scaled::Paused(timer)=>timer.time(),
|
||||
Scaled::Unpaused(timer)=>timer.time(time),
|
||||
}
|
||||
}
|
||||
pub fn pause(&mut self,time:TIME){
|
||||
match &self.timer{
|
||||
Scaled::Paused(_)=>(),
|
||||
Scaled::Unpaused(timer)=>self.timer=Scaled::Paused(timer.clone().pause(time)),
|
||||
};
|
||||
}
|
||||
pub fn unpause(&mut self,time:TIME){
|
||||
match &self.timer{
|
||||
Scaled::Paused(timer)=>self.timer=Scaled::Unpaused(timer.clone().unpause(time)),
|
||||
Scaled::Unpaused(_)=>(),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
//unscaled timer wrapper
|
||||
enum Unscaled{
|
||||
Paused(Timer<Paused>),
|
||||
Unpaused(Timer<Unpaused>),
|
||||
}
|
||||
pub struct UnscaledTimer{
|
||||
timer:Unscaled,
|
||||
}
|
||||
|
||||
impl UnscaledTimer{
|
||||
pub fn unpaused()->Self{
|
||||
Self{
|
||||
timer:Unscaled::Unpaused(unpaused())
|
||||
}
|
||||
}
|
||||
pub fn time(&self,time:TIME)->TIME{
|
||||
match &self.timer{
|
||||
Unscaled::Paused(timer)=>timer.time(),
|
||||
Unscaled::Unpaused(timer)=>timer.time(time),
|
||||
}
|
||||
}
|
||||
pub fn pause(&mut self,time:TIME){
|
||||
match &self.timer{
|
||||
Unscaled::Paused(_)=>(),
|
||||
Unscaled::Unpaused(timer)=>self.timer=Unscaled::Paused(timer.clone().pause(time)),
|
||||
};
|
||||
}
|
||||
pub fn unpause(&mut self,time:TIME){
|
||||
match &self.timer{
|
||||
Unscaled::Paused(timer)=>self.timer=Unscaled::Unpaused(timer.clone().unpause(time)),
|
||||
Unscaled::Unpaused(_)=>(),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct Timer<State:TimerState>{
|
||||
offset:crate::physics::TIME,
|
||||
state:State,
|
||||
}
|
||||
|
||||
fn get_offset(time:TIME,write_time:TIME)->TIME{
|
||||
write_time-time
|
||||
}
|
||||
fn get_offset_scaled(time:TIME,write_time:TIME,scale:&Timescale)->TIME{
|
||||
write_time-time*scale.num/scale.den.get() as i64
|
||||
}
|
||||
|
||||
fn paused()->Timer<Paused>{
|
||||
Timer{
|
||||
offset:0,
|
||||
state:Paused{},
|
||||
}
|
||||
}
|
||||
fn unpaused()->Timer<Unpaused>{
|
||||
Timer{
|
||||
offset:0,
|
||||
state:Unpaused{},
|
||||
}
|
||||
}
|
||||
fn paused_scaled(scale:Timescale)->Timer<PausedScaled>{
|
||||
Timer{
|
||||
offset:0,
|
||||
state:PausedScaled{scale},
|
||||
}
|
||||
}
|
||||
fn unpaused_scaled(scale:Timescale)->Timer<UnpausedScaled>{
|
||||
Timer{
|
||||
offset:0,
|
||||
state:UnpausedScaled{scale},
|
||||
}
|
||||
}
|
||||
impl Timer<Paused>{
|
||||
pub fn time(&self)->TIME{
|
||||
self.offset
|
||||
}
|
||||
pub fn unpause(self,time:TIME)->Timer<Unpaused>{
|
||||
Timer{
|
||||
offset:get_offset(time,self.time()),
|
||||
state:Unpaused{},
|
||||
}
|
||||
}
|
||||
pub fn set_time(&mut self,time:TIME,write_time:TIME){
|
||||
self.offset=get_offset(time,write_time);
|
||||
}
|
||||
pub fn set_scale(self,time:TIME,scale:Timescale)->Timer<PausedScaled>{
|
||||
Timer{
|
||||
offset:get_offset_scaled(time,self.time(),&scale),
|
||||
state:PausedScaled{scale},
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Timer<Unpaused>{
|
||||
pub fn time(&self,time:TIME)->TIME{
|
||||
self.offset+time
|
||||
}
|
||||
pub fn pause(self,time:TIME)->Timer<Paused>{
|
||||
Timer{
|
||||
offset:self.time(time),
|
||||
state:Paused{},
|
||||
}
|
||||
}
|
||||
pub fn set_time(&mut self,time:TIME,write_time:TIME){
|
||||
self.offset=get_offset(time,write_time);
|
||||
}
|
||||
pub fn set_scale(self,time:TIME,scale:Timescale)->Timer<UnpausedScaled>{
|
||||
Timer{
|
||||
offset:get_offset_scaled(time,self.time(time),&scale),
|
||||
state:UnpausedScaled{scale},
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Timer<PausedScaled>{
|
||||
pub fn time(&self)->TIME{
|
||||
self.offset
|
||||
}
|
||||
pub fn unpause(self,time:TIME)->Timer<UnpausedScaled>{
|
||||
Timer{
|
||||
offset:get_offset_scaled(time,self.time(),&self.state.scale),
|
||||
state:UnpausedScaled{scale:self.state.scale},
|
||||
}
|
||||
}
|
||||
pub fn set_time(&mut self,time:TIME,write_time:TIME){
|
||||
self.offset=get_offset_scaled(time,write_time,&self.state.scale);
|
||||
}
|
||||
pub fn set_scale(self,time:TIME,scale:Timescale)->Timer<PausedScaled>{
|
||||
Timer{
|
||||
offset:get_offset_scaled(time,self.time(),&scale),
|
||||
state:PausedScaled{scale},
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Timer<UnpausedScaled>{
|
||||
pub fn time(&self,time:TIME)->TIME{
|
||||
self.offset+time*self.state.scale.num/self.state.scale.den.get() as i64
|
||||
}
|
||||
pub fn pause(self,time:TIME)->Timer<PausedScaled>{
|
||||
Timer{
|
||||
offset:self.time(time),
|
||||
state:PausedScaled{scale:self.state.scale},
|
||||
}
|
||||
}
|
||||
pub fn set_time(&mut self,time:TIME,write_time:TIME){
|
||||
self.offset=get_offset_scaled(time,write_time,&self.state.scale);
|
||||
}
|
||||
pub fn set_scale(self,time:TIME,scale:Timescale)->Timer<UnpausedScaled>{
|
||||
Timer{
|
||||
offset:get_offset_scaled(time,self.time(time),&scale),
|
||||
//self.offset+time*self.state.scale.num/self.state.scale.den.get() as i64-time*scale.num/scale.den.get() as i64
|
||||
state:UnpausedScaled{scale},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_timer_unscaled(){
|
||||
const ONE_SECOND:TIME=1_000_000_000;
|
||||
let run_prepare=paused();
|
||||
|
||||
let run_start=run_prepare.unpause(ONE_SECOND);
|
||||
let run_finish=run_start.pause(11*ONE_SECOND);
|
||||
|
||||
assert_eq!(run_finish.time(),10*ONE_SECOND);
|
||||
}
|
107
src/worker.rs
Normal file
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));
|
||||
}
|
Reference in New Issue
Block a user