diff --git a/lib/snf/.gitignore b/lib/snf/.gitignore
new file mode 100644
index 0000000..ea8c4bf
--- /dev/null
+++ b/lib/snf/.gitignore
@@ -0,0 +1 @@
+/target
diff --git a/lib/snf/Cargo.lock b/lib/snf/Cargo.lock
new file mode 100644
index 0000000..58d2c57
--- /dev/null
+++ b/lib/snf/Cargo.lock
@@ -0,0 +1,191 @@
+# This file is automatically @generated by Cargo.
+# It is not intended for manual editing.
+version = 3
+
+[[package]]
+name = "array-init"
+version = "2.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3d62b7694a562cdf5a74227903507c56ab2cc8bdd1f781ed5cb4cf9c9f810bfc"
+
+[[package]]
+name = "arrayvec"
+version = "0.7.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50"
+
+[[package]]
+name = "binrw"
+version = "0.14.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3f36b7cb3ab9ff6a2858650d8dc360e783a5d14dc29594db48c56a3c233cc265"
+dependencies = [
+ "array-init",
+ "binrw_derive",
+ "bytemuck",
+]
+
+[[package]]
+name = "binrw_derive"
+version = "0.14.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "20ea7a8c5c8eeffffac6d54d172444e15beffac6f817fac714460a9a9aa88da3"
+dependencies = [
+ "either",
+ "owo-colors",
+ "proc-macro2",
+ "quote",
+ "syn 1.0.109",
+]
+
+[[package]]
+name = "bitflags"
+version = "2.6.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b048fb63fd8b5923fc5aa7b340d8e156aec7ec02f0c78fa8a6ddc2613f6f71de"
+
+[[package]]
+name = "bnum"
+version = "0.12.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "50202def95bf36cb7d1d7a7962cea1c36a3f8ad42425e5d2b71d7acb8041b5b8"
+
+[[package]]
+name = "bytemuck"
+version = "1.16.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "102087e286b4677862ea56cf8fc58bb2cdfa8725c40ffb80fe3a008eb7f2fc83"
+
+[[package]]
+name = "either"
+version = "1.13.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "60b1af1c220855b6ceac025d3f6ecdd2b7c4894bfe9cd9bda4fbb4bc7c0d4cf0"
+
+[[package]]
+name = "fixed_wide"
+version = "0.1.0"
+source = "sparse+https://git.itzana.me/api/packages/strafesnet/cargo/"
+checksum = "7a8d6e10c51c9df39ead915c62288afbc41d13e00368e526037e530ee5c58e13"
+dependencies = [
+ "arrayvec",
+ "bnum",
+ "paste",
+ "ratio_ops",
+]
+
+[[package]]
+name = "glam"
+version = "0.28.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "779ae4bf7e8421cf91c0b3b64e7e8b40b862fba4d393f59150042de7c4965a94"
+
+[[package]]
+name = "id"
+version = "0.1.0"
+source = "sparse+https://git.itzana.me/api/packages/strafesnet/cargo/"
+checksum = "2337e7a6c273082b672e377e159d7a168fb51438461b7c4033c79a515dd7a25a"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.72",
+]
+
+[[package]]
+name = "linear_ops"
+version = "0.1.0"
+source = "sparse+https://git.itzana.me/api/packages/strafesnet/cargo/"
+checksum = "b2e6977ac24f47086d8a7a2d4ae1c720e86dfdc8407cf5e34c18bfa01053c456"
+dependencies = [
+ "fixed_wide",
+ "paste",
+ "ratio_ops",
+]
+
+[[package]]
+name = "owo-colors"
+version = "3.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c1b04fb49957986fdce4d6ee7a65027d55d4b6d2265e5848bbb507b58ccfdb6f"
+
+[[package]]
+name = "paste"
+version = "1.0.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a"
+
+[[package]]
+name = "proc-macro2"
+version = "1.0.86"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5e719e8df665df0d1c8fbfd238015744736151d4445ec0836b8e628aae103b77"
+dependencies = [
+ "unicode-ident",
+]
+
+[[package]]
+name = "quote"
+version = "1.0.36"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0fa76aaf39101c457836aec0ce2316dbdc3ab723cdda1c6bd4e6ad4208acaca7"
+dependencies = [
+ "proc-macro2",
+]
+
+[[package]]
+name = "ratio_ops"
+version = "0.1.0"
+source = "sparse+https://git.itzana.me/api/packages/strafesnet/cargo/"
+checksum = "01239195d6afe0509e7e3511b716c0540251dfe7ece0a9a5a27116afb766c42c"
+
+[[package]]
+name = "strafesnet_common"
+version = "0.5.0"
+source = "sparse+https://git.itzana.me/api/packages/strafesnet/cargo/"
+checksum = "d8fcc44793ae84a1d80882f367980913292241c94eb87584de4010bdad4a918d"
+dependencies = [
+ "arrayvec",
+ "bitflags",
+ "fixed_wide",
+ "glam",
+ "id",
+ "linear_ops",
+ "ratio_ops",
+]
+
+[[package]]
+name = "strafesnet_snf"
+version = "0.2.0"
+dependencies = [
+ "binrw",
+ "id",
+ "strafesnet_common",
+]
+
+[[package]]
+name = "syn"
+version = "1.0.109"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "unicode-ident",
+]
+
+[[package]]
+name = "syn"
+version = "2.0.72"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dc4b9b9bf2add8093d3f2c0204471e951b2285580335de42f9d2534f3ae7a8af"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "unicode-ident",
+]
+
+[[package]]
+name = "unicode-ident"
+version = "1.0.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b"
diff --git a/lib/snf/Cargo.toml b/lib/snf/Cargo.toml
new file mode 100644
index 0000000..300777c
--- /dev/null
+++ b/lib/snf/Cargo.toml
@@ -0,0 +1,11 @@
+[package]
+name = "strafesnet_snf"
+version = "0.2.0"
+edition = "2021"
+
+# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
+
+[dependencies]
+binrw = "0.14.0"
+id = { version = "0.1.0", registry = "strafesnet" }
+strafesnet_common = { version = "0.5.0", registry = "strafesnet" }
diff --git a/lib/snf/LICENSE-APACHE b/lib/snf/LICENSE-APACHE
new file mode 100644
index 0000000..a7e77cb
--- /dev/null
+++ b/lib/snf/LICENSE-APACHE
@@ -0,0 +1,176 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+END OF TERMS AND CONDITIONS
\ No newline at end of file
diff --git a/lib/snf/LICENSE-MIT b/lib/snf/LICENSE-MIT
new file mode 100644
index 0000000..468cd79
--- /dev/null
+++ b/lib/snf/LICENSE-MIT
@@ -0,0 +1,23 @@
+Permission is hereby granted, free of charge, to any
+person obtaining a copy of this software and associated
+documentation files (the "Software"), to deal in the
+Software without restriction, including without
+limitation the rights to use, copy, modify, merge,
+publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software
+is furnished to do so, subject to the following
+conditions:
+
+The above copyright notice and this permission notice
+shall be included in all copies or substantial portions
+of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
+ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
+TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
+SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
+IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
\ No newline at end of file
diff --git a/lib/snf/README.md b/lib/snf/README.md
new file mode 100644
index 0000000..1d9e111
--- /dev/null
+++ b/lib/snf/README.md
@@ -0,0 +1,30 @@
+StrafesNET File Format
+======================
+
+## Example
+
+```rust
+let file=std::fs::File::open(path)?;
+let mut input=std::io::BufReader::new(file);
+let snf=snf::read(input)?;
+match snf{
+ snf::SNF::Map(map)=>{},
+ snf::SNF::Bot(bot)=>{},
+ snf::SNF::Demo(demo)=>{},
+}
+```
+
+#### License
+
+
+Licensed under either of Apache License, Version
+2.0 or MIT license at your option.
+
+
+
+
+
+Unless you explicitly state otherwise, any contribution intentionally submitted
+for inclusion in this crate by you, as defined in the Apache-2.0 license, shall
+be dual licensed as above, without any additional terms or conditions.
+
\ No newline at end of file
diff --git a/lib/snf/src/bot.rs b/lib/snf/src/bot.rs
new file mode 100644
index 0000000..ffdaee8
--- /dev/null
+++ b/lib/snf/src/bot.rs
@@ -0,0 +1,98 @@
+use binrw::{BinReaderExt, binrw};
+
+#[derive(Debug)]
+pub enum Error{
+ InvalidHeader,
+ InvalidSegment(binrw::Error),
+ InvalidSegmentId(SegmentId),
+ File(crate::file::Error),
+}
+
+/* block types
+
+BLOCK_BOT_HEADER:
+u128 map_resource_uuid //which map is this bot running
+//don't include style info in bot header because it's in the simulation state
+//blocks are laid out in chronological order, but indices may jump around.
+u64 num_segments
+for _ in 0..num_segments{
+ i64 time //simulation_state timestamp
+ u64 block_id
+}
+
+BLOCK_BOT_SEGMENT:
+//format version indicates what version of these structures to use
+SimulationState simulation_state //SimulationState is just under ClientState which includes Play/Pause events that the simulation doesn't know about.
+//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 instruction
+}
+
+*/
+
+//error hiding mock code
+mod simulation{
+ #[super::binrw]
+ #[brw(little)]
+ pub struct State{}
+ #[super::binrw]
+ #[brw(little)]
+ pub struct Instruction{}
+}
+// mod instruction{
+ // #[super::binrw]
+ // #[brw(little)]
+ // pub struct TimedInstruction{
+ // time:u64,
+ // instruction:Instruction
+ // }
+// }
+// mod timeline{
+ // #[super::binrw]
+ // #[brw(little)]
+ // pub struct Timeline{
+ // #[bw(try_calc(u32::try_from(instructions.len())))]
+ // instruction_count:u32,
+ // #[br(count=instruction_count)]
+ // instructions:Vec>
+ // }
+// }
+
+//serious code
+
+#[binrw]
+#[brw(little)]
+#[derive(Clone,Copy,Debug,id::Id)]
+pub struct SegmentId(u32);
+
+#[binrw]
+#[brw(little)]
+pub struct Segment{
+ state:simulation::State,
+ //#[bw(try_calc(u32::try_from(instructions.len())))]
+ //instruction_count:u32,
+ //#[br(count=instruction_count)]
+ //instructions:Vec>
+
+ //please remember that strafe ticks are implicit! 33% smaller bot files
+}
+
+pub struct StreamableBot{
+ file:crate::file::File,
+ //timeline:timeline::Timeline,
+ segment_id_to_block_id:Vec,
+}
+impl StreamableBot{
+ pub(crate) fn new(file:crate::file::File)->Result{
+ Err(Error::InvalidHeader)
+ }
+ pub fn load_segment(&mut self,segment_id:SegmentId)->Result{
+ let block_id=*self.segment_id_to_block_id.get(segment_id.get() as usize).ok_or(Error::InvalidSegmentId(segment_id))?;
+ let mut block=self.file.block_reader(block_id).map_err(Error::File)?;
+ let segment=block.read_le().map_err(Error::InvalidSegment)?;
+ Ok(segment)
+ }
+}
diff --git a/lib/snf/src/demo.rs b/lib/snf/src/demo.rs
new file mode 100644
index 0000000..119290a
--- /dev/null
+++ b/lib/snf/src/demo.rs
@@ -0,0 +1,31 @@
+use binrw::BinReaderExt;
+
+#[derive(Debug)]
+pub enum Error{
+ InvalidHeader,
+}
+
+/*
+BLOCK_DEMO_HEADER:
+u128 map_resource_id
+u64 map_header_block_id
+u32 num_bots
+for bot_id in 0..num_bots{
+ u128 bot_resource_id
+ u64 bot_header_block_id
+}
+
+//bot loading timeline
+how to do worldstate for deathrun!?
+
+*/
+
+pub struct StreamableDemo{
+ map:Box>,
+ bots:Vec>,
+}
+impl StreamableDemo{
+ pub(crate) fn new(file:crate::file::File)->Result{
+ Err(Error::InvalidHeader)
+ }
+}
diff --git a/lib/snf/src/file.rs b/lib/snf/src/file.rs
new file mode 100644
index 0000000..fb04c3e
--- /dev/null
+++ b/lib/snf/src/file.rs
@@ -0,0 +1,110 @@
+//file format "sniff"
+
+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
+
+//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
+//the start of the first block is implicitly after the global header (32)
+//num_blocks+1 used in Header.block_location is implicitly the end of the file
+for block_id in 1..num_blocks{
+ u64 first_byte
+}
+
+//end global header
+
+//begin blocks
+
+//each block is compressed with zstd or gz or something
+
+*/
+#[binrw]
+#[brw(little)]
+#[derive(Clone,Copy,Debug)]
+pub(crate) enum FourCC{
+ #[brw(magic=b"SNFM")]
+ Map,
+ #[brw(magic=b"SNFB")]
+ Bot,
+ #[brw(magic=b"SNFD")]
+ Demo,
+}
+#[binrw]
+#[brw(little)]
+#[derive(Debug)]
+pub struct Header{
+ /// Type of file
+ pub fourcc:FourCC,
+ /// File format version
+ pub version:u32,
+ /// Minimum data required to know the location of all streamable resources for this specific file
+ pub priming:u64,
+ /// uuid for this file
+ pub resource:u128,
+ //don't need try_calc: the struct will force field initialization anyways and it can be calculated there
+ pub block_count:u32,
+ #[br(count=block_count+1)]
+ pub block_location:Vec,
+}
+
+#[binrw]
+#[brw(little)]
+#[derive(Clone,Copy,Debug,Hash,id::Id,Eq,Ord,PartialEq,PartialOrd)]
+pub struct BlockId(u32);
+
+pub(crate) struct File{
+ header:Header,
+ //reference to the data
+ data:R,
+}
+
+impl File{
+ pub(crate) fn new(mut input:R)->Result,Error>{
+ Ok(File{
+ header:input.read_le().map_err(Error::InvalidHeader)?,
+ data:input,
+ })
+ }
+ pub(crate) fn data_mut(&mut self)->&mut R{
+ &mut self.data
+ }
+ pub(crate) fn block_reader(&mut self,block_id:BlockId)->Result,Error>{
+ if self.header.block_location.len() as u32<=block_id.get(){
+ return Err(Error::InvalidBlockId(block_id))
+ }
+ 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(self.data_mut().take_seek(block_end-block_start))
+ }
+ pub(crate) fn fourcc(&self)->FourCC{
+ self.header.fourcc
+ }
+}
diff --git a/lib/snf/src/lib.rs b/lib/snf/src/lib.rs
new file mode 100644
index 0000000..675dfdb
--- /dev/null
+++ b/lib/snf/src/lib.rs
@@ -0,0 +1,68 @@
+use binrw::BinReaderExt;
+
+mod newtypes;
+
+mod file;
+pub mod map;
+pub mod bot;
+pub mod demo;
+
+#[derive(Debug)]
+pub enum Error{
+ UnexpectedFourCC,
+ Header(file::Error),
+ Map(map::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{
+ Map(map::StreamableMap),
+ Bot(bot::StreamableBot),
+ Demo(demo::StreamableDemo),
+}
+
+pub fn read_snf(input:R)->Result,Error>{
+ let file=file::File::new(input).map_err(Error::Header)?;
+ Ok(match file.fourcc(){
+ file::FourCC::Map=>SNF::Map(map::StreamableMap::new(file).map_err(Error::Map)?),
+ file::FourCC::Bot=>SNF::Bot(bot::StreamableBot::new(file).map_err(Error::Bot)?),
+ file::FourCC::Demo=>SNF::Demo(demo::StreamableDemo::new(file).map_err(Error::Demo)?),
+ })
+}
+pub fn read_map(input:R)->Result,Error>{
+ let file=file::File::new(input).map_err(Error::Header)?;
+ match file.fourcc(){
+ file::FourCC::Map=>Ok(map::StreamableMap::new(file).map_err(Error::Map)?),
+ _=>Err(Error::UnexpectedFourCC)
+ }
+}
+pub fn read_bot(input:R)->Result,Error>{
+ let file=file::File::new(input).map_err(Error::Header)?;
+ match file.fourcc(){
+ file::FourCC::Bot=>Ok(bot::StreamableBot::new(file).map_err(Error::Bot)?),
+ _=>Err(Error::UnexpectedFourCC)
+ }
+}
+pub fn read_demo(input:R)->Result,Error>{
+ let file=file::File::new(input).map_err(Error::Header)?;
+ match file.fourcc(){
+ file::FourCC::Demo=>Ok(demo::StreamableDemo::new(file).map_err(Error::Demo)?),
+ _=>Err(Error::UnexpectedFourCC)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ //use super::*;
+
+ #[test]
+ fn test() {
+ }
+}
diff --git a/lib/snf/src/map.rs b/lib/snf/src/map.rs
new file mode 100644
index 0000000..a5ef6f7
--- /dev/null
+++ b/lib/snf/src/map.rs
@@ -0,0 +1,444 @@
+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(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
+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{
+ u32 parent_node
+}
+
+//NOTE: alternate realities are not necessary.
+//portals/wormholes simply use an in-model and and out-model.
+//skyboxes are inverted models with a special shader.
+
+//ideally spacial blocks are sorted from distance to start zone
+//texture blocks are inserted before the first spacial block they are used in
+for spacial_block_id in 0..num_spacial_blocks{
+ u32 node_id
+ u32 block_id //data block
+ Aabb extents
+}
+//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:
+Resource resource_type
+//an individual one of the following:
+ - model (Mesh)
+ - shader (compiled SPIR-V)
+ - image (JpegXL)
+ - sound (Opus)
+ - video (AV1)
+ - animation (Trey thing)
+
+BLOCK_MAP_REGION:
+u64 num_models
+for model_id in 0..num_models{
+ ModelInstance mode_instance
+}
+
+*/
+
+//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,
+}
+const RESOURCE_TYPE_VARIANT_COUNT:u8=2;
+#[binrw]
+#[brw(little)]
+struct ResourceId(u128);
+impl ResourceId{
+ fn resource_type(&self)->Option{
+ 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)(){
+ match discriminantSome(unsafe{std::mem::transmute::(discriminant)}),
+ false=>None,
+ }
+ }
+}
+
+struct ResourceMap{
+ meshes:HashMap,
+ textures:HashMap,
+}
+impl Default for ResourceMap{
+ fn default()->Self{
+ Self{
+ meshes:HashMap::new(),
+ textures:HashMap::new(),
+ }
+ }
+}
+
+#[binrw]
+#[brw(little)]
+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,
+ #[br(count=num_resource_blocks)]
+ resource_blocks:Vec,
+ //#[br(count=num_resources_external)]
+ //external_resources:Vec,
+ #[br(count=num_modes)]
+ modes:Vec,
+ #[br(count=num_attributes)]
+ attributes:Vec,
+ #[br(count=num_render_configs)]
+ render_configs:Vec,
+}
+
+#[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<(u32,newtypes::model::Model)>,
+}
+
+//code deduplication reused in into_complete_map
+fn read_region(file:&mut crate::file::File,block_id:BlockId)->Result,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(file:&mut crate::file::File,block_id:BlockId)->Result{
+ 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(file:&mut crate::file::File,block_id:BlockId)->Result,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{
+ file:crate::file::File,
+ //this includes every platform... move the unconstrained datas to their appropriate data block?
+ modes:gameplay_modes::Modes,
+ //this is every possible attribute... need some sort of streaming system
+ attributes:Vec,
+ //this is every possible render configuration... shaders and such... need streaming
+ render_configs:Vec,
+ //this makes sense to keep in memory for streaming, a map of which blocks occupy what space
+ bvh:BvhNode,
+ //something something resources hashmaps
+ resource_blocks:ResourceMap,
+ //resource_external:ResourceMap,
+}
+impl StreamableMap{
+ pub(crate) fn new(mut file:crate::file::File)->Result{
+ //assume the file seek is in the right place to start reading a map header
+ let header:MapHeader=file.data_mut().read_le().map_err(Error::InvalidHeader)?;
+ let modes=header.modes.into_iter().map(TryInto::try_into).collect::>().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 get_intersecting_region_block_ids(&self,aabb:&Aabb)->Vec{
+ let mut block_ids=Vec::new();
+ self.bvh.the_tester(aabb,&mut |&block_id|block_ids.push(block_id));
+ block_ids
+ }
+ pub fn load_region(&mut self,block_id:BlockId)->Result,Error>{
+ read_region(&mut self.file,block_id)
+ }
+ pub fn load_mesh(&mut self,mesh_id:model::MeshId)->Result{
+ 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,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{
+ 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,
+ block_headers:&mut Vec,
+ sequential_block_data:&mut std::io::Cursor<&mut Vec>,
+ bvh_node:strafesnet_common::bvh::BvhWeightNode
+)->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()