Compare commits

..

23 Commits

Author SHA1 Message Date
a6dd7f3111 cast bool to int 2023-10-20 13:21:16 -07:00
a6c51654e5 rustge 2023-10-20 00:30:35 -07:00
abbab00eea rewrite 2023-10-18 20:55:05 -07:00
99db653c14 why not it work??? 2023-10-18 20:55:05 -07:00
e9ba0c694c use InputInstruction to drastically reduce the size of mouse instructions 2023-10-18 20:55:05 -07:00
261854cfa5 write_input_instruction 2023-10-18 20:55:05 -07:00
e3eb040675 ideas 2023-10-18 19:10:30 -07:00
fdb8f93b0b how could I forger shaders 2023-10-18 19:10:30 -07:00
a2ce319cb2 modify bot header to not depend on ownership of all blocks 2023-10-18 19:10:30 -07:00
a79157da88 sniffa 2023-10-18 19:10:30 -07:00
7be7d2c0df literally into_worker 2023-10-18 18:21:11 -07:00
cb6b0acd44 TODO: need real functions 2023-10-18 18:21:11 -07:00
cbcf047c3f basic wormholes (no velocity or camera transformation) 2023-10-18 18:21:11 -07:00
6e5de4aa46 overhaul TempIndexedAttributes + add Wormhole indexing 2023-10-18 18:21:11 -07:00
cc776e7cb4 model_id is usize + PhysicsModels struct 2023-10-18 18:21:11 -07:00
5a66ac46b9 functionate that damn code block 2023-10-18 18:21:11 -07:00
38f6e1df3f overhaul attributes 2023-10-18 18:21:11 -07:00
849dcf98f7 overhaul StyleModifiers 2023-10-18 18:21:11 -07:00
d04d1be27e overhaul WalkState + implement ladders 2023-10-18 18:21:11 -07:00
35bfd1d366 implement simulate_move_rotation 2023-10-18 18:21:11 -07:00
586bf8ce89 unpub a bunch of physics stuff 2023-10-18 18:21:11 -07:00
127b205401 implement MoveState + TouchingState 2023-10-18 18:21:11 -07:00
4f596ca5d7 unneeded mut 2023-10-18 16:30:02 -07:00
8 changed files with 380 additions and 259 deletions

