Compare commits

..

6 Commits

Author SHA1 Message Date
91f8652ece fix fix 2023-10-26 20:24:43 -07:00
0ec0d24302 the goober 2023-10-26 20:20:12 -07:00
f7ee18076a iter wrong code but it has no red squiggle 2023-10-26 20:16:45 -07:00
ee7df7787a stack :( 2023-10-26 20:01:26 -07:00
db5f4e1da3 fix usage 2023-10-26 20:01:26 -07:00
01a8efe4d4 return fixed length array and len to avoid heap allocation 2023-10-26 19:51:14 -07:00
24 changed files with 612 additions and 720 deletions

548
Cargo.lock generated

File diff suppressed because it is too large Load Diff

@ -18,7 +18,7 @@ rbx_binary = "0.7.1"
rbx_dom_weak = "2.5.0" rbx_dom_weak = "2.5.0"
rbx_reflection_database = "0.2.7" rbx_reflection_database = "0.2.7"
rbx_xml = "0.13.1" rbx_xml = "0.13.1"
wgpu = "0.18.0" wgpu = "0.17.0"
winit = { version = "0.29.2", features = ["rwh_05"] } winit = { version = "0.29.2", features = ["rwh_05"] }
#[profile.release] #[profile.release]

@ -9,34 +9,22 @@ use crate::aabb::Aabb;
//start with bisection into octrees because a bad bvh is still 1000x better than no bvh //start with bisection into octrees because a bad bvh is still 1000x better than no bvh
//sort the centerpoints on each axis (3 lists) //sort the centerpoints on each axis (3 lists)
//bv is put into octant based on whether it is upper or lower in each list //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)] #[derive(Default)]
pub struct BvhNode{ pub struct BvhNode{
content:BvhNodeContent, children:Vec<Self>,
models:Vec<usize>,
aabb:Aabb, aabb:Aabb,
} }
impl BvhNode{ impl BvhNode{
pub fn the_tester<F:FnMut(usize)>(&self,aabb:&Aabb,f:&mut F){ pub fn the_tester<F:FnMut(usize)>(&self,aabb:&Aabb,f:&mut F){
match &self.content{ for &model in &self.models{
&BvhNodeContent::Leaf(model)=>f(model), f(model);
BvhNodeContent::Branch(children)=>for child in children{ }
//this test could be moved outside the match statement for child in &self.children{
//but that would test the root node aabb if aabb.intersects(&child.aabb){
//you're probably not going to spend a lot of time outside the map, child.the_tester(aabb,f);
//so the test is extra work for nothing }
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(); let n=boxen.len();
if n<20{ if n<20{
let mut aabb=Aabb::default(); let mut aabb=Aabb::default();
let nodes=boxen.into_iter().map(|b|{ let models=boxen.into_iter().map(|b|{aabb.join(&b.1);b.0}).collect();
aabb.join(&b.1);
BvhNode{
content:BvhNodeContent::Leaf(b.0),
aabb:b.1,
}
}).collect();
BvhNode{ BvhNode{
content:BvhNodeContent::Branch(nodes), children:Vec::new(),
models,
aabb, aabb,
} }
}else{ }else{
@ -116,7 +99,8 @@ fn generate_bvh_node(boxen:Vec<(usize,Aabb)>)->BvhNode{
node node
}).collect(); }).collect();
BvhNode{ BvhNode{
content:BvhNodeContent::Branch(children), children,
models:Vec::new(),
aabb, aabb,
} }
} }

@ -3,11 +3,11 @@ pub type INWorker<'a,Task>=CompatNWorker<'a,Task>;
pub struct CompatNWorker<'a,Task>{ pub struct CompatNWorker<'a,Task>{
data:std::marker::PhantomData<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>{ 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{ Self{
data:std::marker::PhantomData, data:std::marker::PhantomData,
f:Box::new(f), f:Box::new(f),

@ -1,38 +1,24 @@
use std::borrow::Cow; use std::borrow::Cow;
use wgpu::{util::DeviceExt,AstcBlock,AstcChannel}; 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)] #[derive(Clone)]
pub struct GraphicsModelUpdate{ pub struct ModelUpdate{
transform:Option<glam::Mat4>, transform:Option<glam::Mat4>,
color:Option<glam::Vec4>, color:Option<glam::Vec4>,
} }
struct Entity{ struct Entity {
index_count:u32, index_count: u32,
index_buf:wgpu::Buffer, 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 GraphicsModel{ struct ModelGraphics {
entities:Vec<Entity>, instances: Vec<ModelGraphicsInstance>,
model_buf:wgpu::Buffer, vertex_buf: wgpu::Buffer,
vertex_buf:wgpu::Buffer, entities: Vec<Entity>,
bind_group:wgpu::BindGroup, bind_group: wgpu::BindGroup,
index_format:wgpu::IndexFormat, model_buf: wgpu::Buffer,
instances:Vec<GraphicsModelInstance>,
} }
pub struct GraphicsSamplers{ 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{ impl GraphicsCamera{
pub fn new(screen_size:glam::UVec2,fov:glam::Vec2)->Self{
Self{
screen_size,
fov,
}
}
pub fn proj(&self)->glam::Mat4{ pub fn proj(&self)->glam::Mat4{
perspective_rh(self.fov.x, self.fov.y, 0.5, 2000.0) perspective_rh(self.fov.x, self.fov.y, 0.5, 2000.0)
} }
@ -110,7 +102,7 @@ pub struct GraphicsState{
camera:GraphicsCamera, camera:GraphicsCamera,
camera_buf: wgpu::Buffer, camera_buf: wgpu::Buffer,
temp_squid_texture_view: wgpu::TextureView, temp_squid_texture_view: wgpu::TextureView,
models: Vec<GraphicsModel>, models: Vec<ModelGraphics>,
depth_view: wgpu::TextureView, depth_view: wgpu::TextureView,
staging_belt: wgpu::util::StagingBelt, staging_belt: wgpu::util::StagingBelt,
} }
@ -214,15 +206,15 @@ impl GraphicsState{
let indexed_models_len=indexed_models.models.len(); let indexed_models_len=indexed_models.models.len();
let mut unique_texture_models=Vec::with_capacity(indexed_models_len); let mut unique_texture_models=Vec::with_capacity(indexed_models_len);
for model in indexed_models.models.into_iter(){ for model in indexed_models.models.into_iter(){
//convert ModelInstance into GraphicsModelInstance //convert ModelInstance into ModelGraphicsInstance
let instances:Vec<GraphicsModelInstance>=model.instances.into_iter().filter_map(|instance|{ let instances:Vec<ModelGraphicsInstance>=model.instances.into_iter().filter_map(|instance|{
if instance.color.w==0.0{ if instance.color.w==0.0{
None None
}else{ }else{
Some(GraphicsModelInstance{ Some(ModelGraphicsInstance{
transform: instance.transform.into(), transform: instance.transform.into(),
normal_transform: Into::<glam::Mat3>::into(instance.transform.matrix3).inverse().transpose(), normal_transform: Into::<glam::Mat3>::into(instance.transform.matrix3).inverse().transpose(),
color:GraphicsModelColor4::from(instance.color), color:ModelGraphicsColor4::from(instance.color),
}) })
} }
}).collect(); }).collect();
@ -241,7 +233,7 @@ impl GraphicsState{
//create new texture_index //create new texture_index
let texture_index=unique_textures.len(); let texture_index=unique_textures.len();
unique_textures.push(group.texture); 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_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_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(), 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 //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 map_vertex_id:Vec<u32>=model.unique_vertices.iter().map(|unmapped_vertex|{
let vertex=crate::model::IndexedVertex{ let vertex=crate::model::IndexedVertex{
pos:map_pos_id[unmapped_vertex.pos as usize], pos:map_pos_id[unmapped_vertex.pos as usize] as u32,
tex:map_tex_id[unmapped_vertex.tex as usize], tex:map_tex_id[unmapped_vertex.tex as usize] as u32,
normal:map_normal_id[unmapped_vertex.normal as usize], normal:map_normal_id[unmapped_vertex.normal as usize] as u32,
color:map_color_id[unmapped_vertex.color as usize], color:map_color_id[unmapped_vertex.color as usize] as u32,
}; };
(if let Some(&vertex_id)=vertex_id_from.get(&vertex){ (if let Some(&vertex_id)=vertex_id_from.get(&vertex){
vertex_id vertex_id
@ -396,7 +388,7 @@ impl GraphicsState{
} }
} }
//push model into dedup //push model into dedup
deduplicated_models.push(IndexedGraphicsModelSingleTexture{ deduplicated_models.push(IndexedModelGraphicsSingleTexture{
unique_pos, unique_pos,
unique_tex, unique_tex,
unique_normal, unique_normal,
@ -406,7 +398,7 @@ impl GraphicsState{
groups:vec![IndexedGroupFixedTexture{ groups:vec![IndexedGroupFixedTexture{
polys polys
}], }],
instances:vec![GraphicsModelInstance{ instances:vec![ModelGraphicsInstance{
transform:glam::Mat4::IDENTITY, transform:glam::Mat4::IDENTITY,
normal_transform:glam::Mat3::IDENTITY, normal_transform:glam::Mat3::IDENTITY,
color color
@ -424,9 +416,10 @@ impl GraphicsState{
//de-index models //de-index models
let deduplicated_models_len=deduplicated_models.len(); 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 vertices = Vec::new();
let mut index_from_vertex = std::collections::HashMap::new();//::<IndexedVertex,usize> 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 //this mut be combined in a more complex way if the models use different render patterns per group
let mut indices = Vec::new(); let mut indices = Vec::new();
for group in model.groups { for group in model.groups {
@ -437,7 +430,7 @@ impl GraphicsState{
if let Some(&i)=index_from_vertex.get(&vertex_index){ if let Some(&i)=index_from_vertex.get(&vertex_index){
indices.push(i); indices.push(i);
}else{ }else{
let i=vertices.len(); let i=vertices.len() as u16;
let vertex=&model.unique_vertices[vertex_index as usize]; let vertex=&model.unique_vertices[vertex_index as usize];
vertices.push(GraphicsVertex{ vertices.push(GraphicsVertex{
pos: model.unique_pos[vertex.pos as usize], pos: model.unique_pos[vertex.pos as usize],
@ -452,16 +445,11 @@ impl GraphicsState{
} }
} }
} }
GraphicsModelSingleTexture{ entities.push(indices);
ModelGraphicsSingleTexture{
instances:model.instances, 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, vertices,
entities,
texture:model.texture, texture:model.texture,
} }
}).collect(); }).collect();
@ -514,17 +502,20 @@ impl GraphicsState{
usage: wgpu::BufferUsages::VERTEX, usage: wgpu::BufferUsages::VERTEX,
}); });
//all of these are being moved here //all of these are being moved here
self.models.push(GraphicsModel{ self.models.push(ModelGraphics{
instances:instances_chunk.to_vec(), instances:instances_chunk.to_vec(),
vertex_buf, vertex_buf,
index_format:match &model.entities{ entities: model.entities.iter().map(|indices|{
crate::model_graphics::Entities::U32(_)=>wgpu::IndexFormat::Uint32, let index_buf = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
crate::model_graphics::Entities::U16(_)=>wgpu::IndexFormat::Uint16, label: Some("Index"),
}, contents: bytemuck::cast_slice(&indices),
entities:match &model.entities{ usage: wgpu::BufferUsages::INDEX,
crate::model_graphics::Entities::U32(entities)=>create_entities(device,entities), });
crate::model_graphics::Entities::U16(entities)=>create_entities(device,entities), Entity {
}, index_buf,
index_count: indices.len() as u32,
}
}).collect(),
bind_group: model_bind_group, bind_group: model_bind_group,
model_buf, model_buf,
}); });
@ -944,19 +935,17 @@ impl GraphicsState{
b: 0.3, b: 0.3,
a: 1.0, a: 1.0,
}), }),
store:wgpu::StoreOp::Store, store: true,
}, },
})], })],
depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment { depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
view: &self.depth_view, view: &self.depth_view,
depth_ops: Some(wgpu::Operations { depth_ops: Some(wgpu::Operations {
load: wgpu::LoadOp::Clear(1.0), load: wgpu::LoadOp::Clear(1.0),
store:wgpu::StoreOp::Discard, store: false,
}), }),
stencil_ops: None, stencil_ops: None,
}), }),
timestamp_writes:Default::default(),
occlusion_query_set:Default::default(),
}); });
rpass.set_bind_group(0, &self.bind_groups.camera, &[]); rpass.set_bind_group(0, &self.bind_groups.camera, &[]);
@ -967,9 +956,9 @@ impl GraphicsState{
rpass.set_bind_group(2, &model.bind_group, &[]); rpass.set_bind_group(2, &model.bind_group, &[]);
rpass.set_vertex_buffer(0, model.vertex_buf.slice(..)); rpass.set_vertex_buffer(0, model.vertex_buf.slice(..));
for entity in model.entities.iter(){ for entity in model.entities.iter() {
rpass.set_index_buffer(entity.index_buf.slice(..),model.index_format); 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); rpass.draw_indexed(0..entity.index_count, 0, 0..model.instances.len() as u32);
} }
} }
@ -984,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:usize=4*4 + 12 + 4;//let size=std::mem::size_of::<ModelInstance>();
const MODEL_BUFFER_SIZE_BYTES:usize=MODEL_BUFFER_SIZE*4; 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()); let mut raw = Vec::with_capacity(MODEL_BUFFER_SIZE*instances.len());
for (i,mi) in instances.iter().enumerate(){ for (i,mi) in instances.iter().enumerate(){
let mut v = raw.split_off(MODEL_BUFFER_SIZE*i); let mut v = raw.split_off(MODEL_BUFFER_SIZE*i);
//model transform //model transform
raw.extend_from_slice(&AsRef::<[f32; 4*4]>::as_ref(&mi.transform)[..]); raw.extend_from_slice(&AsRef::<[f32; 4*4]>::as_ref(&mi.transform)[..]);
//normal transform //normal transform
raw.extend_from_slice(AsRef::<[f32; 3]>::as_ref(&mi.normal_transform.x_axis)); raw.extend_from_slice(AsRef::<[f32; 3]>::as_ref(&mi.normal_transform.x_axis));
raw.extend_from_slice(&[0.0]); raw.extend_from_slice(&[0.0]);
raw.extend_from_slice(AsRef::<[f32; 3]>::as_ref(&mi.normal_transform.y_axis)); raw.extend_from_slice(AsRef::<[f32; 3]>::as_ref(&mi.normal_transform.y_axis));
raw.extend_from_slice(&[0.0]); raw.extend_from_slice(&[0.0]);
raw.extend_from_slice(AsRef::<[f32; 3]>::as_ref(&mi.normal_transform.z_axis)); raw.extend_from_slice(AsRef::<[f32; 3]>::as_ref(&mi.normal_transform.z_axis));
raw.extend_from_slice(&[0.0]); raw.extend_from_slice(&[0.0]);
//color //color
raw.extend_from_slice(AsRef::<[f32; 4]>::as_ref(&mi.color.get())); raw.extend_from_slice(AsRef::<[f32; 4]>::as_ref(&mi.color.get()));
raw.append(&mut v); raw.append(&mut v);
} }
raw raw
} }

