forked from StrafesNET/strafe-project
Compare commits
6 Commits
file-forma
...
zeroes-opt
Author | SHA1 | Date | |
---|---|---|---|
91f8652ece | |||
0ec0d24302 | |||
f7ee18076a | |||
ee7df7787a | |||
db5f4e1da3 | |||
01a8efe4d4 |
829
Cargo.lock
generated
829
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "strafe-client"
|
||||
version = "0.9.0"
|
||||
version = "0.8.0"
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
@ -18,7 +18,7 @@ rbx_binary = "0.7.1"
|
||||
rbx_dom_weak = "2.5.0"
|
||||
rbx_reflection_database = "0.2.7"
|
||||
rbx_xml = "0.13.1"
|
||||
wgpu = "0.18.0"
|
||||
wgpu = "0.17.0"
|
||||
winit = { version = "0.29.2", features = ["rwh_05"] }
|
||||
|
||||
#[profile.release]
|
||||
|
53
src/aabb.rs
53
src/aabb.rs
@ -1,9 +1,18 @@
|
||||
use crate::integer::Planar64Vec3;
|
||||
|
||||
#[derive(Debug,Clone,Copy,Hash,Eq,PartialEq)]
|
||||
pub enum AabbFace{
|
||||
Right,//+X
|
||||
Top,
|
||||
Back,
|
||||
Left,
|
||||
Bottom,
|
||||
Front,
|
||||
}
|
||||
#[derive(Clone)]
|
||||
pub struct Aabb{
|
||||
min:Planar64Vec3,
|
||||
max:Planar64Vec3,
|
||||
pub min:Planar64Vec3,
|
||||
pub max:Planar64Vec3,
|
||||
}
|
||||
|
||||
impl Default for Aabb {
|
||||
@ -13,6 +22,17 @@ impl Default for Aabb {
|
||||
}
|
||||
|
||||
impl Aabb{
|
||||
const VERTEX_DATA:[Planar64Vec3;8]=[
|
||||
Planar64Vec3::int( 1,-1,-1),
|
||||
Planar64Vec3::int( 1, 1,-1),
|
||||
Planar64Vec3::int( 1, 1, 1),
|
||||
Planar64Vec3::int( 1,-1, 1),
|
||||
Planar64Vec3::int(-1,-1, 1),
|
||||
Planar64Vec3::int(-1, 1, 1),
|
||||
Planar64Vec3::int(-1, 1,-1),
|
||||
Planar64Vec3::int(-1,-1,-1),
|
||||
];
|
||||
|
||||
pub fn grow(&mut self,point:Planar64Vec3){
|
||||
self.min=self.min.min(point);
|
||||
self.max=self.max.max(point);
|
||||
@ -28,11 +48,34 @@ impl Aabb{
|
||||
pub fn intersects(&self,aabb:&Aabb)->bool{
|
||||
(self.min.cmplt(aabb.max)&aabb.min.cmplt(self.max)).all()
|
||||
}
|
||||
pub fn size(&self)->Planar64Vec3{
|
||||
self.max-self.min
|
||||
pub fn normal(face:AabbFace)->Planar64Vec3{
|
||||
match face {
|
||||
AabbFace::Right=>Planar64Vec3::int(1,0,0),
|
||||
AabbFace::Top=>Planar64Vec3::int(0,1,0),
|
||||
AabbFace::Back=>Planar64Vec3::int(0,0,1),
|
||||
AabbFace::Left=>Planar64Vec3::int(-1,0,0),
|
||||
AabbFace::Bottom=>Planar64Vec3::int(0,-1,0),
|
||||
AabbFace::Front=>Planar64Vec3::int(0,0,-1),
|
||||
}
|
||||
}
|
||||
pub fn unit_vertices()->[Planar64Vec3;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)->Planar64Vec3{
|
||||
self.min.midpoint(self.max)
|
||||
return self.min.midpoint(self.max)
|
||||
}
|
||||
//probably use floats for area & volume because we don't care about precision
|
||||
// pub fn area_weight(&self)->f32{
|
||||
|
50
src/bvh.rs
50
src/bvh.rs
@ -9,34 +9,22 @@ use crate::aabb::Aabb;
|
||||
//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
|
||||
enum BvhNodeContent{
|
||||
Branch(Vec<BvhNode>),
|
||||
Leaf(usize),
|
||||
}
|
||||
impl Default for BvhNodeContent{
|
||||
fn default()->Self{
|
||||
Self::Branch(Vec::new())
|
||||
}
|
||||
}
|
||||
#[derive(Default)]
|
||||
pub struct BvhNode{
|
||||
content:BvhNodeContent,
|
||||
children:Vec<Self>,
|
||||
models:Vec<usize>,
|
||||
aabb:Aabb,
|
||||
}
|
||||
|
||||
impl BvhNode{
|
||||
pub fn the_tester<F:FnMut(usize)>(&self,aabb:&Aabb,f:&mut F){
|
||||
match &self.content{
|
||||
&BvhNodeContent::Leaf(model)=>f(model),
|
||||
BvhNodeContent::Branch(children)=>for child in children{
|
||||
//this test could be moved outside the match statement
|
||||
//but that would test the root node aabb
|
||||
//you're probably not going to spend a lot of time outside the map,
|
||||
//so the test is extra work for nothing
|
||||
if aabb.intersects(&child.aabb){
|
||||
child.the_tester(aabb,f);
|
||||
}
|
||||
},
|
||||
for &model in &self.models{
|
||||
f(model);
|
||||
}
|
||||
for child in &self.children{
|
||||
if aabb.intersects(&child.aabb){
|
||||
child.the_tester(aabb,f);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -49,15 +37,10 @@ fn generate_bvh_node(boxen:Vec<(usize,Aabb)>)->BvhNode{
|
||||
let n=boxen.len();
|
||||
if n<20{
|
||||
let mut aabb=Aabb::default();
|
||||
let nodes=boxen.into_iter().map(|b|{
|
||||
aabb.join(&b.1);
|
||||
BvhNode{
|
||||
content:BvhNodeContent::Leaf(b.0),
|
||||
aabb:b.1,
|
||||
}
|
||||
}).collect();
|
||||
let models=boxen.into_iter().map(|b|{aabb.join(&b.1);b.0}).collect();
|
||||
BvhNode{
|
||||
content:BvhNodeContent::Branch(nodes),
|
||||
children:Vec::new(),
|
||||
models,
|
||||
aabb,
|
||||
}
|
||||
}else{
|
||||
@ -72,9 +55,9 @@ fn generate_bvh_node(boxen:Vec<(usize,Aabb)>)->BvhNode{
|
||||
sort_y.push((*i,center.y()));
|
||||
sort_z.push((*i,center.z()));
|
||||
}
|
||||
sort_x.sort_by(|tup0,tup1|tup0.1.cmp(&tup1.1));
|
||||
sort_y.sort_by(|tup0,tup1|tup0.1.cmp(&tup1.1));
|
||||
sort_z.sort_by(|tup0,tup1|tup0.1.cmp(&tup1.1));
|
||||
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;
|
||||
@ -116,7 +99,8 @@ fn generate_bvh_node(boxen:Vec<(usize,Aabb)>)->BvhNode{
|
||||
node
|
||||
}).collect();
|
||||
BvhNode{
|
||||
content:BvhNodeContent::Branch(children),
|
||||
children,
|
||||
models:Vec::new(),
|
||||
aabb,
|
||||
}
|
||||
}
|
||||
|
@ -3,11 +3,11 @@ pub type INWorker<'a,Task>=CompatNWorker<'a,Task>;
|
||||
|
||||
pub struct CompatNWorker<'a,Task>{
|
||||
data:std::marker::PhantomData<Task>,
|
||||
f:Box<dyn FnMut(Task)+Send+'a>,
|
||||
f:Box<dyn FnMut(Task)+'a>,
|
||||
}
|
||||
|
||||
impl<'a,Task> CompatNWorker<'a,Task>{
|
||||
pub fn new(f:impl FnMut(Task)+Send+'a)->CompatNWorker<'a,Task>{
|
||||
pub fn new(f:impl FnMut(Task)+'a)->CompatNWorker<'a,Task>{
|
||||
Self{
|
||||
data:std::marker::PhantomData,
|
||||
f:Box::new(f),
|
||||
|
@ -1,119 +0,0 @@
|
||||
use crate::physics::Body;
|
||||
use crate::model_physics::{FEV,MeshQuery,DirectedEdge};
|
||||
use crate::integer::{Time,Planar64};
|
||||
use crate::zeroes::zeroes2;
|
||||
|
||||
enum Transition<F,E:DirectedEdge,V>{
|
||||
Miss,
|
||||
Next(FEV<F,E,V>,Time),
|
||||
Hit(F,Time),
|
||||
}
|
||||
|
||||
fn next_transition<F:Copy,E:Copy+DirectedEdge,V:Copy>(fev:&FEV<F,E,V>,time:Time,mesh:&impl MeshQuery<F,E,V>,body:&Body,time_limit:Time)->Transition<F,E,V>{
|
||||
//conflicting derivative means it crosses in the wrong direction.
|
||||
//if the transition time is equal to an already tested transition, do not replace the current best.
|
||||
let mut best_time=time_limit;
|
||||
let mut best_transtition=Transition::Miss;
|
||||
match fev{
|
||||
&FEV::<F,E,V>::Face(face_id)=>{
|
||||
//test own face collision time, ignoring roots with zero or conflicting derivative
|
||||
//n=face.normal d=face.dot
|
||||
//n.a t^2+n.v t+n.p-d==0
|
||||
let (n,d)=mesh.face_nd(face_id);
|
||||
//TODO: use higher precision d value?
|
||||
//use the mesh transform translation instead of baking it into the d value.
|
||||
for t in zeroes2((n.dot(body.position)-d)*2,n.dot(body.velocity)*2,n.dot(body.acceleration)){
|
||||
let t=body.time+Time::from(t);
|
||||
if time<=t&&t<best_time&&n.dot(body.extrapolated_velocity(t))<Planar64::ZERO{
|
||||
best_time=t;
|
||||
best_transtition=Transition::Hit(face_id,t);
|
||||
break;
|
||||
}
|
||||
}
|
||||
//test each edge collision time, ignoring roots with zero or conflicting derivative
|
||||
for &directed_edge_id in mesh.face_edges(face_id).iter(){
|
||||
let edge_n=mesh.directed_edge_n(directed_edge_id);
|
||||
let n=n.cross(edge_n);
|
||||
let verts=mesh.edge_verts(directed_edge_id.as_undirected());
|
||||
//WARNING: d is moved out of the *2 block because of adding two vertices!
|
||||
for t in zeroes2(n.dot(body.position*2-(mesh.vert(verts[0])+mesh.vert(verts[1]))),n.dot(body.velocity)*2,n.dot(body.acceleration)){
|
||||
let t=body.time+Time::from(t);
|
||||
if time<=t&&t<best_time&&n.dot(body.extrapolated_velocity(t))<Planar64::ZERO{
|
||||
best_time=t;
|
||||
best_transtition=Transition::Next(FEV::<F,E,V>::Edge(directed_edge_id.as_undirected()),t);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
//if none:
|
||||
},
|
||||
&FEV::<F,E,V>::Edge(edge_id)=>{
|
||||
//test each face collision time, ignoring roots with zero or conflicting derivative
|
||||
let edge_n=mesh.edge_n(edge_id);
|
||||
let edge_verts=mesh.edge_verts(edge_id);
|
||||
let delta_pos=body.position*2-(mesh.vert(edge_verts[0])+mesh.vert(edge_verts[1]));
|
||||
for (i,&edge_face_id) in mesh.edge_faces(edge_id).iter().enumerate(){
|
||||
let face_n=mesh.face_nd(edge_face_id).0;
|
||||
//edge_n gets parity from the order of edge_faces
|
||||
let n=face_n.cross(edge_n)*((i as i64)*2-1);
|
||||
//WARNING yada yada d *2
|
||||
for t in zeroes2(n.dot(delta_pos),n.dot(body.velocity)*2,n.dot(body.acceleration)){
|
||||
let t=body.time+Time::from(t);
|
||||
if time<=t&&t<best_time&&n.dot(body.extrapolated_velocity(t))<Planar64::ZERO{
|
||||
best_time=t;
|
||||
best_transtition=Transition::Next(FEV::<F,E,V>::Face(edge_face_id),t);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
//test each vertex collision time, ignoring roots with zero or conflicting derivative
|
||||
for (i,&vert_id) in edge_verts.iter().enumerate(){
|
||||
//vertex normal gets parity from vert index
|
||||
let n=edge_n*(1-2*(i as i64));
|
||||
for t in zeroes2((n.dot(body.position-mesh.vert(vert_id)))*2,n.dot(body.velocity)*2,n.dot(body.acceleration)){
|
||||
let t=body.time+Time::from(t);
|
||||
if time<=t&&t<best_time&&n.dot(body.extrapolated_velocity(t))<Planar64::ZERO{
|
||||
best_time=t;
|
||||
best_transtition=Transition::Next(FEV::<F,E,V>::Vert(vert_id),t);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
//if none:
|
||||
},
|
||||
&FEV::<F,E,V>::Vert(vert_id)=>{
|
||||
//test each edge collision time, ignoring roots with zero or conflicting derivative
|
||||
for &directed_edge_id in mesh.vert_edges(vert_id).iter(){
|
||||
//edge is directed away from vertex, but we want the dot product to turn out negative
|
||||
let n=-mesh.directed_edge_n(directed_edge_id);
|
||||
for t in zeroes2((n.dot(body.position-mesh.vert(vert_id)))*2,n.dot(body.velocity)*2,n.dot(body.acceleration)){
|
||||
let t=body.time+Time::from(t);
|
||||
if time<=t&&t<best_time&&n.dot(body.extrapolated_velocity(t))<Planar64::ZERO{
|
||||
best_time=t;
|
||||
best_transtition=Transition::Next(FEV::<F,E,V>::Edge(directed_edge_id.as_undirected()),t);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
//if none:
|
||||
},
|
||||
}
|
||||
best_transtition
|
||||
}
|
||||
pub enum CrawlResult<F,E:DirectedEdge,V>{
|
||||
Miss(FEV<F,E,V>),
|
||||
Hit(F,Time),
|
||||
}
|
||||
pub fn crawl_fev<F:Copy,E:Copy+DirectedEdge,V:Copy>(mut fev:FEV<F,E,V>,mesh:&impl MeshQuery<F,E,V>,relative_body:&Body,start_time:Time,time_limit:Time)->CrawlResult<F,E,V>{
|
||||
let mut time=start_time;
|
||||
for _ in 0..20{
|
||||
match next_transition(&fev,time,mesh,relative_body,time_limit){
|
||||
Transition::Miss=>return CrawlResult::Miss(fev),
|
||||
Transition::Next(next_fev,next_time)=>(fev,time)=(next_fev,next_time),
|
||||
Transition::Hit(face,time)=>return CrawlResult::Hit(face,time),
|
||||
}
|
||||
}
|
||||
//TODO: fix all bugs
|
||||
println!("Too many iterations! Using default behaviour instead of crashing...");
|
||||
CrawlResult::Miss(fev)
|
||||
}
|
146
src/graphics.rs
146
src/graphics.rs
@ -1,38 +1,24 @@
|
||||
use std::borrow::Cow;
|
||||
use wgpu::{util::DeviceExt,AstcBlock,AstcChannel};
|
||||
use crate::model_graphics::{GraphicsVertex,GraphicsModelColor4,GraphicsModelInstance,GraphicsModelSingleTexture,IndexedGraphicsModelSingleTexture,IndexedGroupFixedTexture};
|
||||
use crate::model_graphics::{GraphicsVertex,ModelGraphicsColor4,ModelGraphicsInstance,ModelGraphicsSingleTexture,IndexedModelGraphicsSingleTexture,IndexedGroupFixedTexture};
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct GraphicsModelUpdate{
|
||||
pub struct ModelUpdate{
|
||||
transform:Option<glam::Mat4>,
|
||||
color:Option<glam::Vec4>,
|
||||
}
|
||||
|
||||
struct Entity{
|
||||
index_count:u32,
|
||||
index_buf:wgpu::Buffer,
|
||||
}
|
||||
fn create_entities<T:bytemuck::Pod>(device:&wgpu::Device,entities:&Vec<Vec<T>>)->Vec<Entity>{
|
||||
entities.iter().map(|indices|{
|
||||
let index_buf=device.create_buffer_init(&wgpu::util::BufferInitDescriptor{
|
||||
label:Some("Index"),
|
||||
contents:bytemuck::cast_slice(indices),
|
||||
usage:wgpu::BufferUsages::INDEX,
|
||||
});
|
||||
Entity{
|
||||
index_buf,
|
||||
index_count:indices.len() as u32,
|
||||
}
|
||||
}).collect()
|
||||
struct Entity {
|
||||
index_count: u32,
|
||||
index_buf: wgpu::Buffer,
|
||||
}
|
||||
|
||||
struct GraphicsModel{
|
||||
entities:Vec<Entity>,
|
||||
model_buf:wgpu::Buffer,
|
||||
vertex_buf:wgpu::Buffer,
|
||||
bind_group:wgpu::BindGroup,
|
||||
index_format:wgpu::IndexFormat,
|
||||
instances:Vec<GraphicsModelInstance>,
|
||||
struct ModelGraphics {
|
||||
instances: Vec<ModelGraphicsInstance>,
|
||||
vertex_buf: wgpu::Buffer,
|
||||
entities: Vec<Entity>,
|
||||
bind_group: wgpu::BindGroup,
|
||||
model_buf: wgpu::Buffer,
|
||||
}
|
||||
|
||||
pub struct GraphicsSamplers{
|
||||
@ -71,6 +57,12 @@ fn perspective_rh(fov_x_slope: f32, fov_y_slope: f32, z_near: f32, z_far: f32) -
|
||||
)
|
||||
}
|
||||
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)
|
||||
}
|
||||
@ -110,7 +102,7 @@ pub struct GraphicsState{
|
||||
camera:GraphicsCamera,
|
||||
camera_buf: wgpu::Buffer,
|
||||
temp_squid_texture_view: wgpu::TextureView,
|
||||
models: Vec<GraphicsModel>,
|
||||
models: Vec<ModelGraphics>,
|
||||
depth_view: wgpu::TextureView,
|
||||
staging_belt: wgpu::util::StagingBelt,
|
||||
}
|
||||
@ -214,15 +206,15 @@ impl GraphicsState{
|
||||
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 GraphicsModelInstance
|
||||
let instances:Vec<GraphicsModelInstance>=model.instances.into_iter().filter_map(|instance|{
|
||||
//convert ModelInstance into ModelGraphicsInstance
|
||||
let instances:Vec<ModelGraphicsInstance>=model.instances.into_iter().filter_map(|instance|{
|
||||
if instance.color.w==0.0{
|
||||
None
|
||||
}else{
|
||||
Some(GraphicsModelInstance{
|
||||
Some(ModelGraphicsInstance{
|
||||
transform: instance.transform.into(),
|
||||
normal_transform: Into::<glam::Mat3>::into(instance.transform.matrix3).inverse().transpose(),
|
||||
color:GraphicsModelColor4::from(instance.color),
|
||||
color:ModelGraphicsColor4::from(instance.color),
|
||||
})
|
||||
}
|
||||
}).collect();
|
||||
@ -241,7 +233,7 @@ impl GraphicsState{
|
||||
//create new texture_index
|
||||
let texture_index=unique_textures.len();
|
||||
unique_textures.push(group.texture);
|
||||
unique_texture_models.push(IndexedGraphicsModelSingleTexture{
|
||||
unique_texture_models.push(IndexedModelGraphicsSingleTexture{
|
||||
unique_pos:model.unique_pos.iter().map(|&v|*Into::<glam::Vec3>::into(v).as_ref()).collect(),
|
||||
unique_tex:model.unique_tex.iter().map(|v|*v.as_ref()).collect(),
|
||||
unique_normal:model.unique_normal.iter().map(|&v|*Into::<glam::Vec3>::into(v).as_ref()).collect(),
|
||||
@ -375,10 +367,10 @@ impl GraphicsState{
|
||||
//creating the vertex map is slightly different because the vertices are directly hashable
|
||||
let map_vertex_id:Vec<u32>=model.unique_vertices.iter().map(|unmapped_vertex|{
|
||||
let vertex=crate::model::IndexedVertex{
|
||||
pos:map_pos_id[unmapped_vertex.pos as usize],
|
||||
tex:map_tex_id[unmapped_vertex.tex as usize],
|
||||
normal:map_normal_id[unmapped_vertex.normal as usize],
|
||||
color:map_color_id[unmapped_vertex.color as usize],
|
||||
pos:map_pos_id[unmapped_vertex.pos as usize] as u32,
|
||||
tex:map_tex_id[unmapped_vertex.tex as usize] as u32,
|
||||
normal:map_normal_id[unmapped_vertex.normal as usize] as u32,
|
||||
color:map_color_id[unmapped_vertex.color as usize] as u32,
|
||||
};
|
||||
(if let Some(&vertex_id)=vertex_id_from.get(&vertex){
|
||||
vertex_id
|
||||
@ -396,7 +388,7 @@ impl GraphicsState{
|
||||
}
|
||||
}
|
||||
//push model into dedup
|
||||
deduplicated_models.push(IndexedGraphicsModelSingleTexture{
|
||||
deduplicated_models.push(IndexedModelGraphicsSingleTexture{
|
||||
unique_pos,
|
||||
unique_tex,
|
||||
unique_normal,
|
||||
@ -406,7 +398,7 @@ impl GraphicsState{
|
||||
groups:vec![IndexedGroupFixedTexture{
|
||||
polys
|
||||
}],
|
||||
instances:vec![GraphicsModelInstance{
|
||||
instances:vec![ModelGraphicsInstance{
|
||||
transform:glam::Mat4::IDENTITY,
|
||||
normal_transform:glam::Mat3::IDENTITY,
|
||||
color
|
||||
@ -424,9 +416,10 @@ impl GraphicsState{
|
||||
|
||||
//de-index models
|
||||
let deduplicated_models_len=deduplicated_models.len();
|
||||
let models:Vec<GraphicsModelSingleTexture>=deduplicated_models.into_iter().map(|model|{
|
||||
let models:Vec<ModelGraphicsSingleTexture>=deduplicated_models.into_iter().map(|model|{
|
||||
let mut vertices = Vec::new();
|
||||
let mut index_from_vertex = std::collections::HashMap::new();//::<IndexedVertex,usize>
|
||||
let mut entities = Vec::new();
|
||||
//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 {
|
||||
@ -437,7 +430,7 @@ impl GraphicsState{
|
||||
if let Some(&i)=index_from_vertex.get(&vertex_index){
|
||||
indices.push(i);
|
||||
}else{
|
||||
let i=vertices.len();
|
||||
let i=vertices.len() as u16;
|
||||
let vertex=&model.unique_vertices[vertex_index as usize];
|
||||
vertices.push(GraphicsVertex{
|
||||
pos: model.unique_pos[vertex.pos as usize],
|
||||
@ -452,16 +445,11 @@ impl GraphicsState{
|
||||
}
|
||||
}
|
||||
}
|
||||
GraphicsModelSingleTexture{
|
||||
entities.push(indices);
|
||||
ModelGraphicsSingleTexture{
|
||||
instances:model.instances,
|
||||
entities:if (u32::MAX as usize)<vertices.len(){
|
||||
panic!("Model has too many vertices!")
|
||||
}else if (u16::MAX as usize)<vertices.len(){
|
||||
crate::model_graphics::Entities::U32(vec![indices.into_iter().map(|vertex_id|vertex_id as u32).collect()])
|
||||
}else{
|
||||
crate::model_graphics::Entities::U16(vec![indices.into_iter().map(|vertex_id|vertex_id as u16).collect()])
|
||||
},
|
||||
vertices,
|
||||
entities,
|
||||
texture:model.texture,
|
||||
}
|
||||
}).collect();
|
||||
@ -514,17 +502,20 @@ impl GraphicsState{
|
||||
usage: wgpu::BufferUsages::VERTEX,
|
||||
});
|
||||
//all of these are being moved here
|
||||
self.models.push(GraphicsModel{
|
||||
self.models.push(ModelGraphics{
|
||||
instances:instances_chunk.to_vec(),
|
||||
vertex_buf,
|
||||
index_format:match &model.entities{
|
||||
crate::model_graphics::Entities::U32(_)=>wgpu::IndexFormat::Uint32,
|
||||
crate::model_graphics::Entities::U16(_)=>wgpu::IndexFormat::Uint16,
|
||||
},
|
||||
entities:match &model.entities{
|
||||
crate::model_graphics::Entities::U32(entities)=>create_entities(device,entities),
|
||||
crate::model_graphics::Entities::U16(entities)=>create_entities(device,entities),
|
||||
},
|
||||
entities: model.entities.iter().map(|indices|{
|
||||
let index_buf = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||
label: Some("Index"),
|
||||
contents: bytemuck::cast_slice(&indices),
|
||||
usage: wgpu::BufferUsages::INDEX,
|
||||
});
|
||||
Entity {
|
||||
index_buf,
|
||||
index_count: indices.len() as u32,
|
||||
}
|
||||
}).collect(),
|
||||
bind_group: model_bind_group,
|
||||
model_buf,
|
||||
});
|
||||
@ -629,7 +620,6 @@ impl GraphicsState{
|
||||
mag_filter: wgpu::FilterMode::Linear,
|
||||
min_filter: wgpu::FilterMode::Linear,
|
||||
mipmap_filter: wgpu::FilterMode::Linear,
|
||||
anisotropy_clamp:16,
|
||||
..Default::default()
|
||||
});
|
||||
|
||||
@ -945,19 +935,17 @@ impl GraphicsState{
|
||||
b: 0.3,
|
||||
a: 1.0,
|
||||
}),
|
||||
store:wgpu::StoreOp::Store,
|
||||
store: true,
|
||||
},
|
||||
})],
|
||||
depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
|
||||
view: &self.depth_view,
|
||||
depth_ops: Some(wgpu::Operations {
|
||||
load: wgpu::LoadOp::Clear(1.0),
|
||||
store:wgpu::StoreOp::Discard,
|
||||
store: false,
|
||||
}),
|
||||
stencil_ops: None,
|
||||
}),
|
||||
timestamp_writes:Default::default(),
|
||||
occlusion_query_set:Default::default(),
|
||||
});
|
||||
|
||||
rpass.set_bind_group(0, &self.bind_groups.camera, &[]);
|
||||
@ -968,9 +956,9 @@ impl GraphicsState{
|
||||
rpass.set_bind_group(2, &model.bind_group, &[]);
|
||||
rpass.set_vertex_buffer(0, model.vertex_buf.slice(..));
|
||||
|
||||
for entity in model.entities.iter(){
|
||||
rpass.set_index_buffer(entity.index_buf.slice(..),model.index_format);
|
||||
rpass.draw_indexed(0..entity.index_count,0,0..model.instances.len() as u32);
|
||||
for entity in model.entities.iter() {
|
||||
rpass.set_index_buffer(entity.index_buf.slice(..), wgpu::IndexFormat::Uint16);
|
||||
rpass.draw_indexed(0..entity.index_count, 0, 0..model.instances.len() as u32);
|
||||
}
|
||||
}
|
||||
|
||||
@ -985,22 +973,22 @@ impl GraphicsState{
|
||||
}
|
||||
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:&[GraphicsModelInstance]) -> Vec<f32> {
|
||||
fn get_instances_buffer_data(instances:&[ModelGraphicsInstance]) -> Vec<f32> {
|
||||
let mut raw = Vec::with_capacity(MODEL_BUFFER_SIZE*instances.len());
|
||||
for (i,mi) in instances.iter().enumerate(){
|
||||
let mut v = raw.split_off(MODEL_BUFFER_SIZE*i);
|
||||
//model transform
|
||||
raw.extend_from_slice(&AsRef::<[f32; 4*4]>::as_ref(&mi.transform)[..]);
|
||||
//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.get()));
|
||||
raw.append(&mut v);
|
||||
let mut v = raw.split_off(MODEL_BUFFER_SIZE*i);
|
||||
//model transform
|
||||
raw.extend_from_slice(&AsRef::<[f32; 4*4]>::as_ref(&mi.transform)[..]);
|
||||
//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.get()));
|
||||
raw.append(&mut v);
|
||||
}
|
||||
raw
|
||||
}
|
||||
}
|
@ -1,6 +1,6 @@
|
||||
pub enum Instruction{
|
||||
Render(crate::physics::PhysicsOutputState,crate::integer::Time,glam::IVec2),
|
||||
//UpdateModel(crate::graphics::GraphicsModelUpdate),
|
||||
//UpdateModel(crate::graphics::ModelUpdate),
|
||||
Resize(winit::dpi::PhysicalSize<u32>,crate::settings::UserSettings),
|
||||
GenerateModels(crate::model::IndexedModelInstances),
|
||||
ClearModels,
|
||||
@ -22,7 +22,6 @@ pub fn new<'a>(
|
||||
device:wgpu::Device,
|
||||
queue:wgpu::Queue,
|
||||
)->crate::compat_worker::INWorker<'a,Instruction>{
|
||||
let mut resize=None;
|
||||
crate::compat_worker::INWorker::new(move |ins:Instruction|{
|
||||
match ins{
|
||||
Instruction::GenerateModels(indexed_model_instances)=>{
|
||||
@ -32,20 +31,13 @@ pub fn new<'a>(
|
||||
graphics.clear();
|
||||
},
|
||||
Instruction::Resize(size,user_settings)=>{
|
||||
resize=Some((size,user_settings));
|
||||
println!("Resizing to {:?}",size);
|
||||
config.width=size.width.max(1);
|
||||
config.height=size.height.max(1);
|
||||
surface.configure(&device,&config);
|
||||
graphics.resize(&device,&config,&user_settings);
|
||||
}
|
||||
Instruction::Render(physics_output,predicted_time,mouse_pos)=>{
|
||||
if let Some((size,user_settings))=&resize{
|
||||
println!("Resizing to {:?}",size);
|
||||
let t0=std::time::Instant::now();
|
||||
config.width=size.width.max(1);
|
||||
config.height=size.height.max(1);
|
||||
surface.configure(&device,&config);
|
||||
graphics.resize(&device,&config,user_settings);
|
||||
println!("Resize took {:?}",t0.elapsed());
|
||||
}
|
||||
//clear every time w/e
|
||||
resize=None;
|
||||
//this has to go deeper somehow
|
||||
let frame=match surface.get_current_texture(){
|
||||
Ok(frame)=>frame,
|
||||
|
@ -25,10 +25,7 @@ impl<I> InstructionCollector<I>{
|
||||
instruction:None
|
||||
}
|
||||
}
|
||||
#[inline]
|
||||
pub fn time(&self)->Time{
|
||||
self.time
|
||||
}
|
||||
|
||||
pub fn collect(&mut self,instruction:Option<TimedInstruction<I>>){
|
||||
match instruction{
|
||||
Some(unwrap_instruction)=>{
|
||||
|
200
src/integer.rs
200
src/integer.rs
@ -1,9 +1,7 @@
|
||||
//integer units
|
||||
#[derive(Clone,Copy,Hash,Eq,PartialEq,PartialOrd,Debug)]
|
||||
#[derive(Clone,Copy,Hash,PartialEq,PartialOrd,Debug)]
|
||||
pub struct Time(i64);
|
||||
impl Time{
|
||||
pub const MIN:Self=Self(i64::MIN);
|
||||
pub const MAX:Self=Self(i64::MAX);
|
||||
pub const ZERO:Self=Self(0);
|
||||
pub const ONE_SECOND:Self=Self(1_000_000_000);
|
||||
pub const ONE_MILLISECOND:Self=Self(1_000_000);
|
||||
@ -105,23 +103,23 @@ impl Ratio64{
|
||||
None
|
||||
}else{
|
||||
let d=gcd(num.unsigned_abs(),den);
|
||||
Some(Self{num:num/(d as i64),den:den/d})
|
||||
Some(Self{num:num/d as i64,den:den/d})
|
||||
}
|
||||
}
|
||||
#[inline]
|
||||
pub fn mul_int(&self,rhs:i64)->i64{
|
||||
rhs*self.num/(self.den as i64)
|
||||
rhs*self.num/self.den as i64
|
||||
}
|
||||
#[inline]
|
||||
pub fn rhs_div_int(&self,rhs:i64)->i64{
|
||||
rhs*(self.den as i64)/self.num
|
||||
rhs*self.den as i64/self.num
|
||||
}
|
||||
#[inline]
|
||||
pub fn mul_ref(&self,rhs:&Ratio64)->Ratio64{
|
||||
let (num,den)=(self.num*rhs.num,self.den*rhs.den);
|
||||
let d=gcd(num.unsigned_abs(),den);
|
||||
Self{
|
||||
num:num/(d as i64),
|
||||
num:num/d as i64,
|
||||
den:den/d,
|
||||
}
|
||||
}
|
||||
@ -209,8 +207,8 @@ impl TryFrom<f32> for Ratio64{
|
||||
std::num::FpCategory::Nan=>Err(Self::Error::Nan),
|
||||
std::num::FpCategory::Infinite=>Err(Self::Error::Infinite),
|
||||
std::num::FpCategory::Zero=>Ok(Self::ZERO),
|
||||
std::num::FpCategory::Subnormal
|
||||
|std::num::FpCategory::Normal=>ratio64_from_mes(integer_decode_f32(value)),
|
||||
std::num::FpCategory::Subnormal=>Err(Self::Error::Subnormal),
|
||||
std::num::FpCategory::Normal=>ratio64_from_mes(integer_decode_f32(value)),
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -222,8 +220,8 @@ impl TryFrom<f64> for Ratio64{
|
||||
std::num::FpCategory::Nan=>Err(Self::Error::Nan),
|
||||
std::num::FpCategory::Infinite=>Err(Self::Error::Infinite),
|
||||
std::num::FpCategory::Zero=>Ok(Self::ZERO),
|
||||
std::num::FpCategory::Subnormal
|
||||
|std::num::FpCategory::Normal=>ratio64_from_mes(integer_decode_f64(value)),
|
||||
std::num::FpCategory::Subnormal=>Err(Self::Error::Subnormal),
|
||||
std::num::FpCategory::Normal=>ratio64_from_mes(integer_decode_f64(value)),
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -234,7 +232,7 @@ impl std::ops::Mul<Ratio64> for Ratio64{
|
||||
let (num,den)=(self.num*rhs.num,self.den*rhs.den);
|
||||
let d=gcd(num.unsigned_abs(),den);
|
||||
Self{
|
||||
num:num/(d as i64),
|
||||
num:num/d as i64,
|
||||
den:den/d,
|
||||
}
|
||||
}
|
||||
@ -317,8 +315,8 @@ impl Angle32{
|
||||
pub fn clamp(&self,theta_min:Self,theta_max:Self)->Self{
|
||||
//((max-min as u32)/2 as i32)+min
|
||||
let midpoint=((
|
||||
(theta_max.0 as u32)
|
||||
.wrapping_sub(theta_min.0 as u32)
|
||||
u32::from_ne_bytes(theta_max.0.to_ne_bytes())
|
||||
.wrapping_sub(u32::from_ne_bytes(theta_min.0.to_ne_bytes()))
|
||||
/2
|
||||
) as i32)//(u32::MAX/2) as i32 ALWAYS works
|
||||
.wrapping_add(theta_min.0);
|
||||
@ -416,8 +414,6 @@ pub struct Planar64(i64);
|
||||
impl Planar64{
|
||||
pub const ZERO:Self=Self(0);
|
||||
pub const ONE:Self=Self(1<<32);
|
||||
pub const MAX:Self=Self(i64::MAX);
|
||||
pub const MIN:Self=Self(i64::MIN);
|
||||
#[inline]
|
||||
pub const fn int(num:i32)->Self{
|
||||
Self(Self::ONE.0*num as i64)
|
||||
@ -430,14 +426,9 @@ impl Planar64{
|
||||
pub const fn get(&self)->i64{
|
||||
self.0
|
||||
}
|
||||
#[inline]
|
||||
pub fn sqrt(&self)->Self{
|
||||
Planar64(unsafe{(((self.0 as i128)<<32) as f64).sqrt().to_int_unchecked()})
|
||||
}
|
||||
#[inline]
|
||||
pub const fn signum_i64(&self)->i64{
|
||||
((self.0&(1<<63)!=0) as i64)*2-1
|
||||
}
|
||||
}
|
||||
const PLANAR64_ONE_FLOAT32:f32=(1u64<<32) as f32;
|
||||
const PLANAR64_CONVERT_TO_FLOAT32:f32=1.0/PLANAR64_ONE_FLOAT32;
|
||||
@ -451,7 +442,7 @@ impl Into<f32> for Planar64{
|
||||
impl From<Ratio64> for Planar64{
|
||||
#[inline]
|
||||
fn from(ratio:Ratio64)->Self{
|
||||
Self((((ratio.num as i128)<<32)/(ratio.den as i128)) as i64)
|
||||
Self((((ratio.num as i128)<<32)/ratio.den as i128) as i64)
|
||||
}
|
||||
}
|
||||
#[derive(Debug)]
|
||||
@ -459,8 +450,26 @@ pub enum Planar64TryFromFloatError{
|
||||
Nan,
|
||||
Infinite,
|
||||
Subnormal,
|
||||
HighlyNegativeExponent,
|
||||
HighlyPositiveExponent,
|
||||
HighlyNegativeExponent(i16),
|
||||
HighlyPositiveExponent(i16),
|
||||
}
|
||||
#[inline]
|
||||
fn planar64_from_mes((m,e,s):(u64,i16,i8))->Result<Planar64,Planar64TryFromFloatError>{
|
||||
let e32=e+32;
|
||||
if e32<0&&(m>>-e32)==0{//shifting m will underflow to 0
|
||||
Ok(Planar64::ZERO)
|
||||
// println!("m{} e{} s{}",m,e,s);
|
||||
// println!("f={}",(m as f64)*(2.0f64.powf(e as f64))*(s as f64));
|
||||
// Err(Planar64TryFromFloatError::HighlyNegativeExponent(e))
|
||||
}else if (64-m.leading_zeros() as i16)+e32<64{//shifting m will not overflow
|
||||
if e32<0{
|
||||
Ok(Planar64((m as i64)*(s as i64)>>-e32))
|
||||
}else{
|
||||
Ok(Planar64((m as i64)*(s as i64)<<e32))
|
||||
}
|
||||
}else{//if shifting m will overflow (prev check failed)
|
||||
Err(Planar64TryFromFloatError::HighlyPositiveExponent(e))
|
||||
}
|
||||
}
|
||||
impl TryFrom<f32> for Planar64{
|
||||
type Error=Planar64TryFromFloatError;
|
||||
@ -470,15 +479,8 @@ impl TryFrom<f32> for Planar64{
|
||||
std::num::FpCategory::Nan=>Err(Self::Error::Nan),
|
||||
std::num::FpCategory::Infinite=>Err(Self::Error::Infinite),
|
||||
std::num::FpCategory::Zero=>Ok(Self::ZERO),
|
||||
std::num::FpCategory::Subnormal
|
||||
|std::num::FpCategory::Normal=>{
|
||||
let planar=value*PLANAR64_ONE_FLOAT32;
|
||||
if planar<(i64::MIN as f32)||(i64::MAX as f32)<planar{
|
||||
Err(Self::Error::HighlyPositiveExponent)
|
||||
}else{
|
||||
Ok(Planar64(unsafe{planar.to_int_unchecked()}))
|
||||
}
|
||||
}
|
||||
std::num::FpCategory::Subnormal=>Err(Self::Error::Subnormal),
|
||||
std::num::FpCategory::Normal=>planar64_from_mes(integer_decode_f32(value)),
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -490,15 +492,8 @@ impl TryFrom<f64> for Planar64{
|
||||
std::num::FpCategory::Nan=>Err(Self::Error::Nan),
|
||||
std::num::FpCategory::Infinite=>Err(Self::Error::Infinite),
|
||||
std::num::FpCategory::Zero=>Ok(Self::ZERO),
|
||||
std::num::FpCategory::Subnormal
|
||||
|std::num::FpCategory::Normal=>{
|
||||
let planar=value*PLANAR64_ONE_FLOAT64;
|
||||
if planar<(i64::MIN as f64)||(i64::MAX as f64)<planar{
|
||||
Err(Self::Error::HighlyPositiveExponent)
|
||||
}else{
|
||||
Ok(Planar64(unsafe{planar.to_int_unchecked()}))
|
||||
}
|
||||
}
|
||||
std::num::FpCategory::Subnormal=>Err(Self::Error::Subnormal),
|
||||
std::num::FpCategory::Normal=>planar64_from_mes(integer_decode_f64(value)),
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -523,12 +518,6 @@ impl std::ops::Add<Planar64> for Planar64{
|
||||
Planar64(self.0+rhs.0)
|
||||
}
|
||||
}
|
||||
impl std::ops::AddAssign<Planar64> for Planar64{
|
||||
#[inline]
|
||||
fn add_assign(&mut self,rhs:Self){
|
||||
*self=*self+rhs;
|
||||
}
|
||||
}
|
||||
impl std::ops::Sub<Planar64> for Planar64{
|
||||
type Output=Planar64;
|
||||
#[inline]
|
||||
@ -568,7 +557,7 @@ impl std::ops::Div<Planar64> for Planar64{
|
||||
type Output=Planar64;
|
||||
#[inline]
|
||||
fn div(self, rhs: Planar64) -> Self::Output {
|
||||
Planar64((((self.0 as i128)<<32)/(rhs.0 as i128)) as i64)
|
||||
Planar64((((self.0 as i128)<<32)/rhs.0 as i128) as i64)
|
||||
}
|
||||
}
|
||||
// impl PartialOrd<i64> for Planar64{
|
||||
@ -593,10 +582,6 @@ impl Planar64Vec3{
|
||||
pub const MIN:Self=Planar64Vec3(glam::I64Vec3::MIN);
|
||||
pub const MAX:Self=Planar64Vec3(glam::I64Vec3::MAX);
|
||||
#[inline]
|
||||
pub const fn new(x:Planar64,y:Planar64,z:Planar64)->Self{
|
||||
Self(glam::i64vec3(x.0,y.0,z.0))
|
||||
}
|
||||
#[inline]
|
||||
pub const fn int(x:i32,y:i32,z:i32)->Self{
|
||||
Self(glam::i64vec3((x as i64)<<32,(y as i64)<<32,(z as i64)<<32))
|
||||
}
|
||||
@ -649,26 +634,6 @@ impl Planar64Vec3{
|
||||
)>>32) as i64)
|
||||
}
|
||||
#[inline]
|
||||
pub fn dot128(&self,rhs:Self)->i128{
|
||||
(self.0.x as i128)*(rhs.0.x as i128)+
|
||||
(self.0.y as i128)*(rhs.0.y as i128)+
|
||||
(self.0.z as i128)*(rhs.0.z as i128)
|
||||
}
|
||||
#[inline]
|
||||
pub fn cross(&self,rhs:Self)->Planar64Vec3{
|
||||
Planar64Vec3(glam::i64vec3(
|
||||
(((self.0.y as i128)*(rhs.0.z as i128)-(self.0.z as i128)*(rhs.0.y as i128))>>32) as i64,
|
||||
(((self.0.z as i128)*(rhs.0.x as i128)-(self.0.x as i128)*(rhs.0.z as i128))>>32) as i64,
|
||||
(((self.0.x as i128)*(rhs.0.y as i128)-(self.0.y as i128)*(rhs.0.x as i128))>>32) as i64,
|
||||
))
|
||||
}
|
||||
#[inline]
|
||||
pub fn walkable(&self,slope:Planar64,up:Self)->bool{
|
||||
let y=self.dot(up);
|
||||
let x=self.cross(up).length();
|
||||
x*slope<y
|
||||
}
|
||||
#[inline]
|
||||
pub fn length(&self)->Planar64{
|
||||
let radicand=(self.0.x as i128)*(self.0.x as i128)+(self.0.y as i128)*(self.0.y as i128)+(self.0.z as i128)*(self.0.z as i128);
|
||||
Planar64(unsafe{(radicand as f64).sqrt().to_int_unchecked()})
|
||||
@ -803,17 +768,6 @@ impl std::ops::Mul<Time> for Planar64Vec3{
|
||||
))
|
||||
}
|
||||
}
|
||||
impl std::ops::Div<Planar64> for Planar64Vec3{
|
||||
type Output=Planar64Vec3;
|
||||
#[inline]
|
||||
fn div(self,rhs:Planar64)->Self::Output{
|
||||
Planar64Vec3(glam::i64vec3(
|
||||
(((self.0.x as i128)<<32)/(rhs.0 as i128)) as i64,
|
||||
(((self.0.y as i128)<<32)/(rhs.0 as i128)) as i64,
|
||||
(((self.0.z as i128)<<32)/(rhs.0 as i128)) as i64,
|
||||
))
|
||||
}
|
||||
}
|
||||
impl std::ops::Div<i64> for Planar64Vec3{
|
||||
type Output=Planar64Vec3;
|
||||
#[inline]
|
||||
@ -827,7 +781,7 @@ impl std::ops::Div<i64> for Planar64Vec3{
|
||||
}
|
||||
|
||||
///[-1.0,1.0] = [-2^32,2^32]
|
||||
#[derive(Clone,Copy,Hash,Eq,PartialEq)]
|
||||
#[derive(Clone,Copy)]
|
||||
pub struct Planar64Mat3{
|
||||
x_axis:Planar64Vec3,
|
||||
y_axis:Planar64Vec3,
|
||||
@ -843,6 +797,16 @@ impl Default for Planar64Mat3{
|
||||
}
|
||||
}
|
||||
}
|
||||
impl std::ops::Mul<Planar64Vec3> for Planar64Mat3{
|
||||
type Output=Planar64Vec3;
|
||||
#[inline]
|
||||
fn mul(self,rhs:Planar64Vec3) -> Self::Output {
|
||||
self.x_axis*rhs.x()
|
||||
+self.y_axis*rhs.y()
|
||||
+self.z_axis*rhs.z()
|
||||
}
|
||||
}
|
||||
|
||||
impl Planar64Mat3{
|
||||
#[inline]
|
||||
pub fn from_cols(x_axis:Planar64Vec3,y_axis:Planar64Vec3,z_axis:Planar64Vec3)->Self{
|
||||
@ -860,14 +824,6 @@ impl Planar64Mat3{
|
||||
}
|
||||
}
|
||||
#[inline]
|
||||
pub const fn from_diagonal(diagonal:Planar64Vec3)->Self{
|
||||
Self{
|
||||
x_axis:Planar64Vec3::raw(diagonal.0.x,0,0),
|
||||
y_axis:Planar64Vec3::raw(0,diagonal.0.y,0),
|
||||
z_axis:Planar64Vec3::raw(0,0,diagonal.0.z),
|
||||
}
|
||||
}
|
||||
#[inline]
|
||||
pub fn from_rotation_yx(yaw:Angle32,pitch:Angle32)->Self{
|
||||
let xtheta=yaw.0 as f64*ANGLE32_TO_FLOAT64_RADIANS;
|
||||
let (xs,xc)=xtheta.sin_cos();
|
||||
@ -897,49 +853,6 @@ impl Planar64Mat3{
|
||||
Planar64Vec3(glam::i64vec3(s,0,c)),
|
||||
)
|
||||
}
|
||||
#[inline]
|
||||
pub const fn inverse(&self)->Self{
|
||||
let det=(
|
||||
-self.x_axis.0.z as i128*self.y_axis.0.y as i128*self.z_axis.0.x as i128
|
||||
+self.x_axis.0.y as i128*self.y_axis.0.z as i128*self.z_axis.0.x as i128
|
||||
+self.x_axis.0.z as i128*self.y_axis.0.x as i128*self.z_axis.0.y as i128
|
||||
-self.x_axis.0.x as i128*self.y_axis.0.z as i128*self.z_axis.0.y as i128
|
||||
-self.x_axis.0.y as i128*self.y_axis.0.x as i128*self.z_axis.0.z as i128
|
||||
+self.x_axis.0.x as i128*self.y_axis.0.y as i128*self.z_axis.0.z as i128
|
||||
)>>32;
|
||||
Self{
|
||||
x_axis:Planar64Vec3::raw((((-(self.y_axis.0.z as i128*self.z_axis.0.y as i128)+self.y_axis.0.y as i128*self.z_axis.0.z as i128)<<32)/det) as i64,(((self.x_axis.0.z as i128*self.z_axis.0.y as i128-self.x_axis.0.y as i128*self.z_axis.0.z as i128)<<32)/det) as i64,(((-(self.x_axis.0.z as i128*self.y_axis.0.y as i128)+self.x_axis.0.y as i128*self.y_axis.0.z as i128)<<32)/det) as i64),
|
||||
y_axis:Planar64Vec3::raw((((self.y_axis.0.z as i128*self.z_axis.0.x as i128-self.y_axis.0.x as i128*self.z_axis.0.z as i128)<<32)/det) as i64,(((-(self.x_axis.0.z as i128*self.z_axis.0.x as i128)+self.x_axis.0.x as i128*self.z_axis.0.z as i128)<<32)/det) as i64,(((self.x_axis.0.z as i128*self.y_axis.0.x as i128-self.x_axis.0.x as i128*self.y_axis.0.z as i128)<<32)/det) as i64),
|
||||
z_axis:Planar64Vec3::raw((((-(self.y_axis.0.y as i128*self.z_axis.0.x as i128)+self.y_axis.0.x as i128*self.z_axis.0.y as i128)<<32)/det) as i64,(((self.x_axis.0.y as i128*self.z_axis.0.x as i128-self.x_axis.0.x as i128*self.z_axis.0.y as i128)<<32)/det) as i64,(((-(self.x_axis.0.y as i128*self.y_axis.0.x as i128)+self.x_axis.0.x as i128*self.y_axis.0.y as i128)<<32)/det) as i64),
|
||||
}
|
||||
}
|
||||
#[inline]
|
||||
pub const fn inverse_times_det(&self)->Self{
|
||||
Self{
|
||||
x_axis:Planar64Vec3::raw(((-(self.y_axis.0.z as i128*self.z_axis.0.y as i128)+self.y_axis.0.y as i128*self.z_axis.0.z as i128)>>32) as i64,((self.x_axis.0.z as i128*self.z_axis.0.y as i128-self.x_axis.0.y as i128*self.z_axis.0.z as i128)>>32) as i64,((-(self.x_axis.0.z as i128*self.y_axis.0.y as i128)+self.x_axis.0.y as i128*self.y_axis.0.z as i128)>>32) as i64),
|
||||
y_axis:Planar64Vec3::raw(((self.y_axis.0.z as i128*self.z_axis.0.x as i128-self.y_axis.0.x as i128*self.z_axis.0.z as i128)>>32) as i64,((-(self.x_axis.0.z as i128*self.z_axis.0.x as i128)+self.x_axis.0.x as i128*self.z_axis.0.z as i128)>>32) as i64,((self.x_axis.0.z as i128*self.y_axis.0.x as i128-self.x_axis.0.x as i128*self.y_axis.0.z as i128)>>32) as i64),
|
||||
z_axis:Planar64Vec3::raw(((-(self.y_axis.0.y as i128*self.z_axis.0.x as i128)+self.y_axis.0.x as i128*self.z_axis.0.y as i128)>>32) as i64,((self.x_axis.0.y as i128*self.z_axis.0.x as i128-self.x_axis.0.x as i128*self.z_axis.0.y as i128)>>32) as i64,((-(self.x_axis.0.y as i128*self.y_axis.0.x as i128)+self.x_axis.0.x as i128*self.y_axis.0.y as i128)>>32) as i64),
|
||||
}
|
||||
}
|
||||
#[inline]
|
||||
pub const fn transpose(&self)->Self{
|
||||
Self{
|
||||
x_axis:Planar64Vec3::raw(self.x_axis.0.x,self.y_axis.0.x,self.z_axis.0.x),
|
||||
y_axis:Planar64Vec3::raw(self.x_axis.0.y,self.y_axis.0.y,self.z_axis.0.y),
|
||||
z_axis:Planar64Vec3::raw(self.x_axis.0.z,self.y_axis.0.z,self.z_axis.0.z),
|
||||
}
|
||||
}
|
||||
#[inline]
|
||||
pub const fn determinant(&self)->Planar64{
|
||||
Planar64(((
|
||||
-self.x_axis.0.z as i128*self.y_axis.0.y as i128*self.z_axis.0.x as i128
|
||||
+self.x_axis.0.y as i128*self.y_axis.0.z as i128*self.z_axis.0.x as i128
|
||||
+self.x_axis.0.z as i128*self.y_axis.0.x as i128*self.z_axis.0.y as i128
|
||||
-self.x_axis.0.x as i128*self.y_axis.0.z as i128*self.z_axis.0.y as i128
|
||||
-self.x_axis.0.y as i128*self.y_axis.0.x as i128*self.z_axis.0.z as i128
|
||||
+self.x_axis.0.x as i128*self.y_axis.0.y as i128*self.z_axis.0.z as i128
|
||||
)>>64) as i64)
|
||||
}
|
||||
}
|
||||
impl Into<glam::Mat3> for Planar64Mat3{
|
||||
#[inline]
|
||||
@ -971,15 +884,6 @@ impl std::fmt::Display for Planar64Mat3{
|
||||
)
|
||||
}
|
||||
}
|
||||
impl std::ops::Mul<Planar64Vec3> for Planar64Mat3{
|
||||
type Output=Planar64Vec3;
|
||||
#[inline]
|
||||
fn mul(self,rhs:Planar64Vec3) -> Self::Output {
|
||||
self.x_axis*rhs.x()
|
||||
+self.y_axis*rhs.y()
|
||||
+self.z_axis*rhs.z()
|
||||
}
|
||||
}
|
||||
impl std::ops::Div<i64> for Planar64Mat3{
|
||||
type Output=Planar64Mat3;
|
||||
#[inline]
|
||||
@ -993,7 +897,7 @@ impl std::ops::Div<i64> for Planar64Mat3{
|
||||
}
|
||||
|
||||
///[-1.0,1.0] = [-2^32,2^32]
|
||||
#[derive(Clone,Copy,Default,Hash,Eq,PartialEq)]
|
||||
#[derive(Clone,Copy,Default)]
|
||||
pub struct Planar64Affine3{
|
||||
pub matrix3:Planar64Mat3,//includes scale above 1
|
||||
pub translation:Planar64Vec3,
|
||||
@ -1048,7 +952,7 @@ impl std::fmt::Display for Planar64Affine3{
|
||||
#[test]
|
||||
fn test_sqrt(){
|
||||
let r=Planar64::int(400);
|
||||
assert_eq!(1717986918400,r.get());
|
||||
println!("r{}",r.get());
|
||||
let s=r.sqrt();
|
||||
assert_eq!(85899345920,s.get());
|
||||
println!("s{}",s.get());
|
||||
}
|
@ -14,15 +14,12 @@ fn class_is_a(class: &str, superclass: &str) -> bool {
|
||||
return false
|
||||
}
|
||||
fn recursive_collect_superclass(objects: &mut std::vec::Vec<rbx_dom_weak::types::Ref>,dom: &rbx_dom_weak::WeakDom, instance: &rbx_dom_weak::Instance, superclass: &str){
|
||||
let mut stack=vec![instance];
|
||||
while let Some(item)=stack.pop(){
|
||||
for &referent in item.children(){
|
||||
if let Some(c)=dom.get_by_ref(referent){
|
||||
if class_is_a(c.class.as_str(),superclass){
|
||||
objects.push(c.referent());//copy ref
|
||||
}
|
||||
stack.push(c);
|
||||
for &referent in instance.children() {
|
||||
if let Some(c) = dom.get_by_ref(referent) {
|
||||
if class_is_a(c.class.as_str(), superclass) {
|
||||
objects.push(c.referent());//copy ref
|
||||
}
|
||||
recursive_collect_superclass(objects,dom,c,superclass);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -48,19 +45,13 @@ fn get_attributes(name:&str,can_collide:bool,velocity:Planar64Vec3,force_interse
|
||||
"Water"=>{
|
||||
force_can_collide=false;
|
||||
//TODO: read stupid CustomPhysicalProperties
|
||||
intersecting.water=Some(crate::model::IntersectingWater{density:Planar64::ONE,viscosity:Planar64::ONE/10,velocity});
|
||||
intersecting.water=Some(crate::model::IntersectingWater{density:Planar64::ONE,viscosity:Planar64::ONE/10,current:velocity});
|
||||
},
|
||||
"Accelerator"=>{
|
||||
//although the new game supports collidable accelerators, this is a roblox compatability map loader
|
||||
force_can_collide=false;
|
||||
general.accelerator=Some(crate::model::GameMechanicAccelerator{acceleration:velocity});
|
||||
},
|
||||
// "UnorderedCheckpoint"=>general.teleport_behaviour=Some(crate::model::TeleportBehaviour::StageElement(crate::model::GameMechanicStageElement{
|
||||
// mode_id:0,
|
||||
// stage_id:0,
|
||||
// force:false,
|
||||
// behaviour:crate::model::StageElementBehaviour::Unordered
|
||||
// })),
|
||||
"SetVelocity"=>general.trajectory=Some(crate::model::GameMechanicSetTrajectory::Velocity(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})},
|
||||
@ -120,13 +111,6 @@ fn get_attributes(name:&str,can_collide:bool,velocity:Planar64Vec3,force_interse
|
||||
_=>panic!("regex3[1] messed up bad"),
|
||||
}
|
||||
}
|
||||
// else if let Some(captures)=lazy_regex::regex!(r"^(OrderedCheckpoint)(\d+)$")
|
||||
// .captures(other){
|
||||
// match &captures[1]{
|
||||
// "OrderedCheckpoint"=>general.checkpoint=Some(crate::model::GameMechanicCheckpoint::Ordered{mode_id:0,checkpoint_id:captures[2].parse::<u32>().unwrap()}),
|
||||
// _=>panic!("regex3[1] messed up bad"),
|
||||
// }
|
||||
// }
|
||||
}
|
||||
}
|
||||
//need some way to skip this
|
||||
@ -226,9 +210,9 @@ type RobloxWedgeDescription=[Option<RobloxFaceTextureDescription>;5];
|
||||
type RobloxCornerWedgeDescription=[Option<RobloxFaceTextureDescription>;5];
|
||||
#[derive(Clone,Eq,Hash,PartialEq)]
|
||||
enum RobloxBasePartDescription{
|
||||
Sphere(RobloxPartDescription),
|
||||
Sphere,
|
||||
Part(RobloxPartDescription),
|
||||
Cylinder(RobloxPartDescription),
|
||||
Cylinder,
|
||||
Wedge(RobloxWedgeDescription),
|
||||
CornerWedge(RobloxCornerWedgeDescription),
|
||||
}
|
||||
@ -265,18 +249,6 @@ pub fn generate_indexed_models(dom:rbx_dom_weak::WeakDom) -> crate::model::Index
|
||||
{
|
||||
let model_transform=planar64_affine3_from_roblox(cf,size);
|
||||
|
||||
if model_transform.matrix3.determinant()==Planar64::ZERO{
|
||||
let mut parent_ref=object.parent();
|
||||
let mut full_path=object.name.clone();
|
||||
while let Some(parent)=dom.get_by_ref(parent_ref){
|
||||
full_path=format!("{}.{}",parent.name,full_path);
|
||||
parent_ref=parent.parent();
|
||||
}
|
||||
println!("Zero determinant CFrame at location {}",full_path);
|
||||
println!("matrix3:{}",model_transform.matrix3);
|
||||
continue;
|
||||
}
|
||||
|
||||
//push TempIndexedAttributes
|
||||
let mut force_intersecting=false;
|
||||
let mut temp_indexing_attributes=Vec::new();
|
||||
@ -285,12 +257,14 @@ pub fn generate_indexed_models(dom:rbx_dom_weak::WeakDom) -> crate::model::Index
|
||||
spawn_point=model_transform.transform_point3(Planar64Vec3::ZERO)+Planar64Vec3::Y*5/2;
|
||||
Some(crate::model::TempIndexedAttributes::Start(crate::model::TempAttrStart{mode_id:0}))
|
||||
},
|
||||
"UnorderedCheckpoint"=>Some(crate::model::TempIndexedAttributes::UnorderedCheckpoint(crate::model::TempAttrUnorderedCheckpoint{mode_id:0})),
|
||||
other=>{
|
||||
let regman=lazy_regex::regex!(r"^(BonusStart|Spawn|ForceSpawn|WormholeOut)(\d+)$");
|
||||
let regman=lazy_regex::regex!(r"^(BonusStart|Spawn|ForceSpawn|OrderedCheckpoint|WormholeOut)(\d+)$");
|
||||
if let Some(captures) = regman.captures(other) {
|
||||
match &captures[1]{
|
||||
"BonusStart"=>Some(crate::model::TempIndexedAttributes::Start(crate::model::TempAttrStart{mode_id:captures[2].parse::<u32>().unwrap()})),
|
||||
"Spawn"|"ForceSpawn"=>Some(crate::model::TempIndexedAttributes::Spawn(crate::model::TempAttrSpawn{mode_id:0,stage_id:captures[2].parse::<u32>().unwrap()})),
|
||||
"OrderedCheckpoint"=>Some(crate::model::TempIndexedAttributes::OrderedCheckpoint(crate::model::TempAttrOrderedCheckpoint{mode_id:0,checkpoint_id:captures[2].parse::<u32>().unwrap()})),
|
||||
"WormholeOut"=>Some(crate::model::TempIndexedAttributes::Wormhole(crate::model::TempAttrWormhole{wormhole_id:captures[2].parse::<u32>().unwrap()})),
|
||||
_=>None,
|
||||
}
|
||||
@ -319,7 +293,6 @@ pub fn generate_indexed_models(dom:rbx_dom_weak::WeakDom) -> crate::model::Index
|
||||
panic!("Part has no Shape!");
|
||||
}
|
||||
},
|
||||
"TrussPart"=>primitives::Primitives::Cube,
|
||||
"WedgePart"=>primitives::Primitives::Wedge,
|
||||
"CornerWedgePart"=>primitives::Primitives::CornerWedge,
|
||||
_=>{
|
||||
@ -414,9 +387,9 @@ pub fn generate_indexed_models(dom:rbx_dom_weak::WeakDom) -> crate::model::Index
|
||||
f5,//Cube::Front
|
||||
]=part_texture_description;
|
||||
let basepart_texture_description=match shape{
|
||||
primitives::Primitives::Sphere=>RobloxBasePartDescription::Sphere([f0,f1,f2,f3,f4,f5]),
|
||||
primitives::Primitives::Sphere=>RobloxBasePartDescription::Sphere,
|
||||
primitives::Primitives::Cube=>RobloxBasePartDescription::Part([f0,f1,f2,f3,f4,f5]),
|
||||
primitives::Primitives::Cylinder=>RobloxBasePartDescription::Cylinder([f0,f1,f2,f3,f4,f5]),
|
||||
primitives::Primitives::Cylinder=>RobloxBasePartDescription::Cylinder,
|
||||
//use front face texture first and use top face texture as a fallback
|
||||
primitives::Primitives::Wedge=>RobloxBasePartDescription::Wedge([
|
||||
f0,//Cube::Right->Wedge::Right
|
||||
@ -442,10 +415,9 @@ pub fn generate_indexed_models(dom:rbx_dom_weak::WeakDom) -> crate::model::Index
|
||||
let model_id=indexed_models.len();
|
||||
model_id_from_description.insert(basepart_texture_description.clone(),model_id);//borrow checker going crazy
|
||||
indexed_models.push(match basepart_texture_description{
|
||||
RobloxBasePartDescription::Sphere(part_texture_description)
|
||||
|RobloxBasePartDescription::Cylinder(part_texture_description)
|
||||
|RobloxBasePartDescription::Part(part_texture_description)=>{
|
||||
let mut cube_face_description=primitives::CubeFaceDescription::default();
|
||||
RobloxBasePartDescription::Sphere=>primitives::unit_sphere(),
|
||||
RobloxBasePartDescription::Part(part_texture_description)=>{
|
||||
let mut cube_face_description=primitives::CubeFaceDescription::new();
|
||||
for (face_id,roblox_face_description) in part_texture_description.iter().enumerate(){
|
||||
cube_face_description.insert(
|
||||
match face_id{
|
||||
@ -464,8 +436,9 @@ pub fn generate_indexed_models(dom:rbx_dom_weak::WeakDom) -> crate::model::Index
|
||||
}
|
||||
primitives::generate_partial_unit_cube(cube_face_description)
|
||||
},
|
||||
RobloxBasePartDescription::Cylinder=>primitives::unit_cylinder(),
|
||||
RobloxBasePartDescription::Wedge(wedge_texture_description)=>{
|
||||
let mut wedge_face_description=primitives::WedgeFaceDescription::default();
|
||||
let mut wedge_face_description=primitives::WedgeFaceDescription::new();
|
||||
for (face_id,roblox_face_description) in wedge_texture_description.iter().enumerate(){
|
||||
wedge_face_description.insert(
|
||||
match face_id{
|
||||
@ -484,7 +457,7 @@ pub fn generate_indexed_models(dom:rbx_dom_weak::WeakDom) -> crate::model::Index
|
||||
primitives::generate_partial_unit_wedge(wedge_face_description)
|
||||
},
|
||||
RobloxBasePartDescription::CornerWedge(cornerwedge_texture_description)=>{
|
||||
let mut cornerwedge_face_description=primitives::CornerWedgeFaceDescription::default();
|
||||
let mut cornerwedge_face_description=primitives::CornerWedgeFaceDescription::new();
|
||||
for (face_id,roblox_face_description) in cornerwedge_texture_description.iter().enumerate(){
|
||||
cornerwedge_face_description.insert(
|
||||
match face_id{
|
||||
|
22
src/main.rs
22
src/main.rs
@ -7,15 +7,12 @@ mod worker;
|
||||
mod zeroes;
|
||||
mod integer;
|
||||
mod physics;
|
||||
mod sniffer;
|
||||
mod graphics;
|
||||
mod settings;
|
||||
mod primitives;
|
||||
mod instruction;
|
||||
mod load_roblox;
|
||||
mod face_crawler;
|
||||
mod compat_worker;
|
||||
mod model_physics;
|
||||
mod model_graphics;
|
||||
mod physics_worker;
|
||||
mod graphics_worker;
|
||||
@ -67,44 +64,49 @@ fn load_file(path: std::path::PathBuf)->Option<model::IndexedModelInstances>{
|
||||
|
||||
pub fn default_models()->model::IndexedModelInstances{
|
||||
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));
|
||||
indexed_models.push(primitives::unit_sphere());
|
||||
indexed_models.push(primitives::unit_cylinder());
|
||||
indexed_models.push(primitives::unit_cube());
|
||||
println!("models.len = {:?}", indexed_models.len());
|
||||
//quad monkeys
|
||||
indexed_models[0].instances.push(model::ModelInstance{
|
||||
transform:integer::Planar64Affine3::try_from(glam::Affine3A::from_translation(glam::vec3(10.,0.,-10.))).unwrap(),
|
||||
..Default::default()
|
||||
});
|
||||
//quad monkeys
|
||||
indexed_models[1].instances.push(model::ModelInstance{
|
||||
transform:integer::Planar64Affine3::try_from(glam::Affine3A::from_translation(glam::vec3(10.,5.,10.))).unwrap(),
|
||||
..Default::default()
|
||||
});
|
||||
indexed_models[0].instances.push(model::ModelInstance{
|
||||
indexed_models[1].instances.push(model::ModelInstance{
|
||||
transform:integer::Planar64Affine3::try_from(glam::Affine3A::from_translation(glam::vec3(20.,5.,10.))).unwrap(),
|
||||
color:glam::vec4(1.0,0.0,0.0,1.0),
|
||||
..Default::default()
|
||||
});
|
||||
indexed_models[0].instances.push(model::ModelInstance{
|
||||
indexed_models[1].instances.push(model::ModelInstance{
|
||||
transform:integer::Planar64Affine3::try_from(glam::Affine3A::from_translation(glam::vec3(10.,5.,20.))).unwrap(),
|
||||
color:glam::vec4(0.0,1.0,0.0,1.0),
|
||||
..Default::default()
|
||||
});
|
||||
indexed_models[0].instances.push(model::ModelInstance{
|
||||
indexed_models[1].instances.push(model::ModelInstance{
|
||||
transform:integer::Planar64Affine3::try_from(glam::Affine3A::from_translation(glam::vec3(20.,5.,20.))).unwrap(),
|
||||
color:glam::vec4(0.0,0.0,1.0,1.0),
|
||||
..Default::default()
|
||||
});
|
||||
//decorative monkey
|
||||
indexed_models[0].instances.push(model::ModelInstance{
|
||||
indexed_models[1].instances.push(model::ModelInstance{
|
||||
transform:integer::Planar64Affine3::try_from(glam::Affine3A::from_translation(glam::vec3(15.,10.,15.))).unwrap(),
|
||||
color:glam::vec4(0.5,0.5,0.5,0.5),
|
||||
attributes:model::CollisionAttributes::Decoration,
|
||||
..Default::default()
|
||||
});
|
||||
//teapot
|
||||
indexed_models[1].instances.push(model::ModelInstance{
|
||||
indexed_models[2].instances.push(model::ModelInstance{
|
||||
transform:integer::Planar64Affine3::try_from(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.))).unwrap(),
|
||||
..Default::default()
|
||||
});
|
||||
//ground
|
||||
indexed_models[2].instances.push(model::ModelInstance{
|
||||
indexed_models[3].instances.push(model::ModelInstance{
|
||||
transform:integer::Planar64Affine3::try_from(glam::Affine3A::from_translation(glam::vec3(0.,0.,0.))*glam::Affine3A::from_scale(glam::vec3(160.0, 1.0, 160.0))).unwrap(),
|
||||
..Default::default()
|
||||
});
|
||||
|
121
src/model.rs
121
src/model.rs
@ -50,10 +50,10 @@ pub struct IndexedModelInstances{
|
||||
}
|
||||
//stage description referencing flattened ids is spooky, but the map loading is meant to be deterministic.
|
||||
pub struct ModeDescription{
|
||||
//TODO: put "default" style modifiers in mode
|
||||
//pub style:StyleModifiers,
|
||||
pub start:usize,//start=model_id
|
||||
pub spawns:Vec<usize>,//spawns[spawn_id]=model_id
|
||||
pub ordered_checkpoints:Vec<usize>,//ordered_checkpoints[checkpoint_id]=model_id
|
||||
pub unordered_checkpoints:Vec<usize>,//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>,
|
||||
}
|
||||
@ -61,6 +61,9 @@ impl ModeDescription{
|
||||
pub fn get_spawn_model_id(&self,stage_id:u32)->Option<&usize>{
|
||||
self.spawns.get(*self.spawn_from_stage_id.get(&stage_id)?)
|
||||
}
|
||||
pub fn get_ordered_checkpoint_model_id(&self,checkpoint_id:u32)->Option<&usize>{
|
||||
self.ordered_checkpoints.get(*self.ordered_checkpoint_from_checkpoint_id.get(&checkpoint_id)?)
|
||||
}
|
||||
}
|
||||
//I don't want this code to exist!
|
||||
#[derive(Clone)]
|
||||
@ -73,88 +76,84 @@ pub struct TempAttrSpawn{
|
||||
pub stage_id:u32,
|
||||
}
|
||||
#[derive(Clone)]
|
||||
pub struct TempAttrOrderedCheckpoint{
|
||||
pub mode_id:u32,
|
||||
pub checkpoint_id:u32,
|
||||
}
|
||||
#[derive(Clone)]
|
||||
pub struct TempAttrUnorderedCheckpoint{
|
||||
pub mode_id:u32,
|
||||
}
|
||||
#[derive(Clone)]
|
||||
pub struct TempAttrWormhole{
|
||||
pub wormhole_id:u32,
|
||||
}
|
||||
pub enum TempIndexedAttributes{
|
||||
Start(TempAttrStart),
|
||||
Spawn(TempAttrSpawn),
|
||||
OrderedCheckpoint(TempAttrOrderedCheckpoint),
|
||||
UnorderedCheckpoint(TempAttrUnorderedCheckpoint),
|
||||
Wormhole(TempAttrWormhole),
|
||||
}
|
||||
|
||||
//you have this effect while in contact
|
||||
#[derive(Clone,Hash,Eq,PartialEq)]
|
||||
#[derive(Clone)]
|
||||
pub struct ContactingLadder{
|
||||
pub sticky:bool
|
||||
}
|
||||
#[derive(Clone,Hash,Eq,PartialEq)]
|
||||
#[derive(Clone)]
|
||||
pub enum ContactingBehaviour{
|
||||
Surf,
|
||||
Cling,//usable as a zipline, or other weird and wonderful things
|
||||
Ladder(ContactingLadder),
|
||||
Elastic(u32),//[1/2^32,1] 0=None (elasticity+1)/2^32
|
||||
Surf,
|
||||
Ladder(ContactingLadder),
|
||||
Elastic(u32),//[1/2^32,1] 0=None (elasticity+1)/2^32
|
||||
}
|
||||
//you have this effect while intersecting
|
||||
#[derive(Clone,Hash,Eq,PartialEq)]
|
||||
#[derive(Clone)]
|
||||
pub struct IntersectingWater{
|
||||
pub viscosity:Planar64,
|
||||
pub density:Planar64,
|
||||
pub velocity:Planar64Vec3,
|
||||
pub current:Planar64Vec3,
|
||||
}
|
||||
//All models can be given these attributes
|
||||
#[derive(Clone,Hash,Eq,PartialEq)]
|
||||
#[derive(Clone)]
|
||||
pub struct GameMechanicAccelerator{
|
||||
pub acceleration:Planar64Vec3
|
||||
}
|
||||
#[derive(Clone,Hash,Eq,PartialEq)]
|
||||
#[derive(Clone)]
|
||||
pub enum GameMechanicBooster{
|
||||
Affine(Planar64Affine3),//capable of SetVelocity,DotVelocity,normal booster,bouncy part,redirect velocity, and much more
|
||||
Velocity(Planar64Vec3),//straight up boost velocity adds to your current velocity
|
||||
Energy{direction:Planar64Vec3,energy:Planar64},//increase energy in direction
|
||||
}
|
||||
#[derive(Clone,Hash,Eq,PartialEq)]
|
||||
#[derive(Clone)]
|
||||
pub enum TrajectoryChoice{
|
||||
HighArcLongDuration,//underhand lob at target: less horizontal speed and more air time
|
||||
LowArcShortDuration,//overhand throw at target: more horizontal speed and less air time
|
||||
}
|
||||
#[derive(Clone,Hash,Eq,PartialEq)]
|
||||
#[derive(Clone)]
|
||||
pub enum GameMechanicSetTrajectory{
|
||||
//Speed-type SetTrajectory
|
||||
AirTime(Time),//air time (relative to gravity direction) is invariant across mass and gravity changes
|
||||
Height(Planar64),//boost height (relative to gravity direction) is invariant across mass and gravity changes
|
||||
DotVelocity{direction:Planar64Vec3,dot:Planar64},//set your velocity in a specific direction without touching other directions
|
||||
//Velocity-type SetTrajectory
|
||||
TargetPointTime{//launch on a trajectory that will land at a target point in a set amount of time
|
||||
target_point:Planar64Vec3,
|
||||
time:Time,//short time = fast and direct, long time = launch high in the air, negative time = wrong way
|
||||
},
|
||||
TargetPointSpeed{//launch at a fixed speed and land at a target point
|
||||
TrajectoryTargetPoint{//launch at a fixed speed and land at a target point
|
||||
target_point:Planar64Vec3,
|
||||
speed:Planar64,//if speed is too low this will fail to reach the target. The closest-passing trajectory will be chosen instead
|
||||
trajectory_choice:TrajectoryChoice,
|
||||
},
|
||||
Velocity(Planar64Vec3),//SetVelocity
|
||||
DotVelocity{direction:Planar64Vec3,dot:Planar64},//set your velocity in a specific direction without touching other directions
|
||||
}
|
||||
impl GameMechanicSetTrajectory{
|
||||
fn is_velocity(&self)->bool{
|
||||
match self{
|
||||
GameMechanicSetTrajectory::AirTime(_)
|
||||
|GameMechanicSetTrajectory::Height(_)
|
||||
|GameMechanicSetTrajectory::DotVelocity{direction:_,dot:_}=>false,
|
||||
GameMechanicSetTrajectory::TargetPointTime{target_point:_,time:_}
|
||||
|GameMechanicSetTrajectory::TargetPointSpeed{target_point:_,speed:_,trajectory_choice:_}
|
||||
|GameMechanicSetTrajectory::Velocity(_)=>true,
|
||||
}
|
||||
}
|
||||
}
|
||||
#[derive(Clone,Hash,Eq,PartialEq)]
|
||||
#[derive(Clone)]
|
||||
pub enum ZoneBehaviour{
|
||||
//Start is indexed
|
||||
//Checkpoints are indexed
|
||||
Finish,
|
||||
Anitcheat,
|
||||
}
|
||||
#[derive(Clone,Hash,Eq,PartialEq)]
|
||||
#[derive(Clone)]
|
||||
pub struct GameMechanicZone{
|
||||
pub mode_id:u32,
|
||||
pub behaviour:ZoneBehaviour,
|
||||
@ -165,36 +164,24 @@ pub struct GameMechanicZone{
|
||||
// InRange(Planar64,Planar64),
|
||||
// OutsideRange(Planar64,Planar64),
|
||||
// }
|
||||
#[derive(Clone,Hash,Eq,PartialEq)]
|
||||
#[derive(Clone)]
|
||||
pub enum StageElementBehaviour{
|
||||
//Spawn,//The behaviour of stepping on a spawn setting the spawnid
|
||||
SpawnAt,//must be standing on top to get effect. except cancollide false
|
||||
Trigger,
|
||||
Teleport,
|
||||
Platform,
|
||||
//Checkpoint acts like a trigger if you haven't hit all the checkpoints yet.
|
||||
//Note that all stage elements act like this for the next stage.
|
||||
Checkpoint,
|
||||
//OrderedCheckpoint. You must pass through all of these in ascending order.
|
||||
//If you hit them out of order it acts like a trigger.
|
||||
//Do not support backtracking at all for now.
|
||||
Ordered{
|
||||
checkpoint_id:u32,
|
||||
},
|
||||
//UnorderedCheckpoint. You must pass through all of these in any order.
|
||||
Unordered,
|
||||
//If you get reset by a jump limit
|
||||
JumpLimit(u32),
|
||||
//Speedtrap(TrapCondition),//Acts as a trigger with a speed condition
|
||||
//Spawn,//The behaviour of stepping on a spawn setting the spawnid
|
||||
SpawnAt,
|
||||
Trigger,
|
||||
Teleport,
|
||||
Platform,
|
||||
JumpLimit(u32),
|
||||
//Speedtrap(TrapCondition),//Acts as a trigger with a speed condition
|
||||
}
|
||||
#[derive(Clone,Hash,Eq,PartialEq)]
|
||||
#[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,Hash,Eq,PartialEq)]
|
||||
#[derive(Clone)]
|
||||
pub struct GameMechanicWormhole{
|
||||
//destination does not need to be another wormhole
|
||||
//this defines a one way portal to a destination model transform
|
||||
@ -202,13 +189,13 @@ pub struct GameMechanicWormhole{
|
||||
pub destination_model_id:u32,
|
||||
//(position,angles)*=origin.transform.inverse()*destination.transform
|
||||
}
|
||||
#[derive(Clone,Hash,Eq,PartialEq)]
|
||||
#[derive(Clone)]
|
||||
pub enum TeleportBehaviour{
|
||||
StageElement(GameMechanicStageElement),
|
||||
Wormhole(GameMechanicWormhole),
|
||||
}
|
||||
//attributes listed in order of handling
|
||||
#[derive(Default,Clone,Hash,Eq,PartialEq)]
|
||||
#[derive(Default,Clone)]
|
||||
pub struct GameMechanicAttributes{
|
||||
pub zone:Option<GameMechanicZone>,
|
||||
pub booster:Option<GameMechanicBooster>,
|
||||
@ -218,28 +205,14 @@ pub struct GameMechanicAttributes{
|
||||
}
|
||||
impl GameMechanicAttributes{
|
||||
pub fn any(&self)->bool{
|
||||
self.zone.is_some()
|
||||
||self.booster.is_some()
|
||||
self.booster.is_some()
|
||||
||self.trajectory.is_some()
|
||||
||self.zone.is_some()
|
||||
||self.teleport_behaviour.is_some()
|
||||
||self.accelerator.is_some()
|
||||
}
|
||||
pub fn is_wrcp(&self,current_mode_id:u32)->bool{
|
||||
self.trajectory.as_ref().map_or(false,|t|t.is_velocity())
|
||||
&&match &self.teleport_behaviour{
|
||||
Some(TeleportBehaviour::StageElement(
|
||||
GameMechanicStageElement{
|
||||
mode_id,
|
||||
stage_id:_,
|
||||
force:true,
|
||||
behaviour:StageElementBehaviour::Trigger|StageElementBehaviour::Teleport
|
||||
}
|
||||
))=>current_mode_id==*mode_id,
|
||||
_=>false,
|
||||
}
|
||||
}
|
||||
}
|
||||
#[derive(Default,Clone,Hash,Eq,PartialEq)]
|
||||
#[derive(Default,Clone)]
|
||||
pub struct ContactingAttributes{
|
||||
//friction?
|
||||
pub contact_behaviour:Option<ContactingBehaviour>,
|
||||
@ -249,7 +222,7 @@ impl ContactingAttributes{
|
||||
self.contact_behaviour.is_some()
|
||||
}
|
||||
}
|
||||
#[derive(Default,Clone,Hash,Eq,PartialEq)]
|
||||
#[derive(Default,Clone)]
|
||||
pub struct IntersectingAttributes{
|
||||
pub water:Option<IntersectingWater>,
|
||||
}
|
||||
|
@ -11,7 +11,7 @@ pub struct GraphicsVertex {
|
||||
pub struct IndexedGroupFixedTexture{
|
||||
pub polys:Vec<IndexedPolygon>,
|
||||
}
|
||||
pub struct IndexedGraphicsModelSingleTexture{
|
||||
pub struct IndexedModelGraphicsSingleTexture{
|
||||
pub unique_pos:Vec<[f32; 3]>,
|
||||
pub unique_tex:Vec<[f32; 2]>,
|
||||
pub unique_normal:Vec<[f32; 3]>,
|
||||
@ -19,41 +19,37 @@ pub struct IndexedGraphicsModelSingleTexture{
|
||||
pub unique_vertices:Vec<IndexedVertex>,
|
||||
pub texture:Option<u32>,//RenderPattern? material/texture/shader/flat color
|
||||
pub groups: Vec<IndexedGroupFixedTexture>,
|
||||
pub instances:Vec<GraphicsModelInstance>,
|
||||
pub instances:Vec<ModelGraphicsInstance>,
|
||||
}
|
||||
pub enum Entities{
|
||||
U32(Vec<Vec<u32>>),
|
||||
U16(Vec<Vec<u16>>),
|
||||
}
|
||||
pub struct GraphicsModelSingleTexture{
|
||||
pub instances:Vec<GraphicsModelInstance>,
|
||||
pub vertices:Vec<GraphicsVertex>,
|
||||
pub entities:Entities,
|
||||
pub texture:Option<u32>,
|
||||
pub struct ModelGraphicsSingleTexture{
|
||||
pub instances: Vec<ModelGraphicsInstance>,
|
||||
pub vertices: Vec<GraphicsVertex>,
|
||||
pub entities: Vec<Vec<u16>>,
|
||||
pub texture: Option<u32>,
|
||||
}
|
||||
#[derive(Clone,PartialEq)]
|
||||
pub struct GraphicsModelColor4(glam::Vec4);
|
||||
impl GraphicsModelColor4{
|
||||
pub struct ModelGraphicsColor4(glam::Vec4);
|
||||
impl ModelGraphicsColor4{
|
||||
pub const fn get(&self)->glam::Vec4{
|
||||
self.0
|
||||
}
|
||||
}
|
||||
impl From<glam::Vec4> for GraphicsModelColor4{
|
||||
impl From<glam::Vec4> for ModelGraphicsColor4{
|
||||
fn from(value:glam::Vec4)->Self{
|
||||
Self(value)
|
||||
}
|
||||
}
|
||||
impl std::hash::Hash for GraphicsModelColor4{
|
||||
impl std::hash::Hash for ModelGraphicsColor4{
|
||||
fn hash<H: std::hash::Hasher>(&self,state:&mut H) {
|
||||
for &f in self.0.as_ref(){
|
||||
bytemuck::cast::<f32,u32>(f).hash(state);
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Eq for GraphicsModelColor4{}
|
||||
impl Eq for ModelGraphicsColor4{}
|
||||
#[derive(Clone)]
|
||||
pub struct GraphicsModelInstance{
|
||||
pub struct ModelGraphicsInstance{
|
||||
pub transform:glam::Mat4,
|
||||
pub normal_transform:glam::Mat3,
|
||||
pub color:GraphicsModelColor4,
|
||||
}
|
||||
pub color:ModelGraphicsColor4,
|
||||
}
|
@ -1,744 +1 @@
|
||||
use crate::integer::{Planar64,Planar64Vec3};
|
||||
use std::borrow::{Borrow,Cow};
|
||||
|
||||
#[derive(Debug,Clone,Copy,Hash,Eq,PartialEq)]
|
||||
pub struct VertId(usize);
|
||||
#[derive(Debug,Clone,Copy,Hash,Eq,PartialEq)]
|
||||
pub struct EdgeId(usize);
|
||||
pub trait UndirectedEdge{
|
||||
type DirectedEdge:Copy+DirectedEdge;
|
||||
fn as_directed(&self,parity:bool)->Self::DirectedEdge;
|
||||
}
|
||||
impl UndirectedEdge for EdgeId{
|
||||
type DirectedEdge=DirectedEdgeId;
|
||||
fn as_directed(&self,parity:bool)->DirectedEdgeId{
|
||||
DirectedEdgeId(self.0|((parity as usize)<<(usize::BITS-1)))
|
||||
}
|
||||
}
|
||||
pub trait DirectedEdge{
|
||||
type UndirectedEdge:Copy+UndirectedEdge;
|
||||
fn as_undirected(&self)->Self::UndirectedEdge;
|
||||
fn parity(&self)->bool;
|
||||
//this is stupid but may work fine
|
||||
fn reverse(&self)-><<Self as DirectedEdge>::UndirectedEdge as UndirectedEdge>::DirectedEdge{
|
||||
self.as_undirected().as_directed(!self.parity())
|
||||
}
|
||||
}
|
||||
/// DirectedEdgeId refers to an EdgeId when undirected.
|
||||
#[derive(Debug,Clone,Copy,Hash,Eq,PartialEq)]
|
||||
pub struct DirectedEdgeId(usize);
|
||||
impl DirectedEdge for DirectedEdgeId{
|
||||
type UndirectedEdge=EdgeId;
|
||||
fn as_undirected(&self)->EdgeId{
|
||||
EdgeId(self.0&!(1<<(usize::BITS-1)))
|
||||
}
|
||||
fn parity(&self)->bool{
|
||||
self.0&(1<<(usize::BITS-1))!=0
|
||||
}
|
||||
}
|
||||
#[derive(Debug,Clone,Copy,Hash,Eq,PartialEq)]
|
||||
pub struct FaceId(usize);
|
||||
|
||||
//Vertex <-> Edge <-> Face -> Collide
|
||||
pub enum FEV<F,E:DirectedEdge,V>{
|
||||
Face(F),
|
||||
Edge(E::UndirectedEdge),
|
||||
Vert(V),
|
||||
}
|
||||
|
||||
//use Unit32 #[repr(C)] for map files
|
||||
struct Face{
|
||||
normal:Planar64Vec3,
|
||||
dot:Planar64,
|
||||
}
|
||||
struct Vert(Planar64Vec3);
|
||||
pub trait MeshQuery<FACE:Clone,EDGE:Clone+DirectedEdge,VERT:Clone>{
|
||||
fn edge_n(&self,edge_id:EDGE::UndirectedEdge)->Planar64Vec3{
|
||||
let verts=self.edge_verts(edge_id);
|
||||
self.vert(verts[1].clone())-self.vert(verts[0].clone())
|
||||
}
|
||||
fn directed_edge_n(&self,directed_edge_id:EDGE)->Planar64Vec3{
|
||||
let verts=self.edge_verts(directed_edge_id.as_undirected());
|
||||
(self.vert(verts[1].clone())-self.vert(verts[0].clone()))*((directed_edge_id.parity() as i64)*2-1)
|
||||
}
|
||||
fn vert(&self,vert_id:VERT)->Planar64Vec3;
|
||||
fn face_nd(&self,face_id:FACE)->(Planar64Vec3,Planar64);
|
||||
fn face_edges(&self,face_id:FACE)->Cow<Vec<EDGE>>;
|
||||
fn edge_faces(&self,edge_id:EDGE::UndirectedEdge)->Cow<[FACE;2]>;
|
||||
fn edge_verts(&self,edge_id:EDGE::UndirectedEdge)->Cow<[VERT;2]>;
|
||||
fn vert_edges(&self,vert_id:VERT)->Cow<Vec<EDGE>>;
|
||||
fn vert_faces(&self,vert_id:VERT)->Cow<Vec<FACE>>;
|
||||
}
|
||||
struct FaceRefs{
|
||||
edges:Vec<DirectedEdgeId>,
|
||||
//verts:Vec<VertId>,
|
||||
}
|
||||
struct EdgeRefs{
|
||||
faces:[FaceId;2],//left, right
|
||||
verts:[VertId;2],//bottom, top
|
||||
}
|
||||
struct VertRefs{
|
||||
faces:Vec<FaceId>,
|
||||
edges:Vec<DirectedEdgeId>,
|
||||
}
|
||||
pub struct PhysicsMesh{
|
||||
faces:Vec<Face>,
|
||||
verts:Vec<Vert>,
|
||||
face_topology:Vec<FaceRefs>,
|
||||
edge_topology:Vec<EdgeRefs>,
|
||||
vert_topology:Vec<VertRefs>,
|
||||
}
|
||||
|
||||
#[derive(Default,Clone)]
|
||||
struct VertRefGuy{
|
||||
edges:std::collections::HashSet<DirectedEdgeId>,
|
||||
faces:std::collections::HashSet<FaceId>,
|
||||
}
|
||||
#[derive(Clone,Hash,Eq,PartialEq)]
|
||||
struct EdgeRefVerts([VertId;2]);
|
||||
impl EdgeRefVerts{
|
||||
fn new(v0:VertId,v1:VertId)->(Self,bool){
|
||||
(if v0.0<v1.0{
|
||||
Self([v0,v1])
|
||||
}else{
|
||||
Self([v1,v0])
|
||||
},v0.0<v1.0)
|
||||
}
|
||||
}
|
||||
struct EdgeRefFaces([FaceId;2]);
|
||||
impl EdgeRefFaces{
|
||||
fn new()->Self{
|
||||
Self([FaceId(0);2])
|
||||
}
|
||||
fn push(&mut self,i:usize,face_id:FaceId){
|
||||
self.0[i]=face_id;
|
||||
}
|
||||
}
|
||||
struct FaceRefEdges(Vec<DirectedEdgeId>);
|
||||
#[derive(Default)]
|
||||
struct EdgePool{
|
||||
edge_guys:Vec<(EdgeRefVerts,EdgeRefFaces)>,
|
||||
edge_id_from_guy:std::collections::HashMap<EdgeRefVerts,usize>,
|
||||
}
|
||||
impl EdgePool{
|
||||
fn push(&mut self,edge_ref_verts:EdgeRefVerts)->(&mut EdgeRefFaces,EdgeId){
|
||||
let edge_id=if let Some(&edge_id)=self.edge_id_from_guy.get(&edge_ref_verts){
|
||||
edge_id
|
||||
}else{
|
||||
let edge_id=self.edge_guys.len();
|
||||
self.edge_guys.push((edge_ref_verts.clone(),EdgeRefFaces::new()));
|
||||
self.edge_id_from_guy.insert(edge_ref_verts,edge_id);
|
||||
edge_id
|
||||
};
|
||||
(&mut unsafe{self.edge_guys.get_unchecked_mut(edge_id)}.1,EdgeId(edge_id))
|
||||
}
|
||||
}
|
||||
impl From<&crate::model::IndexedModel> for PhysicsMesh{
|
||||
fn from(indexed_model:&crate::model::IndexedModel)->Self{
|
||||
assert!(indexed_model.unique_pos.len()!=0,"Mesh cannot have 0 vertices");
|
||||
let verts=indexed_model.unique_pos.iter().map(|v|Vert(v.clone())).collect();
|
||||
let mut vert_ref_guys=vec![VertRefGuy::default();indexed_model.unique_pos.len()];
|
||||
let mut edge_pool=EdgePool::default();
|
||||
let mut face_i=0;
|
||||
let mut faces=Vec::new();
|
||||
let mut face_ref_guys=Vec::new();
|
||||
for group in indexed_model.groups.iter(){for poly in group.polys.iter(){
|
||||
let face_id=FaceId(face_i);
|
||||
//one face per poly
|
||||
let mut normal=Planar64Vec3::ZERO;
|
||||
let len=poly.vertices.len();
|
||||
let face_edges=poly.vertices.iter().enumerate().map(|(i,&vert_id)|{
|
||||
let vert0_id=indexed_model.unique_vertices[vert_id as usize].pos as usize;
|
||||
let vert1_id=indexed_model.unique_vertices[poly.vertices[(i+1)%len] as usize].pos as usize;
|
||||
//https://www.khronos.org/opengl/wiki/Calculating_a_Surface_Normal (Newell's Method)
|
||||
let v0=indexed_model.unique_pos[vert0_id];
|
||||
let v1=indexed_model.unique_pos[vert1_id];
|
||||
normal+=Planar64Vec3::new(
|
||||
(v0.y()-v1.y())*(v0.z()+v1.z()),
|
||||
(v0.z()-v1.z())*(v0.x()+v1.x()),
|
||||
(v0.x()-v1.x())*(v0.y()+v1.y()),
|
||||
);
|
||||
//get/create edge and push face into it
|
||||
let (edge_ref_verts,is_sorted)=EdgeRefVerts::new(VertId(vert0_id),VertId(vert1_id));
|
||||
let (edge_ref_faces,edge_id)=edge_pool.push(edge_ref_verts);
|
||||
//polygon vertices as assumed to be listed clockwise
|
||||
//populate the edge face on the left or right depending on how the edge vertices got sorted
|
||||
edge_ref_faces.push(!is_sorted as usize,face_id);
|
||||
//index edges & face into vertices
|
||||
{
|
||||
let vert_ref_guy=unsafe{vert_ref_guys.get_unchecked_mut(vert0_id)};
|
||||
vert_ref_guy.edges.insert(edge_id.as_directed(is_sorted));
|
||||
vert_ref_guy.faces.insert(face_id);
|
||||
unsafe{vert_ref_guys.get_unchecked_mut(vert1_id)}.edges.insert(edge_id.as_directed(!is_sorted));
|
||||
}
|
||||
//return directed_edge_id
|
||||
edge_id.as_directed(is_sorted)
|
||||
}).collect();
|
||||
//choose precision loss randomly idk
|
||||
normal=normal/len as i64;
|
||||
let mut dot=Planar64::ZERO;
|
||||
for &v in poly.vertices.iter(){
|
||||
dot+=normal.dot(indexed_model.unique_pos[indexed_model.unique_vertices[v as usize].pos as usize]);
|
||||
}
|
||||
faces.push(Face{normal,dot:dot/len as i64});
|
||||
face_ref_guys.push(FaceRefEdges(face_edges));
|
||||
face_i+=1;
|
||||
}}
|
||||
//conceivably faces, edges, and vertices exist now
|
||||
Self{
|
||||
faces,
|
||||
verts,
|
||||
face_topology:face_ref_guys.into_iter().map(|face_ref_guy|{
|
||||
FaceRefs{edges:face_ref_guy.0}
|
||||
}).collect(),
|
||||
edge_topology:edge_pool.edge_guys.into_iter().map(|(edge_ref_verts,edge_ref_faces)|
|
||||
EdgeRefs{faces:edge_ref_faces.0,verts:edge_ref_verts.0}
|
||||
).collect(),
|
||||
vert_topology:vert_ref_guys.into_iter().map(|vert_ref_guy|
|
||||
VertRefs{
|
||||
edges:vert_ref_guy.edges.into_iter().collect(),
|
||||
faces:vert_ref_guy.faces.into_iter().collect(),
|
||||
}
|
||||
).collect(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl PhysicsMesh{
|
||||
pub fn verts<'a>(&'a self)->impl Iterator<Item=Planar64Vec3>+'a{
|
||||
self.verts.iter().map(|Vert(pos)|*pos)
|
||||
}
|
||||
}
|
||||
impl MeshQuery<FaceId,DirectedEdgeId,VertId> for PhysicsMesh{
|
||||
fn face_nd(&self,face_id:FaceId)->(Planar64Vec3,Planar64){
|
||||
(self.faces[face_id.0].normal,self.faces[face_id.0].dot)
|
||||
}
|
||||
//ideally I never calculate the vertex position, but I have to for the graphical meshes...
|
||||
fn vert(&self,vert_id:VertId)->Planar64Vec3{
|
||||
self.verts[vert_id.0].0
|
||||
}
|
||||
fn face_edges(&self,face_id:FaceId)->Cow<Vec<DirectedEdgeId>>{
|
||||
Cow::Borrowed(&self.face_topology[face_id.0].edges)
|
||||
}
|
||||
fn edge_faces(&self,edge_id:EdgeId)->Cow<[FaceId;2]>{
|
||||
Cow::Borrowed(&self.edge_topology[edge_id.0].faces)
|
||||
}
|
||||
fn edge_verts(&self,edge_id:EdgeId)->Cow<[VertId;2]>{
|
||||
Cow::Borrowed(&self.edge_topology[edge_id.0].verts)
|
||||
}
|
||||
fn vert_edges(&self,vert_id:VertId)->Cow<Vec<DirectedEdgeId>>{
|
||||
Cow::Borrowed(&self.vert_topology[vert_id.0].edges)
|
||||
}
|
||||
fn vert_faces(&self,vert_id:VertId)->Cow<Vec<FaceId>>{
|
||||
Cow::Borrowed(&self.vert_topology[vert_id.0].faces)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct TransformedMesh<'a>{
|
||||
mesh:&'a PhysicsMesh,
|
||||
transform:&'a crate::integer::Planar64Affine3,
|
||||
normal_transform:&'a crate::integer::Planar64Mat3,
|
||||
transform_det:Planar64,
|
||||
}
|
||||
impl TransformedMesh<'_>{
|
||||
pub fn new<'a>(
|
||||
mesh:&'a PhysicsMesh,
|
||||
transform:&'a crate::integer::Planar64Affine3,
|
||||
normal_transform:&'a crate::integer::Planar64Mat3,
|
||||
transform_det:Planar64,
|
||||
)->TransformedMesh<'a>{
|
||||
TransformedMesh{
|
||||
mesh,
|
||||
transform,
|
||||
normal_transform,
|
||||
transform_det,
|
||||
}
|
||||
}
|
||||
fn farthest_vert(&self,dir:Planar64Vec3)->VertId{
|
||||
let mut best_dot=Planar64::MIN;
|
||||
let mut best_vert=VertId(0);
|
||||
for (i,vert) in self.mesh.verts.iter().enumerate(){
|
||||
let p=self.transform.transform_point3(vert.0);
|
||||
let d=dir.dot(p);
|
||||
if best_dot<d{
|
||||
best_dot=d;
|
||||
best_vert=VertId(i);
|
||||
}
|
||||
}
|
||||
best_vert
|
||||
}
|
||||
}
|
||||
impl MeshQuery<FaceId,DirectedEdgeId,VertId> for TransformedMesh<'_>{
|
||||
fn face_nd(&self,face_id:FaceId)->(Planar64Vec3,Planar64){
|
||||
let (n,d)=self.mesh.face_nd(face_id);
|
||||
let transformed_n=*self.normal_transform*n;
|
||||
let transformed_d=d+transformed_n.dot(self.transform.translation)/self.transform_det;
|
||||
(transformed_n/self.transform_det,transformed_d)
|
||||
}
|
||||
fn vert(&self,vert_id:VertId)->Planar64Vec3{
|
||||
self.transform.transform_point3(self.mesh.vert(vert_id))
|
||||
}
|
||||
#[inline]
|
||||
fn face_edges(&self,face_id:FaceId)->Cow<Vec<DirectedEdgeId>>{
|
||||
self.mesh.face_edges(face_id)
|
||||
}
|
||||
#[inline]
|
||||
fn edge_faces(&self,edge_id:EdgeId)->Cow<[FaceId;2]>{
|
||||
self.mesh.edge_faces(edge_id)
|
||||
}
|
||||
#[inline]
|
||||
fn edge_verts(&self,edge_id:EdgeId)->Cow<[VertId;2]>{
|
||||
self.mesh.edge_verts(edge_id)
|
||||
}
|
||||
#[inline]
|
||||
fn vert_edges(&self,vert_id:VertId)->Cow<Vec<DirectedEdgeId>>{
|
||||
self.mesh.vert_edges(vert_id)
|
||||
}
|
||||
#[inline]
|
||||
fn vert_faces(&self,vert_id:VertId)->Cow<Vec<FaceId>>{
|
||||
self.mesh.vert_faces(vert_id)
|
||||
}
|
||||
}
|
||||
|
||||
//Note that a face on a minkowski mesh refers to a pair of fevs on the meshes it's summed from
|
||||
//(face,vertex)
|
||||
//(edge,edge)
|
||||
//(vertex,face)
|
||||
#[derive(Clone,Copy)]
|
||||
pub enum MinkowskiVert{
|
||||
VertVert(VertId,VertId),
|
||||
}
|
||||
#[derive(Clone,Copy)]
|
||||
pub enum MinkowskiEdge{
|
||||
VertEdge(VertId,EdgeId),
|
||||
EdgeVert(EdgeId,VertId),
|
||||
//EdgeEdge when edges are parallel
|
||||
}
|
||||
impl UndirectedEdge for MinkowskiEdge{
|
||||
type DirectedEdge=MinkowskiDirectedEdge;
|
||||
fn as_directed(&self,parity:bool)->Self::DirectedEdge{
|
||||
match self{
|
||||
MinkowskiEdge::VertEdge(v0,e1)=>MinkowskiDirectedEdge::VertEdge(*v0,e1.as_directed(parity)),
|
||||
MinkowskiEdge::EdgeVert(e0,v1)=>MinkowskiDirectedEdge::EdgeVert(e0.as_directed(parity),*v1),
|
||||
}
|
||||
}
|
||||
}
|
||||
#[derive(Clone,Copy)]
|
||||
pub enum MinkowskiDirectedEdge{
|
||||
VertEdge(VertId,DirectedEdgeId),
|
||||
EdgeVert(DirectedEdgeId,VertId),
|
||||
//EdgeEdge when edges are parallel
|
||||
}
|
||||
impl DirectedEdge for MinkowskiDirectedEdge{
|
||||
type UndirectedEdge=MinkowskiEdge;
|
||||
fn as_undirected(&self)->Self::UndirectedEdge{
|
||||
match self{
|
||||
MinkowskiDirectedEdge::VertEdge(v0,e1)=>MinkowskiEdge::VertEdge(*v0,e1.as_undirected()),
|
||||
MinkowskiDirectedEdge::EdgeVert(e0,v1)=>MinkowskiEdge::EdgeVert(e0.as_undirected(),*v1),
|
||||
}
|
||||
}
|
||||
fn parity(&self)->bool{
|
||||
match self{
|
||||
MinkowskiDirectedEdge::VertEdge(_,e)
|
||||
|MinkowskiDirectedEdge::EdgeVert(e,_)=>e.parity(),
|
||||
}
|
||||
}
|
||||
}
|
||||
#[derive(Debug,Clone,Copy,Hash,Eq,PartialEq)]
|
||||
pub enum MinkowskiFace{
|
||||
VertFace(VertId,FaceId),
|
||||
EdgeEdge(EdgeId,EdgeId,bool),
|
||||
FaceVert(FaceId,VertId),
|
||||
//EdgeFace
|
||||
//FaceEdge
|
||||
//FaceFace
|
||||
}
|
||||
|
||||
pub struct MinkowskiMesh<'a>{
|
||||
mesh0:&'a TransformedMesh<'a>,
|
||||
mesh1:&'a TransformedMesh<'a>,
|
||||
}
|
||||
|
||||
//infinity fev algorithm state transition
|
||||
enum Transition{
|
||||
Done,//found closest vert, no edges are better
|
||||
Vert(MinkowskiVert),//transition to vert
|
||||
}
|
||||
enum EV{
|
||||
Vert(MinkowskiVert),
|
||||
Edge(MinkowskiEdge),
|
||||
}
|
||||
|
||||
impl MinkowskiMesh<'_>{
|
||||
pub fn minkowski_sum<'a>(mesh0:&'a TransformedMesh,mesh1:&'a TransformedMesh)->MinkowskiMesh<'a>{
|
||||
MinkowskiMesh{
|
||||
mesh0,
|
||||
mesh1,
|
||||
}
|
||||
}
|
||||
fn farthest_vert(&self,dir:Planar64Vec3)->MinkowskiVert{
|
||||
MinkowskiVert::VertVert(self.mesh0.farthest_vert(dir),self.mesh1.farthest_vert(-dir))
|
||||
}
|
||||
fn next_transition_vert(&self,vert_id:MinkowskiVert,best_distance_squared:&mut Planar64,infinity_dir:Planar64Vec3,point:Planar64Vec3)->Transition{
|
||||
let mut best_transition=Transition::Done;
|
||||
for &directed_edge_id in self.vert_edges(vert_id).iter(){
|
||||
let edge_n=self.directed_edge_n(directed_edge_id);
|
||||
//is boundary uncrossable by a crawl from infinity
|
||||
let edge_verts=self.edge_verts(directed_edge_id.as_undirected());
|
||||
//select opposite vertex
|
||||
let test_vert_id=edge_verts[directed_edge_id.parity() as usize];
|
||||
//test if it's closer
|
||||
let diff=point-self.vert(test_vert_id);
|
||||
if crate::zeroes::zeroes1(edge_n.dot(diff),edge_n.dot(infinity_dir)).len()==0{
|
||||
let distance_squared=diff.dot(diff);
|
||||
if distance_squared<*best_distance_squared{
|
||||
best_transition=Transition::Vert(test_vert_id);
|
||||
*best_distance_squared=distance_squared;
|
||||
}
|
||||
}
|
||||
}
|
||||
best_transition
|
||||
}
|
||||
fn final_ev(&self,vert_id:MinkowskiVert,best_distance_squared:&mut Planar64,infinity_dir:Planar64Vec3,point:Planar64Vec3)->EV{
|
||||
let mut best_transition=EV::Vert(vert_id);
|
||||
let diff=point-self.vert(vert_id);
|
||||
for &directed_edge_id in self.vert_edges(vert_id).iter(){
|
||||
let edge_n=self.directed_edge_n(directed_edge_id);
|
||||
//is boundary uncrossable by a crawl from infinity
|
||||
//check if time of collision is outside Time::MIN..Time::MAX
|
||||
let d=edge_n.dot(diff);
|
||||
if crate::zeroes::zeroes1(d,edge_n.dot(infinity_dir)).len()==0{
|
||||
//test the edge
|
||||
let edge_nn=edge_n.dot(edge_n);
|
||||
if Planar64::ZERO<=d&&d<=edge_nn{
|
||||
let distance_squared={
|
||||
let c=diff.cross(edge_n);
|
||||
c.dot(c)/edge_nn
|
||||
};
|
||||
if distance_squared<=*best_distance_squared{
|
||||
best_transition=EV::Edge(directed_edge_id.as_undirected());
|
||||
*best_distance_squared=distance_squared;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
best_transition
|
||||
}
|
||||
fn crawl_boundaries(&self,mut vert_id:MinkowskiVert,infinity_dir:Planar64Vec3,point:Planar64Vec3)->EV{
|
||||
let mut best_distance_squared={
|
||||
let diff=point-self.vert(vert_id);
|
||||
diff.dot(diff)
|
||||
};
|
||||
loop{
|
||||
match self.next_transition_vert(vert_id,&mut best_distance_squared,infinity_dir,point){
|
||||
Transition::Done=>return self.final_ev(vert_id,&mut best_distance_squared,infinity_dir,point),
|
||||
Transition::Vert(new_vert_id)=>vert_id=new_vert_id,
|
||||
}
|
||||
}
|
||||
}
|
||||
/// This function drops a vertex down to an edge or a face if the path from infinity did not cross any vertex-edge boundaries but the point is supposed to have already crossed a boundary down from a vertex
|
||||
fn infinity_fev(&self,infinity_dir:Planar64Vec3,point:Planar64Vec3)->FEV::<MinkowskiFace,MinkowskiDirectedEdge,MinkowskiVert>{
|
||||
//start on any vertex
|
||||
//cross uncrossable vertex-edge boundaries until you find the closest vertex or edge
|
||||
//cross edge-face boundary if it's uncrossable
|
||||
match self.crawl_boundaries(self.farthest_vert(infinity_dir),infinity_dir,point){
|
||||
//if a vert is returned, it is the closest point to the infinity point
|
||||
EV::Vert(vert_id)=>FEV::<MinkowskiFace,MinkowskiDirectedEdge,MinkowskiVert>::Vert(vert_id),
|
||||
EV::Edge(edge_id)=>{
|
||||
//cross to face if the boundary is not crossable and we are on the wrong side
|
||||
let edge_n=self.edge_n(edge_id);
|
||||
// point is multiplied by two because vert_sum sums two vertices.
|
||||
let delta_pos=point*2-{
|
||||
let &[v0,v1]=self.edge_verts(edge_id).borrow();
|
||||
self.vert(v0)+self.vert(v1)
|
||||
};
|
||||
for (i,&face_id) in self.edge_faces(edge_id).iter().enumerate(){
|
||||
let face_n=self.face_nd(face_id).0;
|
||||
//edge-face boundary nd, n facing out of the face towards the edge
|
||||
let boundary_n=face_n.cross(edge_n)*(i as i64*2-1);
|
||||
let boundary_d=boundary_n.dot(delta_pos);
|
||||
//check if time of collision is outside Time::MIN..Time::MAX
|
||||
//infinity_dir can always be treated as a velocity
|
||||
if (boundary_d)<=Planar64::ZERO&&crate::zeroes::zeroes1(boundary_d,boundary_n.dot(infinity_dir)*2).len()==0{
|
||||
//both faces cannot pass this condition, return early if one does.
|
||||
return FEV::<MinkowskiFace,MinkowskiDirectedEdge,MinkowskiVert>::Face(face_id);
|
||||
}
|
||||
}
|
||||
FEV::<MinkowskiFace,MinkowskiDirectedEdge,MinkowskiVert>::Edge(edge_id)
|
||||
},
|
||||
}
|
||||
}
|
||||
fn closest_fev_not_inside(&self,mut infinity_body:crate::physics::Body)->Option<FEV::<MinkowskiFace,MinkowskiDirectedEdge,MinkowskiVert>>{
|
||||
infinity_body.infinity_dir().map_or(None,|dir|{
|
||||
let infinity_fev=self.infinity_fev(-dir,infinity_body.position);
|
||||
//a line is simpler to solve than a parabola
|
||||
infinity_body.velocity=dir;
|
||||
infinity_body.acceleration=Planar64Vec3::ZERO;
|
||||
//crawl in from negative infinity along a tangent line to get the closest fev
|
||||
match crate::face_crawler::crawl_fev(infinity_fev,self,&infinity_body,crate::integer::Time::MIN,infinity_body.time){
|
||||
crate::face_crawler::CrawlResult::Miss(fev)=>Some(fev),
|
||||
crate::face_crawler::CrawlResult::Hit(_,_)=>None,
|
||||
}
|
||||
})
|
||||
}
|
||||
pub fn predict_collision_in(&self,relative_body:&crate::physics::Body,time_limit:crate::integer::Time)->Option<(MinkowskiFace,crate::integer::Time)>{
|
||||
self.closest_fev_not_inside(relative_body.clone()).map_or(None,|fev|{
|
||||
//continue forwards along the body parabola
|
||||
match crate::face_crawler::crawl_fev(fev,self,relative_body,relative_body.time,time_limit){
|
||||
crate::face_crawler::CrawlResult::Miss(_)=>None,
|
||||
crate::face_crawler::CrawlResult::Hit(face,time)=>Some((face,time)),
|
||||
}
|
||||
})
|
||||
}
|
||||
pub fn predict_collision_out(&self,relative_body:&crate::physics::Body,time_limit:crate::integer::Time)->Option<(MinkowskiFace,crate::integer::Time)>{
|
||||
//create an extrapolated body at time_limit
|
||||
let infinity_body=crate::physics::Body::new(
|
||||
relative_body.extrapolated_position(time_limit),
|
||||
-relative_body.extrapolated_velocity(time_limit),
|
||||
relative_body.acceleration,
|
||||
-time_limit,
|
||||
);
|
||||
self.closest_fev_not_inside(infinity_body).map_or(None,|fev|{
|
||||
//continue backwards along the body parabola
|
||||
match crate::face_crawler::crawl_fev(fev,self,&-relative_body.clone(),-time_limit,-relative_body.time){
|
||||
crate::face_crawler::CrawlResult::Miss(_)=>None,
|
||||
crate::face_crawler::CrawlResult::Hit(face,time)=>Some((face,-time)),//no need to test -time<time_limit because of the first step
|
||||
}
|
||||
})
|
||||
}
|
||||
pub fn predict_collision_face_out(&self,relative_body:&crate::physics::Body,time_limit:crate::integer::Time,contact_face_id:MinkowskiFace)->Option<(MinkowskiEdge,crate::integer::Time)>{
|
||||
//no algorithm needed, there is only one state and two cases (Edge,None)
|
||||
//determine when it passes an edge ("sliding off" case)
|
||||
let mut best_time=time_limit;
|
||||
let mut best_edge=None;
|
||||
let face_n=self.face_nd(contact_face_id).0;
|
||||
for &directed_edge_id in self.face_edges(contact_face_id).iter(){
|
||||
let edge_n=self.directed_edge_n(directed_edge_id);
|
||||
//f x e points in
|
||||
let n=face_n.cross(edge_n);
|
||||
let verts=self.edge_verts(directed_edge_id.as_undirected());
|
||||
let d=n.dot(self.vert(verts[0])+self.vert(verts[1]));
|
||||
//WARNING! d outside of *2
|
||||
for t in crate::zeroes::zeroes2((n.dot(relative_body.position))*2-d,n.dot(relative_body.velocity)*2,n.dot(relative_body.acceleration)){
|
||||
let t=relative_body.time+crate::integer::Time::from(t);
|
||||
if relative_body.time<t&&t<best_time&&n.dot(relative_body.extrapolated_velocity(t))<Planar64::ZERO{
|
||||
best_time=t;
|
||||
best_edge=Some(directed_edge_id);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
best_edge.map(|e|(e.as_undirected(),best_time))
|
||||
}
|
||||
}
|
||||
impl MeshQuery<MinkowskiFace,MinkowskiDirectedEdge,MinkowskiVert> for MinkowskiMesh<'_>{
|
||||
fn face_nd(&self,face_id:MinkowskiFace)->(Planar64Vec3,Planar64){
|
||||
match face_id{
|
||||
MinkowskiFace::VertFace(v0,f1)=>{
|
||||
let (n,d)=self.mesh1.face_nd(f1);
|
||||
(-n,d-n.dot(self.mesh0.vert(v0)))
|
||||
},
|
||||
MinkowskiFace::EdgeEdge(e0,e1,parity)=>{
|
||||
let edge0_n=self.mesh0.edge_n(e0);
|
||||
let edge1_n=self.mesh1.edge_n(e1);
|
||||
let &[e0v0,e0v1]=self.mesh0.edge_verts(e0).borrow();
|
||||
let &[e1v0,e1v1]=self.mesh1.edge_verts(e1).borrow();
|
||||
let n=edge0_n.cross(edge1_n);
|
||||
let e0d=n.dot(self.mesh0.vert(e0v0)+self.mesh0.vert(e0v1));
|
||||
let e1d=n.dot(self.mesh1.vert(e1v0)+self.mesh1.vert(e1v1));
|
||||
(n*(parity as i64*4-2),(e0d-e1d)*(parity as i64*2-1))
|
||||
},
|
||||
MinkowskiFace::FaceVert(f0,v1)=>{
|
||||
let (n,d)=self.mesh0.face_nd(f0);
|
||||
(n,d-n.dot(self.mesh1.vert(v1)))
|
||||
},
|
||||
}
|
||||
}
|
||||
fn vert(&self,vert_id:MinkowskiVert)->Planar64Vec3{
|
||||
match vert_id{
|
||||
MinkowskiVert::VertVert(v0,v1)=>{
|
||||
self.mesh0.vert(v0)-self.mesh1.vert(v1)
|
||||
},
|
||||
}
|
||||
}
|
||||
fn face_edges(&self,face_id:MinkowskiFace)->Cow<Vec<MinkowskiDirectedEdge>>{
|
||||
match face_id{
|
||||
MinkowskiFace::VertFace(v0,f1)=>{
|
||||
Cow::Owned(self.mesh1.face_edges(f1).iter().map(|&edge_id1|{
|
||||
MinkowskiDirectedEdge::VertEdge(v0,edge_id1.reverse())
|
||||
}).collect())
|
||||
},
|
||||
MinkowskiFace::EdgeEdge(e0,e1,parity)=>{
|
||||
let e0v=self.mesh0.edge_verts(e0);
|
||||
let e1v=self.mesh1.edge_verts(e1);
|
||||
//could sort this if ordered edges are needed
|
||||
//probably just need to reverse this list according to parity
|
||||
Cow::Owned(vec![
|
||||
MinkowskiDirectedEdge::VertEdge(e0v[0],e1.as_directed(parity)),
|
||||
MinkowskiDirectedEdge::EdgeVert(e0.as_directed(!parity),e1v[0]),
|
||||
MinkowskiDirectedEdge::VertEdge(e0v[1],e1.as_directed(!parity)),
|
||||
MinkowskiDirectedEdge::EdgeVert(e0.as_directed(parity),e1v[1]),
|
||||
])
|
||||
},
|
||||
MinkowskiFace::FaceVert(f0,v1)=>{
|
||||
Cow::Owned(self.mesh0.face_edges(f0).iter().map(|&edge_id0|{
|
||||
MinkowskiDirectedEdge::EdgeVert(edge_id0,v1)
|
||||
}).collect())
|
||||
},
|
||||
}
|
||||
}
|
||||
fn edge_faces(&self,edge_id:MinkowskiEdge)->Cow<[MinkowskiFace;2]>{
|
||||
match edge_id{
|
||||
MinkowskiEdge::VertEdge(v0,e1)=>{
|
||||
//faces are listed backwards from the minkowski mesh
|
||||
let v0e=self.mesh0.vert_edges(v0);
|
||||
let &[e1f0,e1f1]=self.mesh1.edge_faces(e1).borrow();
|
||||
Cow::Owned([(e1f1,false),(e1f0,true)].map(|(edge_face_id1,face_parity)|{
|
||||
let mut best_edge=None;
|
||||
let mut best_d=Planar64::ZERO;
|
||||
let edge_face1_n=self.mesh1.face_nd(edge_face_id1).0;
|
||||
let edge_face1_nn=edge_face1_n.dot(edge_face1_n);
|
||||
for &directed_edge_id0 in v0e.iter(){
|
||||
let edge0_n=self.mesh0.directed_edge_n(directed_edge_id0);
|
||||
//must be behind other face.
|
||||
let d=edge_face1_n.dot(edge0_n);
|
||||
if d<Planar64::ZERO{
|
||||
let edge0_nn=edge0_n.dot(edge0_n);
|
||||
//divide by zero???
|
||||
let dd=d*d/(edge_face1_nn*edge0_nn);
|
||||
if best_d<dd{
|
||||
best_d=dd;
|
||||
best_edge=Some(directed_edge_id0);
|
||||
}
|
||||
}
|
||||
}
|
||||
best_edge.map_or(
|
||||
MinkowskiFace::VertFace(v0,edge_face_id1),
|
||||
|directed_edge_id0|MinkowskiFace::EdgeEdge(directed_edge_id0.as_undirected(),e1,directed_edge_id0.parity()^face_parity)
|
||||
)
|
||||
}))
|
||||
},
|
||||
MinkowskiEdge::EdgeVert(e0,v1)=>{
|
||||
//tracking index with an external variable because .enumerate() is not available
|
||||
let v1e=self.mesh1.vert_edges(v1);
|
||||
let &[e0f0,e0f1]=self.mesh0.edge_faces(e0).borrow();
|
||||
Cow::Owned([(e0f0,true),(e0f1,false)].map(|(edge_face_id0,face_parity)|{
|
||||
let mut best_edge=None;
|
||||
let mut best_d=Planar64::ZERO;
|
||||
let edge_face0_n=self.mesh0.face_nd(edge_face_id0).0;
|
||||
let edge_face0_nn=edge_face0_n.dot(edge_face0_n);
|
||||
for &directed_edge_id1 in v1e.iter(){
|
||||
let edge1_n=self.mesh1.directed_edge_n(directed_edge_id1);
|
||||
let d=edge_face0_n.dot(edge1_n);
|
||||
if d<Planar64::ZERO{
|
||||
let edge1_nn=edge1_n.dot(edge1_n);
|
||||
let dd=d*d/(edge_face0_nn*edge1_nn);
|
||||
if best_d<dd{
|
||||
best_d=dd;
|
||||
best_edge=Some(directed_edge_id1);
|
||||
}
|
||||
}
|
||||
}
|
||||
best_edge.map_or(
|
||||
MinkowskiFace::FaceVert(edge_face_id0,v1),
|
||||
|directed_edge_id1|MinkowskiFace::EdgeEdge(e0,directed_edge_id1.as_undirected(),directed_edge_id1.parity()^face_parity)
|
||||
)
|
||||
}))
|
||||
},
|
||||
}
|
||||
}
|
||||
fn edge_verts(&self,edge_id:MinkowskiEdge)->Cow<[MinkowskiVert;2]>{
|
||||
match edge_id{
|
||||
MinkowskiEdge::VertEdge(v0,e1)=>{
|
||||
Cow::Owned(self.mesh1.edge_verts(e1).map(|vert_id1|{
|
||||
MinkowskiVert::VertVert(v0,vert_id1)
|
||||
}))
|
||||
},
|
||||
MinkowskiEdge::EdgeVert(e0,v1)=>{
|
||||
Cow::Owned(self.mesh0.edge_verts(e0).map(|vert_id0|{
|
||||
MinkowskiVert::VertVert(vert_id0,v1)
|
||||
}))
|
||||
},
|
||||
}
|
||||
}
|
||||
fn vert_edges(&self,vert_id:MinkowskiVert)->Cow<Vec<MinkowskiDirectedEdge>>{
|
||||
match vert_id{
|
||||
MinkowskiVert::VertVert(v0,v1)=>{
|
||||
let mut edges=Vec::new();
|
||||
//detect shared volume when the other mesh is mirrored along a test edge dir
|
||||
let v0f=self.mesh0.vert_faces(v0);
|
||||
let v1f=self.mesh1.vert_faces(v1);
|
||||
let v0f_n:Vec<Planar64Vec3>=v0f.iter().map(|&face_id|self.mesh0.face_nd(face_id).0).collect();
|
||||
let v1f_n:Vec<Planar64Vec3>=v1f.iter().map(|&face_id|self.mesh1.face_nd(face_id).0).collect();
|
||||
let the_len=v0f.len()+v1f.len();
|
||||
for &directed_edge_id in self.mesh0.vert_edges(v0).iter(){
|
||||
let n=self.mesh0.directed_edge_n(directed_edge_id);
|
||||
let nn=n.dot(n);
|
||||
//make a set of faces
|
||||
let mut face_normals=Vec::with_capacity(the_len);
|
||||
//add mesh0 faces as-is
|
||||
face_normals.clone_from(&v0f_n);
|
||||
for face_n in &v1f_n{
|
||||
//add reflected mesh1 faces
|
||||
face_normals.push(*face_n-n*(face_n.dot(n)*2/nn));
|
||||
}
|
||||
if is_empty_volume(face_normals){
|
||||
edges.push(MinkowskiDirectedEdge::EdgeVert(directed_edge_id,v1));
|
||||
}
|
||||
}
|
||||
for &directed_edge_id in self.mesh1.vert_edges(v1).iter(){
|
||||
let n=self.mesh1.directed_edge_n(directed_edge_id);
|
||||
let nn=n.dot(n);
|
||||
let mut face_normals=Vec::with_capacity(the_len);
|
||||
face_normals.clone_from(&v1f_n);
|
||||
for face_n in &v0f_n{
|
||||
face_normals.push(*face_n-n*(face_n.dot(n)*2/nn));
|
||||
}
|
||||
if is_empty_volume(face_normals){
|
||||
edges.push(MinkowskiDirectedEdge::VertEdge(v0,directed_edge_id));
|
||||
}
|
||||
}
|
||||
Cow::Owned(edges)
|
||||
},
|
||||
}
|
||||
}
|
||||
fn vert_faces(&self,_vert_id:MinkowskiVert)->Cow<Vec<MinkowskiFace>>{
|
||||
unimplemented!()
|
||||
}
|
||||
}
|
||||
|
||||
fn is_empty_volume(normals:Vec<Planar64Vec3>)->bool{
|
||||
let len=normals.len();
|
||||
for i in 0..len-1{
|
||||
for j in i+1..len{
|
||||
let n=normals[i].cross(normals[j]);
|
||||
let mut d_comp=None;
|
||||
for k in 0..len{
|
||||
if k!=i&&k!=j{
|
||||
let d=n.dot(normals[k]);
|
||||
if let Some(comp)=&d_comp{
|
||||
if *comp*d<Planar64::ZERO{
|
||||
return true;
|
||||
}
|
||||
}else{
|
||||
d_comp=Some(d);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_is_empty_volume(){
|
||||
assert!(!is_empty_volume([Planar64Vec3::X,Planar64Vec3::Y,Planar64Vec3::Z].to_vec()));
|
||||
assert!(is_empty_volume([Planar64Vec3::X,Planar64Vec3::Y,Planar64Vec3::Z,Planar64Vec3::NEG_X].to_vec()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn build_me_a_cube(){
|
||||
let unit_cube=crate::primitives::unit_cube();
|
||||
let mesh=PhysicsMesh::from(&unit_cube);
|
||||
//println!("mesh={:?}",mesh);
|
||||
}
|
||||
//
|
1723
src/physics.rs
1723
src/physics.rs
File diff suppressed because it is too large
Load Diff
@ -126,21 +126,17 @@ const CORNERWEDGE_DEFAULT_NORMALS:[Planar64Vec3;5]=[
|
||||
Planar64Vec3::int( 0,-1, 0),//CornerWedge::Bottom
|
||||
Planar64Vec3::int( 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{
|
||||
unit_cube()
|
||||
}
|
||||
#[derive(Default)]
|
||||
pub struct CubeFaceDescription([Option<FaceDescription>;6]);
|
||||
impl CubeFaceDescription{
|
||||
pub fn insert(&mut self,index:CubeFace,value:FaceDescription){
|
||||
self.0[index as usize]=Some(value);
|
||||
}
|
||||
pub fn pairs(self)->std::iter::FilterMap<std::iter::Enumerate<std::array::IntoIter<Option<FaceDescription>,6>>,impl FnMut((usize,Option<FaceDescription>))->Option<(usize,FaceDescription)>>{
|
||||
self.0.into_iter().enumerate().filter_map(|v|v.1.map(|u|(v.0,u)))
|
||||
let mut indexed_model=crate::model::generate_indexed_model_list_from_obj(obj::ObjData::load_buf(&include_bytes!("../models/suzanne.obj")[..]).unwrap(),Color4::ONE).remove(0);
|
||||
for pos in indexed_model.unique_pos.iter_mut(){
|
||||
*pos=*pos/2;
|
||||
}
|
||||
indexed_model
|
||||
}
|
||||
pub type CubeFaceDescription=std::collections::HashMap::<CubeFace,FaceDescription>;
|
||||
pub fn unit_cube()->crate::model::IndexedModel{
|
||||
let mut t=CubeFaceDescription::default();
|
||||
let mut t=CubeFaceDescription::new();
|
||||
t.insert(CubeFace::Right,FaceDescription::default());
|
||||
t.insert(CubeFace::Top,FaceDescription::default());
|
||||
t.insert(CubeFace::Back,FaceDescription::default());
|
||||
@ -149,21 +145,17 @@ pub fn unit_cube()->crate::model::IndexedModel{
|
||||
t.insert(CubeFace::Front,FaceDescription::default());
|
||||
generate_partial_unit_cube(t)
|
||||
}
|
||||
const TEAPOT_TRANSFORM:crate::integer::Planar64Mat3=crate::integer::Planar64Mat3::int_from_cols_array([0,1,0, -1,0,0, 0,0,1]);
|
||||
pub fn unit_cylinder()->crate::model::IndexedModel{
|
||||
unit_cube()
|
||||
}
|
||||
#[derive(Default)]
|
||||
pub struct WedgeFaceDescription([Option<FaceDescription>;5]);
|
||||
impl WedgeFaceDescription{
|
||||
pub fn insert(&mut self,index:WedgeFace,value:FaceDescription){
|
||||
self.0[index as usize]=Some(value);
|
||||
}
|
||||
pub fn pairs(self)->std::iter::FilterMap<std::iter::Enumerate<std::array::IntoIter<Option<FaceDescription>,5>>,impl FnMut((usize,Option<FaceDescription>))->Option<(usize,FaceDescription)>>{
|
||||
self.0.into_iter().enumerate().filter_map(|v|v.1.map(|u|(v.0,u)))
|
||||
let mut indexed_model=crate::model::generate_indexed_model_list_from_obj(obj::ObjData::load_buf(&include_bytes!("../models/teapot.obj")[..]).unwrap(),Color4::ONE).remove(0);
|
||||
for pos in indexed_model.unique_pos.iter_mut(){
|
||||
*pos=TEAPOT_TRANSFORM*(*pos)/10;
|
||||
}
|
||||
indexed_model
|
||||
}
|
||||
pub type WedgeFaceDescription=std::collections::HashMap::<WedgeFace,FaceDescription>;
|
||||
pub fn unit_wedge()->crate::model::IndexedModel{
|
||||
let mut t=WedgeFaceDescription::default();
|
||||
let mut t=WedgeFaceDescription::new();
|
||||
t.insert(WedgeFace::Right,FaceDescription::default());
|
||||
t.insert(WedgeFace::TopFront,FaceDescription::default());
|
||||
t.insert(WedgeFace::Back,FaceDescription::default());
|
||||
@ -171,18 +163,9 @@ pub fn unit_wedge()->crate::model::IndexedModel{
|
||||
t.insert(WedgeFace::Bottom,FaceDescription::default());
|
||||
generate_partial_unit_wedge(t)
|
||||
}
|
||||
#[derive(Default)]
|
||||
pub struct CornerWedgeFaceDescription([Option<FaceDescription>;5]);
|
||||
impl CornerWedgeFaceDescription{
|
||||
pub fn insert(&mut self,index:CornerWedgeFace,value:FaceDescription){
|
||||
self.0[index as usize]=Some(value);
|
||||
}
|
||||
pub fn pairs(self)->std::iter::FilterMap<std::iter::Enumerate<std::array::IntoIter<Option<FaceDescription>,5>>,impl FnMut((usize,Option<FaceDescription>))->Option<(usize,FaceDescription)>>{
|
||||
self.0.into_iter().enumerate().filter_map(|v|v.1.map(|u|(v.0,u)))
|
||||
}
|
||||
}
|
||||
pub type CornerWedgeFaceDescription=std::collections::HashMap::<CornerWedgeFace,FaceDescription>;
|
||||
pub fn unit_cornerwedge()->crate::model::IndexedModel{
|
||||
let mut t=CornerWedgeFaceDescription::default();
|
||||
let mut t=CornerWedgeFaceDescription::new();
|
||||
t.insert(CornerWedgeFace::Right,FaceDescription::default());
|
||||
t.insert(CornerWedgeFace::TopBack,FaceDescription::default());
|
||||
t.insert(CornerWedgeFace::TopLeft,FaceDescription::default());
|
||||
@ -206,6 +189,18 @@ impl std::default::Default for FaceDescription{
|
||||
}
|
||||
}
|
||||
}
|
||||
impl FaceDescription{
|
||||
pub fn new(texture:u32,transform:glam::Affine2,color:Color4)->Self{
|
||||
Self{texture:Some(texture),transform,color}
|
||||
}
|
||||
pub fn from_texture(texture:u32)->Self{
|
||||
Self{
|
||||
texture:Some(texture),
|
||||
transform:glam::Affine2::IDENTITY,
|
||||
color:Color4::ONE,
|
||||
}
|
||||
}
|
||||
}
|
||||
//TODO: it's probably better to use a shared vertex buffer between all primitives and use indexed rendering instead of generating a unique vertex buffer for each primitive.
|
||||
//implementation: put all roblox primitives into one model.groups <- this won't work but I forget why
|
||||
pub fn generate_partial_unit_cube(face_descriptions:CubeFaceDescription)->crate::model::IndexedModel{
|
||||
@ -217,7 +212,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_id,face_description) in face_descriptions.pairs(){
|
||||
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
|
||||
@ -238,6 +233,14 @@ pub fn generate_partial_unit_cube(face_descriptions:CubeFaceDescription)->crate:
|
||||
generated_color.push(face_description.color);
|
||||
color_index
|
||||
} as u32;
|
||||
let face_id=match face{
|
||||
CubeFace::Right => 0,
|
||||
CubeFace::Top => 1,
|
||||
CubeFace::Back => 2,
|
||||
CubeFace::Left => 3,
|
||||
CubeFace::Bottom => 4,
|
||||
CubeFace::Front => 5,
|
||||
};
|
||||
//always push normal
|
||||
let normal_index=generated_normal.len() as u32;
|
||||
generated_normal.push(CUBE_DEFAULT_NORMALS[face_id]);
|
||||
@ -324,7 +327,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_id,face_description) in face_descriptions.pairs(){
|
||||
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
|
||||
@ -345,6 +348,13 @@ pub fn generate_partial_unit_wedge(face_descriptions:WedgeFaceDescription)->crat
|
||||
generated_color.push(face_description.color);
|
||||
color_index
|
||||
} as u32;
|
||||
let face_id=match face{
|
||||
WedgeFace::Right => 0,
|
||||
WedgeFace::TopFront => 1,
|
||||
WedgeFace::Back => 2,
|
||||
WedgeFace::Left => 3,
|
||||
WedgeFace::Bottom => 4,
|
||||
};
|
||||
//always push normal
|
||||
let normal_index=generated_normal.len() as u32;
|
||||
generated_normal.push(WEDGE_DEFAULT_NORMALS[face_id]);
|
||||
@ -429,7 +439,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_id,face_description) in face_descriptions.pairs(){
|
||||
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
|
||||
@ -450,6 +460,13 @@ pub fn generate_partial_unit_cornerwedge(face_descriptions:CornerWedgeFaceDescri
|
||||
generated_color.push(face_description.color);
|
||||
color_index
|
||||
} as u32;
|
||||
let face_id=match face{
|
||||
CornerWedgeFace::Right => 0,
|
||||
CornerWedgeFace::TopBack => 1,
|
||||
CornerWedgeFace::TopLeft => 2,
|
||||
CornerWedgeFace::Bottom => 3,
|
||||
CornerWedgeFace::Front => 4,
|
||||
};
|
||||
//always push normal
|
||||
let normal_index=generated_normal.len() as u32;
|
||||
generated_normal.push(CORNERWEDGE_DEFAULT_NORMALS[face_id]);
|
||||
|
@ -41,7 +41,6 @@ fn create_instance()->SetupContextPartial1{
|
||||
instance:wgpu::Instance::new(wgpu::InstanceDescriptor{
|
||||
backends,
|
||||
dx12_shader_compiler,
|
||||
..Default::default()
|
||||
}),
|
||||
}
|
||||
}
|
||||
@ -170,7 +169,6 @@ impl SetupContextPartial4{
|
||||
.expect("Surface isn't supported by the adapter.");
|
||||
let surface_view_format=config.format.add_srgb_suffix();
|
||||
config.view_formats.push(surface_view_format);
|
||||
config.present_mode=wgpu::PresentMode::AutoNoVsync;
|
||||
self.surface.configure(&self.device, &config);
|
||||
|
||||
SetupContext{
|
||||
|
134
src/sniffer.rs
134
src/sniffer.rs
@ -1,134 +0,0 @@
|
||||
//file format "sniff"
|
||||
|
||||
/* spec
|
||||
|
||||
//begin global header
|
||||
|
||||
//global metadata (32 bytes)
|
||||
b"SNFB"
|
||||
u32 format_version
|
||||
u64 priming_bytes
|
||||
//how many bytes of the file must be read to guarantee all of the expected
|
||||
//format-specific metadata is available to facilitate streaming the remaining contents
|
||||
//used by the database to guarantee that it serves at least the bare minimum
|
||||
u128 resource_uuid
|
||||
//identifies the file from anywhere for any other file
|
||||
|
||||
//global block layout (variable size)
|
||||
u64 num_blocks
|
||||
for block_id in 0..num_blocks{
|
||||
u64 first_byte
|
||||
}
|
||||
|
||||
//end global header
|
||||
|
||||
//begin blocks
|
||||
|
||||
//each block is compressed with zstd or gz or something
|
||||
|
||||
*/
|
||||
|
||||
/* block types
|
||||
BLOCK_MAP_HEADER:
|
||||
DefaultStyleInfo style_info
|
||||
//bvh goes here
|
||||
u64 num_nodes
|
||||
//node 0 parent node is implied to be None
|
||||
for node_id in 1..num_nodes{
|
||||
u64 parent_node
|
||||
}
|
||||
u64 num_spacial_blocks
|
||||
for spacial_block_id in 0..num_spacial_blocks{
|
||||
u64 node_id
|
||||
u64 block_id //data block
|
||||
Aabb block_extents
|
||||
}
|
||||
//ideally spacial blocks are sorted from distance to start zone
|
||||
//texture blocks are inserted before the first spacial block they are used in
|
||||
|
||||
BLOCK_MAP_RESOURCE:
|
||||
//an individual one of the following:
|
||||
- model (IndexedModel)
|
||||
- shader (compiled SPIR-V)
|
||||
- image (JpegXL)
|
||||
- sound (Opus)
|
||||
- video (AV1)
|
||||
- animation (Trey thing)
|
||||
|
||||
BLOCK_MAP_OBJECT:
|
||||
//an individual one of the following:
|
||||
- model instance
|
||||
- located resource
|
||||
//for a list of resources, parse the object.
|
||||
//alternatively, BLOCK_MAP_REGION lists a group of objects to be decoded all at once
|
||||
|
||||
BLOCK_BOT_HEADER:
|
||||
u128 map_resource_uuid //which map is this bot running
|
||||
u128 time_resource_uuid //resource database time
|
||||
//don't include style info in bot header because it's in the physics state
|
||||
//blocks are laid out in chronological order, but indices may jump around.
|
||||
u64 num_segments
|
||||
for _ in 0..num_segments{
|
||||
i64 time //physics_state timestamp
|
||||
u64 block_id
|
||||
}
|
||||
|
||||
BLOCK_BOT_SEGMENT:
|
||||
//format version indicates what version of these structures to use
|
||||
PhysicsState physics_state
|
||||
//to read, greedily decode instructions until eof
|
||||
loop{
|
||||
//delta encode as much as possible (time,mousepos)
|
||||
//strafe ticks are implied
|
||||
//physics can be implied in an input-only bot file
|
||||
TimedInstruction<PhysicsInstruction> instruction
|
||||
}
|
||||
|
||||
BLOCK_DEMO_HEADER:
|
||||
//timeline of loading maps, player equipment, bots
|
||||
*/
|
||||
struct InputInstructionCodecState{
|
||||
mouse_pos:glam::IVec2,
|
||||
time:crate::integer::Time,
|
||||
}
|
||||
//8B - 12B
|
||||
impl InputInstructionCodecState{
|
||||
pub fn encode(&mut self,ins:&crate::instruction::TimedInstruction<crate::physics::InputInstruction>)->([u8;12],usize){
|
||||
let dt=ins.time-self.time;
|
||||
self.time=ins.time;
|
||||
let mut data=[0u8;12];
|
||||
[data[0],data[1],data[2],data[3]]=(dt.nanos() as u32).to_le_bytes();//4B
|
||||
//instruction id packed with game control parity bit. This could be 1 byte but it ruins the alignment
|
||||
[data[4],data[5],data[6],data[7]]=ins.instruction.id().to_le_bytes();//4B
|
||||
match &ins.instruction{
|
||||
&crate::physics::InputInstruction::MoveMouse(m)=>{//4B
|
||||
let dm=m-self.mouse_pos;
|
||||
[data[8],data[9]]=(dm.x as i16).to_le_bytes();
|
||||
[data[10],data[11]]=(dm.y as i16).to_le_bytes();
|
||||
self.mouse_pos=m;
|
||||
(data,12)
|
||||
},
|
||||
//0B
|
||||
crate::physics::InputInstruction::MoveRight(_)
|
||||
|crate::physics::InputInstruction::MoveUp(_)
|
||||
|crate::physics::InputInstruction::MoveBack(_)
|
||||
|crate::physics::InputInstruction::MoveLeft(_)
|
||||
|crate::physics::InputInstruction::MoveDown(_)
|
||||
|crate::physics::InputInstruction::MoveForward(_)
|
||||
|crate::physics::InputInstruction::Jump(_)
|
||||
|crate::physics::InputInstruction::Zoom(_)
|
||||
|crate::physics::InputInstruction::Reset
|
||||
|crate::physics::InputInstruction::Idle=>(data,8),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//everything must be 4 byte aligned, it's all going to be compressed so don't think too had about saving less than 4 bytes
|
||||
//TODO: Omit (mouse only?) instructions that don't surround an actual physics instruction
|
||||
fn write_input_instruction<W:std::io::Write>(state:&mut InputInstructionCodecState,w:&mut W,ins:&crate::instruction::TimedInstruction<crate::physics::InputInstruction>)->Result<usize,std::io::Error>{
|
||||
//TODO: insert idle instruction if gap is over u32 nanoseconds
|
||||
//TODO: don't write idle instructions
|
||||
//OR: end the data block! the full state at the start of the next block will contain an absolute timestamp
|
||||
let (data,size)=state.encode(ins);
|
||||
w.write(&data[0..size])//8B-12B
|
||||
}
|
8
src/sweep.rs
Normal file
8
src/sweep.rs
Normal file
@ -0,0 +1,8 @@
|
||||
|
||||
//something that implements body + hitbox + transform can predict collision
|
||||
impl crate::sweep::PredictCollision for Model {
|
||||
fn predict_collision(&self,other:&Model) -> Option<crate::event::EventStruct> {
|
||||
//math!
|
||||
None
|
||||
}
|
||||
}
|
@ -175,10 +175,10 @@ impl<'a,Task:Send+'a> INWorker<'a,Task>{
|
||||
|
||||
#[test]//How to run this test with printing: cargo test --release -- --nocapture
|
||||
fn test_worker() {
|
||||
println!("hiiiii");
|
||||
// Create the worker thread
|
||||
let test_body=crate::physics::Body::new(crate::integer::Planar64Vec3::ONE,crate::integer::Planar64Vec3::ONE,crate::integer::Planar64Vec3::ONE,crate::integer::Time::ZERO);
|
||||
let worker=QRWorker::new(crate::physics::Body::default(),
|
||||
|_|crate::physics::Body::new(crate::integer::Planar64Vec3::ONE,crate::integer::Planar64Vec3::ONE,crate::integer::Planar64Vec3::ONE,crate::integer::Time::ZERO)
|
||||
let worker=QRWorker::new(crate::physics::Body::with_pva(crate::integer::Planar64Vec3::ZERO,crate::integer::Planar64Vec3::ZERO,crate::integer::Planar64Vec3::ZERO),
|
||||
|_|crate::physics::Body::with_pva(crate::integer::Planar64Vec3::ONE,crate::integer::Planar64Vec3::ONE,crate::integer::Planar64Vec3::ONE)
|
||||
);
|
||||
|
||||
// Send tasks to the worker
|
||||
@ -194,7 +194,7 @@ fn test_worker() {
|
||||
// sender.send("STOP".to_string()).unwrap();
|
||||
|
||||
// Sleep to allow the worker thread to finish processing
|
||||
thread::sleep(std::time::Duration::from_millis(10));
|
||||
thread::sleep(std::time::Duration::from_secs(2));
|
||||
|
||||
// Send a new task
|
||||
let task = crate::instruction::TimedInstruction{
|
||||
@ -203,8 +203,8 @@ fn test_worker() {
|
||||
};
|
||||
worker.send(task).unwrap();
|
||||
|
||||
//assert_eq!(test_body,worker.grab_clone());
|
||||
println!("value={}",worker.grab_clone());
|
||||
|
||||
// wait long enough to see print from final task
|
||||
thread::sleep(std::time::Duration::from_millis(10));
|
||||
thread::sleep(std::time::Duration::from_secs(1));
|
||||
}
|
||||
|
@ -2,39 +2,32 @@
|
||||
use crate::integer::Planar64;
|
||||
|
||||
#[inline]
|
||||
pub fn zeroes2(a0:Planar64,a1:Planar64,a2:Planar64) -> Vec<Planar64>{
|
||||
pub fn zeroes2(a0:Planar64,a1:Planar64,a2:Planar64)->([Planar64;2],usize){
|
||||
if a2==Planar64::ZERO{
|
||||
return zeroes1(a0, a1);
|
||||
let ([ret],ret_len)=zeroes1(a0,a1);
|
||||
return ([ret,Planar64::ZERO],ret_len);
|
||||
}
|
||||
let radicand=a1.get() as i128*a1.get() as i128-a2.get() as i128*a0.get() as i128*4;
|
||||
if 0<radicand {
|
||||
if 0<radicand{
|
||||
//start with f64 sqrt
|
||||
//failure case: 2^63 < sqrt(2^127)
|
||||
let planar_radicand=Planar64::raw(unsafe{(radicand as f64).sqrt().to_int_unchecked()});
|
||||
//TODO: one or two newtons
|
||||
//sort roots ascending and avoid taking the difference of large numbers
|
||||
match (Planar64::ZERO<a2,Planar64::ZERO<a1){
|
||||
(true, true )=>vec![(-a1-planar_radicand)/(a2*2),(a0*2)/(-a1-planar_radicand)],
|
||||
(true, false)=>vec![(a0*2)/(-a1+planar_radicand),(-a1+planar_radicand)/(a2*2)],
|
||||
(false,true )=>vec![(a0*2)/(-a1-planar_radicand),(-a1-planar_radicand)/(a2*2)],
|
||||
(false,false)=>vec![(-a1+planar_radicand)/(a2*2),(a0*2)/(-a1+planar_radicand)],
|
||||
if Planar64::ZERO<a2{
|
||||
([(-a1-planar_radicand)/(a2*2),(-a1+planar_radicand)/(a2*2)],2)
|
||||
}else{
|
||||
([(-a1+planar_radicand)/(a2*2),(-a1-planar_radicand)/(a2*2)],2)
|
||||
}
|
||||
} else if radicand==0 {
|
||||
return vec![a1/(a2*-2)];
|
||||
} else {
|
||||
return vec![];
|
||||
}else if radicand==0{
|
||||
([a1/(a2*-2),Planar64::ZERO],1)
|
||||
}else{
|
||||
([Planar64::ZERO,Planar64::ZERO],0)
|
||||
}
|
||||
}
|
||||
#[inline]
|
||||
pub fn zeroes1(a0:Planar64,a1:Planar64) -> Vec<Planar64> {
|
||||
pub fn zeroes1(a0:Planar64,a1:Planar64)->([Planar64;1],usize){
|
||||
if a1==Planar64::ZERO{
|
||||
return vec![];
|
||||
return ([Planar64::ZERO],0);
|
||||
}else{
|
||||
let q=((-a0.get() as i128)<<32)/(a1.get() as i128);
|
||||
if i64::MIN as i128<=q&&q<=i64::MAX as i128{
|
||||
return vec![Planar64::raw(q as i64)];
|
||||
}else{
|
||||
return vec![];
|
||||
}
|
||||
return ([-a0/a1],1);
|
||||
}
|
||||
}
|
@ -1 +0,0 @@
|
||||
mangohud ../target/release/strafe-client bhop_maps/5692113331.rbxm
|
@ -1 +0,0 @@
|
||||
/run/media/quat/Files/Documents/map-files/verify-scripts/maps/bhop_all/
|
@ -1 +0,0 @@
|
||||
cargo build --release --target x86_64-pc-windows-gnu
|
@ -1,4 +0,0 @@
|
||||
mkdir -p ../target/demo
|
||||
mv ../target/x86_64-pc-windows-gnu/release/strafe-client.exe ../target/demo/strafe-client.exe
|
||||
rm ../target/demo.7z
|
||||
7z a -t7z -mx=9 -mfb=273 -ms -md=31 -myx=9 -mtm=- -mmt -mmtf -md=1536m -mmf=bt3 -mmc=10000 -mpb=0 -mlc=0 ../target/demo.7z ../target/demo
|
@ -1 +0,0 @@
|
||||
mangohud ../target/release/strafe-client "$1"
|
@ -1,4 +0,0 @@
|
||||
[camera]
|
||||
sensitivity_x=98384
|
||||
fov_y=1.0
|
||||
#fov_x_from_y_ratio=1.33333333333333333333333333333333
|
@ -1 +0,0 @@
|
||||
/run/media/quat/Files/Documents/map-files/verify-scripts/maps/surf_all/
|
@ -1 +0,0 @@
|
||||
/run/media/quat/Files/Documents/map-files/verify-scripts/textures/dds/
|
@ -1 +0,0 @@
|
||||
mangohud ../target/release/strafe-client bhop_maps/5692152916.rbxm
|
@ -1 +0,0 @@
|
||||
mangohud ../target/release/strafe-client surf_maps/5692145408.rbxm
|
Reference in New Issue
Block a user