28 Commits

Author SHA1 Message Date
4e1ed43161 read bot debug function 2024-08-05 18:42:52 -07:00
00ac7960e0 please don't fill my hard drive 2024-08-05 17:32:03 -07:00
f2e9f81fe4 special place for debug bots 2024-08-05 17:27:17 -07:00
bfcf973524 rethink physics instructions 2024-08-05 17:26:46 -07:00
97da935d9d drop droppable instructions 2024-08-05 13:34:30 -07:00
68ccee81b1 newtypes 2024-08-05 13:34:11 -07:00
2c000cca67 prototype 2024-08-02 13:44:47 -07:00
cd65db0008 newtypes 2024-08-02 13:44:41 -07:00
91b90675c4 prototype 2024-08-02 12:11:23 -07:00
8911968a7c rand dep 2024-08-02 12:11:17 -07:00
d036a33501 v0.1.1 no panic 2024-07-29 18:22:26 -07:00
05c8db4750 don't panic 2024-07-29 18:20:44 -07:00
e3130661f4 v0.1.0 2024-07-29 16:38:32 -07:00
a1ee34c7a3 binrw enums 2024-07-29 16:36:00 -07:00
5d25400942 there's no way that a max heap is better than just sorting 2024-07-27 10:31:44 -07:00
a00b6a63c9 wow it's wrong again 2024-07-26 17:26:57 -07:00
931cef52b1 serial file access 2024-07-26 16:13:51 -07:00
3e8c5167dc do not include unused features 2024-07-26 15:42:38 -07:00
2262c6feac fixes 2024-07-26 15:24:20 -07:00
fa7e7d58bf load textures and meshes in ascending order 2024-07-26 15:10:49 -07:00
0705e879db fix block_location 2024-07-26 12:19:09 -07:00
d3e114c7b6 implement error traits 2024-07-25 17:47:00 -07:00
e1cdddc892 write map 2024-07-25 16:09:03 -07:00
4abeefa7e8 todo: header machinery in file (file.add_block) 2024-07-25 16:09:03 -07:00
47aef14ff3 newtypes from engine types (boilerplate) 2024-07-25 15:35:51 -07:00
3434cd394a implement map file format 2024-07-25 11:33:41 -07:00
b6935b4f5f file tweaks 2024-07-25 11:33:41 -07:00
f0035bcee9 newtypes (boilerplate) 2024-07-25 11:33:41 -07:00
18 changed files with 2215 additions and 77 deletions

102
Cargo.lock generated
View File