@ -1,6 +1,6 @@
pub enum Instruction{ pub enum Instruction{
Render(crate::physics::PhysicsOutputState,crate::integer::Time,glam::IVec2), 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), Resize(winit::dpi::PhysicalSize<u32>,crate::settings::UserSettings),
GenerateModels(crate::model::IndexedModelInstances), GenerateModels(crate::model::IndexedModelInstances),
ClearModels, ClearModels,
@ -16,15 +16,13 @@ WorkerDescription{
//up to three frames in flight, dropping new frame requests when all three are busy, and dropping output frames when one renders out of order //up to three frames in flight, dropping new frame requests when all three are busy, and dropping output frames when one renders out of order
pub fn new<'a>( pub fn new<'a>(
scope:&'a std::thread::Scope<'a,'_>,
mut graphics:crate::graphics::GraphicsState, mut graphics:crate::graphics::GraphicsState,
mut config:wgpu::SurfaceConfiguration, mut config:wgpu::SurfaceConfiguration,
surface:wgpu::Surface, surface:wgpu::Surface,
device:wgpu::Device, device:wgpu::Device,
queue:wgpu::Queue, queue:wgpu::Queue,
)->crate::worker::INWorker<'a,Instruction>{ )->crate::compat_worker::INWorker<'a,Instruction>{
let mut resize=None; crate::compat_worker::INWorker::new(move |ins:Instruction|{
crate::worker::INWorker::new(scope,move |ins:Instruction|{
match ins{ match ins{
Instruction::GenerateModels(indexed_model_instances)=>{ Instruction::GenerateModels(indexed_model_instances)=>{
graphics.generate_models(&device,&queue,indexed_model_instances); graphics.generate_models(&device,&queue,indexed_model_instances);
@ -33,20 +31,13 @@ pub fn new<'a>(
graphics.clear(); graphics.clear();
}, },
Instruction::Resize(size,user_settings)=>{ 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)=>{ 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 //this has to go deeper somehow
let frame=match surface.get_current_texture(){ let frame=match surface.get_current_texture(){
Ok(frame)=>frame, Ok(frame)=>frame,
@ -68,4 +59,4 @@ pub fn new<'a>(
} }
} }
}) })
} }

@ -315,8 +315,8 @@ impl Angle32{
pub fn clamp(&self,theta_min:Self,theta_max:Self)->Self{ pub fn clamp(&self,theta_min:Self,theta_max:Self)->Self{
//((max-min as u32)/2 as i32)+min //((max-min as u32)/2 as i32)+min
let midpoint=(( let midpoint=((
(theta_max.0 as u32) u32::from_ne_bytes(theta_max.0.to_ne_bytes())
.wrapping_sub(theta_min.0 as u32) .wrapping_sub(u32::from_ne_bytes(theta_min.0.to_ne_bytes()))
/2 /2
) as i32)//(u32::MAX/2) as i32 ALWAYS works ) as i32)//(u32::MAX/2) as i32 ALWAYS works
.wrapping_add(theta_min.0); .wrapping_add(theta_min.0);

@ -52,7 +52,6 @@ fn get_attributes(name:&str,can_collide:bool,velocity:Planar64Vec3,force_interse
force_can_collide=false; force_can_collide=false;
general.accelerator=Some(crate::model::GameMechanicAccelerator{acceleration:velocity}); general.accelerator=Some(crate::model::GameMechanicAccelerator{acceleration:velocity});
}, },
"UnorderedCheckpoint"=>general.checkpoint=Some(crate::model::GameMechanicCheckpoint::Unordered{mode_id:0}),
"SetVelocity"=>general.trajectory=Some(crate::model::GameMechanicSetTrajectory::Velocity(velocity)), "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})}, "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})}, "MapAnticheat"=>{force_can_collide=false;general.zone=Some(crate::model::GameMechanicZone{mode_id:0,behaviour:crate::model::ZoneBehaviour::Anitcheat})},
@ -111,12 +110,6 @@ fn get_attributes(name:&str,can_collide:bool,velocity:Planar64Vec3,force_interse
"WormholeIn"=>general.teleport_behaviour=Some(crate::model::TeleportBehaviour::Wormhole(crate::model::GameMechanicWormhole{destination_model_id:captures[2].parse::<u32>().unwrap()})), "WormholeIn"=>general.teleport_behaviour=Some(crate::model::TeleportBehaviour::Wormhole(crate::model::GameMechanicWormhole{destination_model_id:captures[2].parse::<u32>().unwrap()})),
_=>panic!("regex3[1] messed up bad"), _=>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"),
}
} }
} }
} }
@ -217,9 +210,9 @@ type RobloxWedgeDescription=[Option<RobloxFaceTextureDescription>;5];
type RobloxCornerWedgeDescription=[Option<RobloxFaceTextureDescription>;5]; type RobloxCornerWedgeDescription=[Option<RobloxFaceTextureDescription>;5];
#[derive(Clone,Eq,Hash,PartialEq)] #[derive(Clone,Eq,Hash,PartialEq)]
enum RobloxBasePartDescription{ enum RobloxBasePartDescription{
Sphere(RobloxPartDescription), Sphere,
Part(RobloxPartDescription), Part(RobloxPartDescription),
Cylinder(RobloxPartDescription), Cylinder,
Wedge(RobloxWedgeDescription), Wedge(RobloxWedgeDescription),
CornerWedge(RobloxCornerWedgeDescription), CornerWedge(RobloxCornerWedgeDescription),
} }
@ -264,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; spawn_point=model_transform.transform_point3(Planar64Vec3::ZERO)+Planar64Vec3::Y*5/2;
Some(crate::model::TempIndexedAttributes::Start(crate::model::TempAttrStart{mode_id:0})) Some(crate::model::TempIndexedAttributes::Start(crate::model::TempAttrStart{mode_id:0}))
}, },
"UnorderedCheckpoint"=>Some(crate::model::TempIndexedAttributes::UnorderedCheckpoint(crate::model::TempAttrUnorderedCheckpoint{mode_id:0})),
other=>{ 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) { if let Some(captures) = regman.captures(other) {
match &captures[1]{ match &captures[1]{
"BonusStart"=>Some(crate::model::TempIndexedAttributes::Start(crate::model::TempAttrStart{mode_id:captures[2].parse::<u32>().unwrap()})), "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()})), "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()})), "WormholeOut"=>Some(crate::model::TempIndexedAttributes::Wormhole(crate::model::TempAttrWormhole{wormhole_id:captures[2].parse::<u32>().unwrap()})),
_=>None, _=>None,
} }
@ -298,7 +293,6 @@ pub fn generate_indexed_models(dom:rbx_dom_weak::WeakDom) -> crate::model::Index
panic!("Part has no Shape!"); panic!("Part has no Shape!");
} }
}, },
"TrussPart"=>primitives::Primitives::Cube,
"WedgePart"=>primitives::Primitives::Wedge, "WedgePart"=>primitives::Primitives::Wedge,
"CornerWedgePart"=>primitives::Primitives::CornerWedge, "CornerWedgePart"=>primitives::Primitives::CornerWedge,
_=>{ _=>{
@ -393,9 +387,9 @@ pub fn generate_indexed_models(dom:rbx_dom_weak::WeakDom) -> crate::model::Index
f5,//Cube::Front f5,//Cube::Front
]=part_texture_description; ]=part_texture_description;
let basepart_texture_description=match shape{ 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::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 //use front face texture first and use top face texture as a fallback
primitives::Primitives::Wedge=>RobloxBasePartDescription::Wedge([ primitives::Primitives::Wedge=>RobloxBasePartDescription::Wedge([
f0,//Cube::Right->Wedge::Right f0,//Cube::Right->Wedge::Right
@ -421,10 +415,9 @@ pub fn generate_indexed_models(dom:rbx_dom_weak::WeakDom) -> crate::model::Index
let model_id=indexed_models.len(); let model_id=indexed_models.len();
model_id_from_description.insert(basepart_texture_description.clone(),model_id);//borrow checker going crazy model_id_from_description.insert(basepart_texture_description.clone(),model_id);//borrow checker going crazy
indexed_models.push(match basepart_texture_description{ indexed_models.push(match basepart_texture_description{
RobloxBasePartDescription::Sphere(part_texture_description) RobloxBasePartDescription::Sphere=>primitives::unit_sphere(),
|RobloxBasePartDescription::Cylinder(part_texture_description) RobloxBasePartDescription::Part(part_texture_description)=>{
|RobloxBasePartDescription::Part(part_texture_description)=>{ let mut cube_face_description=primitives::CubeFaceDescription::new();
let mut cube_face_description=primitives::CubeFaceDescription::default();
for (face_id,roblox_face_description) in part_texture_description.iter().enumerate(){ for (face_id,roblox_face_description) in part_texture_description.iter().enumerate(){
cube_face_description.insert( cube_face_description.insert(
match face_id{ match face_id{
@ -443,8 +436,9 @@ pub fn generate_indexed_models(dom:rbx_dom_weak::WeakDom) -> crate::model::Index
} }
primitives::generate_partial_unit_cube(cube_face_description) primitives::generate_partial_unit_cube(cube_face_description)
}, },
RobloxBasePartDescription::Cylinder=>primitives::unit_cylinder(),
RobloxBasePartDescription::Wedge(wedge_texture_description)=>{ 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(){ for (face_id,roblox_face_description) in wedge_texture_description.iter().enumerate(){
wedge_face_description.insert( wedge_face_description.insert(
match face_id{ match face_id{
@ -463,7 +457,7 @@ pub fn generate_indexed_models(dom:rbx_dom_weak::WeakDom) -> crate::model::Index
primitives::generate_partial_unit_wedge(wedge_face_description) primitives::generate_partial_unit_wedge(wedge_face_description)
}, },
RobloxBasePartDescription::CornerWedge(cornerwedge_texture_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(){ for (face_id,roblox_face_description) in cornerwedge_texture_description.iter().enumerate(){
cornerwedge_face_description.insert( cornerwedge_face_description.insert(
match face_id{ match face_id{

@ -50,10 +50,10 @@ pub struct IndexedModelInstances{
} }
//stage description referencing flattened ids is spooky, but the map loading is meant to be deterministic. //stage description referencing flattened ids is spooky, but the map loading is meant to be deterministic.
pub struct ModeDescription{ pub struct ModeDescription{
//TODO: put "default" style modifiers in mode
//pub style:StyleModifiers,
pub start:usize,//start=model_id pub start:usize,//start=model_id
pub spawns:Vec<usize>,//spawns[spawn_id]=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 spawn_from_stage_id:std::collections::HashMap::<u32,usize>,
pub ordered_checkpoint_from_checkpoint_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>{ pub fn get_spawn_model_id(&self,stage_id:u32)->Option<&usize>{
self.spawns.get(*self.spawn_from_stage_id.get(&stage_id)?) 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! //I don't want this code to exist!
#[derive(Clone)] #[derive(Clone)]
@ -73,12 +76,23 @@ pub struct TempAttrSpawn{
pub stage_id:u32, pub stage_id:u32,
} }
#[derive(Clone)] #[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 struct TempAttrWormhole{
pub wormhole_id:u32, pub wormhole_id:u32,
} }
pub enum TempIndexedAttributes{ pub enum TempIndexedAttributes{
Start(TempAttrStart), Start(TempAttrStart),
Spawn(TempAttrSpawn), Spawn(TempAttrSpawn),
OrderedCheckpoint(TempAttrOrderedCheckpoint),
UnorderedCheckpoint(TempAttrUnorderedCheckpoint),
Wormhole(TempAttrWormhole), Wormhole(TempAttrWormhole),
} }
@ -112,16 +126,6 @@ pub enum GameMechanicBooster{
Energy{direction:Planar64Vec3,energy:Planar64},//increase energy in direction Energy{direction:Planar64Vec3,energy:Planar64},//increase energy in direction
} }
#[derive(Clone)] #[derive(Clone)]
pub enum GameMechanicCheckpoint{
Ordered{
mode_id:u32,
checkpoint_id:u32,
},
Unordered{
mode_id:u32,
},
}
#[derive(Clone)]
pub enum TrajectoryChoice{ pub enum TrajectoryChoice{
HighArcLongDuration,//underhand lob at target: less horizontal speed and more air time HighArcLongDuration,//underhand lob at target: less horizontal speed and more air time
LowArcShortDuration,//overhand throw at target: more horizontal speed and less air time LowArcShortDuration,//overhand throw at target: more horizontal speed and less air time
@ -167,13 +171,6 @@ pub enum StageElementBehaviour{
Trigger, Trigger,
Teleport, Teleport,
Platform, Platform,
//Acts like a trigger if you haven't hit all the checkpoints.
Checkpoint{
//if this is 2 you must have hit OrderedCheckpoint(0) OrderedCheckpoint(1) OrderedCheckpoint(2) to pass
ordered_checkpoint_id:Option<u32>,
//if this is 2 you must have hit at least 2 UnorderedCheckpoints to pass
unordered_checkpoint_count:u32,
},
JumpLimit(u32), JumpLimit(u32),
//Speedtrap(TrapCondition),//Acts as a trigger with a speed condition //Speedtrap(TrapCondition),//Acts as a trigger with a speed condition
} }
@ -202,17 +199,15 @@ pub enum TeleportBehaviour{
pub struct GameMechanicAttributes{ pub struct GameMechanicAttributes{
pub zone:Option<GameMechanicZone>, pub zone:Option<GameMechanicZone>,
pub booster:Option<GameMechanicBooster>, pub booster:Option<GameMechanicBooster>,
pub checkpoint:Option<GameMechanicCheckpoint>,
pub trajectory:Option<GameMechanicSetTrajectory>, pub trajectory:Option<GameMechanicSetTrajectory>,
pub teleport_behaviour:Option<TeleportBehaviour>, pub teleport_behaviour:Option<TeleportBehaviour>,
pub accelerator:Option<GameMechanicAccelerator>, pub accelerator:Option<GameMechanicAccelerator>,
} }
impl GameMechanicAttributes{ impl GameMechanicAttributes{
pub fn any(&self)->bool{ pub fn any(&self)->bool{
self.zone.is_some() self.booster.is_some()
||self.booster.is_some()
||self.checkpoint.is_some()
||self.trajectory.is_some() ||self.trajectory.is_some()
||self.zone.is_some()
||self.teleport_behaviour.is_some() ||self.teleport_behaviour.is_some()
||self.accelerator.is_some() ||self.accelerator.is_some()
} }

@ -11,7 +11,7 @@ pub struct GraphicsVertex {
pub struct IndexedGroupFixedTexture{ pub struct IndexedGroupFixedTexture{
pub polys:Vec<IndexedPolygon>, pub polys:Vec<IndexedPolygon>,
} }
pub struct IndexedGraphicsModelSingleTexture{ pub struct IndexedModelGraphicsSingleTexture{
pub unique_pos:Vec<[f32; 3]>, pub unique_pos:Vec<[f32; 3]>,
pub unique_tex:Vec<[f32; 2]>, pub unique_tex:Vec<[f32; 2]>,
pub unique_normal:Vec<[f32; 3]>, pub unique_normal:Vec<[f32; 3]>,
@ -19,41 +19,37 @@ pub struct IndexedGraphicsModelSingleTexture{
pub unique_vertices:Vec<IndexedVertex>, pub unique_vertices:Vec<IndexedVertex>,
pub texture:Option<u32>,//RenderPattern? material/texture/shader/flat color pub texture:Option<u32>,//RenderPattern? material/texture/shader/flat color
pub groups: Vec<IndexedGroupFixedTexture>, pub groups: Vec<IndexedGroupFixedTexture>,
pub instances:Vec<GraphicsModelInstance>, pub instances:Vec<ModelGraphicsInstance>,
} }
pub enum Entities{ pub struct ModelGraphicsSingleTexture{
U32(Vec<Vec<u32>>), pub instances: Vec<ModelGraphicsInstance>,
U16(Vec<Vec<u16>>), pub vertices: Vec<GraphicsVertex>,
} pub entities: Vec<Vec<u16>>,
pub struct GraphicsModelSingleTexture{ pub texture: Option<u32>,
pub instances:Vec<GraphicsModelInstance>,
pub vertices:Vec<GraphicsVertex>,
pub entities:Entities,
pub texture:Option<u32>,
} }
#[derive(Clone,PartialEq)] #[derive(Clone,PartialEq)]
pub struct GraphicsModelColor4(glam::Vec4); pub struct ModelGraphicsColor4(glam::Vec4);
impl GraphicsModelColor4{ impl ModelGraphicsColor4{
pub const fn get(&self)->glam::Vec4{ pub const fn get(&self)->glam::Vec4{
self.0 self.0
} }
} }
impl From<glam::Vec4> for GraphicsModelColor4{ impl From<glam::Vec4> for ModelGraphicsColor4{
fn from(value:glam::Vec4)->Self{ fn from(value:glam::Vec4)->Self{
Self(value) Self(value)
} }
} }
impl std::hash::Hash for GraphicsModelColor4{ impl std::hash::Hash for ModelGraphicsColor4{
fn hash<H: std::hash::Hasher>(&self,state:&mut H) { fn hash<H: std::hash::Hasher>(&self,state:&mut H) {
for &f in self.0.as_ref(){ for &f in self.0.as_ref(){
bytemuck::cast::<f32,u32>(f).hash(state); bytemuck::cast::<f32,u32>(f).hash(state);
} }
} }
} }
impl Eq for GraphicsModelColor4{} impl Eq for ModelGraphicsColor4{}
#[derive(Clone)] #[derive(Clone)]
pub struct GraphicsModelInstance{ pub struct ModelGraphicsInstance{
pub transform:glam::Mat4, pub transform:glam::Mat4,
pub normal_transform:glam::Mat3, pub normal_transform:glam::Mat3,
pub color:GraphicsModelColor4, pub color:ModelGraphicsColor4,
} }

@ -155,7 +155,7 @@ impl Default for Modes{
} }
struct PhysicsModels{ struct PhysicsModels{
models:Vec<PhysicsModel>, models:Vec<ModelPhysics>,
model_id_from_wormhole_id:std::collections::HashMap::<u32,usize>, model_id_from_wormhole_id:std::collections::HashMap::<u32,usize>,
} }
impl PhysicsModels{ impl PhysicsModels{
@ -163,13 +163,13 @@ impl PhysicsModels{
self.models.clear(); self.models.clear();
self.model_id_from_wormhole_id.clear(); self.model_id_from_wormhole_id.clear();
} }
fn get(&self,i:usize)->Option<&PhysicsModel>{ fn get(&self,i:usize)->Option<&ModelPhysics>{
self.models.get(i) self.models.get(i)
} }
fn get_wormhole_model(&self,wormhole_id:u32)->Option<&PhysicsModel>{ fn get_wormhole_model(&self,wormhole_id:u32)->Option<&ModelPhysics>{
self.models.get(*self.model_id_from_wormhole_id.get(&wormhole_id)?) self.models.get(*self.model_id_from_wormhole_id.get(&wormhole_id)?)
} }
fn push(&mut self,model:PhysicsModel)->usize{ fn push(&mut self,model:ModelPhysics)->usize{
let model_id=self.models.len(); let model_id=self.models.len();
self.models.push(model); self.models.push(model);
model_id model_id
@ -185,7 +185,8 @@ impl Default for PhysicsModels{
} }
#[derive(Clone)] #[derive(Clone)]
pub struct PhysicsCamera{ pub struct PhysicsCamera {
offset: Planar64Vec3,
//punch: Planar64Vec3, //punch: Planar64Vec3,
//punch_velocity: Planar64Vec3, //punch_velocity: Planar64Vec3,
sensitivity:Ratio64Vec2,//dots to Angle32 ratios sensitivity:Ratio64Vec2,//dots to Angle32 ratios
@ -203,6 +204,16 @@ pub struct PhysicsCamera{
} }
impl PhysicsCamera { impl PhysicsCamera {
pub fn from_offset(offset:Planar64Vec3) -> Self {
Self{
offset,
sensitivity:Ratio64Vec2::ONE*200_000,
mouse:MouseState::default(),//t=0 does not cause divide by zero because it's immediately replaced
clamped_mouse_pos:glam::IVec2::ZERO,
angle_pitch_lower_limit:-Angle32::FRAC_PI_2,
angle_pitch_upper_limit:Angle32::FRAC_PI_2,
}
}
pub fn move_mouse(&mut self,mouse_pos:glam::IVec2){ pub fn move_mouse(&mut self,mouse_pos:glam::IVec2){
let mut unclamped_mouse_pos=self.clamped_mouse_pos+mouse_pos-self.mouse.pos; let mut unclamped_mouse_pos=self.clamped_mouse_pos+mouse_pos-self.mouse.pos;
unclamped_mouse_pos.y=unclamped_mouse_pos.y.clamp( unclamped_mouse_pos.y=unclamped_mouse_pos.y.clamp(
@ -236,6 +247,7 @@ impl PhysicsCamera {
impl std::default::Default for PhysicsCamera{ impl std::default::Default for PhysicsCamera{
fn default()->Self{ fn default()->Self{
Self{ Self{
offset:Planar64Vec3::ZERO,//TODO: delete this from PhysicsCamera, it should be GraphicsCamera only
sensitivity:Ratio64Vec2::ONE*200_000, sensitivity:Ratio64Vec2::ONE*200_000,
mouse:MouseState::default(),//t=0 does not cause divide by zero because it's immediately replaced mouse:MouseState::default(),//t=0 does not cause divide by zero because it's immediately replaced
clamped_mouse_pos:glam::IVec2::ZERO, clamped_mouse_pos:glam::IVec2::ZERO,
@ -246,18 +258,13 @@ impl std::default::Default for PhysicsCamera{
} }
pub struct GameMechanicsState{ pub struct GameMechanicsState{
stage_id:u32, pub stage_id:u32,
jump_counts:std::collections::HashMap<usize,u32>,//model_id -> jump count //jump_counts:HashMap<u32,u32>,
next_ordered_checkpoint_id:u32,//which OrderedCheckpoint model_id you must pass next (if 0 you haven't passed OrderedCheckpoint0)
unordered_checkpoints:std::collections::HashSet<usize>,//hashset of UnorderedCheckpoint model ids
} }
impl std::default::Default for GameMechanicsState{ impl std::default::Default for GameMechanicsState{
fn default()->Self{ fn default() -> Self {
Self{ Self{
stage_id:0, stage_id:0,
next_ordered_checkpoint_id:0,
unordered_checkpoints:std::collections::HashSet::new(),
jump_counts:std::collections::HashMap::new(),
} }
} }
} }
@ -281,23 +288,10 @@ enum JumpImpulse{
//Energy means it adds energy //Energy means it adds energy
//Linear means it linearly adds on //Linear means it linearly adds on
enum EnableStrafe{
Always,
MaskAny(u32),//hsw, shsw
MaskAll(u32),
//Function(Box<dyn Fn(u32)->bool>),
}
struct StrafeSettings{
enable:EnableStrafe,
air_accel_limit:Option<Planar64>,
tick_rate:Ratio64,
}
struct StyleModifiers{ struct StyleModifiers{
controls_used:u32,//controls which are allowed to pass into gameplay controls_mask:u32,//controls which are unable to be activated
controls_mask:u32,//controls which are masked from control state (e.g. jump in scroll style) controls_held:u32,//controls which must be active to be able to strafe
strafe:Option<StrafeSettings>, strafe_tick_rate:Option<Ratio64>,
jump_impulse:JumpImpulse, jump_impulse:JumpImpulse,
jump_calculation:JumpCalculation, jump_calculation:JumpCalculation,
static_friction:Planar64, static_friction:Planar64,
@ -310,13 +304,13 @@ struct StyleModifiers{
swim_speed:Planar64, swim_speed:Planar64,
mass:Planar64, mass:Planar64,
mv:Planar64, mv:Planar64,
air_accel_limit:Option<Planar64>,
rocket_force:Option<Planar64>, rocket_force:Option<Planar64>,
gravity:Planar64Vec3, gravity:Planar64Vec3,
hitbox_halfsize:Planar64Vec3, hitbox_halfsize:Planar64Vec3,
camera_offset:Planar64Vec3,
} }
impl std::default::Default for StyleModifiers{ impl std::default::Default for StyleModifiers{
fn default()->Self{ fn default() -> Self {
Self::roblox_bhop() Self::roblox_bhop()
} }
} }
@ -336,13 +330,9 @@ impl StyleModifiers{
fn new()->Self{ fn new()->Self{
Self{ Self{
controls_used:!0,
controls_mask:!0,//&!(Self::CONTROL_MOVEUP|Self::CONTROL_MOVEDOWN), controls_mask:!0,//&!(Self::CONTROL_MOVEUP|Self::CONTROL_MOVEDOWN),
strafe:Some(StrafeSettings{ controls_held:0,
enable:EnableStrafe::Always, strafe_tick_rate:Some(Ratio64::new(128,Time::ONE_SECOND.nanos() as u64).unwrap()),
air_accel_limit:None,
tick_rate:Ratio64::new(128,Time::ONE_SECOND.nanos() as u64).unwrap(),
}),
jump_impulse:JumpImpulse::FromEnergy(Planar64::int(512)), jump_impulse:JumpImpulse::FromEnergy(Planar64::int(512)),
jump_calculation:JumpCalculation::Energy, jump_calculation:JumpCalculation::Energy,
gravity:Planar64Vec3::int(0,-80,0), gravity:Planar64Vec3::int(0,-80,0),
@ -350,6 +340,7 @@ impl StyleModifiers{
kinetic_friction:Planar64::int(3),//unrealistic: kinetic friction is typically lower than static kinetic_friction:Planar64::int(3),//unrealistic: kinetic friction is typically lower than static
mass:Planar64::int(1), mass:Planar64::int(1),
mv:Planar64::int(2), mv:Planar64::int(2),
air_accel_limit:None,
rocket_force:None, rocket_force:None,
walk_speed:Planar64::int(16), walk_speed:Planar64::int(16),
walk_accel:Planar64::int(80), walk_accel:Planar64::int(80),
@ -358,19 +349,14 @@ impl StyleModifiers{
ladder_dot:(Planar64::int(1)/2).sqrt(), ladder_dot:(Planar64::int(1)/2).sqrt(),
swim_speed:Planar64::int(12), swim_speed:Planar64::int(12),
hitbox_halfsize:Planar64Vec3::int(2,5,2)/2, hitbox_halfsize:Planar64Vec3::int(2,5,2)/2,
camera_offset:Planar64Vec3::int(0,2,0),//4.5-2.5=2
} }
} }
fn roblox_bhop()->Self{ fn roblox_bhop()->Self{
Self{ Self{
controls_used:!0,
controls_mask:!0,//&!(Self::CONTROL_MOVEUP|Self::CONTROL_MOVEDOWN), controls_mask:!0,//&!(Self::CONTROL_MOVEUP|Self::CONTROL_MOVEDOWN),
strafe:Some(StrafeSettings{ controls_held:0,
enable:EnableStrafe::Always, strafe_tick_rate:Some(Ratio64::new(100,Time::ONE_SECOND.nanos() as u64).unwrap()),
air_accel_limit:None,
tick_rate:Ratio64::new(100,Time::ONE_SECOND.nanos() as u64).unwrap(),
}),
jump_impulse:JumpImpulse::FromTime(Time::from_micros(715_588)), jump_impulse:JumpImpulse::FromTime(Time::from_micros(715_588)),
jump_calculation:JumpCalculation::Capped, jump_calculation:JumpCalculation::Capped,
gravity:Planar64Vec3::int(0,-100,0), gravity:Planar64Vec3::int(0,-100,0),
@ -378,6 +364,7 @@ impl StyleModifiers{
kinetic_friction:Planar64::int(3),//unrealistic: kinetic friction is typically lower than static kinetic_friction:Planar64::int(3),//unrealistic: kinetic friction is typically lower than static
mass:Planar64::int(1), mass:Planar64::int(1),
mv:Planar64::int(27)/10, mv:Planar64::int(27)/10,
air_accel_limit:None,
rocket_force:None, rocket_force:None,
walk_speed:Planar64::int(18), walk_speed:Planar64::int(18),
walk_accel:Planar64::int(90), walk_accel:Planar64::int(90),
@ -386,18 +373,13 @@ impl StyleModifiers{
ladder_dot:(Planar64::int(1)/2).sqrt(), ladder_dot:(Planar64::int(1)/2).sqrt(),
swim_speed:Planar64::int(12), swim_speed:Planar64::int(12),
hitbox_halfsize:Planar64Vec3::int(2,5,2)/2, hitbox_halfsize:Planar64Vec3::int(2,5,2)/2,
camera_offset:Planar64Vec3::int(0,2,0),//4.5-2.5=2
} }
} }
fn roblox_surf()->Self{ fn roblox_surf()->Self{
Self{ Self{
controls_used:!0,
controls_mask:!0,//&!(Self::CONTROL_MOVEUP|Self::CONTROL_MOVEDOWN), controls_mask:!0,//&!(Self::CONTROL_MOVEUP|Self::CONTROL_MOVEDOWN),
strafe:Some(StrafeSettings{ controls_held:0,
enable:EnableStrafe::Always, strafe_tick_rate:Some(Ratio64::new(100,Time::ONE_SECOND.nanos() as u64).unwrap()),
air_accel_limit:None,
tick_rate:Ratio64::new(100,Time::ONE_SECOND.nanos() as u64).unwrap(),
}),
jump_impulse:JumpImpulse::FromTime(Time::from_micros(715_588)), jump_impulse:JumpImpulse::FromTime(Time::from_micros(715_588)),
jump_calculation:JumpCalculation::Capped, jump_calculation:JumpCalculation::Capped,
gravity:Planar64Vec3::int(0,-50,0), gravity:Planar64Vec3::int(0,-50,0),
@ -405,6 +387,7 @@ impl StyleModifiers{
kinetic_friction:Planar64::int(3),//unrealistic: kinetic friction is typically lower than static kinetic_friction:Planar64::int(3),//unrealistic: kinetic friction is typically lower than static
mass:Planar64::int(1), mass:Planar64::int(1),
mv:Planar64::int(27)/10, mv:Planar64::int(27)/10,
air_accel_limit:None,
rocket_force:None, rocket_force:None,
walk_speed:Planar64::int(18), walk_speed:Planar64::int(18),
walk_accel:Planar64::int(90), walk_accel:Planar64::int(90),
@ -413,19 +396,15 @@ impl StyleModifiers{
ladder_dot:(Planar64::int(1)/2).sqrt(), ladder_dot:(Planar64::int(1)/2).sqrt(),
swim_speed:Planar64::int(12), swim_speed:Planar64::int(12),
hitbox_halfsize:Planar64Vec3::int(2,5,2)/2, hitbox_halfsize:Planar64Vec3::int(2,5,2)/2,
camera_offset:Planar64Vec3::int(0,2,0),//4.5-2.5=2
} }
} }
fn source_bhop()->Self{ fn source_bhop()->Self{
//camera_offset=vec3(0,64/16-73/16/2,0),
Self{ Self{
controls_used:!0,
controls_mask:!0,//&!(Self::CONTROL_MOVEUP|Self::CONTROL_MOVEDOWN), controls_mask:!0,//&!(Self::CONTROL_MOVEUP|Self::CONTROL_MOVEDOWN),
strafe:Some(StrafeSettings{ controls_held:0,
enable:EnableStrafe::Always, strafe_tick_rate:Some(Ratio64::new(100,Time::ONE_SECOND.nanos() as u64).unwrap()),
air_accel_limit:Some(Planar64::raw(150<<28)*66),
tick_rate:Ratio64::new(100,Time::ONE_SECOND.nanos() as u64).unwrap(),
}),
jump_impulse:JumpImpulse::FromHeight(Planar64::raw(52<<28)), jump_impulse:JumpImpulse::FromHeight(Planar64::raw(52<<28)),
jump_calculation:JumpCalculation::Linear, jump_calculation:JumpCalculation::Linear,
gravity:Planar64Vec3::raw(0,-800<<28,0), gravity:Planar64Vec3::raw(0,-800<<28,0),
@ -433,6 +412,7 @@ impl StyleModifiers{
kinetic_friction:Planar64::int(3),//? kinetic_friction:Planar64::int(3),//?
mass:Planar64::int(1), mass:Planar64::int(1),
mv:Planar64::raw(30<<28), mv:Planar64::raw(30<<28),
air_accel_limit:Some(Planar64::raw(150<<28)*66),
rocket_force:None, rocket_force:None,
walk_speed:Planar64::int(18),//? walk_speed:Planar64::int(18),//?
walk_accel:Planar64::int(90),//? walk_accel:Planar64::int(90),//?
@ -441,18 +421,14 @@ impl StyleModifiers{
ladder_dot:(Planar64::int(1)/2).sqrt(),//? ladder_dot:(Planar64::int(1)/2).sqrt(),//?
swim_speed:Planar64::int(12),//? swim_speed:Planar64::int(12),//?
hitbox_halfsize:Planar64Vec3::raw(33<<28,73<<28,33<<28)/2, hitbox_halfsize:Planar64Vec3::raw(33<<28,73<<28,33<<28)/2,
camera_offset:Planar64Vec3::raw(0,(64<<28)-(73<<27),0),
} }
} }
fn source_surf()->Self{ fn source_surf()->Self{
//camera_offset=vec3(0,64/16-73/16/2,0),
Self{ Self{
controls_used:!0,
controls_mask:!0,//&!(Self::CONTROL_MOVEUP|Self::CONTROL_MOVEDOWN), controls_mask:!0,//&!(Self::CONTROL_MOVEUP|Self::CONTROL_MOVEDOWN),
strafe:Some(StrafeSettings{ controls_held:0,
enable:EnableStrafe::Always, strafe_tick_rate:Some(Ratio64::new(66,Time::ONE_SECOND.nanos() as u64).unwrap()),
air_accel_limit:Some(Planar64::raw(150<<28)*66),
tick_rate:Ratio64::new(66,Time::ONE_SECOND.nanos() as u64).unwrap(),
}),
jump_impulse:JumpImpulse::FromHeight(Planar64::raw(52<<28)), jump_impulse:JumpImpulse::FromHeight(Planar64::raw(52<<28)),
jump_calculation:JumpCalculation::Linear, jump_calculation:JumpCalculation::Linear,
gravity:Planar64Vec3::raw(0,-800<<28,0), gravity:Planar64Vec3::raw(0,-800<<28,0),
@ -460,6 +436,7 @@ impl StyleModifiers{
kinetic_friction:Planar64::int(3),//? kinetic_friction:Planar64::int(3),//?
mass:Planar64::int(1), mass:Planar64::int(1),
mv:Planar64::raw(30<<28), mv:Planar64::raw(30<<28),
air_accel_limit:Some(Planar64::raw(150<<28)*66),
rocket_force:None, rocket_force:None,
walk_speed:Planar64::int(18),//? walk_speed:Planar64::int(18),//?
walk_accel:Planar64::int(90),//? walk_accel:Planar64::int(90),//?
@ -468,14 +445,13 @@ impl StyleModifiers{
ladder_dot:(Planar64::int(1)/2).sqrt(),//? ladder_dot:(Planar64::int(1)/2).sqrt(),//?
swim_speed:Planar64::int(12),//? swim_speed:Planar64::int(12),//?
hitbox_halfsize:Planar64Vec3::raw(33<<28,73<<28,33<<28)/2, hitbox_halfsize:Planar64Vec3::raw(33<<28,73<<28,33<<28)/2,
camera_offset:Planar64Vec3::raw(0,(64<<28)-(73<<27),0),
} }
} }
fn roblox_rocket()->Self{ fn roblox_rocket()->Self{
Self{ Self{
controls_used:!0, controls_mask:!0,//&!(Self::CONTROL_MOVEUP|Self::CONTROL_MOVEDOWN),
controls_mask:!0, controls_held:0,
strafe:None, strafe_tick_rate:None,
jump_impulse:JumpImpulse::FromTime(Time::from_micros(715_588)), jump_impulse:JumpImpulse::FromTime(Time::from_micros(715_588)),
jump_calculation:JumpCalculation::Capped, jump_calculation:JumpCalculation::Capped,
gravity:Planar64Vec3::int(0,-100,0), gravity:Planar64Vec3::int(0,-100,0),
@ -483,6 +459,7 @@ impl StyleModifiers{
kinetic_friction:Planar64::int(3),//unrealistic: kinetic friction is typically lower than static kinetic_friction:Planar64::int(3),//unrealistic: kinetic friction is typically lower than static
mass:Planar64::int(1), mass:Planar64::int(1),
mv:Planar64::int(27)/10, mv:Planar64::int(27)/10,
air_accel_limit:None,
rocket_force:Some(Planar64::int(200)), rocket_force:Some(Planar64::int(200)),
walk_speed:Planar64::int(18), walk_speed:Planar64::int(18),
walk_accel:Planar64::int(90), walk_accel:Planar64::int(90),
@ -491,7 +468,6 @@ impl StyleModifiers{
ladder_dot:(Planar64::int(1)/2).sqrt(), ladder_dot:(Planar64::int(1)/2).sqrt(),
swim_speed:Planar64::int(12), swim_speed:Planar64::int(12),
hitbox_halfsize:Planar64Vec3::int(2,5,2)/2, hitbox_halfsize:Planar64Vec3::int(2,5,2)/2,
camera_offset:Planar64Vec3::int(0,2,0),//4.5-2.5=2
} }
} }
@ -499,19 +475,13 @@ impl StyleModifiers{
controls&self.controls_mask&control==control controls&self.controls_mask&control==control
} }
fn allow_strafe(&self,controls:u32)->bool{
//disable strafing according to strafe settings
match &self.strafe{
Some(StrafeSettings{enable:EnableStrafe::Always,air_accel_limit:_,tick_rate:_})=>true,
&Some(StrafeSettings{enable:EnableStrafe::MaskAny(mask),air_accel_limit:_,tick_rate:_})=>mask&controls!=0,
&Some(StrafeSettings{enable:EnableStrafe::MaskAll(mask),air_accel_limit:_,tick_rate:_})=>mask&controls==mask,
None=>false,
}
}
fn get_control_dir(&self,controls:u32)->Planar64Vec3{ fn get_control_dir(&self,controls:u32)->Planar64Vec3{
//don't get fancy just do it //don't get fancy just do it
let mut control_dir:Planar64Vec3 = Planar64Vec3::ZERO; let mut control_dir:Planar64Vec3 = Planar64Vec3::ZERO;
//Disallow strafing if held controls are not held
if controls&self.controls_held!=self.controls_held{
return control_dir;
}
//Apply mask after held check so you can require non-allowed keys to be held for some reason //Apply mask after held check so you can require non-allowed keys to be held for some reason
let controls=controls&self.controls_mask; let controls=controls&self.controls_mask;
if controls & Self::CONTROL_MOVEFORWARD == Self::CONTROL_MOVEFORWARD { if controls & Self::CONTROL_MOVEFORWARD == Self::CONTROL_MOVEFORWARD {
@ -603,13 +573,12 @@ pub struct PhysicsState{
} }
#[derive(Clone,Default)] #[derive(Clone,Default)]
pub struct PhysicsOutputState{ pub struct PhysicsOutputState{
body:Body,
camera:PhysicsCamera, camera:PhysicsCamera,
camera_offset:Planar64Vec3, body:Body,
} }
impl PhysicsOutputState{ impl PhysicsOutputState{
pub fn extrapolate(&self,mouse_pos:glam::IVec2,time:Time)->(glam::Vec3,glam::Vec2){ pub fn extrapolate(&self,mouse_pos:glam::IVec2,time:Time)->(glam::Vec3,glam::Vec2){
((self.body.extrapolated_position(time)+self.camera_offset).into(),self.camera.simulate_move_angles(mouse_pos)) ((self.body.extrapolated_position(time)+self.camera.offset).into(),self.camera.simulate_move_angles(mouse_pos))
} }
} }
@ -628,7 +597,7 @@ enum PhysicsCollisionAttributes{
}, },
} }
pub struct PhysicsModel { pub struct ModelPhysics {
//A model is a thing that has a hitbox. can be represented by a list of TreyMesh-es //A model is a thing that has a hitbox. can be represented by a list of TreyMesh-es
//in this iteration, all it needs is extents. //in this iteration, all it needs is extents.
mesh: TreyMesh, mesh: TreyMesh,
@ -636,7 +605,7 @@ pub struct PhysicsModel {
attributes:PhysicsCollisionAttributes, attributes:PhysicsCollisionAttributes,
} }
impl PhysicsModel { impl ModelPhysics {
fn from_model_transform_attributes(model:&crate::model::IndexedModel,transform:&crate::integer::Planar64Affine3,attributes:PhysicsCollisionAttributes)->Self{ fn from_model_transform_attributes(model:&crate::model::IndexedModel,transform:&crate::integer::Planar64Affine3,attributes:PhysicsCollisionAttributes)->Self{
let mut aabb=TreyMesh::default(); let mut aabb=TreyMesh::default();
for indexed_vertex in &model.unique_vertices { for indexed_vertex in &model.unique_vertices {
@ -650,8 +619,8 @@ impl PhysicsModel {
} }
pub fn from_model(model:&crate::model::IndexedModel,instance:&crate::model::ModelInstance) -> Option<Self> { pub fn from_model(model:&crate::model::IndexedModel,instance:&crate::model::ModelInstance) -> Option<Self> {
match &instance.attributes{ match &instance.attributes{
crate::model::CollisionAttributes::Contact{contacting,general}=>Some(PhysicsModel::from_model_transform_attributes(model,&instance.transform,PhysicsCollisionAttributes::Contact{contacting:contacting.clone(),general:general.clone()})), crate::model::CollisionAttributes::Contact{contacting,general}=>Some(ModelPhysics::from_model_transform_attributes(model,&instance.transform,PhysicsCollisionAttributes::Contact{contacting:contacting.clone(),general:general.clone()})),
crate::model::CollisionAttributes::Intersect{intersecting,general}=>Some(PhysicsModel::from_model_transform_attributes(model,&instance.transform,PhysicsCollisionAttributes::Intersect{intersecting:intersecting.clone(),general:general.clone()})), crate::model::CollisionAttributes::Intersect{intersecting,general}=>Some(ModelPhysics::from_model_transform_attributes(model,&instance.transform,PhysicsCollisionAttributes::Intersect{intersecting:intersecting.clone(),general:general.clone()})),
crate::model::CollisionAttributes::Decoration=>None, crate::model::CollisionAttributes::Decoration=>None,
} }
} }
@ -678,10 +647,10 @@ pub struct RelativeCollision {
} }
impl RelativeCollision { impl RelativeCollision {
fn model<'a>(&self,models:&'a PhysicsModels)->Option<&'a PhysicsModel>{ fn model<'a>(&self,models:&'a PhysicsModels)->Option<&'a ModelPhysics>{
models.get(self.model) models.get(self.model)
} }
// pub fn mesh(&self,models:&Vec<PhysicsModel>) -> TreyMesh { // pub fn mesh(&self,models:&Vec<ModelPhysics>) -> TreyMesh {
// return self.model(models).unwrap().face_mesh(self.face).clone() // return self.model(models).unwrap().face_mesh(self.face).clone()
// } // }
fn normal(&self,models:&PhysicsModels) -> Planar64Vec3 { fn normal(&self,models:&PhysicsModels) -> Planar64Vec3 {
@ -768,19 +737,19 @@ impl std::fmt::Display for Body{
} }
impl Default for PhysicsState{ impl Default for PhysicsState{
fn default()->Self{ fn default() -> Self {
Self{ Self{
spawn_point:Planar64Vec3::int(0,50,0), spawn_point:Planar64Vec3::int(0,50,0),
body:Body::with_pva(Planar64Vec3::int(0,50,0),Planar64Vec3::int(0,0,0),Planar64Vec3::int(0,-100,0)), body: Body::with_pva(Planar64Vec3::int(0,50,0),Planar64Vec3::int(0,0,0),Planar64Vec3::int(0,-100,0)),
time:Time::ZERO, time: Time::ZERO,
style:StyleModifiers::default(), style:StyleModifiers::default(),
touching:TouchingState::default(), touching:TouchingState::default(),
models:PhysicsModels::default(), models:PhysicsModels::default(),
bvh:crate::bvh::BvhNode::default(), bvh:crate::bvh::BvhNode::default(),
move_state: MoveState::Air, move_state: MoveState::Air,
camera:PhysicsCamera::default(), camera: PhysicsCamera::from_offset(Planar64Vec3::int(0,2,0)),//4.5-2.5=2
next_mouse:MouseState::default(), next_mouse: MouseState::default(),
controls:0, controls: 0,
world:WorldState{}, world:WorldState{},
game:GameMechanicsState::default(), game:GameMechanicsState::default(),
modes:Modes::default(), modes:Modes::default(),
@ -800,7 +769,6 @@ impl PhysicsState {
PhysicsOutputState{ PhysicsOutputState{
body:self.body.clone(), body:self.body.clone(),
camera:self.camera.clone(), camera:self.camera.clone(),
camera_offset:self.style.camera_offset.clone(),
} }
} }
@ -816,15 +784,19 @@ impl PhysicsState {
pub fn generate_models(&mut self,indexed_models:&crate::model::IndexedModelInstances){ pub fn generate_models(&mut self,indexed_models:&crate::model::IndexedModelInstances){
let mut starts=Vec::new(); let mut starts=Vec::new();
let mut spawns=Vec::new(); let mut spawns=Vec::new();
let mut ordered_checkpoints=Vec::new();
let mut unordered_checkpoints=Vec::new();
for model in &indexed_models.models{ for model in &indexed_models.models{
//make aabb and run vertices to get realistic bounds //make aabb and run vertices to get realistic bounds
for model_instance in &model.instances{ for model_instance in &model.instances{
if let Some(model_physics)=PhysicsModel::from_model(model,model_instance){ if let Some(model_physics)=ModelPhysics::from_model(model,model_instance){
let model_id=self.models.push(model_physics); let model_id=self.models.push(model_physics);
for attr in &model_instance.temp_indexing{ for attr in &model_instance.temp_indexing{
match attr{ match attr{
crate::model::TempIndexedAttributes::Start(s)=>starts.push((model_id,s.clone())), crate::model::TempIndexedAttributes::Start(s)=>starts.push((model_id,s.clone())),
crate::model::TempIndexedAttributes::Spawn(s)=>spawns.push((model_id,s.clone())), crate::model::TempIndexedAttributes::Spawn(s)=>spawns.push((model_id,s.clone())),
crate::model::TempIndexedAttributes::OrderedCheckpoint(s)=>ordered_checkpoints.push((model_id,s.clone())),
crate::model::TempIndexedAttributes::UnorderedCheckpoint(s)=>unordered_checkpoints.push((model_id,s.clone())),
crate::model::TempIndexedAttributes::Wormhole(s)=>{self.models.model_id_from_wormhole_id.insert(s.wormhole_id,model_id);}, crate::model::TempIndexedAttributes::Wormhole(s)=>{self.models.model_id_from_wormhole_id.insert(s.wormhole_id,model_id);},
} }
} }
@ -836,9 +808,9 @@ impl PhysicsState {
//this code builds ModeDescriptions from the unsorted lists at the top of the function //this code builds ModeDescriptions from the unsorted lists at the top of the function
starts.sort_by_key(|tup|tup.1.mode_id); starts.sort_by_key(|tup|tup.1.mode_id);
let mut mode_id_from_map_mode_id=std::collections::HashMap::new(); let mut mode_id_from_map_mode_id=std::collections::HashMap::new();
let mut modedatas:Vec<(usize,Vec<(u32,usize)>,u32)>=starts.into_iter().enumerate().map(|(i,(model_id,s))|{ let mut modedatas:Vec<(usize,Vec<(u32,usize)>,Vec<(u32,usize)>,Vec<usize>,u32)>=starts.into_iter().enumerate().map(|(i,(model_id,s))|{
mode_id_from_map_mode_id.insert(s.mode_id,i); mode_id_from_map_mode_id.insert(s.mode_id,i);
(model_id,Vec::new(),s.mode_id) (model_id,Vec::new(),Vec::new(),Vec::new(),s.mode_id)
}).collect(); }).collect();
for (model_id,s) in spawns{ for (model_id,s) in spawns{
if let Some(mode_id)=mode_id_from_map_mode_id.get(&s.mode_id){ if let Some(mode_id)=mode_id_from_map_mode_id.get(&s.mode_id){
@ -847,13 +819,30 @@ impl PhysicsState {
} }
} }
} }
for (model_id,s) in ordered_checkpoints{
if let Some(mode_id)=mode_id_from_map_mode_id.get(&s.mode_id){
if let Some(modedata)=modedatas.get_mut(*mode_id){
modedata.2.push((s.checkpoint_id,model_id));
}
}
}
for (model_id,s) in unordered_checkpoints{
if let Some(mode_id)=mode_id_from_map_mode_id.get(&s.mode_id){
if let Some(modedata)=modedatas.get_mut(*mode_id){
modedata.3.push(model_id);
}
}
}
for mut tup in modedatas.into_iter(){ for mut tup in modedatas.into_iter(){
tup.1.sort_by_key(|tup|tup.0); tup.1.sort_by_key(|tup|tup.0);
tup.2.sort_by_key(|tup|tup.0);
let mut eshmep1=std::collections::HashMap::new(); let mut eshmep1=std::collections::HashMap::new();
let mut eshmep2=std::collections::HashMap::new(); let mut eshmep2=std::collections::HashMap::new();
self.modes.insert(tup.2,crate::model::ModeDescription{ self.modes.insert(tup.4,crate::model::ModeDescription{
start:tup.0, start:tup.0,
spawns:tup.1.into_iter().enumerate().map(|(i,tup)|{eshmep1.insert(tup.0,i);tup.1}).collect(), spawns:tup.1.into_iter().enumerate().map(|(i,tup)|{eshmep1.insert(tup.0,i);tup.1}).collect(),
ordered_checkpoints:tup.2.into_iter().enumerate().map(|(i,tup)|{eshmep2.insert(tup.0,i);tup.1}).collect(),
unordered_checkpoints:tup.3,
spawn_from_stage_id:eshmep1, spawn_from_stage_id:eshmep1,
ordered_checkpoint_from_checkpoint_id:eshmep2, ordered_checkpoint_from_checkpoint_id:eshmep2,
}); });
@ -894,10 +883,10 @@ impl PhysicsState {
} }
} }
fn next_strafe_instruction(&self)->Option<TimedInstruction<PhysicsInstruction>>{ fn next_strafe_instruction(&self) -> Option<TimedInstruction<PhysicsInstruction>> {
self.style.strafe.as_ref().map(|strafe|{ self.style.strafe_tick_rate.as_ref().map(|strafe_tick_rate|{
TimedInstruction{ TimedInstruction{
time:Time::from_nanos(strafe.tick_rate.rhs_div_int(strafe.tick_rate.mul_int(self.time.nanos())+1)), time:Time::from_nanos(strafe_tick_rate.rhs_div_int(strafe_tick_rate.mul_int(self.time.nanos())+1)),
//only poll the physics if there is a before and after mouse event //only poll the physics if there is a before and after mouse event
instruction:PhysicsInstruction::StrafeTick instruction:PhysicsInstruction::StrafeTick
} }
@ -986,7 +975,8 @@ impl PhysicsState {
//collect x //collect x
match collision_data.face { match collision_data.face {
TreyMeshFace::Top|TreyMeshFace::Back|TreyMeshFace::Bottom|TreyMeshFace::Front=>{ TreyMeshFace::Top|TreyMeshFace::Back|TreyMeshFace::Bottom|TreyMeshFace::Front=>{
for t in zeroes2(mesh0.max.x()-mesh1.min.x(),v.x(),a.x()/2) { let (roots,nroots)=zeroes2(mesh0.max.x()-mesh1.min.x(),v.x(),a.x()/2);
for &t in &roots[0..nroots]{
//negative t = back in time //negative t = back in time
//must be moving towards surface to collide //must be moving towards surface to collide
//must beat the current soonest collision time //must beat the current soonest collision time
@ -999,7 +989,8 @@ impl PhysicsState {
break; break;
} }
} }
for t in zeroes2(mesh0.min.x()-mesh1.max.x(),v.x(),a.x()/2) { let (roots,nroots)=zeroes2(mesh0.min.x()-mesh1.max.x(),v.x(),a.x()/2);
for &t in &roots[0..nroots]{
//negative t = back in time //negative t = back in time
//must be moving towards surface to collide //must be moving towards surface to collide
//must beat the current soonest collision time //must beat the current soonest collision time
@ -1031,7 +1022,8 @@ impl PhysicsState {
//collect y //collect y
match collision_data.face { match collision_data.face {
TreyMeshFace::Left|TreyMeshFace::Back|TreyMeshFace::Right|TreyMeshFace::Front=>{ TreyMeshFace::Left|TreyMeshFace::Back|TreyMeshFace::Right|TreyMeshFace::Front=>{
for t in zeroes2(mesh0.max.y()-mesh1.min.y(),v.y(),a.y()/2) { let (roots,nroots)=zeroes2(mesh0.max.y()-mesh1.min.y(),v.y(),a.y()/2);
for &t in &roots[0..nroots]{
//negative t = back in time //negative t = back in time
//must be moving towards surface to collide //must be moving towards surface to collide
//must beat the current soonest collision time //must beat the current soonest collision time
@ -1044,7 +1036,8 @@ impl PhysicsState {
break; break;
} }
} }
for t in zeroes2(mesh0.min.y()-mesh1.max.y(),v.y(),a.y()/2) { let (roots,nroots)=zeroes2(mesh0.min.y()-mesh1.max.y(),v.y(),a.y()/2);
for &t in &roots[0..nroots]{
//negative t = back in time //negative t = back in time
//must be moving towards surface to collide //must be moving towards surface to collide
//must beat the current soonest collision time //must beat the current soonest collision time
@ -1076,7 +1069,8 @@ impl PhysicsState {
//collect z //collect z
match collision_data.face { match collision_data.face {
TreyMeshFace::Left|TreyMeshFace::Bottom|TreyMeshFace::Right|TreyMeshFace::Top=>{ TreyMeshFace::Left|TreyMeshFace::Bottom|TreyMeshFace::Right|TreyMeshFace::Top=>{
for t in zeroes2(mesh0.max.z()-mesh1.min.z(),v.z(),a.z()/2) { let (roots,nroots)=zeroes2(mesh0.max.z()-mesh1.min.z(),v.z(),a.z()/2);
for &t in &roots[0..nroots]{
//negative t = back in time //negative t = back in time
//must be moving towards surface to collide //must be moving towards surface to collide
//must beat the current soonest collision time //must beat the current soonest collision time
@ -1089,7 +1083,8 @@ impl PhysicsState {
break; break;
} }
} }
for t in zeroes2(mesh0.min.z()-mesh1.max.z(),v.z(),a.z()/2) { let (roots,nroots)=zeroes2(mesh0.min.z()-mesh1.max.z(),v.z(),a.z()/2);
for &t in &roots[0..nroots]{
//negative t = back in time //negative t = back in time
//must be moving towards surface to collide //must be moving towards surface to collide
//must beat the current soonest collision time //must beat the current soonest collision time
@ -1135,7 +1130,8 @@ impl PhysicsState {
let mut best_time=time_limit; let mut best_time=time_limit;
let mut best_face:Option<TreyMeshFace>=None; let mut best_face:Option<TreyMeshFace>=None;
//collect x //collect x
for t in zeroes2(mesh0.max.x()-mesh1.min.x(),v.x(),a.x()/2) { let (roots,nroots)=zeroes2(mesh0.max.x()-mesh1.min.x(),v.x(),a.x()/2);
for &t in &roots[0..nroots]{
//must collide now or in the future //must collide now or in the future
//must beat the current soonest collision time //must beat the current soonest collision time
//must be moving towards surface //must be moving towards surface
@ -1151,7 +1147,8 @@ impl PhysicsState {
} }
} }
} }
for t in zeroes2(mesh0.min.x()-mesh1.max.x(),v.x(),a.x()/2) { let (roots,nroots)=zeroes2(mesh0.min.x()-mesh1.max.x(),v.x(),a.x()/2);
for &t in &roots[0..nroots]{
//must collide now or in the future //must collide now or in the future
//must beat the current soonest collision time //must beat the current soonest collision time
//must be moving towards surface //must be moving towards surface
@ -1168,7 +1165,8 @@ impl PhysicsState {
} }
} }
//collect y //collect y
for t in zeroes2(mesh0.max.y()-mesh1.min.y(),v.y(),a.y()/2) { let (roots,nroots)=zeroes2(mesh0.max.y()-mesh1.min.y(),v.y(),a.y()/2);
for &t in &roots[0..nroots]{
//must collide now or in the future //must collide now or in the future
//must beat the current soonest collision time //must beat the current soonest collision time
//must be moving towards surface //must be moving towards surface
@ -1184,7 +1182,8 @@ impl PhysicsState {
} }
} }
} }
for t in zeroes2(mesh0.min.y()-mesh1.max.y(),v.y(),a.y()/2) { let (roots,nroots)=zeroes2(mesh0.min.y()-mesh1.max.y(),v.y(),a.y()/2);
for &t in &roots[0..nroots]{
//must collide now or in the future //must collide now or in the future
//must beat the current soonest collision time //must beat the current soonest collision time
//must be moving towards surface //must be moving towards surface
@ -1201,7 +1200,8 @@ impl PhysicsState {
} }
} }
//collect z //collect z
for t in zeroes2(mesh0.max.z()-mesh1.min.z(),v.z(),a.z()/2) { let (roots,nroots)=zeroes2(mesh0.max.z()-mesh1.min.z(),v.z(),a.z()/2);
for &t in &roots[0..nroots]{
//must collide now or in the future //must collide now or in the future
//must beat the current soonest collision time //must beat the current soonest collision time
//must be moving towards surface //must be moving towards surface
@ -1217,7 +1217,8 @@ impl PhysicsState {
} }
} }
} }
for t in zeroes2(mesh0.min.z()-mesh1.max.z(),v.z(),a.z()/2) { let (roots,nroots)=zeroes2(mesh0.min.z()-mesh1.max.z(),v.z(),a.z()/2);
for &t in &roots[0..nroots]{
//must collide now or in the future //must collide now or in the future
//must beat the current soonest collision time //must beat the current soonest collision time
//must be moving towards surface //must be moving towards surface
@ -1284,13 +1285,8 @@ fn teleport(body:&mut Body,touching:&mut TouchingState,style:&StyleModifiers,poi
//TODO: calculate contacts and determine the actual state //TODO: calculate contacts and determine the actual state
//touching.recalculate(body); //touching.recalculate(body);
} }
fn teleport_to_spawn(body:&mut Body,touching:&mut TouchingState,style:&StyleModifiers,mode:&crate::model::ModeDescription,models:&PhysicsModels,stage_id:u32)->Option<MoveState>{
let model=models.get(*mode.get_spawn_model_id(stage_id)? as usize)?;
let point=model.transform.transform_point3(Planar64Vec3::Y)+Planar64Vec3::Y*(style.hitbox_halfsize.y()+Planar64::ONE/16);
Some(teleport(body,touching,style,point))
}
fn run_teleport_behaviour(teleport_behaviour:&Option<crate::model::TeleportBehaviour>,game:&mut GameMechanicsState,models:&PhysicsModels,modes:&Modes,style:&StyleModifiers,touching:&mut TouchingState,body:&mut Body,model:&PhysicsModel)->Option<MoveState>{ fn run_teleport_behaviour(teleport_behaviour:&Option<crate::model::TeleportBehaviour>,game:&mut GameMechanicsState,models:&PhysicsModels,modes:&Modes,style:&StyleModifiers,touching:&mut TouchingState,body:&mut Body,model:&ModelPhysics)->Option<MoveState>{
match teleport_behaviour{ match teleport_behaviour{
Some(crate::model::TeleportBehaviour::StageElement(stage_element))=>{ Some(crate::model::TeleportBehaviour::StageElement(stage_element))=>{
if stage_element.force||game.stage_id<stage_element.stage_id{ if stage_element.force||game.stage_id<stage_element.stage_id{
@ -1301,24 +1297,12 @@ fn run_teleport_behaviour(teleport_behaviour:&Option<crate::model::TeleportBehav
crate::model::StageElementBehaviour::Trigger crate::model::StageElementBehaviour::Trigger
|crate::model::StageElementBehaviour::Teleport=>{ |crate::model::StageElementBehaviour::Teleport=>{
//I guess this is correct behaviour when trying to teleport to a non-existent spawn but it's still weird //I guess this is correct behaviour when trying to teleport to a non-existent spawn but it's still weird
teleport_to_spawn(body,touching,style,modes.get_mode(stage_element.mode_id)?,models,game.stage_id) let model=models.get(*modes.get_mode(stage_element.mode_id)?.get_spawn_model_id(game.stage_id)? as usize)?;
let point=model.transform.transform_point3(Planar64Vec3::Y)+Planar64Vec3::Y*(style.hitbox_halfsize.y()+Planar64::ONE/16);
Some(teleport(body,touching,style,point))
}, },
crate::model::StageElementBehaviour::Platform=>None, crate::model::StageElementBehaviour::Platform=>None,
&crate::model::StageElementBehaviour::JumpLimit(jump_limit)=>{ crate::model::StageElementBehaviour::JumpLimit(_)=>None,//TODO
//let count=game.jump_counts.get(&model.id);
//TODO
None
},
&crate::model::StageElementBehaviour::Checkpoint{ordered_checkpoint_id,unordered_checkpoint_count}=>{
if (ordered_checkpoint_id.is_none()||ordered_checkpoint_id.is_some_and(|id|id<game.next_ordered_checkpoint_id))
&&unordered_checkpoint_count<=game.unordered_checkpoints.len() as u32{
//pass
None
}else{
//fail
teleport_to_spawn(body,touching,style,modes.get_mode(stage_element.mode_id)?,models,game.stage_id)
}
},
} }
}, },
Some(crate::model::TeleportBehaviour::Wormhole(wormhole))=>{ Some(crate::model::TeleportBehaviour::Wormhole(wormhole))=>{

@ -23,11 +23,11 @@ pub enum Instruction{
//Graphics(crate::graphics_worker::Instruction), //Graphics(crate::graphics_worker::Instruction),
} }
pub fn new<'a>(scope:&'a std::thread::Scope<'a,'_>,mut physics:crate::physics::PhysicsState,graphics_worker:crate::worker::INWorker<'a,crate::graphics_worker::Instruction>)->crate::worker::QNWorker<'a,TimedInstruction<Instruction>>{ pub fn new(mut physics:crate::physics::PhysicsState,mut graphics_worker:crate::compat_worker::INWorker<crate::graphics_worker::Instruction>)->crate::compat_worker::QNWorker<TimedInstruction<Instruction>>{
let mut mouse_blocking=true; let mut mouse_blocking=true;
let mut last_mouse_time=physics.next_mouse.time; let mut last_mouse_time=physics.next_mouse.time;
let mut timeline=std::collections::VecDeque::new(); let mut timeline=std::collections::VecDeque::new();
crate::worker::QNWorker::new(scope,move |ins:TimedInstruction<Instruction>|{ crate::compat_worker::QNWorker::new(move |ins:TimedInstruction<Instruction>|{
if if let Some(phys_input)=match &ins.instruction{ if if let Some(phys_input)=match &ins.instruction{
Instruction::Input(input_instruction)=>match input_instruction{ Instruction::Input(input_instruction)=>match input_instruction{
&InputInstruction::MoveMouse(m)=>{ &InputInstruction::MoveMouse(m)=>{
@ -113,11 +113,10 @@ pub enum Instruction{
} }
match ins.instruction{ match ins.instruction{
Instruction::Render=>{ Instruction::Render=>{
let _=graphics_worker.send(crate::graphics_worker::Instruction::Render(physics.output(),ins.time,physics.next_mouse.pos)); graphics_worker.send(crate::graphics_worker::Instruction::Render(physics.output(),ins.time,physics.next_mouse.pos)).unwrap();
}, },
Instruction::Resize(size,user_settings)=>{ Instruction::Resize(size,user_settings)=>{
//block! graphics_worker.send(crate::graphics_worker::Instruction::Resize(size,user_settings)).unwrap();
graphics_worker.blocking_send(crate::graphics_worker::Instruction::Resize(size,user_settings)).unwrap();
}, },
Instruction::GenerateModels(indexed_model_instances)=>{ Instruction::GenerateModels(indexed_model_instances)=>{
physics.generate_models(&indexed_model_instances); physics.generate_models(&indexed_model_instances);

@ -126,21 +126,17 @@ const CORNERWEDGE_DEFAULT_NORMALS:[Planar64Vec3;5]=[
Planar64Vec3::int( 0,-1, 0),//CornerWedge::Bottom Planar64Vec3::int( 0,-1, 0),//CornerWedge::Bottom
Planar64Vec3::int( 0, 0,-1),//CornerWedge::Front 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{ pub fn unit_sphere()->crate::model::IndexedModel{
unit_cube() 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(){
#[derive(Default)] *pos=*pos/2;
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)))
} }
indexed_model
} }
pub type CubeFaceDescription=std::collections::HashMap::<CubeFace,FaceDescription>;
pub fn unit_cube()->crate::model::IndexedModel{ 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::Right,FaceDescription::default());
t.insert(CubeFace::Top,FaceDescription::default()); t.insert(CubeFace::Top,FaceDescription::default());
t.insert(CubeFace::Back,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()); t.insert(CubeFace::Front,FaceDescription::default());
generate_partial_unit_cube(t) 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{ pub fn unit_cylinder()->crate::model::IndexedModel{
unit_cube() 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(){
#[derive(Default)] *pos=TEAPOT_TRANSFORM*(*pos)/10;
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)))
} }
indexed_model
} }
pub type WedgeFaceDescription=std::collections::HashMap::<WedgeFace,FaceDescription>;
pub fn unit_wedge()->crate::model::IndexedModel{ 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::Right,FaceDescription::default());
t.insert(WedgeFace::TopFront,FaceDescription::default()); t.insert(WedgeFace::TopFront,FaceDescription::default());
t.insert(WedgeFace::Back,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()); t.insert(WedgeFace::Bottom,FaceDescription::default());
generate_partial_unit_wedge(t) generate_partial_unit_wedge(t)
} }
#[derive(Default)] pub type CornerWedgeFaceDescription=std::collections::HashMap::<CornerWedgeFace,FaceDescription>;
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 fn unit_cornerwedge()->crate::model::IndexedModel{ 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::Right,FaceDescription::default());
t.insert(CornerWedgeFace::TopBack,FaceDescription::default()); t.insert(CornerWedgeFace::TopBack,FaceDescription::default());
t.insert(CornerWedgeFace::TopLeft,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. //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 //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{ 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 groups=Vec::new();
let mut transforms=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. //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. //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){ let transform_index=if let Some(transform_index)=transforms.iter().position(|&transform|transform==face_description.transform){
transform_index transform_index
@ -238,6 +233,14 @@ pub fn generate_partial_unit_cube(face_descriptions:CubeFaceDescription)->crate:
generated_color.push(face_description.color); generated_color.push(face_description.color);
color_index color_index
} as u32; } 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 //always push normal
let normal_index=generated_normal.len() as u32; let normal_index=generated_normal.len() as u32;
generated_normal.push(CUBE_DEFAULT_NORMALS[face_id]); 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 groups=Vec::new();
let mut transforms=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. //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. //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){ let transform_index=if let Some(transform_index)=transforms.iter().position(|&transform|transform==face_description.transform){
transform_index transform_index
@ -345,6 +348,13 @@ pub fn generate_partial_unit_wedge(face_descriptions:WedgeFaceDescription)->crat
generated_color.push(face_description.color); generated_color.push(face_description.color);
color_index color_index
} as u32; } 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 //always push normal
let normal_index=generated_normal.len() as u32; let normal_index=generated_normal.len() as u32;
generated_normal.push(WEDGE_DEFAULT_NORMALS[face_id]); 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 groups=Vec::new();
let mut transforms=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. //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. //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){ let transform_index=if let Some(transform_index)=transforms.iter().position(|&transform|transform==face_description.transform){
transform_index transform_index
@ -450,6 +460,13 @@ pub fn generate_partial_unit_cornerwedge(face_descriptions:CornerWedgeFaceDescri
generated_color.push(face_description.color); generated_color.push(face_description.color);
color_index color_index
} as u32; } 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 //always push normal
let normal_index=generated_normal.len() as u32; let normal_index=generated_normal.len() as u32;
generated_normal.push(CORNERWEDGE_DEFAULT_NORMALS[face_id]); generated_normal.push(CORNERWEDGE_DEFAULT_NORMALS[face_id]);

@ -41,7 +41,6 @@ fn create_instance()->SetupContextPartial1{
instance:wgpu::Instance::new(wgpu::InstanceDescriptor{ instance:wgpu::Instance::new(wgpu::InstanceDescriptor{
backends, backends,
dx12_shader_compiler, dx12_shader_compiler,
..Default::default()
}), }),
} }
} }
@ -170,7 +169,6 @@ impl SetupContextPartial4{
.expect("Surface isn't supported by the adapter."); .expect("Surface isn't supported by the adapter.");
let surface_view_format=config.format.add_srgb_suffix(); let surface_view_format=config.format.add_srgb_suffix();
config.view_formats.push(surface_view_format); config.view_formats.push(surface_view_format);
config.present_mode=wgpu::PresentMode::AutoNoVsync;
self.surface.configure(&self.device, &config); self.surface.configure(&self.device, &config);
SetupContext{ SetupContext{
@ -232,32 +230,20 @@ impl SetupContextSetup{
let (window,event_loop,setup_context)=self.into_split(); let (window,event_loop,setup_context)=self.into_split();
//dedicated thread to ping request redraw back and resize the window doesn't seem logical //dedicated thread to ping request redraw back and resize the window doesn't seem logical
//but here I am doing it
let window=crate::window::WindowContextSetup::new(&setup_context,window);
//the thread that spawns the physics thread
let window_thread=window.into_worker(setup_context);
println!("Entering event loop...");
let root_time=std::time::Instant::now(); let root_time=std::time::Instant::now();
std::thread::scope(|s|{ run_event_loop(event_loop,window_thread,root_time).unwrap();
let window=crate::window::WindowContextSetup::new(&setup_context,window);
//the thread that spawns the physics thread
let window_thread=window.into_worker(s,setup_context);
//schedule frames at 165fps
let event_loop_proxy=event_loop.create_proxy();
s.spawn(move ||{
loop{
std::thread::sleep(std::time::Duration::from_nanos(1_000_000_000/165));
event_loop_proxy.send_event(()).ok();
}
});
println!("Entering event loop...");
run_event_loop(event_loop,window_thread,root_time).unwrap();
});
} }
} }
fn run_event_loop( fn run_event_loop(
event_loop:winit::event_loop::EventLoop<()>, event_loop:winit::event_loop::EventLoop<()>,
window_thread:crate::worker::QNWorker<TimedInstruction<WindowInstruction>>, mut window_thread:crate::compat_worker::QNWorker<TimedInstruction<WindowInstruction>>,
root_time:std::time::Instant root_time:std::time::Instant
)->Result<(),winit::error::EventLoopError>{ )->Result<(),winit::error::EventLoopError>{
event_loop.run(move |event,elwt|{ event_loop.run(move |event,elwt|{
@ -268,7 +254,7 @@ fn run_event_loop(
// winit::event_loop::ControlFlow::Poll // winit::event_loop::ControlFlow::Poll
// }; // };
match event{ match event{
winit::event::Event::UserEvent(())=>{ winit::event::Event::AboutToWait=>{
window_thread.send(TimedInstruction{time,instruction:WindowInstruction::RequestRedraw}).unwrap(); window_thread.send(TimedInstruction{time,instruction:WindowInstruction::RequestRedraw}).unwrap();
} }
winit::event::Event::WindowEvent { winit::event::Event::WindowEvent {
@ -312,4 +298,4 @@ fn run_event_loop(
_=>{} _=>{}
} }
}) })
} }

@ -16,7 +16,7 @@ struct WindowContext<'a>{
screen_size:glam::UVec2, screen_size:glam::UVec2,
user_settings:crate::settings::UserSettings, user_settings:crate::settings::UserSettings,
window:winit::window::Window, window:winit::window::Window,
physics_thread:crate::worker::QNWorker<'a,TimedInstruction<crate::physics_worker::Instruction>>, physics_thread:crate::compat_worker::QNWorker<'a, TimedInstruction<crate::physics_worker::Instruction>>,
} }
impl WindowContext<'_>{ impl WindowContext<'_>{
@ -194,9 +194,9 @@ impl WindowContextSetup{
} }
} }
fn into_context<'a>(self,scope:&'a std::thread::Scope<'a,'_>,setup_context:crate::setup::SetupContext)->WindowContext<'a>{ fn into_context<'a>(self,setup_context:crate::setup::SetupContext)->WindowContext<'a>{
let screen_size=glam::uvec2(setup_context.config.width,setup_context.config.height); let screen_size=glam::uvec2(setup_context.config.width,setup_context.config.height);
let graphics_thread=crate::graphics_worker::new(scope,self.graphics,setup_context.config,setup_context.surface,setup_context.device,setup_context.queue); let graphics_thread=crate::graphics_worker::new(self.graphics,setup_context.config,setup_context.surface,setup_context.device,setup_context.queue);
WindowContext{ WindowContext{
manual_mouse_lock:false, manual_mouse_lock:false,
mouse:crate::physics::MouseState::default(), mouse:crate::physics::MouseState::default(),
@ -204,13 +204,13 @@ impl WindowContextSetup{
screen_size, screen_size,
user_settings:self.user_settings, user_settings:self.user_settings,
window:self.window, window:self.window,
physics_thread:crate::physics_worker::new(scope,self.physics,graphics_thread), physics_thread:crate::physics_worker::new(self.physics,graphics_thread),
} }
} }
pub fn into_worker<'a>(self,scope:&'a std::thread::Scope<'a,'_>,setup_context:crate::setup::SetupContext)->crate::worker::QNWorker<'a,TimedInstruction<WindowInstruction>>{ pub fn into_worker<'a>(self,setup_context:crate::setup::SetupContext)->crate::compat_worker::QNWorker<'a,TimedInstruction<WindowInstruction>>{
let mut window_context=self.into_context(scope,setup_context); let mut window_context=self.into_context(setup_context);
crate::worker::QNWorker::new(scope,move |ins:TimedInstruction<WindowInstruction>|{ crate::compat_worker::QNWorker::new(move |ins:TimedInstruction<WindowInstruction>|{
match ins.instruction{ match ins.instruction{
WindowInstruction::RequestRedraw=>{ WindowInstruction::RequestRedraw=>{
window_context.window.request_redraw(); window_context.window.request_redraw();
@ -240,4 +240,4 @@ impl WindowContextSetup{
} }
}) })
} }
} }

@ -2,31 +2,32 @@
use crate::integer::Planar64; use crate::integer::Planar64;
#[inline] #[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{ 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; 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 //start with f64 sqrt
let planar_radicand=Planar64::raw(unsafe{(radicand as f64).sqrt().to_int_unchecked()}); let planar_radicand=Planar64::raw(unsafe{(radicand as f64).sqrt().to_int_unchecked()});
//TODO: one or two newtons //TODO: one or two newtons
if Planar64::ZERO<a2 { if Planar64::ZERO<a2{
return vec![(-a1-planar_radicand)/(a2*2),(-a1+planar_radicand)/(a2*2)]; ([(-a1-planar_radicand)/(a2*2),(-a1+planar_radicand)/(a2*2)],2)
} else { }else{
return vec![(-a1+planar_radicand)/(a2*2),(-a1-planar_radicand)/(a2*2)]; ([(-a1+planar_radicand)/(a2*2),(-a1-planar_radicand)/(a2*2)],2)
} }
} else if radicand==0 { }else if radicand==0{
return vec![a1/(a2*-2)]; ([a1/(a2*-2),Planar64::ZERO],1)
} else { }else{
return vec![]; ([Planar64::ZERO,Planar64::ZERO],0)
} }
} }
#[inline] #[inline]
pub fn zeroes1(a0:Planar64,a1:Planar64) -> Vec<Planar64> { pub fn zeroes1(a0:Planar64,a1:Planar64)->([Planar64;1],usize){
if a1==Planar64::ZERO{ if a1==Planar64::ZERO{
return vec![]; return ([Planar64::ZERO],0);
} else { }else{
return vec![-a0/a1]; 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/textures/dds/

@ -1 +0,0 @@
mangohud ../target/release/strafe-client bhop_maps/5692152916.rbxm