@ -12,12 +12,12 @@ use crate::aabb::Aabb;
#[derive(Default)]
pub struct BvhNode{
children:Vec<Self>,
models:Vec<u32>,
models:Vec<usize>,
aabb:Aabb,
}
impl BvhNode{
pub fn the_tester<F:FnMut(u32)>(&self,aabb:&Aabb,f:&mut F){
pub fn the_tester<F:FnMut(usize)>(&self,aabb:&Aabb,f:&mut F){
for &model in &self.models{
f(model);
}
@ -37,7 +37,7 @@ fn generate_bvh_node(boxen:Vec<(usize,Aabb)>)->BvhNode{
let n=boxen.len();
if n<20{
let mut aabb=Aabb::default();
let models=boxen.into_iter().map(|b|{aabb.join(&b.1);b.0 as u32}).collect();
let models=boxen.into_iter().map(|b|{aabb.join(&b.1);b.0}).collect();
BvhNode{
children:Vec::new(),
models,

@ -404,12 +404,11 @@ impl TryFrom<[f32;3]> for Unit32Vec3{
*/
///[-1.0,1.0] = [-2^32,2^32]
#[derive(Clone,Copy,Debug,Hash,Eq,Ord,PartialEq,PartialOrd)]
#[derive(Clone,Copy,Hash,Eq,Ord,PartialEq,PartialOrd)]
pub struct Planar64(i64);
impl Planar64{
pub const ZERO:Self=Self(0);
pub const ONE:Self=Self(1<<32);
pub const FRAC_1_SQRT2:Self=Self(3_037_000_500);
#[inline]
pub const fn int(num:i32)->Self{
Self(Self::ONE.0*num as i64)
@ -564,7 +563,7 @@ impl std::ops::Div<Planar64> for Planar64{
///[-1.0,1.0] = [-2^32,2^32]
#[derive(Clone,Copy,Debug,Default,Hash,Eq,PartialEq)]
#[derive(Clone,Copy,Default,Hash,Eq,PartialEq)]
pub struct Planar64Vec3(glam::I64Vec3);
impl Planar64Vec3{
pub const ZERO:Self=Planar64Vec3(glam::I64Vec3::ZERO);
@ -630,14 +629,6 @@ impl Planar64Vec3{
)>>32) as i64)
}
#[inline]
/* pub fn cross(&self,rhs:Self)->Planar64Vec3{
Planar64Vec3(((
(self.0.x as i128)*(rhs.0.x as i128)+
(self.0.y as i128)*(rhs.0.y as i128)+
(self.0.z as i128)*(rhs.0.z as i128)
)>>32) as i64)
}*/
#[inline]
pub fn length(&self)->Planar64{
let radicand=(self.0.x as i128)*(self.0.x as i128)+(self.0.y as i128)*(self.0.y as i128)+(self.0.z as i128)*(self.0.z as i128);
Planar64(unsafe{(radicand as f64).sqrt().to_int_unchecked()})

@ -49,7 +49,6 @@ fn get_attributes(name:&str,can_collide:bool,velocity:Planar64Vec3,force_interse
let mut intersecting=crate::model::IntersectingAttributes::default();
let mut contacting=crate::model::ContactingAttributes::default();
let mut force_can_collide=can_collide;
const GRAVITY:Planar64Vec3=Planar64Vec3::int(0,-100,0);
match name{
"Water"=>{
force_can_collide=false;
@ -124,20 +123,7 @@ fn get_attributes(name:&str,can_collide:bool,velocity:Planar64Vec3,force_interse
}
//need some way to skip this
if velocity!=Planar64Vec3::ZERO{
//assume all vertical boosters are targetting a height
let vg=velocity.dot(GRAVITY);
if Planar64::ZERO<=vg{
//weird down booster
general.booster=Some(crate::model::GameMechanicBooster::Velocity(velocity));
}else{
println!("set attr");
let gg=GRAVITY.dot(GRAVITY);
let height=-vg*gg.sqrt().sqrt()*Planar64::FRAC_1_SQRT2/gg;//vi/sqrt(-2*a)=d
let v=velocity-GRAVITY*(vg/gg);
//if we are adding zero SO BE IT, the check to see if the vectors are parallel is too sensitive
general.booster=Some(crate::model::GameMechanicBooster::Velocity(v));
general.trajectory=Some(crate::model::GameMechanicSetTrajectory::Height(height));
}
general.booster=Some(crate::model::GameMechanicBooster::Velocity(velocity));
}
match force_can_collide{
true=>{
@ -277,16 +263,17 @@ pub fn generate_indexed_models(dom:rbx_dom_weak::WeakDom) -> crate::model::Index
if let Some(attr)=match &object.name[..]{
"MapStart"=>{
spawn_point=model_transform.transform_point3(Planar64Vec3::ZERO)+Planar64Vec3::Y*5/2;
Some(crate::model::TempIndexedAttributes::Start{mode_id:0})
Some(crate::model::TempIndexedAttributes::Start(crate::model::TempAttrStart{mode_id:0}))
},
"UnorderedCheckpoint"=>Some(crate::model::TempIndexedAttributes::UnorderedCheckpoint{mode_id:0}),
"UnorderedCheckpoint"=>Some(crate::model::TempIndexedAttributes::UnorderedCheckpoint(crate::model::TempAttrUnorderedCheckpoint{mode_id:0})),
other=>{
let regman=lazy_regex::regex!(r"^(BonusStart|Spawn|ForceSpawn|OrderedCheckpoint)(\d+)$");
let regman=lazy_regex::regex!(r"^(BonusStart|Spawn|ForceSpawn|OrderedCheckpoint|WormholeOut)(\d+)$");
if let Some(captures) = regman.captures(other) {
match &captures[1]{
"BonusStart"=>Some(crate::model::TempIndexedAttributes::Start{mode_id:captures[2].parse::<u32>().unwrap()}),
"Spawn"|"ForceSpawn"=>Some(crate::model::TempIndexedAttributes::Spawn{mode_id:0,stage_id:captures[2].parse::<u32>().unwrap()}),
"OrderedCheckpoint"=>Some(crate::model::TempIndexedAttributes::OrderedCheckpoint{mode_id:0,checkpoint_id:captures[2].parse::<u32>().unwrap()}),
"BonusStart"=>Some(crate::model::TempIndexedAttributes::Start(crate::model::TempAttrStart{mode_id:captures[2].parse::<u32>().unwrap()})),
"Spawn"|"ForceSpawn"=>Some(crate::model::TempIndexedAttributes::Spawn(crate::model::TempAttrSpawn{mode_id:0,stage_id:captures[2].parse::<u32>().unwrap()})),
"OrderedCheckpoint"=>Some(crate::model::TempIndexedAttributes::OrderedCheckpoint(crate::model::TempAttrOrderedCheckpoint{mode_id:0,checkpoint_id:captures[2].parse::<u32>().unwrap()})),
"WormholeOut"=>Some(crate::model::TempIndexedAttributes::Wormhole(crate::model::TempAttrWormhole{wormhole_id:captures[2].parse::<u32>().unwrap()})),
_=>None,
}
}else{

@ -11,6 +11,7 @@ mod model_graphics;
mod zeroes;
mod worker;
mod physics;
mod sniffer;
mod settings;
mod framework;
mod primitives;

@ -50,44 +50,50 @@ pub struct IndexedModelInstances{
}
//stage description referencing flattened ids is spooky, but the map loading is meant to be deterministic.
pub struct ModeDescription{
pub start:u32,//start=model_id
pub spawns:Vec<u32>,//spawns[spawn_id]=model_id
pub ordered_checkpoints:Vec<u32>,//ordered_checkpoints[checkpoint_id]=model_id
pub unordered_checkpoints:Vec<u32>,//unordered_checkpoints[checkpoint_id]=model_id
pub start:usize,//start=model_id
pub spawns:Vec<usize>,//spawns[spawn_id]=model_id
pub ordered_checkpoints:Vec<usize>,//ordered_checkpoints[checkpoint_id]=model_id
pub unordered_checkpoints:Vec<usize>,//unordered_checkpoints[checkpoint_id]=model_id
pub spawn_from_stage_id:std::collections::HashMap::<u32,usize>,
pub ordered_checkpoint_from_checkpoint_id:std::collections::HashMap::<u32,usize>,
}
impl ModeDescription{
pub fn get_spawn_model_id(&self,stage_id:u32)->Option<&u32>{
if let Some(&spawn)=self.spawn_from_stage_id.get(&stage_id){
self.spawns.get(spawn)
}else{
None
}
pub fn get_spawn_model_id(&self,stage_id:u32)->Option<&usize>{
self.spawns.get(*self.spawn_from_stage_id.get(&stage_id)?)
}
pub fn get_ordered_checkpoint_model_id(&self,checkpoint_id:u32)->Option<&u32>{
if let Some(&checkpoint)=self.ordered_checkpoint_from_checkpoint_id.get(&checkpoint_id){
self.ordered_checkpoints.get(checkpoint)
}else{
None
}
pub fn get_ordered_checkpoint_model_id(&self,checkpoint_id:u32)->Option<&usize>{
self.ordered_checkpoints.get(*self.ordered_checkpoint_from_checkpoint_id.get(&checkpoint_id)?)
}
}
//I don't want this code to exist!
#[derive(Clone)]
pub struct TempAttrStart{
pub mode_id:u32,
}
#[derive(Clone)]
pub struct TempAttrSpawn{
pub mode_id:u32,
pub stage_id:u32,
}
#[derive(Clone)]
pub struct TempAttrOrderedCheckpoint{
pub mode_id:u32,
pub checkpoint_id:u32,
}
#[derive(Clone)]
pub struct TempAttrUnorderedCheckpoint{
pub mode_id:u32,
}
#[derive(Clone)]
pub struct TempAttrWormhole{
pub wormhole_id:u32,
}
pub enum TempIndexedAttributes{
Start{
mode_id:u32,
},
Spawn{
mode_id:u32,
stage_id:u32,
},
OrderedCheckpoint{
mode_id:u32,
checkpoint_id:u32,
},
UnorderedCheckpoint{
mode_id:u32,
},
Start(TempAttrStart),
Spawn(TempAttrSpawn),
OrderedCheckpoint(TempAttrOrderedCheckpoint),
UnorderedCheckpoint(TempAttrUnorderedCheckpoint),
Wormhole(TempAttrWormhole),
}
//you have this effect while in contact
@ -119,12 +125,12 @@ pub enum GameMechanicBooster{
Velocity(Planar64Vec3),//straight up boost velocity adds to your current velocity
Energy{direction:Planar64Vec3,energy:Planar64},//increase energy in direction
}
#[derive(Clone,Debug)]
#[derive(Clone)]
pub enum TrajectoryChoice{
HighArcLongDuration,//underhand lob at target: less horizontal speed and more air time
LowArcShortDuration,//overhand throw at target: more horizontal speed and less air time
}
#[derive(Clone,Debug)]
#[derive(Clone)]
pub enum GameMechanicSetTrajectory{
AirTime(Time),//air time (relative to gravity direction) is invariant across mass and gravity changes
Height(Planar64),//boost height (relative to gravity direction) is invariant across mass and gravity changes

@ -18,9 +18,7 @@ pub enum PhysicsInstruction {
Input(PhysicsInputInstruction),
}
#[derive(Debug)]
pub enum PhysicsInputInstruction {
ReplaceMouse(MouseState,MouseState),
SetNextMouse(MouseState),
pub enum PhysicsInputInstruction{
SetMoveRight(bool),
SetMoveUp(bool),
SetMoveBack(bool),
@ -29,26 +27,51 @@ pub enum PhysicsInputInstruction {
SetMoveForward(bool),
SetJump(bool),
SetZoom(bool),
ReplaceMouse(MouseState,MouseState),
SetNextMouse(MouseState),
Reset,
Idle,
}
#[derive(Debug)]
#[repr(u32)]
pub enum InputInstruction {
MoveMouse(glam::IVec2),
MoveRight(bool),
MoveUp(bool),
MoveBack(bool),
MoveLeft(bool),
MoveDown(bool),
MoveForward(bool),
Jump(bool),
Zoom(bool),
Reset,
Idle,
MoveRight(bool)=0,
MoveUp(bool)=1,
MoveBack(bool)=2,
MoveLeft(bool)=3,
MoveDown(bool)=4,
MoveForward(bool)=5,
Jump(bool)=6,
Zoom(bool)=7,
MoveMouse(glam::IVec2)=64,
Reset=100,
Idle=127,
//Idle: there were no input events, but the simulation is safe to advance to this timestep
//for interpolation / networking / playback reasons, most playback heads will always want
//to be 1 instruction ahead to generate the next state for interpolation.
}
impl InputInstruction{
pub fn id(&self)->u32{
let parity=match self{
crate::physics::InputInstruction::MoveRight(s)
|crate::physics::InputInstruction::MoveUp(s)
|crate::physics::InputInstruction::MoveBack(s)
|crate::physics::InputInstruction::MoveLeft(s)
|crate::physics::InputInstruction::MoveDown(s)
|crate::physics::InputInstruction::MoveForward(s)
|crate::physics::InputInstruction::Jump(s)
|crate::physics::InputInstruction::Zoom(s)=>(*s as u32)<<31,
crate::physics::InputInstruction::MoveMouse(_)
|crate::physics::InputInstruction::Reset
|crate::physics::InputInstruction::Idle=>0u32,
};
self.discriminant()|parity
}
pub fn discriminant(&self)->u32{
//from documentation for std::mem::discriminant(&self)
unsafe{*<*const _>::from(self).cast::<u32>()}
}
}
#[derive(Clone,Hash)]
pub struct Body {
position: Planar64Vec3,//I64 where 2^32 = 1 u
@ -57,38 +80,6 @@ pub struct Body {
time:Time,//nanoseconds x xxxxD!
}
pub enum MoveRestriction {
Air,
Water,
Ground,
Ladder,//multiple ladders how
}
/*
enum InputInstruction {
}
struct InputState {
}
impl InputState {
pub fn get_control(&self,control:u32) -> bool {
self.controls&control!=0
}
}
impl crate::instruction::InstructionEmitter<InputInstruction> for InputState{
fn next_instruction(&self, time_limit:crate::body::Time) -> Option<TimedInstruction<InputInstruction>> {
//this is polled by PhysicsState for actions like Jump
//no, it has to be the other way around. physics is run up until the jump instruction, and then the jump instruction is pushed.
self.queue.get(0)
}
}
impl crate::instruction::InstructionConsumer<InputInstruction> for InputState{
fn process_instruction(&mut self,ins:TimedInstruction<InputInstruction>){
//add to queue
self.queue.push(ins);
}
}
*/
//hey dumbass just use a delta
#[derive(Clone,Debug)]
pub struct MouseState {
@ -130,7 +121,7 @@ struct WalkState{
impl WalkEnum{
//args going crazy
//(walk_enum,body.acceleration)=with_target_velocity();
fn with_target_velocity(touching:&TouchingState,body:&Body,style:&StyleModifiers,models:&Vec<ModelPhysics>,mut velocity:Planar64Vec3,normal:&Planar64Vec3)->(WalkEnum,Planar64Vec3){
fn with_target_velocity(touching:&TouchingState,body:&Body,style:&StyleModifiers,models:&PhysicsModels,mut velocity:Planar64Vec3,normal:&Planar64Vec3)->(WalkEnum,Planar64Vec3){
touching.constrain_velocity(models,&mut velocity);
let mut target_diff=velocity-body.velocity;
//remove normal component
@ -156,14 +147,14 @@ impl WalkEnum{
}
}
impl WalkState{
fn ground(touching:&TouchingState,body:&Body,style:&StyleModifiers,models:&Vec<ModelPhysics>,mut velocity:Planar64Vec3)->(Self,Planar64Vec3){
fn ground(touching:&TouchingState,body:&Body,style:&StyleModifiers,models:&PhysicsModels,velocity:Planar64Vec3)->(Self,Planar64Vec3){
let (walk_enum,a)=WalkEnum::with_target_velocity(touching,body,style,models,velocity,&Planar64Vec3::Y);
(Self{
state:walk_enum,
normal:Planar64Vec3::Y,
},a)
}
fn ladder(touching:&TouchingState,body:&Body,style:&StyleModifiers,models:&Vec<ModelPhysics>,mut velocity:Planar64Vec3,normal:&Planar64Vec3)->(Self,Planar64Vec3){
fn ladder(touching:&TouchingState,body:&Body,style:&StyleModifiers,models:&PhysicsModels,velocity:Planar64Vec3,normal:&Planar64Vec3)->(Self,Planar64Vec3){
let (walk_enum,a)=WalkEnum::with_target_velocity(touching,body,style,models,velocity,normal);
(Self{
state:walk_enum,
@ -172,7 +163,62 @@ impl WalkState{
}
}
struct Modes{
modes:Vec<crate::model::ModeDescription>,
mode_from_mode_id:std::collections::HashMap::<u32,usize>,
}
impl Modes{
fn clear(&mut self){
self.modes.clear();
self.mode_from_mode_id.clear();
}
fn get_mode(&self,mode_id:u32)->Option<&crate::model::ModeDescription>{
self.modes.get(*self.mode_from_mode_id.get(&mode_id)?)
}
fn insert(&mut self,temp_map_mode_id:u32,mode:crate::model::ModeDescription){
let mode_id=self.modes.len();
self.mode_from_mode_id.insert(temp_map_mode_id,mode_id);
self.modes.push(mode);
}
}
impl Default for Modes{
fn default() -> Self {
Self{
modes:Vec::new(),
mode_from_mode_id:std::collections::HashMap::new(),
}
}
}
struct PhysicsModels{
models:Vec<ModelPhysics>,
model_id_from_wormhole_id:std::collections::HashMap::<u32,usize>,
}
impl PhysicsModels{
fn clear(&mut self){
self.models.clear();
self.model_id_from_wormhole_id.clear();
}
fn get(&self,i:usize)->Option<&ModelPhysics>{
self.models.get(i)
}
fn get_wormhole_model(&self,wormhole_id:u32)->Option<&ModelPhysics>{
self.models.get(*self.model_id_from_wormhole_id.get(&wormhole_id)?)
}
fn push(&mut self,model:ModelPhysics)->usize{
let model_id=self.models.len();
self.models.push(model);
model_id
}
}
impl Default for PhysicsModels{
fn default() -> Self {
Self{
models:Vec::new(),
model_id_from_wormhole_id:std::collections::HashMap::new(),
}
}
}
#[derive(Clone)]
pub struct PhysicsCamera {
@ -512,11 +558,10 @@ pub struct PhysicsState{
controls:u32,
move_state:MoveState,
//all models
models:Vec<ModelPhysics>,
models:PhysicsModels,
bvh:crate::bvh::BvhNode,
modes:Vec<crate::model::ModeDescription>,
mode_from_mode_id:std::collections::HashMap::<u32,usize>,
modes:Modes,
//the spawn point is where you spawn when you load into the map.
//This is not the same as Reset which teleports you to Spawn0
pub spawn_point:Planar64Vec3,
@ -592,44 +637,44 @@ impl ModelPhysics {
//OR have a separate list from contacts for model intersection
#[derive(Debug,Clone,Eq,Hash,PartialEq)]
pub struct RelativeCollision {
face: TreyMeshFace,//just an id
model: u32,//using id to avoid lifetimes
face:TreyMeshFace,//just an id
model:usize,//using id to avoid lifetimes
}
impl RelativeCollision {
pub fn model<'a>(&self,models:&'a Vec<ModelPhysics>)->Option<&'a ModelPhysics>{
models.get(self.model as usize)
fn model<'a>(&self,models:&'a PhysicsModels)->Option<&'a ModelPhysics>{
models.get(self.model)
}
// pub fn mesh(&self,models:&Vec<ModelPhysics>) -> TreyMesh {
// return self.model(models).unwrap().face_mesh(self.face).clone()
// }
pub fn normal(&self,models:&Vec<ModelPhysics>) -> Planar64Vec3 {
fn normal(&self,models:&PhysicsModels) -> Planar64Vec3 {
return self.model(models).unwrap().face_normal(self.face)
}
}
struct TouchingState{
contacts:std::collections::HashMap::<u32,RelativeCollision>,
intersects:std::collections::HashMap::<u32,RelativeCollision>,
contacts:std::collections::HashMap::<usize,RelativeCollision>,
intersects:std::collections::HashMap::<usize,RelativeCollision>,
}
impl TouchingState{
fn clear(&mut self){
self.contacts.clear();
self.intersects.clear();
}
fn insert_contact(&mut self,model_id:u32,collision:RelativeCollision)->Option<RelativeCollision>{
fn insert_contact(&mut self,model_id:usize,collision:RelativeCollision)->Option<RelativeCollision>{
self.contacts.insert(model_id,collision)
}
fn remove_contact(&mut self,model_id:u32)->Option<RelativeCollision>{
fn remove_contact(&mut self,model_id:usize)->Option<RelativeCollision>{
self.contacts.remove(&model_id)
}
fn insert_intersect(&mut self,model_id:u32,collision:RelativeCollision)->Option<RelativeCollision>{
fn insert_intersect(&mut self,model_id:usize,collision:RelativeCollision)->Option<RelativeCollision>{
self.intersects.insert(model_id,collision)
}
fn remove_intersect(&mut self,model_id:u32)->Option<RelativeCollision>{
fn remove_intersect(&mut self,model_id:usize)->Option<RelativeCollision>{
self.intersects.remove(&model_id)
}
fn constrain_velocity(&self,models:&Vec<ModelPhysics>,velocity:&mut Planar64Vec3){
fn constrain_velocity(&self,models:&PhysicsModels,velocity:&mut Planar64Vec3){
for (_,contact) in &self.contacts {
let n=contact.normal(models);
let d=velocity.dot(n);
@ -638,7 +683,7 @@ impl TouchingState{
}
}
}
fn constrain_acceleration(&self,models:&Vec<ModelPhysics>,acceleration:&mut Planar64Vec3){
fn constrain_acceleration(&self,models:&PhysicsModels,acceleration:&mut Planar64Vec3){
for (_,contact) in &self.contacts {
let n=contact.normal(models);
let d=acceleration.dot(n);
@ -694,7 +739,7 @@ impl Default for PhysicsState{
time: Time::ZERO,
style:StyleModifiers::default(),
touching:TouchingState::default(),
models: Vec::new(),
models:PhysicsModels::default(),
bvh:crate::bvh::BvhNode::default(),
move_state: MoveState::Air,
camera: PhysicsCamera::from_offset(Planar64Vec3::int(0,2,0)),//4.5-2.5=2
@ -702,8 +747,7 @@ impl Default for PhysicsState{
controls: 0,
world:WorldState{},
game:GameMechanicsState::default(),
modes:Vec::new(),
mode_from_mode_id:std::collections::HashMap::new(),
modes:Modes::default(),
}
}
}
@ -818,81 +862,70 @@ impl PhysicsState {
//make aabb and run vertices to get realistic bounds
for model_instance in &model.instances{
if let Some(model_physics)=ModelPhysics::from_model(model,model_instance){
let model_id=self.models.len() as u32;
self.models.push(model_physics);
let model_id=self.models.push(model_physics);
for attr in &model_instance.temp_indexing{
match attr{
crate::model::TempIndexedAttributes::Start{mode_id}=>starts.push((*mode_id,model_id)),
crate::model::TempIndexedAttributes::Spawn{mode_id,stage_id}=>spawns.push((*mode_id,model_id,*stage_id)),
crate::model::TempIndexedAttributes::OrderedCheckpoint{mode_id,checkpoint_id}=>ordered_checkpoints.push((*mode_id,model_id,*checkpoint_id)),
crate::model::TempIndexedAttributes::UnorderedCheckpoint{mode_id}=>unordered_checkpoints.push((*mode_id,model_id)),
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::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);},
}
}
}
}
}
self.bvh=crate::bvh::generate_bvh(self.models.iter().map(|m|m.mesh().clone()).collect());
self.bvh=crate::bvh::generate_bvh(self.models.models.iter().map(|m|m.mesh().clone()).collect());
//I don't wanna write structs for temporary structures
//this code builds ModeDescriptions from the unsorted lists at the top of the function
starts.sort_by_key(|tup|tup.0);
let mut eshmep=std::collections::HashMap::new();
let mut modedatas:Vec<(u32,Vec<(u32,u32)>,Vec<(u32,u32)>,Vec<u32>)>=starts.into_iter().enumerate().map(|(i,tup)|{
eshmep.insert(tup.0,i);
(tup.1,Vec::new(),Vec::new(),Vec::new())
starts.sort_by_key(|tup|tup.1.mode_id);
let mut mode_id_from_map_mode_id=std::collections::HashMap::new();
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);
(model_id,Vec::new(),Vec::new(),Vec::new(),s.mode_id)
}).collect();
for tup in spawns{
if let Some(mode_id)=eshmep.get(&tup.0){
for (model_id,s) in spawns{
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.1.push((tup.2,tup.1));
modedata.1.push((s.stage_id,model_id));
}
}
}
for tup in ordered_checkpoints{
if let Some(mode_id)=eshmep.get(&tup.0){
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((tup.2,tup.1));
modedata.2.push((s.checkpoint_id,model_id));
}
}
}
for tup in unordered_checkpoints{
if let Some(mode_id)=eshmep.get(&tup.0){
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(tup.1);
modedata.3.push(model_id);
}
}
}
let num_modes=self.modes.len();
for (mode_id,mode) in eshmep{
self.mode_from_mode_id.insert(mode_id,num_modes+mode);
}
self.modes.append(&mut modedatas.into_iter().map(|mut tup|{
for mut tup in modedatas.into_iter(){
tup.1.sort_by_key(|tup|tup.0);
tup.2.sort_by_key(|tup|tup.0);
let mut eshmep1=std::collections::HashMap::new();
let mut eshmep2=std::collections::HashMap::new();
crate::model::ModeDescription{
self.modes.insert(tup.4,crate::model::ModeDescription{
start:tup.0,
spawns:tup.1.into_iter().enumerate().map(|(i,tup)|{eshmep1.insert(tup.0,i);tup.1}).collect(),
ordered_checkpoints:tup.2.into_iter().enumerate().map(|(i,tup)|{eshmep2.insert(tup.0,i);tup.1}).collect(),
unordered_checkpoints:tup.3,
spawn_from_stage_id:eshmep1,
ordered_checkpoint_from_checkpoint_id:eshmep2,
}
}).collect());
println!("Physics Objects: {}",self.models.len());
});
}
println!("Physics Objects: {}",self.models.models.len());
}
pub fn load_user_settings(&mut self,user_settings:&crate::settings::UserSettings){
self.camera.sensitivity=user_settings.calculate_sensitivity();
}
pub fn get_mode(&self,mode_id:u32)->Option<&crate::model::ModeDescription>{
if let Some(&mode)=self.mode_from_mode_id.get(&mode_id){
self.modes.get(mode)
}else{
None
}
}
//tickless gaming
pub fn run(&mut self, time_limit:Time){
//prepare is ommitted - everything is done via instructions.
@ -924,7 +957,7 @@ impl PhysicsState {
fn next_strafe_instruction(&self) -> Option<TimedInstruction<PhysicsInstruction>> {
return Some(TimedInstruction{
time:Time::from_nanos(self.style.strafe_tick_rate.rhs_div_int(self.style.strafe_tick_rate.mul_int(self.time.nanos()+1)+1)),
time:Time::from_nanos(self.style.strafe_tick_rate.rhs_div_int(self.style.strafe_tick_rate.mul_int(self.time.nanos())+1)),
//only poll the physics if there is a before and after mouse event
instruction:PhysicsInstruction::StrafeTick
});
@ -1149,9 +1182,9 @@ impl PhysicsState {
}
None
}
fn predict_collision_start(&self,time:Time,time_limit:Time,model_id:u32) -> Option<TimedInstruction<PhysicsInstruction>> {
fn predict_collision_start(&self,time:Time,time_limit:Time,model_id:usize) -> Option<TimedInstruction<PhysicsInstruction>> {
let mesh0=self.mesh();
let mesh1=self.models.get(model_id as usize).unwrap().mesh();
let mesh1=self.models.get(model_id).unwrap().mesh();
let (p,v,a,body_time)=(self.body.position,self.body.velocity,self.body.acceleration,self.body.time);
//find best t
let mut best_time=time_limit;
@ -1256,12 +1289,12 @@ impl PhysicsState {
}
}
//generate instruction
if let Some(face) = best_face{
return Some(TimedInstruction {
if let Some(face)=best_face{
return Some(TimedInstruction{
time: best_time,
instruction: PhysicsInstruction::CollisionStart(RelativeCollision {
instruction:PhysicsInstruction::CollisionStart(RelativeCollision{
face,
model: model_id
model:model_id
})
})
}
@ -1275,6 +1308,7 @@ impl crate::instruction::InstructionEmitter<PhysicsInstruction> for PhysicsState
//JUST POLLING!!! NO MUTATION
let mut collector = crate::instruction::InstructionCollector::new(time_limit);
//check for collision stop instructions with curent contacts
//TODO: make this into a touching.next_instruction(&mut collector) member function
for (_,collision_data) in &self.touching.contacts {
collector.collect(self.predict_collision_end(self.time,time_limit,collision_data));
}
@ -1296,6 +1330,45 @@ impl crate::instruction::InstructionEmitter<PhysicsInstruction> for PhysicsState
}
}
fn teleport(body:&mut Body,touching:&mut TouchingState,style:&StyleModifiers,point:Planar64Vec3)->MoveState{
body.position=point;
//manual clear //for c in contacts{process_instruction(CollisionEnd(c))}
touching.clear();
body.acceleration=style.gravity;
MoveState::Air
//TODO: calculate contacts and determine the actual state
//touching.recalculate(body);
}
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{
Some(crate::model::TeleportBehaviour::StageElement(stage_element))=>{
if stage_element.force||game.stage_id<stage_element.stage_id{
game.stage_id=stage_element.stage_id;
}
match &stage_element.behaviour{
crate::model::StageElementBehaviour::SpawnAt=>None,
crate::model::StageElementBehaviour::Trigger
|crate::model::StageElementBehaviour::Teleport=>{
//I guess this is correct behaviour when trying to teleport to a non-existent spawn but it's still weird
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::JumpLimit(_)=>None,//TODO
}
},
Some(crate::model::TeleportBehaviour::Wormhole(wormhole))=>{
let origin_model=model;
let destination_model=models.get_wormhole_model(wormhole.destination_model_id)?;
//ignore the transform for now
Some(teleport(body,touching,style,body.position-origin_model.transform.translation+destination_model.transform.translation))
}
None=>None,
}
}
impl crate::instruction::InstructionConsumer<PhysicsInstruction> for PhysicsState {
fn process_instruction(&mut self, ins:TimedInstruction<PhysicsInstruction>) {
match &ins.instruction {
@ -1349,37 +1422,8 @@ impl crate::instruction::InstructionConsumer<PhysicsInstruction> for PhysicsStat
}
//check ground
self.touching.insert_contact(c.model,c);
match &general.teleport_behaviour{
Some(crate::model::TeleportBehaviour::StageElement(stage_element))=>{
if stage_element.force||self.game.stage_id<stage_element.stage_id{
self.game.stage_id=stage_element.stage_id;
}
match &stage_element.behaviour{
crate::model::StageElementBehaviour::SpawnAt=>(),
crate::model::StageElementBehaviour::Trigger
|crate::model::StageElementBehaviour::Teleport=>{
//TODO make good
if let Some(mode)=self.get_mode(stage_element.mode_id){
if let Some(&spawn)=mode.get_spawn_model_id(self.game.stage_id){
if let Some(model)=self.models.get(spawn as usize){
self.body.position=model.transform.transform_point3(Planar64Vec3::Y)+Planar64Vec3::Y*(self.style.hitbox_halfsize.y()+Planar64::ONE/16);
//manual clear //for c in self.contacts{process_instruction(CollisionEnd(c))}
self.touching.clear();
self.body.acceleration=self.style.gravity;
self.move_state=MoveState::Air;//TODO: calculate contacts and determine the actual state
}else{println!("bad1");}
}else{println!("bad2");}
}else{println!("bad3");}
},
crate::model::StageElementBehaviour::Platform=>(),
crate::model::StageElementBehaviour::JumpLimit(_)=>(),//TODO
}
},
Some(crate::model::TeleportBehaviour::Wormhole(wormhole))=>{
//telefart
}
None=>(),
}
//I love making functions with 10 arguments to dodge the borrow checker
run_teleport_behaviour(&general.teleport_behaviour,&mut self.game,&self.models,&self.modes,&self.style,&mut self.touching,&mut self.body,model);
//flatten v
self.touching.constrain_velocity(&self.models,&mut v);
match &general.booster{
@ -1395,25 +1439,13 @@ impl crate::instruction::InstructionConsumer<PhysicsInstruction> for PhysicsStat
}
match &general.trajectory{
Some(trajectory)=>{
println!("??? {:?}",trajectory);
match trajectory{
&crate::model::GameMechanicSetTrajectory::Height(height)=>{
//vg=sqrt(-2*gg*height)
println!("height booster h={}",height);
let vg=v.dot(self.style.gravity);
let gg=self.style.gravity.dot(self.style.gravity);
let hb=(gg.sqrt()*height*2).sqrt()*gg.sqrt();
println!("hb={} vg={}",hb,vg);
let b=self.style.gravity*((-hb-vg)/gg);
println!("bopo {}",b);
v+=b;
},
crate::model::GameMechanicSetTrajectory::AirTime(_) => todo!(),
crate::model::GameMechanicSetTrajectory::Height(_) => todo!(),
crate::model::GameMechanicSetTrajectory::TargetPointTime { target_point, time } => todo!(),
crate::model::GameMechanicSetTrajectory::TrajectoryTargetPoint { target_point, speed, trajectory_choice } => todo!(),
&crate::model::GameMechanicSetTrajectory::Velocity(velocity)=>v=velocity,
crate::model::GameMechanicSetTrajectory::AirTime(_)
|crate::model::GameMechanicSetTrajectory::TargetPointTime{target_point:_,time:_}
|crate::model::GameMechanicSetTrajectory::TrajectoryTargetPoint{target_point:_,speed:_,trajectory_choice:_}
|crate::model::GameMechanicSetTrajectory::DotVelocity{direction:_,dot:_}
=>(),
crate::model::GameMechanicSetTrajectory::DotVelocity { direction, dot } => todo!(),
}
self.touching.constrain_velocity(&self.models,&mut v);
},
@ -1428,37 +1460,7 @@ impl crate::instruction::InstructionConsumer<PhysicsInstruction> for PhysicsStat
PhysicsCollisionAttributes::Intersect{intersecting,general}=>{
//I think that setting the velocity to 0 was preventing surface contacts from entering an infinite loop
self.touching.insert_intersect(c.model,c);
match &general.teleport_behaviour{
Some(crate::model::TeleportBehaviour::StageElement(stage_element))=>{
if stage_element.force||self.game.stage_id<stage_element.stage_id{
self.game.stage_id=stage_element.stage_id;
}
match &stage_element.behaviour{
crate::model::StageElementBehaviour::SpawnAt=>(),
crate::model::StageElementBehaviour::Trigger
|crate::model::StageElementBehaviour::Teleport=>{
//TODO make good
if let Some(mode)=self.get_mode(stage_element.mode_id){
if let Some(&spawn)=mode.get_spawn_model_id(self.game.stage_id){
if let Some(model)=self.models.get(spawn as usize){
self.body.position=model.transform.transform_point3(Planar64Vec3::Y)+Planar64Vec3::Y*(self.style.hitbox_halfsize.y()+Planar64::ONE/16);
//manual clear //for c in self.contacts{process_instruction(CollisionEnd(c))}
self.touching.clear();
self.body.acceleration=self.style.gravity;
self.move_state=MoveState::Air;//TODO: calculate contacts and determine the actual state
}else{println!("bad1");}
}else{println!("bad2");}
}else{println!("bad3");}
},
crate::model::StageElementBehaviour::Platform=>(),
crate::model::StageElementBehaviour::JumpLimit(_)=>(),//TODO
}
},
Some(crate::model::TeleportBehaviour::Wormhole(wormhole))=>{
//telefart
}
None=>(),
}
run_teleport_behaviour(&general.teleport_behaviour,&mut self.game,&self.models,&self.modes,&self.style,&mut self.touching,&mut self.body,model);
},
}
},

134
src/sniffer.rs Normal file

@ -0,0 +1,134 @@
//file format "sniff"
/* spec
//begin global header
//global metadata (32 bytes)
b"SNFB"
u32 format_version
u64 priming_bytes
//how many bytes of the file must be read to guarantee all of the expected
//format-specific metadata is available to facilitate streaming the remaining contents
//used by the database to guarantee that it serves at least the bare minimum
u128 resource_uuid
//identifies the file from anywhere for any other file
//global block layout (variable size)
u64 num_blocks
for block_id in 0..num_blocks{
u64 first_byte
}
//end global header
//begin blocks
//each block is compressed with zstd or gz or something
*/
/* block types
BLOCK_MAP_HEADER:
StyleInfoOverrides style_info_overrides
//bvh goes here
u64 num_nodes
//node 0 parent node is implied to be None
for node_id in 1..num_nodes{
u64 parent_node
}
//block 0 is the current block, not part of the map data
u64 num_spacial_blocks
for block_id in 1..num_spacial_blocks{
u64 node_id
u64 block_id
Aabb block_extents
}
//ideally spacial blocks are sorted from distance to start zone
//texture blocks are inserted before the first spacial block they are used in
BLOCK_MAP_RESOURCE:
//an individual one of the following:
- model (IndexedModel)
- shader (compiled SPIR-V)
- image (JpegXL)
- sound (Opus)
- video (AV1)
- animation (Trey thing)
BLOCK_MAP_OBJECT:
//an individual one of the following:
- model instance
- located resource
//for a list of resources, parse the object.
BLOCK_BOT_HEADER:
u128 map_resource_uuid //which map is this bot running
u128 time_resource_uuid //resource database time
//don't include style info in bot header because it's in the physics state
//blocks are laid out in chronological order, but indices may jump around.
u64 num_segments
for _ in 0..num_segments{
i64 time //physics_state timestamp
u64 block_id
}
BLOCK_BOT_SEGMENT:
//format version indicates what version of these structures to use
PhysicsState physics_state
//to read, greedily decode instructions until eof
loop{
//delta encode as much as possible (time,mousepos)
//strafe ticks are implied
//physics can be implied in an input-only bot file
TimedInstruction<PhysicsInstruction> instruction
}
BLOCK_DEMO_HEADER:
//timeline of loading maps, player equipment, bots
*/
struct InputInstructionCodecState{
mouse_pos:glam::IVec2,
time:crate::integer::Time,
}
//8B - 12B
impl InputInstructionCodecState{
pub fn encode(&mut self,ins:&crate::instruction::TimedInstruction<crate::physics::InputInstruction>)->([u8;12],usize){
let dt=ins.time-self.time;
self.time=ins.time;
let mut data=[0u8;12];
[data[0],data[1],data[2],data[3]]=(dt.nanos() as u32).to_le_bytes();//4B
//instruction id packed with game control parity bit. This could be 1 byte but it ruins the alignment
[data[4],data[5],data[6],data[7]]=ins.instruction.id().to_le_bytes();//4B
match &ins.instruction{
&crate::physics::InputInstruction::MoveMouse(m)=>{//4B
let dm=m-self.mouse_pos;
[data[8],data[9]]=(dm.x as i16).to_le_bytes();
[data[10],data[11]]=(dm.y as i16).to_le_bytes();
self.mouse_pos=m;
(data,12)
},
//0B
crate::physics::InputInstruction::MoveRight(_)
|crate::physics::InputInstruction::MoveUp(_)
|crate::physics::InputInstruction::MoveBack(_)
|crate::physics::InputInstruction::MoveLeft(_)
|crate::physics::InputInstruction::MoveDown(_)
|crate::physics::InputInstruction::MoveForward(_)
|crate::physics::InputInstruction::Jump(_)
|crate::physics::InputInstruction::Zoom(_)
|crate::physics::InputInstruction::Reset
|crate::physics::InputInstruction::Idle=>(data,8),
}
}
}
//everything must be 4 byte aligned, it's all going to be compressed so don't think too had about saving less than 4 bytes
//TODO: Omit (mouse only?) instructions that don't surround an actual physics instruction
fn write_input_instruction<W:std::io::Write>(state:&mut InputInstructionCodecState,w:&mut W,ins:&crate::instruction::TimedInstruction<crate::physics::InputInstruction>)->Result<usize,std::io::Error>{
//TODO: insert idle instruction if gap is over u32 nanoseconds
//TODO: don't write idle instructions
//OR: end the data block! the full state at the start of the next block will contain an absolute timestamp
let (data,size)=state.encode(ins);
w.write(&data[0..size])//8B-12B
}

@ -6,7 +6,7 @@ pub fn zeroes2(a0:Planar64,a1:Planar64,a2:Planar64) -> Vec<Planar64>{
if a2==Planar64::ZERO{
return zeroes1(a0, a1);
}
let mut 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 {
//start with f64 sqrt
let planar_radicand=Planar64::raw(unsafe{(radicand as f64).sqrt().to_int_unchecked()});