@@ -44,12 +44,35 @@ version = "1.16.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b236fc92302c97ed75b38da1f4917b5cdda4984745740f153a5d3059e48d725e"
[[package]]
name = "byteorder"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b"
[[package]]
name = "cfg-if"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
[[package]]
name = "either"
version = "1.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "60b1af1c220855b6ceac025d3f6ecdd2b7c4894bfe9cd9bda4fbb4bc7c0d4cf0"
[[package]]
name = "getrandom"
version = "0.2.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c4567c8db10ae91089c99af84c68c38da3ec2f087c3f82960bcdbf3656b6f4d7"
dependencies = [
"cfg-if",
"libc",
"wasi",
]
[[package]]
name = "glam"
version = "0.28.0"
@@ -67,12 +90,27 @@ dependencies = [
"syn 2.0.72",
]
[[package]]
name = "libc"
version = "0.2.155"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "97b3888a4aecf77e811145cadf6eef5901f4782c53886191b2f693f24761847c"
[[package]]
name = "owo-colors"
version = "3.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c1b04fb49957986fdce4d6ee7a65027d55d4b6d2265e5848bbb507b58ccfdb6f"
[[package]]
name = "ppv-lite86"
version = "0.2.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dee4364d9f3b902ef14fab8a1ddffb783a1cb6b4bba3bfc1fa3922732c7de97f"
dependencies = [
"zerocopy",
]
[[package]]
name = "proc-macro2"
version = "1.0.86"
@@ -91,11 +129,41 @@ dependencies = [
"proc-macro2",
]
[[package]]
name = "rand"
version = "0.8.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404"
dependencies = [
"libc",
"rand_chacha",
"rand_core",
]
[[package]]
name = "rand_chacha"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88"
dependencies = [
"ppv-lite86",
"rand_core",
]
[[package]]
name = "rand_core"
version = "0.6.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c"
dependencies = [
"getrandom",
]
[[package]]
name = "strafesnet_common"
version = "0.1.3"
version = "0.2.0"
source = "sparse+https://git.itzana.me/api/packages/strafesnet/cargo/"
checksum = "10a7e3b69506893bbdde90ce8a9d75cd56d280c0424d2dfdf98f8520179d0c1b"
checksum = "74580c59a09194ce39db49cd814a5c2fc2d61513c88c6b811b5b40c0da6de057"
dependencies = [
"bitflags",
"glam",
@@ -104,10 +172,11 @@ dependencies = [
[[package]]
name = "strafesnet_snf"
version = "0.1.0"
version = "0.1.1"
dependencies = [
"binrw",
"id",
"rand",
"strafesnet_common",
]
@@ -138,3 +207,30 @@ name = "unicode-ident"
version = "1.0.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b"
[[package]]
name = "wasi"
version = "0.11.0+wasi-snapshot-preview1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423"
[[package]]
name = "zerocopy"
version = "0.6.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "854e949ac82d619ee9a14c66a1b674ac730422372ccb759ce0c39cabcf2bf8e6"
dependencies = [
"byteorder",
"zerocopy-derive",
]
[[package]]
name = "zerocopy-derive"
version = "0.6.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "125139de3f6b9d625c39e2efdd73d41bdac468ccd556556440e322be0e1bbd91"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.72",
]

View File

@@ -1,6 +1,6 @@
[package]
name = "strafesnet_snf"
version = "0.1.0"
version = "0.1.1"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
@@ -8,4 +8,5 @@ edition = "2021"
[dependencies]
binrw = "0.14.0"
id = { version = "0.1.0", registry = "strafesnet" }
strafesnet_common = { version = "0.1.3", registry = "strafesnet" }
rand = "0.8.5"
strafesnet_common = { version = "0.2.0", registry = "strafesnet" }

View File

@@ -1,5 +1,9 @@
use binrw::{BinReaderExt, binrw};
use std::io::Seek;
use binrw::{binrw,BinReaderExt,BinWriterExt};
use crate::newtypes::instruction::TimedPhysicsInstruction;
#[derive(Debug)]
pub enum Error{
InvalidHeader,
InvalidSegment(binrw::Error),
@@ -7,6 +11,46 @@ pub enum Error{
File(crate::file::Error),
}
pub struct BotDebug{
name:String,
file:std::fs::File,
}
impl BotDebug{
pub fn new()->std::io::Result<Self>{
let rng:u128=rand::random();
let name=format!("debug_bots/{rng:x}");
Ok(Self{
file:std::fs::File::create(name.as_str())?,
name,
})
}
pub fn delete(self)->std::io::Result<()>{
std::mem::drop(self.file);
std::fs::remove_file(self.name)
}
pub fn push(&mut self,ins:strafesnet_common::instruction::TimedInstruction<strafesnet_common::physics::Instruction>)->Result<(),binrw::Error>{
let ret=match TryInto::<TimedPhysicsInstruction>::try_into(ins){
Ok(ins)=>self.file.write_le(&ins),
Err(crate::newtypes::physics::PhysicsInputInstructionError::DropInstruction)=>Ok(()),
};
//check if too much data has written to be reasonable
//avoid filling my hard drive on an infinite loop basically
if self.file.stream_position().is_ok_and(|pos|50*1024*1024<pos){
panic!();
}
ret
}
}
pub fn read_bot_debug(mut reader:impl BinReaderExt)->Result<Vec<strafesnet_common::instruction::TimedInstruction<strafesnet_common::physics::Instruction>>,binrw::Error>{
let mut instructions=Vec::new();
while let Ok(ins)=reader.read_le::<TimedPhysicsInstruction>(){
instructions.push(ins.try_into().unwrap());
}
Ok(instructions)
}
/* block types
BLOCK_BOT_HEADER:
@@ -64,7 +108,7 @@ mod simulation{
#[binrw]
#[brw(little)]
#[derive(Clone,Copy,id::Id)]
#[derive(Clone,Copy,Debug,id::Id)]
pub struct SegmentId(u32);
#[binrw]

View File

@@ -1,5 +1,6 @@
use binrw::BinReaderExt;
#[derive(Debug)]
pub enum Error{
InvalidHeader,
}
@@ -27,4 +28,4 @@ impl<R:BinReaderExt> StreamableDemo<R>{
pub(crate) fn new(file:crate::file::File<R>)->Result<Self,Error>{
Err(Error::InvalidHeader)
}
}
}

View File

@@ -2,12 +2,19 @@
use binrw::{binrw, BinReaderExt, io::TakeSeekExt};
#[derive(Debug)]
pub enum Error{
InvalidHeader(binrw::Error),
UnexpectedEOF,
InvalidBlockId(BlockId),
Seek(std::io::Error),
}
impl std::fmt::Display for Error{
fn fmt(&self,f:&mut std::fmt::Formatter<'_>)->std::fmt::Result{
write!(f,"{self:?}")
}
}
impl std::error::Error for Error{}
/* spec
@@ -40,7 +47,7 @@ for block_id in 1..num_blocks{
*/
#[binrw]
#[brw(little)]
#[derive(Clone,Copy)]
#[derive(Clone,Copy,Debug)]
pub(crate) enum FourCC{
#[brw(magic=b"SNFM")]
Map,
@@ -51,24 +58,25 @@ pub(crate) enum FourCC{
}
#[binrw]
#[brw(little)]
struct Header{
#[derive(Debug)]
pub struct Header{
/// Type of file
fourcc:FourCC,
/// Type version
version:u32,
pub fourcc:FourCC,
/// File format version
pub version:u32,
/// Minimum data required to know the location of all streamable resources for this specific file
priming:u64,
pub priming:u64,
/// uuid for this file
resource:u128,
pub resource:u128,
//don't need try_calc: the struct will force field initialization anyways and it can be calculated there
block_count:u32,
pub block_count:u32,
#[br(count=block_count+1)]
block_location:Vec<u64>,
pub block_location:Vec<u64>,
}
#[binrw]
#[brw(little)]
#[derive(Clone,Copy,Hash,id::Id,Eq,PartialEq)]
#[derive(Clone,Copy,Debug,Hash,id::Id,Eq,Ord,PartialEq,PartialOrd)]
pub struct BlockId(u32);
pub(crate) struct File<R:BinReaderExt>{
@@ -84,6 +92,9 @@ impl<R:BinReaderExt> File<R>{
data:input,
})
}
pub(crate) fn as_mut(&mut self)->&mut R{
&mut self.data
}
pub(crate) fn block_reader(&mut self,block_id:BlockId)->Result<binrw::io::TakeSeek<&mut R>,Error>{
if self.header.block_location.len() as u32<=block_id.get(){
return Err(Error::InvalidBlockId(block_id))
@@ -91,7 +102,7 @@ impl<R:BinReaderExt> File<R>{
let block_start=self.header.block_location[block_id.get() as usize];
let block_end=self.header.block_location[block_id.get() as usize+1];
self.data.seek(std::io::SeekFrom::Start(block_start)).map_err(Error::Seek)?;
Ok((&mut self.data).take_seek(block_end-block_start))
Ok(self.as_mut().take_seek(block_end-block_start))
}
pub(crate) fn fourcc(&self)->FourCC{
self.header.fourcc

View File

@@ -1,10 +1,13 @@
use binrw::BinReaderExt;
pub mod file;
mod newtypes;
mod file;
pub mod map;
pub mod bot;
pub mod demo;
#[derive(Debug)]
pub enum Error{
UnexpectedFourCC,
Header(file::Error),
@@ -12,6 +15,12 @@ pub enum Error{
Bot(bot::Error),
Demo(demo::Error),
}
impl std::fmt::Display for Error{
fn fmt(&self,f:&mut std::fmt::Formatter<'_>)->std::fmt::Result{
write!(f,"{self:?}")
}
}
impl std::error::Error for Error{}
pub enum SNF<R:BinReaderExt>{
Map(map::StreamableMap<R>),

View File

@@ -1,23 +1,45 @@
//use strafesnet_common::model;
//use strafesnet_common::gameplay_modes;
use binrw::{BinReaderExt, binrw};
use std::io::Read;
use std::collections::HashMap;
use crate::newtypes;
use crate::file::BlockId;
use binrw::{binrw,BinReaderExt,BinWriterExt};
use strafesnet_common::model;
use strafesnet_common::aabb::Aabb;
use strafesnet_common::bvh::BvhNode;
use strafesnet_common::gameplay_modes;
#[derive(Debug)]
pub enum Error{
InvalidHeader,
InvalidBvhNodeId(BvhNodeId),
InvalidRegion(binrw::Error),
InvalidHeader(binrw::Error),
InvalidMode(newtypes::gameplay_modes::ModeError),
InvalidBlockId(BlockId),
InvalidMeshId(model::MeshId),
InvalidModelId(model::ModelId),
InvalidTextureId(model::TextureId),
InvalidData(binrw::Error),
IO(std::io::Error),
File(crate::file::Error),
}
impl std::fmt::Display for Error{
fn fmt(&self,f:&mut std::fmt::Formatter<'_>)->std::fmt::Result{
write!(f,"{self:?}")
}
}
impl std::error::Error for Error{}
/* block types
BLOCK_MAP_HEADER:
DefaultStyleInfo style_info
//bvh goes here
u64 num_nodes
u32 num_nodes
u32 num_spacial_blocks
u32 num_resource_blocks
u32 num_resources_external
//node 0 parent node is implied to be None
for node_id in 1..num_nodes{
u64 parent_node
u32 parent_node
}
//NOTE: alternate realities are not necessary.
@@ -26,17 +48,21 @@ for node_id in 1..num_nodes{
//ideally spacial blocks are sorted from distance to start zone
//texture blocks are inserted before the first spacial block they are used in
u64 num_spacial_blocks
for spacial_block_id in 0..num_spacial_blocks{
u64 node_id
u64 block_id //data block
Aabb block_extents
u32 node_id
u32 block_id //data block
Aabb extents
}
//if the map file references external resources, num_resources = 0
u64 num_resources
for resource_id in 0..num_resources{
u64 block_id
u128 resource_id
//the order of these lists uniquely generates the incremental Ids
//MeshId, TextureId etc. based on resource type
//the first 8 bits of resource_uuid describe the type (mesh, texture, etc)
//if the map file references only external resources, num_resource_blocks = 0
for resource_idx in 0..num_resource_blocks{
Resource resource_type
u32 block_id
}
for resource_idx in 0..num_resources_external{
u128 resource_uuid
}
BLOCK_MAP_RESOURCE:
@@ -52,71 +78,367 @@ Resource resource_type
BLOCK_MAP_REGION:
u64 num_models
for model_id in 0..num_models{
u128 model_resource_uuid
ModelInstance mode_instance
}
*/
//error hiding mock code
mod gameplay_modes{
pub struct Modes{}
//if you hash the resource itself and set the first 8 bits to this, that's the resource uuid
#[binrw]
#[brw(little,repr=u8)]
enum ResourceType{
Mesh,
Texture,
//Shader,
//Sound,
//Video,
//Animation,
}
mod model{
pub struct Mesh{}
#[super::binrw]
#[brw(little)]
pub struct Model{}
}
mod image{
pub struct Image{}
const RESOURCE_TYPE_VARIANT_COUNT:u8=2;
#[binrw]
#[brw(little)]
struct ResourceId(u128);
impl ResourceId{
fn resource_type(&self)->Option<ResourceType>{
let discriminant=self.0 as u8;
//TODO: use this when it is stabilized https://github.com/rust-lang/rust/issues/73662
//if (discriminant as usize)<std::mem::variant_count::<ResourceType>(){
match discriminant<RESOURCE_TYPE_VARIANT_COUNT{
true=>Some(unsafe{std::mem::transmute::<u8,ResourceType>(discriminant)}),
false=>None,
}
}
}
//serious code
struct ModelUuid(u128);
struct ImageUuid(u128);
struct ResourceMap<T>{
meshes:HashMap<strafesnet_common::model::MeshId,T>,
textures:HashMap<strafesnet_common::model::TextureId,T>,
}
impl<T> Default for ResourceMap<T>{
fn default()->Self{
Self{
meshes:HashMap::new(),
textures:HashMap::new(),
}
}
}
#[binrw]
#[brw(little)]
#[derive(Clone,Copy,id::Id)]
pub struct BvhNodeId(u32);
struct BvhNode{
//aabb
//child
struct SpacialBlockHeader{
id:BlockId,
extents:newtypes::aabb::Aabb,
}
#[binrw]
#[brw(little)]
struct ResourceBlockHeader{
resource:ResourceType,
id:BlockId,
}
#[binrw]
#[brw(little)]
struct ResourceExternalHeader{
resource_uuid:ResourceId,
}
#[binrw]
#[brw(little)]
struct MapHeader{
num_spacial_blocks:u32,
num_resource_blocks:u32,
//num_resources_external:u32,
num_modes:u32,
num_attributes:u32,
num_render_configs:u32,
#[br(count=num_spacial_blocks)]
spacial_blocks:Vec<SpacialBlockHeader>,
#[br(count=num_resource_blocks)]
resource_blocks:Vec<ResourceBlockHeader>,
//#[br(count=num_resources_external)]
//external_resources:Vec<ResourceExternalHeader>,
#[br(count=num_modes)]
modes:Vec<newtypes::gameplay_modes::Mode>,
#[br(count=num_attributes)]
attributes:Vec<newtypes::gameplay_attributes::CollisionAttributes>,
#[br(count=num_render_configs)]
render_configs:Vec<newtypes::model::RenderConfig>,
}
#[binrw]
#[brw(little)]
struct Region{
//consider including a bvh in the region instead of needing to rebalance the physics bvh on the fly
model_count:u32,
#[br(count=model_count)]
models:Vec<model::Model>,
models:Vec<(u32,newtypes::model::Model)>,
}
//code deduplication reused in into_complete_map
fn read_region<R:BinReaderExt>(file:&mut crate::file::File<R>,block_id:BlockId)->Result<Vec<(model::ModelId,model::Model)>,Error>{
//load region from disk
//parse the models and determine what resources need to be loaded
//load resources into self.resources
//return Region
let mut block=file.block_reader(block_id).map_err(Error::File)?;
let region:Region=block.read_le().map_err(Error::InvalidData)?;
Ok(region.models.into_iter().map(|(model_id,model)|
(model::ModelId::new(model_id),model.into())
).collect())
}
fn read_mesh<R:BinReaderExt>(file:&mut crate::file::File<R>,block_id:BlockId)->Result<model::Mesh,Error>{
let mut block=file.block_reader(block_id).map_err(Error::File)?;
let mesh:newtypes::model::Mesh=block.read_le().map_err(Error::InvalidData)?;
Ok(mesh.into())
}
fn read_texture<R:BinReaderExt>(file:&mut crate::file::File<R>,block_id:BlockId)->Result<Vec<u8>,Error>{
let mut block=file.block_reader(block_id).map_err(Error::File)?;
let mut texture=Vec::new();
block.read_to_end(&mut texture).map_err(Error::IO)?;
Ok(texture)
}
pub struct StreamableMap<R:BinReaderExt>{
file:crate::file::File<R>,
//this includes every platform... move the unconstrained datas to their appropriate data block?
modes:gameplay_modes::Modes,
bvh:BvhNode,
node_id_to_block_id:Vec<crate::file::BlockId>,
//this is every possible attribute... need some sort of streaming system
attributes:Vec<strafesnet_common::gameplay_attributes::CollisionAttributes>,
//this is every possible render configuration... shaders and such... need streaming
render_configs:Vec<strafesnet_common::model::RenderConfig>,
//this makes sense to keep in memory for streaming, a map of which blocks occupy what space
bvh:BvhNode<BlockId>,
//something something resources hashmaps
resource_blocks:ResourceMap<BlockId>,
//resource_external:ResourceMap<ResourceId>,
}
impl<R:BinReaderExt> StreamableMap<R>{
pub(crate) fn new(file:crate::file::File<R>)->Result<Self,Error>{
Err(Error::InvalidHeader)
pub(crate) fn new(mut file:crate::file::File<R>)->Result<Self,Error>{
//assume the file seek is in the right place to start reading a map header
let header:MapHeader=file.as_mut().read_le().map_err(Error::InvalidHeader)?;
let modes=header.modes.into_iter().map(TryInto::try_into).collect::<Result<_,_>>().map_err(Error::InvalidMode)?;
let attributes=header.attributes.into_iter().map(Into::into).collect();
let render_configs=header.render_configs.into_iter().map(Into::into).collect();
let bvh=header.spacial_blocks.into_iter().map(|spacial_block|
(spacial_block.id,spacial_block.extents.into())
).collect();
//generate mesh ids and texture ids from resource list order
let mut resource_blocks=ResourceMap::default();
for resource_block_header in header.resource_blocks{
match resource_block_header.resource{
ResourceType::Mesh=>{
resource_blocks.meshes.insert(
//generate the id from the current length
model::MeshId::new(resource_blocks.meshes.len() as u32),
resource_block_header.id
);
},
ResourceType::Texture=>{
resource_blocks.textures.insert(
model::TextureId::new(resource_blocks.textures.len() as u32),
resource_block_header.id
);
},
}
}
Ok(Self{
file,
modes:strafesnet_common::gameplay_modes::Modes::new(modes),
attributes,
render_configs,
bvh:strafesnet_common::bvh::generate_bvh(bvh),
resource_blocks,
//resource_external:Default::default(),
})
}
pub fn load_node(&mut self,node_id:BvhNodeId)->Result<Vec<model::Model>,Error>{
//load region from disk
//parse the models and determine what resources need to be loaded
//load resources into self.resources
//return Region
let block_id=*self.node_id_to_block_id.get(node_id.get() as usize).ok_or(Error::InvalidBvhNodeId(node_id))?;
let mut block=self.file.block_reader(block_id).map_err(Error::File)?;
let region:Region=block.read_le().map_err(Error::InvalidRegion)?;
Ok(region.models)
pub fn get_intersecting_region_block_ids(&self,aabb:&Aabb)->Vec<BlockId>{
let mut block_ids=Vec::new();
self.bvh.the_tester(aabb,&mut |&block_id|block_ids.push(block_id));
block_ids
}
// pub fn load_resource(&mut self,resource_id:ResourceId)->Resource{
// //
// }
}
pub fn load_region(&mut self,block_id:BlockId)->Result<Vec<(model::ModelId,model::Model)>,Error>{
read_region(&mut self.file,block_id)
}
pub fn load_mesh(&mut self,mesh_id:model::MeshId)->Result<model::Mesh,Error>{
let block_id=*self.resource_blocks.meshes.get(&mesh_id).ok_or(Error::InvalidMeshId(mesh_id))?;
read_mesh(&mut self.file,block_id)
}
pub fn load_texture(&mut self,texture_id:model::TextureId)->Result<Vec<u8>,Error>{
let block_id=*self.resource_blocks.textures.get(&texture_id).ok_or(Error::InvalidTextureId(texture_id))?;
read_texture(&mut self.file,block_id)
}
pub fn into_complete_map(mut self)->Result<strafesnet_common::map::CompleteMap,Error>{
let mut block_ids=Vec::new();
self.bvh.into_visitor(&mut |block_id|block_ids.push(block_id));
//count on reading the file in sequential order being fastest
block_ids.sort_unstable();
//load all regions
let mut model_pairs=HashMap::new();
for block_id in block_ids{
model_pairs.extend(read_region(&mut self.file,block_id)?);
}
let mut models=Vec::with_capacity(model_pairs.len());
for model_id in 0..model_pairs.len() as u32{
let model_id=model::ModelId::new(model_id);
models.push(model_pairs.remove(&model_id).ok_or(Error::InvalidModelId(model_id))?);
}
//load all meshes
let mut meshes=Vec::with_capacity(self.resource_blocks.meshes.len());
for mesh_id in 0..self.resource_blocks.meshes.len() as u32{
let mesh_id=model::MeshId::new(mesh_id);
let block_id=self.resource_blocks.meshes[&mesh_id];
meshes.push(read_mesh(&mut self.file,block_id)?);
};
//load all textures
let mut textures=Vec::with_capacity(self.resource_blocks.textures.len());
for texture_id in 0..self.resource_blocks.textures.len() as u32{
let texture_id=model::TextureId::new(texture_id);
let block_id=self.resource_blocks.textures[&texture_id];
textures.push(read_texture(&mut self.file,block_id)?);
}
Ok(strafesnet_common::map::CompleteMap{
modes:self.modes,
attributes:self.attributes,
meshes,
models,
textures,
render_configs:self.render_configs,
})
}
}
const BVH_NODE_MAX_WEIGHT:usize=64*1024;//64 kB
fn collect_spacial_blocks(
block_location:&mut Vec<u64>,
block_headers:&mut Vec<SpacialBlockHeader>,
sequential_block_data:&mut std::io::Cursor<&mut Vec<u8>>,
bvh_node:strafesnet_common::bvh::BvhWeightNode<usize,(model::ModelId,newtypes::model::Model)>
)->Result<(),Error>{
//inspect the node weights top-down.
//When a node weighs less than the limit,
//serialize its entire contents into a region block
if *bvh_node.weight()<BVH_NODE_MAX_WEIGHT{
let mut models=Vec::new();
let mut model_count=0;
let extents=bvh_node.aabb().clone().into();
bvh_node.into_visitor(&mut |(model_id,model)|{
model_count+=1;
models.push((model_id.get(),model));
});
let id=BlockId::new(block_headers.len() as u32+1);
block_headers.push(SpacialBlockHeader{
id,
extents,
});
let region=Region{
model_count,
models,
};
binrw::BinWrite::write_le(&region,sequential_block_data).map_err(Error::InvalidData)?;
block_location.push(sequential_block_data.position());
}else{
match bvh_node.into_content(){
strafesnet_common::bvh::RecursiveContent::Branch(bvh_node_list)=>{
for bvh_node in bvh_node_list{
collect_spacial_blocks(block_location,block_headers,sequential_block_data,bvh_node)?;
}
},
strafesnet_common::bvh::RecursiveContent::Leaf(_)=>panic!(),//bvh branches are 20 leaves minimum
}
}
Ok(())
}
/// TODO: Optionally provide a bot that describes the path through the map
/// otherwise sort by distance to start zone
pub fn write_map<W:BinWriterExt>(mut writer:W,map:strafesnet_common::map::CompleteMap)->Result<(),Error>{
//serialize models and make a bvh that knows the file size of the branch
let boxen=map.models.into_iter().enumerate().map(|(model_id,model)|{
//grow your own aabb
let mesh=map.meshes.get(model.mesh.get() as usize).ok_or(Error::InvalidMeshId(model.mesh))?;
let mut aabb=strafesnet_common::aabb::Aabb::default();
for &pos in &mesh.unique_pos{
aabb.grow(model.transform.transform_point3(pos));
}
Ok(((model::ModelId::new(model_id as u32),model.into()),aabb))
}).collect::<Result<Vec<_>,_>>()?;
let bvh=strafesnet_common::bvh::generate_bvh(boxen).weigh_contents(&|_|std::mem::size_of::<newtypes::model::Model>());
//build blocks
//block location is initialized with two values
//the first value represents the location of the first byte after the file header
//the second value represents the first byte of the second data block
//the first data block is always the map header, so the difference is the map header size.
//this information is filled in later after the sizes are known.
let mut block_location=vec![0,0];//for file header
let mut spacial_blocks=Vec::new();//for map header
let mut sequential_block_data=Vec::new();
let mut cursor_to_data=std::io::Cursor::new(&mut sequential_block_data);
collect_spacial_blocks(&mut block_location,&mut spacial_blocks,&mut cursor_to_data,bvh)?;
let mut block_count=spacial_blocks.len() as u32+1;//continue block id
let mut resource_blocks=Vec::new();//for map header
//meshes
for mesh in map.meshes.into_iter(){
resource_blocks.push(ResourceBlockHeader{
resource:ResourceType::Mesh,
id:BlockId::new(block_count),
});
block_count+=1;
let serializable_mesh:newtypes::model::Mesh=mesh.into();
binrw::BinWrite::write_le(&serializable_mesh,&mut cursor_to_data).map_err(Error::InvalidData)?;
block_location.push(cursor_to_data.position());
}
//textures
for mut texture in map.textures.into_iter(){
resource_blocks.push(ResourceBlockHeader{
resource:ResourceType::Texture,
id:BlockId::new(block_count),
});
block_count+=1;
sequential_block_data.append(&mut texture);
block_location.push(sequential_block_data.len() as u64);
}
//build header
let map_header=MapHeader{
num_spacial_blocks:spacial_blocks.len() as u32,
num_resource_blocks:resource_blocks.len() as u32,
//num_resources_external:0,
num_modes:map.modes.modes.len() as u32,
num_attributes:map.attributes.len() as u32,
num_render_configs:map.render_configs.len() as u32,
spacial_blocks,
resource_blocks,
//external_resources:Vec::new(),
modes:map.modes.modes.into_iter().map(Into::into).collect(),
attributes:map.attributes.into_iter().map(Into::into).collect(),
render_configs:map.render_configs.into_iter().map(Into::into).collect(),
};
let mut file_header=crate::file::Header{
fourcc:crate::file::FourCC::Map,
version:0,
priming:0,
resource:0,
block_count,
block_location,
};
//probe header length
let mut file_header_data=Vec::new();
binrw::BinWrite::write_le(&file_header,&mut std::io::Cursor::new(&mut file_header_data)).map_err(Error::InvalidData)?;
let mut map_header_data=Vec::new();
binrw::BinWrite::write_le(&map_header,&mut std::io::Cursor::new(&mut map_header_data)).map_err(Error::InvalidData)?;
//update file header according to probe data
let mut offset=file_header_data.len() as u64;
file_header.priming=offset;
file_header.block_location[0]=offset;
offset+=map_header_data.len() as u64;
for position in &mut file_header.block_location[1..]{
*position+=offset;
}
//write (updated) file header
writer.write_le(&file_header).map_err(Error::InvalidData)?;
//write map header
writer.write(&map_header_data).map_err(Error::IO)?;
//write blocks
writer.write(&sequential_block_data).map_err(Error::IO)?;
Ok(())
}

10
src/newtypes.rs Normal file
View File

@@ -0,0 +1,10 @@
mod common;
pub mod aabb;
pub mod model;
pub mod mouse;
pub mod integer;
pub mod physics;
pub mod instruction;
pub mod gameplay_modes;
pub mod gameplay_style;
pub mod gameplay_attributes;

23
src/newtypes/aabb.rs Normal file
View File

@@ -0,0 +1,23 @@
use super::integer::Planar64Vec3;
#[binrw::binrw]
#[brw(little)]
pub struct Aabb{
pub min:Planar64Vec3,
pub max:Planar64Vec3,
}
impl Into<strafesnet_common::aabb::Aabb> for Aabb{
fn into(self)->strafesnet_common::aabb::Aabb{
strafesnet_common::aabb::Aabb::new(
strafesnet_common::integer::Planar64Vec3::raw_array(self.min),
strafesnet_common::integer::Planar64Vec3::raw_array(self.max),
)
}
}
impl From<strafesnet_common::aabb::Aabb> for Aabb{
fn from(value:strafesnet_common::aabb::Aabb)->Self{
Self{
max:value.max().get().to_array(),
min:value.min().get().to_array(),
}
}
}

26
src/newtypes/common.rs Normal file
View File

@@ -0,0 +1,26 @@
pub const fn flag(b:bool,mask:u8)->u8{
(-(b as i8) as u8)&mask
}
#[binrw::binrw]
#[brw(little,repr=u8)]
pub enum Boolio{
True,
False
}
impl Into<bool> for Boolio{
fn into(self)->bool{
match self{
Boolio::True=>true,
Boolio::False=>false,
}
}
}
impl From<bool> for Boolio{
fn from(value:bool)->Self{
match value{
true=>Boolio::True,
false=>Boolio::False,
}
}
}

View File

@@ -0,0 +1,434 @@
use super::common::{flag,Boolio};
use super::integer::{Time,Planar64,Planar64Vec3};
#[binrw::binrw]
#[brw(little)]
pub struct ContactingLadder{
pub sticky:Boolio,
}
impl Into<strafesnet_common::gameplay_attributes::ContactingLadder> for ContactingLadder{
fn into(self)->strafesnet_common::gameplay_attributes::ContactingLadder{
strafesnet_common::gameplay_attributes::ContactingLadder{
sticky:self.sticky.into(),
}
}
}
impl From<strafesnet_common::gameplay_attributes::ContactingLadder> for ContactingLadder{
fn from(value:strafesnet_common::gameplay_attributes::ContactingLadder)->Self{
Self{
sticky:value.sticky.into(),
}
}
}
#[binrw::binrw]
#[brw(little)]
pub enum ContactingBehaviour{
#[brw(magic=0u8)]
Surf,
#[brw(magic=1u8)]
Ladder(ContactingLadder),
#[brw(magic=2u8)]
NoJump,
#[brw(magic=3u8)]
Cling,
#[brw(magic=4u8)]
Elastic(u32),
}
impl Into<strafesnet_common::gameplay_attributes::ContactingBehaviour> for ContactingBehaviour{
fn into(self)->strafesnet_common::gameplay_attributes::ContactingBehaviour{
match self{
ContactingBehaviour::Surf=>
strafesnet_common::gameplay_attributes::ContactingBehaviour::Surf,
ContactingBehaviour::Ladder(contacting_ladder)=>
strafesnet_common::gameplay_attributes::ContactingBehaviour::Ladder(
contacting_ladder.into(),
),
ContactingBehaviour::NoJump=>
strafesnet_common::gameplay_attributes::ContactingBehaviour::NoJump,
ContactingBehaviour::Cling=>
strafesnet_common::gameplay_attributes::ContactingBehaviour::Cling,
ContactingBehaviour::Elastic(elasticity)=>
strafesnet_common::gameplay_attributes::ContactingBehaviour::Elastic(elasticity),
}
}
}
impl From<strafesnet_common::gameplay_attributes::ContactingBehaviour> for ContactingBehaviour{
fn from(value:strafesnet_common::gameplay_attributes::ContactingBehaviour)->Self{
match value{
strafesnet_common::gameplay_attributes::ContactingBehaviour::Surf=>
ContactingBehaviour::Surf,
strafesnet_common::gameplay_attributes::ContactingBehaviour::Ladder(contacting_ladder)=>
ContactingBehaviour::Ladder(
contacting_ladder.into()
),
strafesnet_common::gameplay_attributes::ContactingBehaviour::NoJump=>
ContactingBehaviour::NoJump,
strafesnet_common::gameplay_attributes::ContactingBehaviour::Cling=>
ContactingBehaviour::Cling,
strafesnet_common::gameplay_attributes::ContactingBehaviour::Elastic(elasticity)=>
ContactingBehaviour::Elastic(elasticity),
}
}
}
#[binrw::binrw]
#[brw(little)]
pub struct IntersectingWater{
pub viscosity:Planar64,
pub density:Planar64,
pub velocity:Planar64Vec3,
}
impl Into<strafesnet_common::gameplay_attributes::IntersectingWater> for IntersectingWater{
fn into(self)->strafesnet_common::gameplay_attributes::IntersectingWater{
strafesnet_common::gameplay_attributes::IntersectingWater{
viscosity:strafesnet_common::integer::Planar64::raw(self.viscosity),
density:strafesnet_common::integer::Planar64::raw(self.density),
velocity:strafesnet_common::integer::Planar64Vec3::raw_array(self.velocity),
}
}
}
impl From<strafesnet_common::gameplay_attributes::IntersectingWater> for IntersectingWater{
fn from(value:strafesnet_common::gameplay_attributes::IntersectingWater)->Self{
Self{
viscosity:value.viscosity.get(),
density:value.density.get(),
velocity:value.velocity.get().to_array(),
}
}
}
#[binrw::binrw]
#[brw(little)]
pub struct Accelerator{
pub acceleration:Planar64Vec3
}
impl Into<strafesnet_common::gameplay_attributes::Accelerator> for Accelerator{
fn into(self)->strafesnet_common::gameplay_attributes::Accelerator{
strafesnet_common::gameplay_attributes::Accelerator{
acceleration:strafesnet_common::integer::Planar64Vec3::raw_array(self.acceleration)
}
}
}
impl From<strafesnet_common::gameplay_attributes::Accelerator> for Accelerator{
fn from(value:strafesnet_common::gameplay_attributes::Accelerator)->Self{
Self{
acceleration:value.acceleration.get().to_array(),
}
}
}
#[binrw::binrw]
#[brw(little)]
pub enum Booster{
#[brw(magic=0u8)]
Velocity(Planar64Vec3),
#[brw(magic=1u8)]
Energy{direction:Planar64Vec3,energy:Planar64},
}
impl Into<strafesnet_common::gameplay_attributes::Booster> for Booster{
fn into(self)->strafesnet_common::gameplay_attributes::Booster{
match self{
Booster::Velocity(velocity)=>
strafesnet_common::gameplay_attributes::Booster::Velocity(
strafesnet_common::integer::Planar64Vec3::raw_array(velocity)
),
Booster::Energy{direction,energy}=>
strafesnet_common::gameplay_attributes::Booster::Energy{
direction:strafesnet_common::integer::Planar64Vec3::raw_array(direction),
energy:strafesnet_common::integer::Planar64::raw(energy)
},
}
}
}
impl From<strafesnet_common::gameplay_attributes::Booster> for Booster{
fn from(value:strafesnet_common::gameplay_attributes::Booster)->Self{
match value{
strafesnet_common::gameplay_attributes::Booster::Velocity(velocity)=>
Booster::Velocity(velocity.get().to_array()),
strafesnet_common::gameplay_attributes::Booster::Energy{direction,energy}=>
Booster::Energy{
direction:direction.get().to_array(),
energy:energy.get(),
},
}
}
}
#[binrw::binrw]
#[brw(little,repr=u8)]
pub enum TrajectoryChoice{
HighArcLongDuration,
LowArcShortDuration,
}
impl Into<strafesnet_common::gameplay_attributes::TrajectoryChoice> for TrajectoryChoice{
fn into(self)->strafesnet_common::gameplay_attributes::TrajectoryChoice{
match self{
TrajectoryChoice::HighArcLongDuration=>
strafesnet_common::gameplay_attributes::TrajectoryChoice::HighArcLongDuration,
TrajectoryChoice::LowArcShortDuration=>
strafesnet_common::gameplay_attributes::TrajectoryChoice::LowArcShortDuration,
}
}
}
impl From<strafesnet_common::gameplay_attributes::TrajectoryChoice> for TrajectoryChoice{
fn from(value:strafesnet_common::gameplay_attributes::TrajectoryChoice)->Self{
match value{
strafesnet_common::gameplay_attributes::TrajectoryChoice::HighArcLongDuration=>
TrajectoryChoice::HighArcLongDuration,
strafesnet_common::gameplay_attributes::TrajectoryChoice::LowArcShortDuration=>
TrajectoryChoice::LowArcShortDuration,
}
}
}
#[binrw::binrw]
#[brw(little)]
pub enum SetTrajectory{
#[brw(magic=0u8)]
AirTime(Time),
#[brw(magic=1u8)]
Height(Planar64),
#[brw(magic=2u8)]
DotVelocity{direction:Planar64Vec3,dot:Planar64},
#[brw(magic=3u8)]
TargetPointTime{
target_point:Planar64Vec3,
time:Time,
},
#[brw(magic=4u8)]
TargetPointSpeed{
target_point:Planar64Vec3,
speed:Planar64,
trajectory_choice:TrajectoryChoice,
},
#[brw(magic=5u8)]
Velocity(Planar64Vec3),
}
impl Into<strafesnet_common::gameplay_attributes::SetTrajectory> for SetTrajectory{
fn into(self)->strafesnet_common::gameplay_attributes::SetTrajectory{
match self{
SetTrajectory::AirTime(time)=>
strafesnet_common::gameplay_attributes::SetTrajectory::AirTime(
strafesnet_common::integer::Time::raw(time)
),
SetTrajectory::Height(height)=>
strafesnet_common::gameplay_attributes::SetTrajectory::Height(
strafesnet_common::integer::Planar64::raw(height)
),
SetTrajectory::DotVelocity{direction,dot}=>
strafesnet_common::gameplay_attributes::SetTrajectory::DotVelocity{
direction:strafesnet_common::integer::Planar64Vec3::raw_array(direction),
dot:strafesnet_common::integer::Planar64::raw(dot),
},
SetTrajectory::TargetPointTime{target_point,time}=>
strafesnet_common::gameplay_attributes::SetTrajectory::TargetPointTime{
target_point:strafesnet_common::integer::Planar64Vec3::raw_array(target_point),
time:strafesnet_common::integer::Time::raw(time),
},
SetTrajectory::TargetPointSpeed{target_point,speed,trajectory_choice}=>
strafesnet_common::gameplay_attributes::SetTrajectory::TargetPointSpeed{
target_point:strafesnet_common::integer::Planar64Vec3::raw_array(target_point),
speed:strafesnet_common::integer::Planar64::raw(speed),
trajectory_choice:trajectory_choice.into(),
},
SetTrajectory::Velocity(velocity)=>
strafesnet_common::gameplay_attributes::SetTrajectory::Velocity(
strafesnet_common::integer::Planar64Vec3::raw_array(velocity)
),
}
}
}
impl From<strafesnet_common::gameplay_attributes::SetTrajectory> for SetTrajectory{
fn from(value:strafesnet_common::gameplay_attributes::SetTrajectory)->Self{
match value{
strafesnet_common::gameplay_attributes::SetTrajectory::AirTime(time)=>
SetTrajectory::AirTime(
time.get()
),
strafesnet_common::gameplay_attributes::SetTrajectory::Height(height)=>
SetTrajectory::Height(
height.get()
),
strafesnet_common::gameplay_attributes::SetTrajectory::DotVelocity{direction,dot}=>
SetTrajectory::DotVelocity{
direction:direction.get().to_array(),
dot:dot.get(),
},
strafesnet_common::gameplay_attributes::SetTrajectory::TargetPointTime{target_point,time}=>
SetTrajectory::TargetPointTime{
target_point:target_point.get().to_array(),
time:time.get(),
},
strafesnet_common::gameplay_attributes::SetTrajectory::TargetPointSpeed{target_point,speed,trajectory_choice}=>
SetTrajectory::TargetPointSpeed{
target_point:target_point.get().to_array(),
speed:speed.get(),
trajectory_choice:trajectory_choice.into(),
},
strafesnet_common::gameplay_attributes::SetTrajectory::Velocity(velocity)=>
SetTrajectory::Velocity(
velocity.get().to_array()
),
}
}
}
#[binrw::binrw]
#[brw(little)]
pub struct Wormhole{
pub destination_model:u32,
}
impl Into<strafesnet_common::gameplay_attributes::Wormhole> for Wormhole{
fn into(self)->strafesnet_common::gameplay_attributes::Wormhole{
strafesnet_common::gameplay_attributes::Wormhole{
destination_model:strafesnet_common::model::ModelId::new(self.destination_model),
}
}
}
impl From<strafesnet_common::gameplay_attributes::Wormhole> for Wormhole{
fn from(value:strafesnet_common::gameplay_attributes::Wormhole)->Self{
Self{
destination_model:value.destination_model.get(),
}
}
}
#[binrw::binrw]
#[brw(little)]
pub struct GeneralAttributes{
pub header:u8,
#[br(if(header&Self::BOOSTER!=0))]
pub booster:Option<Booster>,
#[br(if(header&Self::TRAJECTORY!=0))]
pub trajectory:Option<SetTrajectory>,
#[br(if(header&Self::WORMHOLE!=0))]
pub wormhole:Option<Wormhole>,
#[br(if(header&Self::ACCELERATOR!=0))]
pub accelerator:Option<Accelerator>,
}
impl GeneralAttributes{
const BOOSTER:u8=1<<0;
const TRAJECTORY:u8=1<<1;
const WORMHOLE:u8=1<<2;
const ACCELERATOR:u8=1<<3;
}
impl Into<strafesnet_common::gameplay_attributes::GeneralAttributes> for GeneralAttributes{
fn into(self)->strafesnet_common::gameplay_attributes::GeneralAttributes{
strafesnet_common::gameplay_attributes::GeneralAttributes{
booster:self.booster.map(Into::into),
trajectory:self.trajectory.map(Into::into),
wormhole:self.wormhole.map(Into::into),
accelerator:self.accelerator.map(Into::into),
}
}
}
impl From<strafesnet_common::gameplay_attributes::GeneralAttributes> for GeneralAttributes{
fn from(value:strafesnet_common::gameplay_attributes::GeneralAttributes)->Self{
let header=
flag(value.booster.is_some(),GeneralAttributes::BOOSTER)
|flag(value.trajectory.is_some(),GeneralAttributes::TRAJECTORY)
|flag(value.wormhole.is_some(),GeneralAttributes::WORMHOLE)
|flag(value.accelerator.is_some(),GeneralAttributes::ACCELERATOR);
Self{
header,
booster:value.booster.map(Into::into),
trajectory:value.trajectory.map(Into::into),
wormhole:value.wormhole.map(Into::into),
accelerator:value.accelerator.map(Into::into),
}
}
}
#[binrw::binrw]
#[brw(little)]
pub struct ContactingAttributes{
pub header:u8,
#[br(if(header&Self::CONTACTING_BEHAVIOUR!=0))]
pub contact_behaviour:Option<ContactingBehaviour>,
}
impl ContactingAttributes{
const CONTACTING_BEHAVIOUR:u8=1<<0;
}
impl Into<strafesnet_common::gameplay_attributes::ContactingAttributes> for ContactingAttributes{
fn into(self)->strafesnet_common::gameplay_attributes::ContactingAttributes{
strafesnet_common::gameplay_attributes::ContactingAttributes{
contact_behaviour:self.contact_behaviour.map(Into::into),
}
}
}
impl From<strafesnet_common::gameplay_attributes::ContactingAttributes> for ContactingAttributes{
fn from(value:strafesnet_common::gameplay_attributes::ContactingAttributes)->Self{
Self{
header:flag(value.contact_behaviour.is_some(),ContactingAttributes::CONTACTING_BEHAVIOUR),
contact_behaviour:value.contact_behaviour.map(Into::into),
}
}
}
#[binrw::binrw]
#[brw(little)]
pub struct IntersectingAttributes{
pub header:u8,
#[br(if(header&Self::INTERSECTING_WATER!=0))]
pub water:Option<IntersectingWater>,
}
impl IntersectingAttributes{
const INTERSECTING_WATER:u8=1<<0;
}
impl Into<strafesnet_common::gameplay_attributes::IntersectingAttributes> for IntersectingAttributes{
fn into(self)->strafesnet_common::gameplay_attributes::IntersectingAttributes{
strafesnet_common::gameplay_attributes::IntersectingAttributes{
water:self.water.map(Into::into),
}
}
}
impl From<strafesnet_common::gameplay_attributes::IntersectingAttributes> for IntersectingAttributes{
fn from(value:strafesnet_common::gameplay_attributes::IntersectingAttributes)->Self{
Self{
header:flag(value.water.is_some(),IntersectingAttributes::INTERSECTING_WATER),
water:value.water.map(Into::into),
}
}
}
#[binrw::binrw]
#[brw(little)]
pub enum CollisionAttributes{
#[brw(magic=0u8)]
Decoration,
#[brw(magic=1u8)]
Contact{
contacting:ContactingAttributes,
general:GeneralAttributes,
},
#[brw(magic=2u8)]
Intersect{
intersecting:IntersectingAttributes,
general:GeneralAttributes,
},
}
impl Into<strafesnet_common::gameplay_attributes::CollisionAttributes> for CollisionAttributes{
fn into(self)->strafesnet_common::gameplay_attributes::CollisionAttributes{
match self{
CollisionAttributes::Decoration=>
strafesnet_common::gameplay_attributes::CollisionAttributes::Decoration,
CollisionAttributes::Contact{contacting,general}=>
strafesnet_common::gameplay_attributes::CollisionAttributes::Contact{contacting:contacting.into(),general:general.into()},
CollisionAttributes::Intersect{intersecting,general}=>
strafesnet_common::gameplay_attributes::CollisionAttributes::Intersect{intersecting:intersecting.into(),general:general.into()},
}
}
}
impl From<strafesnet_common::gameplay_attributes::CollisionAttributes> for CollisionAttributes{
fn from(value:strafesnet_common::gameplay_attributes::CollisionAttributes)->Self{
match value{
strafesnet_common::gameplay_attributes::CollisionAttributes::Decoration=>
CollisionAttributes::Decoration,
strafesnet_common::gameplay_attributes::CollisionAttributes::Contact{contacting,general}=>
CollisionAttributes::Contact{contacting:contacting.into(),general:general.into()},
strafesnet_common::gameplay_attributes::CollisionAttributes::Intersect{intersecting,general}=>
CollisionAttributes::Intersect{intersecting:intersecting.into(),general:general.into()},
}
}
}

View File

@@ -0,0 +1,220 @@
use super::common::flag;
pub type ModeId=u32;
pub type StageId=u32;
#[binrw::binrw]
#[brw(little)]
pub struct StageElement{
pub header:u8,
pub stage_id:StageId,
#[br(if(header&Self::JUMP_LIMIT!=0))]
pub jump_limit:Option<u8>,
}
impl StageElement{
const BEHAVIOUR:u8=0b00111;
const JUMP_LIMIT:u8=1<<3;
const FORCE:u8=1<<4;
const fn behaviour(&self)->Option<strafesnet_common::gameplay_modes::StageElementBehaviour>{
match self.header&Self::BEHAVIOUR{
0=>Some(strafesnet_common::gameplay_modes::StageElementBehaviour::SpawnAt),
1=>Some(strafesnet_common::gameplay_modes::StageElementBehaviour::Trigger),
2=>Some(strafesnet_common::gameplay_modes::StageElementBehaviour::Teleport),
3=>Some(strafesnet_common::gameplay_modes::StageElementBehaviour::Platform),
4=>Some(strafesnet_common::gameplay_modes::StageElementBehaviour::Check),
5=>Some(strafesnet_common::gameplay_modes::StageElementBehaviour::Checkpoint),
_=>None,
}
}
const fn force(&self)->bool{
self.header&Self::FORCE!=0
}
}
#[derive(Debug)]
pub enum StageElementError{
InvalidBehaviour,
}
impl std::fmt::Display for StageElementError{
fn fmt(&self,f:&mut std::fmt::Formatter<'_>)->std::fmt::Result{
write!(f,"{self:?}")
}
}
impl std::error::Error for StageElementError{}
impl TryInto<strafesnet_common::gameplay_modes::StageElement> for StageElement{
type Error=StageElementError;
fn try_into(self)->Result<strafesnet_common::gameplay_modes::StageElement,Self::Error>{
Ok(strafesnet_common::gameplay_modes::StageElement::new(
strafesnet_common::gameplay_modes::StageId::new(self.stage_id),
self.force(),
self.behaviour().ok_or(StageElementError::InvalidBehaviour)?,
self.jump_limit,
))
}
}
impl From<strafesnet_common::gameplay_modes::StageElement> for StageElement{
fn from(value:strafesnet_common::gameplay_modes::StageElement)->Self{
let behaviour=match value.behaviour(){
strafesnet_common::gameplay_modes::StageElementBehaviour::SpawnAt=>0,
strafesnet_common::gameplay_modes::StageElementBehaviour::Trigger=>1,
strafesnet_common::gameplay_modes::StageElementBehaviour::Teleport=>2,
strafesnet_common::gameplay_modes::StageElementBehaviour::Platform=>3,
strafesnet_common::gameplay_modes::StageElementBehaviour::Check=>4,
strafesnet_common::gameplay_modes::StageElementBehaviour::Checkpoint=>5,
};
let header=
behaviour
|flag(value.jump_limit().is_some(),StageElement::JUMP_LIMIT)
|flag(value.force(),StageElement::FORCE);
Self{
header,
stage_id:value.stage_id().get(),
jump_limit:value.jump_limit(),
}
}
}
#[binrw::binrw]
#[brw(little)]
pub struct Stage{
pub spawn:u32,
//open world support lol
pub ordered_checkpoints_count:u32,
pub unordered_checkpoints_count:u32,
//currently loaded checkpoint models
#[br(count=ordered_checkpoints_count)]
pub ordered_checkpoints:Vec<(u32,u32)>,
#[br(count=unordered_checkpoints_count)]
pub unordered_checkpoints:Vec<u32>,
}
impl Into<strafesnet_common::gameplay_modes::Stage> for Stage{
fn into(self)->strafesnet_common::gameplay_modes::Stage{
strafesnet_common::gameplay_modes::Stage::new(
strafesnet_common::model::ModelId::new(self.spawn),
self.ordered_checkpoints_count,
self.unordered_checkpoints_count,
self.ordered_checkpoints.into_iter().map(|(checkpoint_id,model_id)|(
strafesnet_common::gameplay_modes::CheckpointId::new(checkpoint_id),
strafesnet_common::model::ModelId::new(model_id),
)).collect(),
self.unordered_checkpoints.into_iter()
.map(strafesnet_common::model::ModelId::new)
.collect(),
)
}
}
impl From<strafesnet_common::gameplay_modes::Stage> for Stage{
fn from(value:strafesnet_common::gameplay_modes::Stage)->Self{
let spawn=value.spawn().get();
let ordered_checkpoints_count=value.ordered_checkpoints_count();
let unordered_checkpoints_count=value.unordered_checkpoints_count();
let (ordered_checkpoints,unordered_checkpoints)=value.into_inner();
Self{
spawn,
ordered_checkpoints_count,
unordered_checkpoints_count,
ordered_checkpoints:ordered_checkpoints.into_iter()
.map(|(checkpoint_id,model_id)|(checkpoint_id.get(),model_id.get()))
.collect(),
unordered_checkpoints:unordered_checkpoints.into_iter()
.map(|model_id|model_id.get())
.collect(),
}
}
}
#[binrw::binrw]
#[brw(little,repr=u8)]
pub enum Zone{
Start,
Finish,
Anticheat,
}
impl Into<strafesnet_common::gameplay_modes::Zone> for Zone{
fn into(self)->strafesnet_common::gameplay_modes::Zone{
match self{
Zone::Start=>strafesnet_common::gameplay_modes::Zone::Start,
Zone::Finish=>strafesnet_common::gameplay_modes::Zone::Finish,
Zone::Anticheat=>strafesnet_common::gameplay_modes::Zone::Anticheat,
}
}
}
impl From<strafesnet_common::gameplay_modes::Zone> for Zone{
fn from(value:strafesnet_common::gameplay_modes::Zone)->Self{
match value{
strafesnet_common::gameplay_modes::Zone::Start=>Zone::Start,
strafesnet_common::gameplay_modes::Zone::Finish=>Zone::Finish,
strafesnet_common::gameplay_modes::Zone::Anticheat=>Zone::Anticheat,
}
}
}
#[binrw::binrw]
#[brw(little)]
pub struct ModeHeader{
pub zones:u32,
pub stages:u32,
pub elements:u32,
}
#[binrw::binrw]
#[brw(little)]
pub struct Mode{
pub header:ModeHeader,
pub style:super::gameplay_style::StyleModifiers,
pub start:u32,
#[br(count=header.zones)]
pub zones:Vec<(u32,Zone)>,
#[br(count=header.stages)]
pub stages:Vec<Stage>,
#[br(count=header.elements)]
pub elements:Vec<(u32,StageElement)>,
}
#[derive(Debug)]
pub enum ModeError{
StyleModifier(super::gameplay_style::StyleModifierError),
StageElement(StageElementError),
}
impl std::fmt::Display for ModeError{
fn fmt(&self,f:&mut std::fmt::Formatter<'_>)->std::fmt::Result{
write!(f,"{self:?}")
}
}
impl std::error::Error for ModeError{}
impl TryInto<strafesnet_common::gameplay_modes::Mode> for Mode{
type Error=ModeError;
fn try_into(self)->Result<strafesnet_common::gameplay_modes::Mode,Self::Error>{
Ok(strafesnet_common::gameplay_modes::Mode::new(
self.style.try_into().map_err(ModeError::StyleModifier)?,
strafesnet_common::model::ModelId::new(self.start),
self.zones.into_iter().map(|(model_id,zone)|
(strafesnet_common::model::ModelId::new(model_id),zone.into())
).collect(),
self.stages.into_iter().map(Into::into).collect(),
self.elements.into_iter().map(|(model_id,stage_element)|
Ok((strafesnet_common::model::ModelId::new(model_id),stage_element.try_into()?))
).collect::<Result<_,_>>().map_err(ModeError::StageElement)?,
))
}
}
impl From<strafesnet_common::gameplay_modes::Mode> for Mode{
fn from(value:strafesnet_common::gameplay_modes::Mode)->Self{
let (style,start,zones,stages,elements)=value.into_inner();
Self{
header:ModeHeader{
zones:zones.len() as u32,
stages:stages.len() as u32,
elements:elements.len() as u32,
},
style:style.into(),
start:start.get(),
zones:zones.into_iter()
.map(|(model_id,zone)|(model_id.get(),zone.into()))
.collect(),
stages:stages.into_iter()
.map(Into::into)
.collect(),
elements:elements.into_iter()
.map(|(model_id,stage_element)|(model_id.get(),stage_element.into()))
.collect(),
}
}
}

View File

@@ -0,0 +1,440 @@
use super::common::flag;
use super::integer::{Time,Ratio64,Planar64,Planar64Vec3};
pub type Controls=u32;
#[derive(Debug)]
pub enum ControlsError{
UnknownBits,
}
impl std::fmt::Display for ControlsError{
fn fmt(&self,f:&mut std::fmt::Formatter<'_>)->std::fmt::Result{
write!(f,"{self:?}")
}
}
impl std::error::Error for ControlsError{}
#[binrw::binrw]
#[brw(little)]
pub struct StyleModifiers{
pub header:u8,
pub controls_mask:Controls,
pub controls_mask_state:Controls,
#[br(if(header&Self::STRAFE!=0))]
pub strafe:Option<StrafeSettings>,
#[br(if(header&Self::ROCKET!=0))]
pub rocket:Option<PropulsionSettings>,
#[br(if(header&Self::JUMP!=0))]
pub jump:Option<JumpSettings>,
#[br(if(header&Self::WALK!=0))]
pub walk:Option<WalkSettings>,
#[br(if(header&Self::LADDER!=0))]
pub ladder:Option<LadderSettings>,
#[br(if(header&Self::SWIM!=0))]
pub swim:Option<PropulsionSettings>,
pub gravity:Planar64Vec3,
pub hitbox:Hitbox,
pub camera_offset:Planar64Vec3,
pub mass:Planar64,
}
impl StyleModifiers{
const STRAFE:u8=1<<0;
const ROCKET:u8=1<<1;
const JUMP:u8=1<<2;
const WALK:u8=1<<3;
const LADDER:u8=1<<4;
const SWIM:u8=1<<5;
}
#[derive(Debug)]
pub enum StyleModifierError{
Controls(ControlsError),
JumpSettings(JumpSettingsError),
StrafeSettings(StrafeSettingsError),
}
impl std::fmt::Display for StyleModifierError{
fn fmt(&self,f:&mut std::fmt::Formatter<'_>)->std::fmt::Result{
write!(f,"{self:?}")
}
}
impl std::error::Error for StyleModifierError{}
impl TryInto<strafesnet_common::gameplay_style::StyleModifiers> for StyleModifiers{
type Error=StyleModifierError;
fn try_into(self)->Result<strafesnet_common::gameplay_style::StyleModifiers,Self::Error>{
Ok(strafesnet_common::gameplay_style::StyleModifiers{
controls_mask:strafesnet_common::controls_bitflag::Controls::from_bits(self.controls_mask).ok_or(StyleModifierError::Controls(ControlsError::UnknownBits))?,
controls_mask_state:strafesnet_common::controls_bitflag::Controls::from_bits(self.controls_mask_state).ok_or(StyleModifierError::Controls(ControlsError::UnknownBits))?,
strafe:self.strafe.map(TryInto::try_into).transpose().map_err(StyleModifierError::StrafeSettings)?,
rocket:self.rocket.map(Into::into),
jump:self.jump.map(TryInto::try_into).transpose().map_err(StyleModifierError::JumpSettings)?,
walk:self.walk.map(Into::into),
ladder:self.ladder.map(Into::into),
swim:self.swim.map(Into::into),
gravity:strafesnet_common::integer::Planar64Vec3::raw_array(self.gravity),
hitbox:self.hitbox.into(),
camera_offset:strafesnet_common::integer::Planar64Vec3::raw_array(self.camera_offset),
mass:strafesnet_common::integer::Planar64::raw(self.mass),
})
}
}
impl From<strafesnet_common::gameplay_style::StyleModifiers> for StyleModifiers{
fn from(value:strafesnet_common::gameplay_style::StyleModifiers)->Self{
let header=
flag(value.strafe.is_some(),StyleModifiers::STRAFE)
|flag(value.rocket.is_some(),StyleModifiers::ROCKET)
|flag(value.jump.is_some(),StyleModifiers::JUMP)
|flag(value.walk.is_some(),StyleModifiers::WALK)
|flag(value.ladder.is_some(),StyleModifiers::LADDER)
|flag(value.swim.is_some(),StyleModifiers::SWIM);
Self{
header,
controls_mask:value.controls_mask.bits(),
controls_mask_state:value.controls_mask_state.bits(),
strafe:value.strafe.map(Into::into),
rocket:value.rocket.map(Into::into),
jump:value.jump.map(Into::into),
walk:value.walk.map(Into::into),
ladder:value.ladder.map(Into::into),
swim:value.swim.map(Into::into),
gravity:value.gravity.get().to_array(),
hitbox:value.hitbox.into(),
camera_offset:value.camera_offset.get().to_array(),
mass:value.mass.get(),
}
}
}
#[binrw::binrw]
#[brw(little,repr=u8)]
pub enum JumpCalculation{
Capped,
Energy,
Linear,
}
impl Into<strafesnet_common::gameplay_style::JumpCalculation> for JumpCalculation{
fn into(self)->strafesnet_common::gameplay_style::JumpCalculation{
match self{
JumpCalculation::Capped=>strafesnet_common::gameplay_style::JumpCalculation::Capped,
JumpCalculation::Energy=>strafesnet_common::gameplay_style::JumpCalculation::Energy,
JumpCalculation::Linear=>strafesnet_common::gameplay_style::JumpCalculation::Linear,
}
}
}
impl From<strafesnet_common::gameplay_style::JumpCalculation> for JumpCalculation{
fn from(value:strafesnet_common::gameplay_style::JumpCalculation)->Self{
match value{
strafesnet_common::gameplay_style::JumpCalculation::Capped=>JumpCalculation::Capped,
strafesnet_common::gameplay_style::JumpCalculation::Energy=>JumpCalculation::Energy,
strafesnet_common::gameplay_style::JumpCalculation::Linear=>JumpCalculation::Linear,
}
}
}
pub enum JumpImpulse{
FromTime(Time),
FromHeight(Planar64),
FromDeltaV(Planar64),
FromEnergy(Planar64),
}
impl Into<strafesnet_common::gameplay_style::JumpImpulse> for JumpImpulse{
fn into(self)->strafesnet_common::gameplay_style::JumpImpulse{
match self{
JumpImpulse::FromTime(time)=>strafesnet_common::gameplay_style::JumpImpulse::FromTime(strafesnet_common::integer::Time::raw(time)),
JumpImpulse::FromHeight(height)=>strafesnet_common::gameplay_style::JumpImpulse::FromHeight(strafesnet_common::integer::Planar64::raw(height)),
JumpImpulse::FromDeltaV(deltav)=>strafesnet_common::gameplay_style::JumpImpulse::FromDeltaV(strafesnet_common::integer::Planar64::raw(deltav)),
JumpImpulse::FromEnergy(energy)=>strafesnet_common::gameplay_style::JumpImpulse::FromEnergy(strafesnet_common::integer::Planar64::raw(energy)),
}
}
}
impl From<strafesnet_common::gameplay_style::JumpImpulse> for JumpImpulse{
fn from(value:strafesnet_common::gameplay_style::JumpImpulse)->Self{
match value{
strafesnet_common::gameplay_style::JumpImpulse::FromTime(time)=>JumpImpulse::FromTime(time.get()),
strafesnet_common::gameplay_style::JumpImpulse::FromHeight(height)=>JumpImpulse::FromHeight(height.get()),
strafesnet_common::gameplay_style::JumpImpulse::FromDeltaV(deltav)=>JumpImpulse::FromDeltaV(deltav.get()),
strafesnet_common::gameplay_style::JumpImpulse::FromEnergy(energy)=>JumpImpulse::FromEnergy(energy.get()),
}
}
}
#[binrw::binrw]
#[brw(little)]
pub struct ControlsActivation{
controls_mask:Controls,
controls_intersects:Controls,
controls_contains:Controls,
}
impl TryInto<strafesnet_common::gameplay_style::ControlsActivation> for ControlsActivation{
type Error=ControlsError;
fn try_into(self)->Result<strafesnet_common::gameplay_style::ControlsActivation,Self::Error>{
Ok(strafesnet_common::gameplay_style::ControlsActivation::new(
strafesnet_common::controls_bitflag::Controls::from_bits(self.controls_mask).ok_or(ControlsError::UnknownBits)?,
strafesnet_common::controls_bitflag::Controls::from_bits(self.controls_intersects).ok_or(ControlsError::UnknownBits)?,
strafesnet_common::controls_bitflag::Controls::from_bits(self.controls_contains).ok_or(ControlsError::UnknownBits)?,
))
}
}
impl From<strafesnet_common::gameplay_style::ControlsActivation> for ControlsActivation{
fn from(value:strafesnet_common::gameplay_style::ControlsActivation)->Self{
Self{
controls_mask:value.controls_mask().bits(),
controls_intersects:value.controls_intersects().bits(),
controls_contains:value.controls_contains().bits(),
}
}
}
#[binrw::binrw]
#[brw(little)]
pub struct StrafeSettings{
header:u8,
enable:ControlsActivation,
mv:Planar64,
#[br(if(header&Self::AIR_ACCEL_LIMIT!=0))]
air_accel_limit:Option<Planar64>,
tick_rate:Ratio64,
}
impl StrafeSettings{
const AIR_ACCEL_LIMIT:u8=1<<0;
}
#[derive(Debug)]
pub enum StrafeSettingsError{
Ratio(super::integer::RatioError),
Controls(ControlsError),
}
impl std::fmt::Display for StrafeSettingsError{
fn fmt(&self,f:&mut std::fmt::Formatter<'_>)->std::fmt::Result{
write!(f,"{self:?}")
}
}
impl std::error::Error for StrafeSettingsError{}
impl TryInto<strafesnet_common::gameplay_style::StrafeSettings> for StrafeSettings{
type Error=StrafeSettingsError;
fn try_into(self)->Result<strafesnet_common::gameplay_style::StrafeSettings,Self::Error>{
Ok(strafesnet_common::gameplay_style::StrafeSettings::new(
self.enable.try_into().map_err(StrafeSettingsError::Controls)?,
strafesnet_common::integer::Planar64::raw(self.mv),
self.air_accel_limit.map(strafesnet_common::integer::Planar64::raw),
self.tick_rate.try_into().map_err(StrafeSettingsError::Ratio)?,
))
}
}
impl From<strafesnet_common::gameplay_style::StrafeSettings> for StrafeSettings{
fn from(value:strafesnet_common::gameplay_style::StrafeSettings)->Self{
let (enable,mv,air_accel_limit,tick_rate)=value.into_inner();
let header=flag(air_accel_limit.is_some(),StrafeSettings::AIR_ACCEL_LIMIT);
Self{
header,
enable:enable.into(),
mv:mv.get(),
air_accel_limit:air_accel_limit.map(|a|a.get()),
tick_rate:tick_rate.into(),
}
}
}
#[binrw::binrw]
#[brw(little)]
pub struct PropulsionSettings{
magnitude:Planar64,
}
impl Into<strafesnet_common::gameplay_style::PropulsionSettings> for PropulsionSettings{
fn into(self)->strafesnet_common::gameplay_style::PropulsionSettings{
strafesnet_common::gameplay_style::PropulsionSettings::new(
strafesnet_common::integer::Planar64::raw(self.magnitude)
)
}
}
impl From<strafesnet_common::gameplay_style::PropulsionSettings> for PropulsionSettings{
fn from(value:strafesnet_common::gameplay_style::PropulsionSettings)->Self{
Self{
magnitude:value.magnitude().get(),
}
}
}
#[binrw::binrw]
#[brw(little)]
pub struct JumpSettings{
header:u8,
impulse:i64,
}
impl JumpSettings{
const IMPULSE:u8=0b0011;
const CALCULATION:u8=0b1100;
const fn impulse(&self)->Option<strafesnet_common::gameplay_style::JumpImpulse>{
match self.header&Self::IMPULSE{
0=>Some(strafesnet_common::gameplay_style::JumpImpulse::FromTime(strafesnet_common::integer::Time::raw(self.impulse))),
1=>Some(strafesnet_common::gameplay_style::JumpImpulse::FromHeight(strafesnet_common::integer::Planar64::raw(self.impulse))),
2=>Some(strafesnet_common::gameplay_style::JumpImpulse::FromDeltaV(strafesnet_common::integer::Planar64::raw(self.impulse))),
3=>Some(strafesnet_common::gameplay_style::JumpImpulse::FromEnergy(strafesnet_common::integer::Planar64::raw(self.impulse))),
_=>None,
}
}
const fn calculation(&self)->Option<strafesnet_common::gameplay_style::JumpCalculation>{
match (self.header&Self::CALCULATION)>>2{
0=>Some(strafesnet_common::gameplay_style::JumpCalculation::Capped),
1=>Some(strafesnet_common::gameplay_style::JumpCalculation::Energy),
2=>Some(strafesnet_common::gameplay_style::JumpCalculation::Linear),
_=>None,
}
}
}
#[derive(Debug)]
pub enum JumpSettingsError{
InvalidImpulseDiscriminant,
InvalidCalculationDiscriminant,
}
impl TryInto<strafesnet_common::gameplay_style::JumpSettings> for JumpSettings{
type Error=JumpSettingsError;
fn try_into(self)->Result<strafesnet_common::gameplay_style::JumpSettings,Self::Error>{
Ok(strafesnet_common::gameplay_style::JumpSettings::new(
self.impulse().ok_or(JumpSettingsError::InvalidImpulseDiscriminant)?,
self.calculation().ok_or(JumpSettingsError::InvalidCalculationDiscriminant)?,
))
}
}
impl From<strafesnet_common::gameplay_style::JumpSettings> for JumpSettings{
fn from(value:strafesnet_common::gameplay_style::JumpSettings)->Self{
let (impulse_enum,calculation)=value.into_inner();
let (impulse,impulse_header)=match impulse_enum{
strafesnet_common::gameplay_style::JumpImpulse::FromTime(impulse)=>(impulse.get(),0),
strafesnet_common::gameplay_style::JumpImpulse::FromHeight(impulse)=>(impulse.get(),1),
strafesnet_common::gameplay_style::JumpImpulse::FromDeltaV(impulse)=>(impulse.get(),2),
strafesnet_common::gameplay_style::JumpImpulse::FromEnergy(impulse)=>(impulse.get(),3),
};
let calculation_header=match calculation{
strafesnet_common::gameplay_style::JumpCalculation::Capped=>0,
strafesnet_common::gameplay_style::JumpCalculation::Energy=>1,
strafesnet_common::gameplay_style::JumpCalculation::Linear=>2,
};
let header=
impulse_header
|(calculation_header<<2);
Self{
header,
impulse,
}
}
}
#[binrw::binrw]
#[brw(little)]
pub struct AccelerateSettings{
accel:Planar64,
topspeed:Planar64,
}
impl Into<strafesnet_common::gameplay_style::AccelerateSettings> for AccelerateSettings{
fn into(self)->strafesnet_common::gameplay_style::AccelerateSettings{
strafesnet_common::gameplay_style::AccelerateSettings::new(
strafesnet_common::integer::Planar64::raw(self.accel),
strafesnet_common::integer::Planar64::raw(self.topspeed),
)
}
}
impl From<strafesnet_common::gameplay_style::AccelerateSettings> for AccelerateSettings{
fn from(value:strafesnet_common::gameplay_style::AccelerateSettings)->Self{
Self{
accel:value.accel().get(),
topspeed:value.topspeed().get(),
}
}
}
#[binrw::binrw]
#[brw(little)]
pub struct WalkSettings{
accelerate:AccelerateSettings,
static_friction:Planar64,
kinetic_friction:Planar64,
surf_dot:Planar64,
}
impl Into<strafesnet_common::gameplay_style::WalkSettings> for WalkSettings{
fn into(self)->strafesnet_common::gameplay_style::WalkSettings{
strafesnet_common::gameplay_style::WalkSettings::new(
self.accelerate.into(),
strafesnet_common::integer::Planar64::raw(self.static_friction),
strafesnet_common::integer::Planar64::raw(self.kinetic_friction),
strafesnet_common::integer::Planar64::raw(self.surf_dot),
)
}
}
impl From<strafesnet_common::gameplay_style::WalkSettings> for WalkSettings{
fn from(value:strafesnet_common::gameplay_style::WalkSettings)->Self{
let (accelerate,static_friction,kinetic_friction,surf_dot)=value.into_inner();
Self{
accelerate:accelerate.into(),
static_friction:static_friction.get(),
kinetic_friction:kinetic_friction.get(),
surf_dot:surf_dot.get(),
}
}
}
#[binrw::binrw]
#[brw(little)]
pub struct LadderSettings{
accelerate:AccelerateSettings,
dot:Planar64,
}
impl Into<strafesnet_common::gameplay_style::LadderSettings> for LadderSettings{
fn into(self)->strafesnet_common::gameplay_style::LadderSettings{
strafesnet_common::gameplay_style::LadderSettings::new(
self.accelerate.into(),
strafesnet_common::integer::Planar64::raw(self.dot),
)
}
}
impl From<strafesnet_common::gameplay_style::LadderSettings> for LadderSettings{
fn from(value:strafesnet_common::gameplay_style::LadderSettings)->Self{
let (accelerate,dot)=value.into_inner();
Self{
accelerate:accelerate.into(),
dot:dot.get(),
}
}
}
#[binrw::binrw]
#[brw(little,repr=u8)]
pub enum HitboxMesh{
Box,
Cylinder,
}
impl Into<strafesnet_common::gameplay_style::HitboxMesh> for HitboxMesh{
fn into(self)->strafesnet_common::gameplay_style::HitboxMesh{
match self{
HitboxMesh::Box=>strafesnet_common::gameplay_style::HitboxMesh::Box,
HitboxMesh::Cylinder=>strafesnet_common::gameplay_style::HitboxMesh::Cylinder,
}
}
}
impl From<strafesnet_common::gameplay_style::HitboxMesh> for HitboxMesh{
fn from(value:strafesnet_common::gameplay_style::HitboxMesh)->Self{
match value{
strafesnet_common::gameplay_style::HitboxMesh::Box=>HitboxMesh::Box,
strafesnet_common::gameplay_style::HitboxMesh::Cylinder=>HitboxMesh::Cylinder,
}
}
}
#[binrw::binrw]
#[brw(little)]
pub struct Hitbox{
pub halfsize:Planar64Vec3,
pub mesh:HitboxMesh,
}
impl Into<strafesnet_common::gameplay_style::Hitbox> for Hitbox{
fn into(self)->strafesnet_common::gameplay_style::Hitbox{
strafesnet_common::gameplay_style::Hitbox{
halfsize:strafesnet_common::integer::Planar64Vec3::raw_array(self.halfsize),
mesh:self.mesh.into(),
}
}
}
impl From<strafesnet_common::gameplay_style::Hitbox> for Hitbox{
fn from(value:strafesnet_common::gameplay_style::Hitbox)->Self{
Self{
halfsize:value.halfsize.get().to_array(),
mesh:value.mesh.into(),
}
}
}

View File

@@ -0,0 +1,27 @@
use super::integer::Time;
#[binrw::binrw]
#[brw(little)]
pub struct TimedPhysicsInstruction{
pub time:Time,
pub instruction:super::physics::PhysicsInputInstruction,
}
impl TryInto<strafesnet_common::instruction::TimedInstruction<strafesnet_common::physics::Instruction>> for TimedPhysicsInstruction{
type Error=super::integer::RatioError;
fn try_into(self)->Result<strafesnet_common::instruction::TimedInstruction<strafesnet_common::physics::Instruction>,Self::Error>{
Ok(strafesnet_common::instruction::TimedInstruction{
time:strafesnet_common::integer::Time::raw(self.time),
instruction:self.instruction.try_into()?,
})
}
}
impl TryFrom<strafesnet_common::instruction::TimedInstruction<strafesnet_common::physics::Instruction>> for TimedPhysicsInstruction{
type Error=super::physics::PhysicsInputInstructionError;
fn try_from(value:strafesnet_common::instruction::TimedInstruction<strafesnet_common::physics::Instruction>)->Result<Self,Self::Error>{
Ok(Self{
time:value.time.get(),
instruction:value.instruction.try_into()?,
})
}
}

63
src/newtypes/integer.rs Normal file
View File

@@ -0,0 +1,63 @@
pub type Time=i64;
#[binrw::binrw]
#[brw(little)]
pub struct Ratio64{
num:i64,
den:u64,
}
#[derive(Debug)]
pub enum RatioError{
ZeroDenominator,
}
impl std::fmt::Display for RatioError{
fn fmt(&self,f:&mut std::fmt::Formatter<'_>)->std::fmt::Result{
write!(f,"{self:?}")
}
}
impl std::error::Error for RatioError{}
impl TryInto<strafesnet_common::integer::Ratio64> for Ratio64{
type Error=RatioError;
fn try_into(self)->Result<strafesnet_common::integer::Ratio64,Self::Error>{
strafesnet_common::integer::Ratio64::new(self.num,self.den)
.ok_or(RatioError::ZeroDenominator)
}
}
impl From<strafesnet_common::integer::Ratio64> for Ratio64{
fn from(value:strafesnet_common::integer::Ratio64)->Self{
Self{
num:value.num(),
den:value.den(),
}
}
}
#[binrw::binrw]
#[brw(little)]
pub struct Ratio64Vec2{
pub x:Ratio64,
pub y:Ratio64,
}
impl TryInto<strafesnet_common::integer::Ratio64Vec2> for Ratio64Vec2{
type Error=RatioError;
fn try_into(self)->Result<strafesnet_common::integer::Ratio64Vec2,Self::Error>{
Ok(strafesnet_common::integer::Ratio64Vec2{
x:self.x.try_into()?,
y:self.y.try_into()?,
})
}
}
impl From<strafesnet_common::integer::Ratio64Vec2> for Ratio64Vec2{
fn from(value:strafesnet_common::integer::Ratio64Vec2)->Self{
Self{
x:value.x.into(),
y:value.y.into(),
}
}
}
pub type Angle32=i32;
pub type Planar64=i64;
pub type Planar64Vec3=[i64;3];
pub type Planar64Mat3=[i64;9];
pub type Planar64Affine3=[i64;12];

276
src/newtypes/model.rs Normal file
View File

@@ -0,0 +1,276 @@
use super::common::flag;
use strafesnet_common::model::PolygonIter;
use super::integer::{Planar64Vec3,Planar64Affine3};
pub type TextureCoordinate=[f32;2];
pub type Color4=[f32;4];
#[binrw::binrw]
#[brw(little)]
pub struct IndexedVertex{
pub pos:u32,
pub tex:u32,
pub normal:u32,
pub color:u32,
}
impl From<strafesnet_common::model::IndexedVertex> for IndexedVertex{
fn from(value:strafesnet_common::model::IndexedVertex)->Self{
Self{
pos:value.pos.get(),
tex:value.tex.get(),
normal:value.normal.get(),
color:value.color.get(),
}
}
}
#[binrw::binrw]
#[brw(little)]
pub struct Polygon{
pub count:u32,
#[br(count=count)]
pub vertices:Vec<u32>,
}
#[binrw::binrw]
#[brw(little)]
pub struct PolygonGroup{
pub count:u32,
#[br(count=count)]
pub polys:Vec<Polygon>,
}
impl From<strafesnet_common::model::PolygonGroup> for PolygonGroup{
fn from(value:strafesnet_common::model::PolygonGroup)->Self{
match value{
strafesnet_common::model::PolygonGroup::PolygonList(polygon_list)=>{
let polys:Vec<Polygon>=polygon_list.polys().map(|poly|{
let vertices:Vec<u32>=poly.iter().map(|vert|vert.get()).collect();
Polygon{
count:vertices.len() as u32,
vertices,
}
}).collect();
Self{
count:polys.len() as u32,
polys,
}
}
}
}
}
#[binrw::binrw]
#[brw(little)]
pub struct RenderConfig{
pub header:u8,
#[br(if(header&Self::TEXTURE!=0))]
pub texture:Option<u32>,
}
impl RenderConfig{
const TEXTURE:u8=1<<0;
}
impl Into<strafesnet_common::model::RenderConfig> for RenderConfig{
fn into(self)->strafesnet_common::model::RenderConfig{
strafesnet_common::model::RenderConfig{
texture:self.texture.map(strafesnet_common::model::TextureId::new),
}
}
}
impl From<strafesnet_common::model::RenderConfig> for RenderConfig{
fn from(value:strafesnet_common::model::RenderConfig)->Self{
let header=flag(value.texture.is_some(),RenderConfig::TEXTURE);
Self{
header,
texture:value.texture.map(|texture_id|texture_id.get()),
}
}
}
#[binrw::binrw]
#[brw(little)]
pub struct IndexedGraphicsGroup{
pub count:u32,
pub render:u32,
#[br(count=count)]
pub groups:Vec<u32>,
}
impl From<strafesnet_common::model::IndexedGraphicsGroup> for IndexedGraphicsGroup{
fn from(value:strafesnet_common::model::IndexedGraphicsGroup)->Self{
Self{
count:value.groups.len() as u32,
render:value.render.get(),
groups:value.groups.into_iter().map(|group_id|group_id.get()).collect(),
}
}
}
#[binrw::binrw]
#[brw(little)]
pub struct IndexedPhysicsGroup{
pub count:u32,
#[br(count=count)]
pub groups:Vec<u32>,
}
impl From<strafesnet_common::model::IndexedPhysicsGroup> for IndexedPhysicsGroup{
fn from(value:strafesnet_common::model::IndexedPhysicsGroup)->Self{
Self{
count:value.groups.len() as u32,
groups:value.groups.into_iter().map(|group_id|group_id.get()).collect(),
}
}
}
#[binrw::binrw]
#[brw(little)]
pub struct MeshHeader{
pub unique_pos:u32,
pub unique_normal:u32,
pub unique_tex:u32,
pub unique_color:u32,
pub unique_vertices:u32,
pub polygon_groups:u32,
pub graphics_groups:u32,
pub physics_groups:u32,
}
#[binrw::binrw]
#[brw(little)]
pub struct Mesh{
pub header:MeshHeader,
#[br(count=header.unique_pos)]
pub unique_pos:Vec<Planar64Vec3>,
#[br(count=header.unique_normal)]
pub unique_normal:Vec<Planar64Vec3>,
#[br(count=header.unique_tex)]
pub unique_tex:Vec<TextureCoordinate>,
#[br(count=header.unique_color)]
pub unique_color:Vec<Color4>,
#[br(count=header.unique_vertices)]
pub unique_vertices:Vec<IndexedVertex>,
#[br(count=header.polygon_groups)]
pub polygon_groups:Vec<PolygonGroup>,
#[br(count=header.graphics_groups)]
pub graphics_groups:Vec<IndexedGraphicsGroup>,
#[br(count=header.physics_groups)]
pub physics_groups:Vec<IndexedPhysicsGroup>,
}
impl Into<strafesnet_common::model::Mesh> for Mesh{
fn into(self)->strafesnet_common::model::Mesh{
strafesnet_common::model::Mesh{
unique_pos:self.unique_pos.into_iter().map(strafesnet_common::integer::Planar64Vec3::raw_array).collect(),
unique_normal:self.unique_normal.into_iter().map(strafesnet_common::integer::Planar64Vec3::raw_array).collect(),
unique_tex:self.unique_tex.into_iter().map(strafesnet_common::model::TextureCoordinate::from_array).collect(),
unique_color:self.unique_color.into_iter().map(strafesnet_common::model::Color4::from_array).collect(),
unique_vertices:self.unique_vertices.into_iter().map(|vert|strafesnet_common::model::IndexedVertex{
pos:strafesnet_common::model::PositionId::new(vert.pos),
tex:strafesnet_common::model::TextureCoordinateId::new(vert.tex),
normal:strafesnet_common::model::NormalId::new(vert.normal),
color:strafesnet_common::model::ColorId::new(vert.color),
}).collect(),
polygon_groups:self.polygon_groups.into_iter().map(|group|
strafesnet_common::model::PolygonGroup::PolygonList(
strafesnet_common::model::PolygonList::new(
group.polys.into_iter().map(|vert|
vert.vertices.into_iter().map(strafesnet_common::model::VertexId::new).collect()
).collect()
)
)
).collect(),
graphics_groups:self.graphics_groups.into_iter().map(|group|
strafesnet_common::model::IndexedGraphicsGroup{
render:strafesnet_common::model::RenderConfigId::new(group.render),
groups:group.groups.into_iter().map(strafesnet_common::model::PolygonGroupId::new).collect(),
}
).collect(),
physics_groups:self.physics_groups.into_iter().map(|group|
strafesnet_common::model::IndexedPhysicsGroup{
groups:group.groups.into_iter().map(strafesnet_common::model::PolygonGroupId::new).collect(),
}
).collect(),
}
}
}
impl From<strafesnet_common::model::Mesh> for Mesh{
fn from(value:strafesnet_common::model::Mesh)->Self{
Self{
header:MeshHeader{
unique_pos:value.unique_pos.len() as u32,
unique_normal:value.unique_normal.len() as u32,
unique_tex:value.unique_tex.len() as u32,
unique_color:value.unique_color.len() as u32,
unique_vertices:value.unique_vertices.len() as u32,
polygon_groups:value.polygon_groups.len() as u32,
graphics_groups:value.graphics_groups.len() as u32,
physics_groups:value.physics_groups.len() as u32,
},
unique_pos:value.unique_pos.into_iter()
.map(|pos|pos.get().to_array())
.collect(),
unique_normal:value.unique_normal.into_iter()
.map(|normal|normal.get().to_array())
.collect(),
unique_tex:value.unique_tex.into_iter()
.map(|tex|tex.to_array())
.collect(),
unique_color:value.unique_color.into_iter()
.map(|color|color.to_array())
.collect(),
unique_vertices:value.unique_vertices.into_iter()
.map(Into::into)
.collect(),
polygon_groups:value.polygon_groups.into_iter()
.map(Into::into)
.collect(),
graphics_groups:value.graphics_groups.into_iter()
.map(Into::into)
.collect(),
physics_groups:value.physics_groups.into_iter()
.map(Into::into)
.collect(),
}
}
}
#[binrw::binrw]
#[brw(little)]
pub struct Model{
pub mesh:u32,
pub attributes:u32,
pub color:Color4,
pub transform:Planar64Affine3,
}
impl Into<strafesnet_common::model::Model> for Model{
fn into(self)->strafesnet_common::model::Model{
let [_0,_1,_2,_3,_4,_5,_6,_7,_8,_9,_a,_b]=self.transform;
strafesnet_common::model::Model{
mesh:strafesnet_common::model::MeshId::new(self.mesh),
attributes:strafesnet_common::gameplay_attributes::CollisionAttributesId::new(self.attributes),
color:strafesnet_common::model::Color4::from_array(self.color),
transform:strafesnet_common::integer::Planar64Affine3::new(
strafesnet_common::integer::Planar64Mat3::from_cols(
strafesnet_common::integer::Planar64Vec3::raw_xyz(_0,_1,_2),
strafesnet_common::integer::Planar64Vec3::raw_xyz(_3,_4,_5),
strafesnet_common::integer::Planar64Vec3::raw_xyz(_6,_7,_8)
),
strafesnet_common::integer::Planar64Vec3::raw_xyz(_9,_a,_b)
),
}
}
}
impl From<strafesnet_common::model::Model> for Model{
fn from(value:strafesnet_common::model::Model)->Self{
let (
[_0,_1,_2],
[_3,_4,_5],
[_6,_7,_8],
[_9,_a,_b]
)=(
value.transform.matrix3.x_axis.get().to_array(),
value.transform.matrix3.y_axis.get().to_array(),
value.transform.matrix3.z_axis.get().to_array(),
value.transform.translation.get().to_array()
);
Self{
mesh:value.mesh.get(),
attributes:value.attributes.get(),
color:value.color.to_array(),
transform:[_0,_1,_2,_3,_4,_5,_6,_7,_8,_9,_a,_b],
}
}
}

37
src/newtypes/mouse.rs Normal file
View File

@@ -0,0 +1,37 @@
use super::integer::Time;
#[binrw::binrw]
#[brw(little)]
pub enum EncodedMouseDelta{
//X did not move Y has 1 byte, time has 2 bytes
X0Y1T2{
y:i8,
t:u16,
},
X1Y1T2
}
///TODO: delta delta encoding lol
#[binrw::binrw]
#[brw(little)]
pub struct MouseState{
pub pos:[i32;2],
pub time:Time,
}
impl Into<strafesnet_common::mouse::MouseState> for MouseState{
fn into(self)->strafesnet_common::mouse::MouseState{
strafesnet_common::mouse::MouseState{
pos:self.pos.into(),
time:strafesnet_common::integer::Time::raw(self.time),
}
}
}
impl From<strafesnet_common::mouse::MouseState> for MouseState{
fn from(value:strafesnet_common::mouse::MouseState)->Self{
Self{
pos:value.pos.to_array(),
time:value.time.get(),
}
}
}

98
src/newtypes/physics.rs Normal file
View File

@@ -0,0 +1,98 @@
use super::common::Boolio;
#[binrw::binrw]
#[brw(little)]
pub enum PhysicsInputInstruction{
#[brw(magic=0u8)]
ReplaceMouse(super::mouse::MouseState,super::mouse::MouseState),
#[brw(magic=1u8)]
SetNextMouse(super::mouse::MouseState),
#[brw(magic=2u8)]
SetMoveRight(Boolio),
#[brw(magic=3u8)]
SetMoveUp(Boolio),
#[brw(magic=4u8)]
SetMoveBack(Boolio),
#[brw(magic=5u8)]
SetMoveLeft(Boolio),
#[brw(magic=6u8)]
SetMoveDown(Boolio),
#[brw(magic=7u8)]
SetMoveForward(Boolio),
#[brw(magic=8u8)]
SetJump(Boolio),
#[brw(magic=9u8)]
SetZoom(Boolio),
#[brw(magic=10u8)]
Reset,
#[brw(magic=11u8)]
Restart,
#[brw(magic=12u8)]
Spawn(super::gameplay_modes::ModeId,super::gameplay_modes::StageId),
#[brw(magic=13u8)]
PracticeFly,
#[brw(magic=14u8)]
SetSensitivity(super::integer::Ratio64Vec2),
}
#[derive(Debug)]
pub enum PhysicsInputInstructionError{
/// This is an instruction that can be dropped when serializing
DropInstruction,
}
impl std::fmt::Display for PhysicsInputInstructionError{
fn fmt(&self,f:&mut std::fmt::Formatter<'_>)->std::fmt::Result{
write!(f,"{self:?}")
}
}
impl std::error::Error for PhysicsInputInstructionError{}
impl TryInto<strafesnet_common::physics::Instruction> for PhysicsInputInstruction{
type Error=super::integer::RatioError;
fn try_into(self)->Result<strafesnet_common::physics::Instruction,Self::Error>{
Ok(match self{
PhysicsInputInstruction::ReplaceMouse(m0,m1)=>strafesnet_common::physics::Instruction::ReplaceMouse(m0.into(),m1.into()),
PhysicsInputInstruction::SetNextMouse(m)=>strafesnet_common::physics::Instruction::SetNextMouse(m.into()),
PhysicsInputInstruction::SetMoveRight(state)=>strafesnet_common::physics::Instruction::SetMoveRight(state.into()),
PhysicsInputInstruction::SetMoveUp(state)=>strafesnet_common::physics::Instruction::SetMoveUp(state.into()),
PhysicsInputInstruction::SetMoveBack(state)=>strafesnet_common::physics::Instruction::SetMoveBack(state.into()),
PhysicsInputInstruction::SetMoveLeft(state)=>strafesnet_common::physics::Instruction::SetMoveLeft(state.into()),
PhysicsInputInstruction::SetMoveDown(state)=>strafesnet_common::physics::Instruction::SetMoveDown(state.into()),
PhysicsInputInstruction::SetMoveForward(state)=>strafesnet_common::physics::Instruction::SetMoveForward(state.into()),
PhysicsInputInstruction::SetJump(state)=>strafesnet_common::physics::Instruction::SetJump(state.into()),
PhysicsInputInstruction::SetZoom(state)=>strafesnet_common::physics::Instruction::SetZoom(state.into()),
PhysicsInputInstruction::Reset=>strafesnet_common::physics::Instruction::Reset,
PhysicsInputInstruction::Restart=>strafesnet_common::physics::Instruction::Restart,
PhysicsInputInstruction::Spawn(mode_id,stage_id)=>strafesnet_common::physics::Instruction::Spawn(
strafesnet_common::gameplay_modes::ModeId::new(mode_id),
strafesnet_common::gameplay_modes::StageId::new(stage_id),
),
PhysicsInputInstruction::PracticeFly=>strafesnet_common::physics::Instruction::PracticeFly,
PhysicsInputInstruction::SetSensitivity(sensitivity)=>strafesnet_common::physics::Instruction::SetSensitivity(sensitivity.try_into()?),
})
}
}
impl TryFrom<strafesnet_common::physics::Instruction> for PhysicsInputInstruction{
type Error=PhysicsInputInstructionError;
fn try_from(value:strafesnet_common::physics::Instruction)->Result<Self,Self::Error>{
match value{
strafesnet_common::physics::Instruction::ReplaceMouse(m0,m1)=>Ok(PhysicsInputInstruction::ReplaceMouse(m0.into(),m1.into())),
strafesnet_common::physics::Instruction::SetNextMouse(m)=>Ok(PhysicsInputInstruction::SetNextMouse(m.into())),
strafesnet_common::physics::Instruction::SetMoveRight(state)=>Ok(PhysicsInputInstruction::SetMoveRight(state.into())),
strafesnet_common::physics::Instruction::SetMoveUp(state)=>Ok(PhysicsInputInstruction::SetMoveUp(state.into())),
strafesnet_common::physics::Instruction::SetMoveBack(state)=>Ok(PhysicsInputInstruction::SetMoveBack(state.into())),
strafesnet_common::physics::Instruction::SetMoveLeft(state)=>Ok(PhysicsInputInstruction::SetMoveLeft(state.into())),
strafesnet_common::physics::Instruction::SetMoveDown(state)=>Ok(PhysicsInputInstruction::SetMoveDown(state.into())),
strafesnet_common::physics::Instruction::SetMoveForward(state)=>Ok(PhysicsInputInstruction::SetMoveForward(state.into())),
strafesnet_common::physics::Instruction::SetJump(state)=>Ok(PhysicsInputInstruction::SetJump(state.into())),
strafesnet_common::physics::Instruction::SetZoom(state)=>Ok(PhysicsInputInstruction::SetZoom(state.into())),
strafesnet_common::physics::Instruction::Reset=>Ok(PhysicsInputInstruction::Reset),
strafesnet_common::physics::Instruction::Restart=>Ok(PhysicsInputInstruction::Restart),
strafesnet_common::physics::Instruction::Spawn(mode_id,stage_id)=>Ok(PhysicsInputInstruction::Spawn(
mode_id.get(),
stage_id.get(),
)),
strafesnet_common::physics::Instruction::PracticeFly=>Ok(PhysicsInputInstruction::PracticeFly),
strafesnet_common::physics::Instruction::SetSensitivity(sensitivity)=>Ok(PhysicsInputInstruction::SetSensitivity(sensitivity.into())),
strafesnet_common::physics::Instruction::Idle=>Err(PhysicsInputInstructionError::DropInstruction),
}
}
}