├── .gitignore ├── all_checks.sh ├── .github ├── workflows │ └── rust.yml ├── dependabot.yml └── FUNDING.yml ├── src ├── lib.rs ├── util_funcs.rs ├── coords.rs ├── iter.rs └── tree.rs ├── Cargo.toml ├── doc └── node_structure.md ├── benches ├── coordinates.rs ├── freelist.rs └── iterators.rs ├── examples ├── rayon.rs └── glium.rs ├── README.md └── LICENSE.txt /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /all_checks.sh: -------------------------------------------------------------------------------- 1 | DIE() 2 | { 3 | echo ERROR:$1 4 | exit 1 5 | } 6 | 7 | 8 | cargo check || DIE 9 | cargo clippy || DIE 10 | cargo test || DIE 11 | cargo bench --no-run --profile dev || DIE 12 | -------------------------------------------------------------------------------- /.github/workflows/rust.yml: -------------------------------------------------------------------------------- 1 | name: Rust 2 | 3 | on: 4 | push: 5 | branches: [ "main" ] 6 | pull_request: 7 | branches: [ "main" ] 8 | 9 | env: 10 | CARGO_TERM_COLOR: always 11 | 12 | jobs: 13 | build: 14 | 15 | runs-on: ubuntu-latest 16 | 17 | steps: 18 | - uses: actions/checkout@v3 19 | - name: Build 20 | run: cargo build --verbose 21 | - name: Run tests 22 | run: cargo test --verbose 23 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | # To get started with Dependabot version updates, you'll need to specify which 2 | # package ecosystems to update and where the package manifests are located. 3 | # Please see the documentation for all configuration options: 4 | # https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates 5 | 6 | version: 2 7 | updates: 8 | - package-ecosystem: "cargo" # See documentation for possible values 9 | directory: "/" # Location of package manifests 10 | schedule: 11 | interval: "weekly" 12 | -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: [alexpyattaev] # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2] 4 | patreon: # Replace with a single Patreon username 5 | open_collective: # Replace with a single Open Collective username 6 | ko_fi: # Replace with a single Ko-fi username 7 | tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel 8 | community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry 9 | liberapay: # Replace with a single Liberapay username 10 | issuehunt: # Replace with a single IssueHunt username 11 | otechie: # Replace with a single Otechie username 12 | lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry 13 | custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] 14 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | /* Generic tree structures for storage of spatial data. 2 | Copyright (C) 2023 Alexander Pyattaev 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with this program. If not, see . 16 | */ 17 | 18 | #![doc = include_str!("../README.md")] 19 | 20 | 21 | pub mod coords; 22 | pub use crate::coords::*; 23 | 24 | pub mod util_funcs; 25 | pub use crate::util_funcs::*; 26 | 27 | pub mod tree; 28 | pub use crate::tree::*; 29 | 30 | 31 | pub mod iter; 32 | pub use crate::iter::*; 33 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "spatialtree" 3 | description = "A fast and flexible generic spatial tree collection (Octree, Quadtree, etc)" 4 | version = "0.1.3" 5 | edition = "2021" 6 | license = "GPL-3.0" 7 | repository = "https://github.com/alexpyattaev/spatialtree" 8 | documentation = "https://docs.rs/spatialtree" 9 | keywords = ["octree", "quadtree", "tree", "lod", "generic"] 10 | categories = ["data-structures"] 11 | exclude = [".github/"] 12 | 13 | 14 | [dependencies] 15 | arrayvec = "0.7" 16 | duplicate = "2.0" 17 | slab = "0.4" 18 | rand = { version = "0.9", features = ['small_rng'], optional = true } 19 | 20 | [features] 21 | default = ["rand"] 22 | rand = ["dep:rand"] 23 | 24 | [dev-dependencies] 25 | freelist = "0.1" 26 | lru = "0.13.0" 27 | rayon = "1.5" 28 | glium = "0.30" 29 | rand_derive = "0.5.0" 30 | criterion = { version = "0.5.1", features = ['html_reports'] } 31 | 32 | [[bench]] 33 | name = "iterators" 34 | harness = false 35 | 36 | [[bench]] 37 | name = "freelist" 38 | harness = false 39 | 40 | [[bench]] 41 | name = "coordinates" 42 | harness = false 43 | 44 | [profile.release] 45 | opt-level = 3 46 | overflow-checks = false 47 | debug = 0 48 | strip = "symbols" 49 | debug-assertions = false 50 | lto = "fat" 51 | 52 | 53 | [profile.bench] 54 | debug = 0 55 | lto = "fat" 56 | strip = "symbols" 57 | -------------------------------------------------------------------------------- /doc/node_structure.md: -------------------------------------------------------------------------------- 1 | Each node has array of children, which are indices into the array of nodes. 2 | Chlidren array can contain zeros, which indicate absence of appropriate child. 3 | There is no way to delete the root node. 4 | 5 | Chunks array points towards chunks associated with a given child. The root node (nodes[0]) 6 | never gets a chunk assigned to itself (as it would require special cases in every lookup function). 7 | For all nodes chunks are optional, and may be added and removed at will. 8 | 9 | Benefits of this layout: 10 | * nodes are automatically grouped, so less operations on nodes array are needed to traverse the same depth of tree. 11 | * vast majority of chunks are optional, which means we can store sparse data more efficiently 12 | 13 | In this example we assume QuadVec addressing. Thus, children and chunks are both 4 elements long, 14 | and their encoding matches the offsets defined in appropriate fn get_child(self, index: u32). 15 | 16 | Pos does not need to be stored in nodes array, we keep it here for clarity of example. 17 | 18 | ``` rust 19 | nodes:Vec=vec![ 20 | {pos:(0,0,0),children:[0,1,2,0],chunks:[0,0,0,0]}, 21 | {pos:(0,1,1),children:[0,0,0,0],chunks:[1,0,0,0]}, 22 | {pos:(1,0,1),children:[0,0,0,0],chunks:[0,2,0,0]}, 23 | ]; 24 | 25 | chunks:Vec=vec![ 26 | {node:0, pos:(0,0,0)}, 27 | {node:1, pos:(0,3,2)}, 28 | {node:2, pos:(3,1,2)}, 29 | ]; 30 | ``` 31 | -------------------------------------------------------------------------------- /benches/coordinates.rs: -------------------------------------------------------------------------------- 1 | /* Generic tree structures for storage of spatial data. 2 | * Copyright (C) 2023 Alexander Pyattaev 3 | * 4 | * This program is free software: you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License as published by 6 | * the Free Software Foundation, either version 3 of the License, or 7 | * (at your option) any later version. 8 | * 9 | * This program is distributed in the hope that it will be useful, 10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | * GNU General Public License for more details. 13 | * 14 | * You should have received a copy of the GNU General Public License 15 | * along with this program. If not, see . 16 | */ 17 | 18 | use criterion::{black_box, criterion_group, criterion_main, BenchmarkId, Criterion}; 19 | use rand::rngs::SmallRng; 20 | use rand::{Rng, SeedableRng}; 21 | 22 | use spatialtree::coords::*; 23 | 24 | fn run_eval>(c: &mut Criterion, title: &str) { 25 | let mut group = c.benchmark_group(title); 26 | let mut rng = SmallRng::seed_from_u64(42); 27 | let samples_num = 10; 28 | 29 | for depth in [1, 4].iter() { 30 | group.significance_level(0.1).sample_size(samples_num); 31 | //TODO: more sensible stuff here 32 | group.bench_with_input(BenchmarkId::from_parameter(depth), depth, |b, &_depth| { 33 | b.iter(|| { 34 | let x: FL = FL::root(); 35 | let c = x.get_child(rng.gen_range(0..FL::MAX_CHILDREN)); 36 | let b = x.contains_child_node(c); 37 | let d = c.contains_child_node(x); 38 | black_box(c); 39 | black_box(d); 40 | black_box(b); 41 | }); 42 | }); 43 | } 44 | group.finish(); 45 | } 46 | 47 | pub fn using_u8(c: &mut Criterion) { 48 | run_eval::<2, QuadVec>(c, "coords_quadvec_u8"); 49 | run_eval::<3, OctVec>(c, "coords_octvec_u8"); 50 | } 51 | 52 | pub fn using_u16(c: &mut Criterion) { 53 | run_eval::<2, QuadVec>(c, "coords_quadvec_u16"); 54 | run_eval::<3, OctVec>(c, "coords_octvec_u16"); 55 | } 56 | 57 | criterion_group!(coordinates, using_u8, using_u16); 58 | criterion_main!(coordinates); 59 | -------------------------------------------------------------------------------- /benches/freelist.rs: -------------------------------------------------------------------------------- 1 | /* Generic tree structures for storage of spatial data. 2 | Copyright (C) 2023 Alexander Pyattaev 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with this program. If not, see . 16 | */ 17 | 18 | use criterion::{black_box, criterion_group, criterion_main, BenchmarkId, Criterion}; 19 | use freelist as libfreelist; 20 | use rand::rngs::SmallRng; 21 | use rand::{Rng, SeedableRng}; 22 | 23 | use std::ops::Index; 24 | 25 | use slab::Slab; 26 | 27 | trait FlHarness { 28 | fn new() -> Self; 29 | fn add(&mut self, d: u32) -> usize; 30 | fn erase(&mut self, idx: usize); 31 | fn get_value(&self, index: usize) -> &u32; 32 | } 33 | 34 | impl FlHarness for Slab { 35 | fn new() -> Self { 36 | Slab::with_capacity(4) 37 | } 38 | 39 | fn add(&mut self, d: u32) -> usize { 40 | self.insert(d) 41 | } 42 | 43 | fn erase(&mut self, idx: usize) { 44 | self.remove(idx); 45 | } 46 | 47 | fn get_value(&self, index: usize) -> &u32 { 48 | &self[index] 49 | } 50 | } 51 | 52 | impl FlHarness for libfreelist::FreeList { 53 | fn new() -> Self { 54 | libfreelist::FreeList::new() 55 | } 56 | 57 | fn add(&mut self, d: u32) -> usize { 58 | self.add(d).get() 59 | } 60 | 61 | fn erase(&mut self, idx: usize) { 62 | self.remove(libfreelist::Idx::new(idx).unwrap()) 63 | } 64 | fn get_value(&self, index: usize) -> &u32 { 65 | self.index(libfreelist::Idx::new(index).unwrap()) 66 | } 67 | } 68 | 69 | fn fill_freelist(n: usize, rng: &mut SmallRng) -> FL { 70 | let mut lst = FL::new(); 71 | for _ in 0..n { 72 | let v: u32 = rng.gen_range(0..1024); 73 | lst.add(v); 74 | } 75 | lst 76 | } 77 | 78 | fn freelist_eval(c: &mut Criterion, title: &str) 79 | where 80 | FL: FlHarness, 81 | { 82 | let mut group = c.benchmark_group(title); 83 | let mut rng = SmallRng::seed_from_u64(42); 84 | let samples_num = 10; 85 | 86 | for depth in [25, 50].iter() { 87 | group.significance_level(0.1).sample_size(samples_num); 88 | group.bench_with_input(BenchmarkId::from_parameter(depth), depth, |b, &depth| { 89 | b.iter(|| { 90 | let mut lst: FL = fill_freelist(depth, &mut rng); 91 | let mut x: u32 = 0; 92 | for n in 1..depth { 93 | x += lst.get_value(n); 94 | lst.erase(n); 95 | } 96 | 97 | for n in 0..depth { 98 | lst.add(n as u32); 99 | } 100 | for n in 1..depth { 101 | x += lst.get_value(n); 102 | lst.erase(n); 103 | } 104 | for n in 0..depth { 105 | lst.add(n as u32); 106 | } 107 | black_box(lst); 108 | }); 109 | }); 110 | } 111 | group.finish(); 112 | } 113 | 114 | pub fn freelist(c: &mut Criterion) { 115 | freelist_eval::>(c, "freelist library"); 116 | freelist_eval::>(c, "freelist slab"); 117 | } 118 | 119 | criterion_group!(benches, freelist); 120 | criterion_main!(benches); 121 | -------------------------------------------------------------------------------- /examples/rayon.rs: -------------------------------------------------------------------------------- 1 | /* Generic tree structures for storage of spatial data. 2 | Copyright (C) 2023 Alexander Pyattaev 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with this program. If not, see . 16 | */ 17 | 18 | /*use spatialtree::*; 19 | use rayon::prelude::*; 20 | 21 | struct Chunk { 22 | // data to store in the chunk, for EG storing voxel or heighmap data 23 | // if you don't use editing, storing this data isn't needed, and only storing the mesh would be enough 24 | data: [f32; 4096], // this amount of data actually makes it slower. To see the true octree speed, replace this with [f32; 0] 25 | } 26 | 27 | impl Chunk { 28 | // this does a cheap init so it can safely be put inside the vec 29 | fn new(_position: OctVec) -> Self { 30 | Self { data: [0.0; 4096] } 31 | } 32 | 33 | // pretend this inits the data with some expensive procedural generation 34 | fn expensive_init(&mut self, _position: OctVec) { 35 | self.data = [1.0; 4096]; 36 | 37 | // emulate a 1ms time to do things 38 | // we can't use sleep because thats 15ms on windows min 39 | let start = std::time::Instant::now(); 40 | 41 | while start.elapsed() < std::time::Duration::from_millis(1) {} 42 | } 43 | 44 | // and pretend this makes chunks visible/invisible 45 | fn set_visible(&mut self, _visibility: bool) {} 46 | 47 | // and pretend this drops anything for when a chunk is permanently deleted 48 | fn cleanup(&mut self) {} 49 | } 50 | 51 | fn main() { 52 | // create an octree 53 | let mut tree = OctTree::::with_capacity(512, 512); 54 | 55 | // the game loop that runs for 42 iterations 56 | for _ in 0..42 { 57 | let start_time = std::time::Instant::now(); 58 | 59 | // get the pending updates 60 | if tree.prepare_update( 61 | &[OctVec::new(4096, 4096, 4096, 32)], // target position in the tree 62 | 2, // the amount of detail 63 | &mut |position_in_tree| Chunk::new(position_in_tree), // and how we should make a new tree inside the function here. This should be done quickly 64 | ) { 65 | let duration = start_time.elapsed().as_micros(); 66 | 67 | println!( 68 | "Took {} microseconds to get the tree update ready", 69 | duration 70 | ); 71 | //TODO: rewrite this to use chunks_add callback which modifies captured Vec and pushes chunk references 72 | // in there for thread pool to consume later. 73 | 74 | // if there was an update, we need to first generate new chunks with expensive_init 75 | tree.get_chunks_to_add_slice_mut().par_iter_mut().for_each( 76 | |ToAddContainer { 77 | position, chunk, .. 78 | }| { 79 | // and run expensive init 80 | chunk.expensive_init(*position); 81 | }, 82 | ); 83 | 84 | 85 | let start_time = std::time::Instant::now(); 86 | 87 | // and don't forget to actually run the update 88 | tree.do_update(); 89 | 90 | // now we probably want to truly clean up the chunks that are going to be deleted from memory 91 | for chunk in tree.iter_chunks_to_delete_mut() { 92 | chunk.cleanup(); 93 | } 94 | 95 | // and actually clean them up 96 | tree.complete_update(); 97 | 98 | let duration = start_time.elapsed().as_micros(); 99 | 100 | println!("Took {} microseconds to execute the update", duration); 101 | } 102 | 103 | let duration = start_time.elapsed().as_micros(); 104 | 105 | println!("Took {} microseconds to do the entire update", duration); 106 | 107 | // and print some data about the run 108 | println!("Num chunks in the tree: {}", tree.get_num_chunks()); 109 | } 110 | } 111 | */ 112 | 113 | fn main() {} 114 | -------------------------------------------------------------------------------- /benches/iterators.rs: -------------------------------------------------------------------------------- 1 | /* Generic tree structures for storage of spatial data. 2 | * Copyright (C) 2023 Alexander Pyattaev 3 | * 4 | * This program is free software: you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License as published by 6 | * the Free Software Foundation, either version 3 of the License, or 7 | * (at your option) any later version. 8 | * 9 | * This program is distributed in the hope that it will be useful, 10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | * GNU General Public License for more details. 13 | * 14 | * You should have received a copy of the GNU General Public License 15 | * along with this program. If not, see . 16 | */ 17 | 18 | use criterion::{black_box, criterion_group, criterion_main, BenchmarkId, Criterion}; 19 | 20 | use rand::rngs::SmallRng; 21 | use rand::SeedableRng; 22 | use spatialtree::coords::*; 23 | use spatialtree::*; 24 | 25 | const N_LOOKUPS: usize = 40; 26 | 27 | type DataType = u8; 28 | 29 | fn generate_area_bounds(rng: &mut SmallRng, depth: u8) -> (OctVec, OctVec) { 30 | let cmax = ((1usize << depth as usize) - 1) as DataType; 31 | 32 | let min = rand_cv( 33 | rng, 34 | OctVec::new([0, 0, 0], depth), 35 | OctVec::new([cmax - 2, cmax - 2, cmax - 2], depth), 36 | ); 37 | let max = rand_cv( 38 | rng, 39 | min + OctVec::new([1, 1, 1], depth), 40 | OctVec::new([cmax, cmax, cmax], depth), 41 | ); 42 | 43 | (min, max) 44 | } 45 | 46 | struct ChuChunk { 47 | a_index: u8, 48 | b_index: u8, 49 | material_index: u16, 50 | } 51 | 52 | impl Default for ChuChunk { 53 | fn default() -> ChuChunk { 54 | ChuChunk { 55 | a_index: 1, 56 | b_index: 2, 57 | material_index: 3, 58 | } 59 | } 60 | } 61 | 62 | fn create_and_fill_octree(num_chunks: u32, depth: u8) -> OctTree { 63 | let mut rng = SmallRng::seed_from_u64(42); 64 | let mut tree: OctTree = 65 | OctTree::with_capacity(num_chunks as usize, num_chunks as usize); 66 | 67 | let cmax = ((1usize << depth as usize) - 1) as u8; 68 | 69 | for _c in 0..num_chunks { 70 | let qv: CoordVec<3> = rand_cv( 71 | &mut rng, 72 | OctVec::new([0, 0, 0], depth), 73 | OctVec::new([cmax, cmax, cmax], depth), 74 | ); 75 | tree.insert(qv, |_p| C::default()); 76 | } 77 | tree 78 | } 79 | 80 | fn bench_lookups_in_octree(tree: &OctTree, depth: u8) { 81 | let mut rng = SmallRng::seed_from_u64(42); 82 | for _ in 0..N_LOOKUPS { 83 | let (min, max) = generate_area_bounds(&mut rng, depth); 84 | for i in tree.iter_chunks_in_aabb(min, max) { 85 | black_box(i); 86 | } 87 | } 88 | } 89 | 90 | fn bench_mut_lookups_in_octree(tree: &mut OctTree, depth: u8) { 91 | let mut rng = SmallRng::seed_from_u64(42); 92 | for _ in 0..N_LOOKUPS { 93 | let (min, max) = generate_area_bounds(&mut rng, depth); 94 | for i in tree.iter_chunks_in_aabb_mut(min, max) { 95 | i.1.material_index = i.1.material_index.wrapping_add(1); 96 | i.1.a_index = i.1.a_index.wrapping_add(1); 97 | i.1.b_index = i.1.b_index.wrapping_add(1); 98 | } 99 | } 100 | } 101 | 102 | pub fn tree_iteration(c: &mut Criterion) { 103 | let mut group = c.benchmark_group("mutable iteration"); 104 | 105 | for (&depth, samples_num) in [4u8, 6, 8].iter().zip([100, 40, 10]) { 106 | group.significance_level(0.1).sample_size(samples_num); 107 | 108 | let num_chunks: u32 = 2u32.pow(depth as u32).pow(3) / 10; 109 | group.bench_with_input(BenchmarkId::from_parameter(depth), &depth, |b, &depth| { 110 | let mut tree = create_and_fill_octree::(num_chunks, depth); 111 | b.iter(|| { 112 | bench_mut_lookups_in_octree(&mut tree, depth); 113 | }); 114 | black_box(tree); 115 | }); 116 | } 117 | group.finish(); 118 | 119 | let mut group = c.benchmark_group("immutable iteration"); 120 | 121 | for (&depth, samples_num) in [4u8, 6, 8].iter().zip([100, 40, 10]) { 122 | group.significance_level(0.1).sample_size(samples_num); 123 | let num_chunks: u32 = 2u32.pow(depth as u32).pow(3) / 10; 124 | group.bench_with_input(BenchmarkId::from_parameter(depth), &depth, |b, &depth| { 125 | let tree = create_and_fill_octree::(num_chunks, depth); 126 | b.iter(|| { 127 | bench_lookups_in_octree(&tree, depth); 128 | }); 129 | }); 130 | } 131 | group.finish(); 132 | } 133 | 134 | pub fn tree_creation(c: &mut Criterion) { 135 | let mut group = c.benchmark_group("tree creation"); 136 | 137 | for (&depth, samples_num) in [4u8, 6, 8].iter().zip([100, 40, 10]) { 138 | group.significance_level(0.1).sample_size(samples_num); 139 | group.bench_with_input(BenchmarkId::from_parameter(depth), &depth, |b, &depth| { 140 | let volume = 2u32.pow(depth as u32).pow(3); 141 | let num_chunks: u32 = volume / 10; 142 | //println!("Creating {num_chunks} voxels out of {volume} possible"); 143 | b.iter(|| { 144 | let t = create_and_fill_octree::(num_chunks, depth); 145 | black_box(t); 146 | }); 147 | }); 148 | } 149 | group.finish(); 150 | } 151 | 152 | criterion_group!(benches, tree_creation, tree_iteration); 153 | criterion_main!(benches); 154 | -------------------------------------------------------------------------------- /src/util_funcs.rs: -------------------------------------------------------------------------------- 1 | /* Generic tree structures for storage of spatial data. 2 | * Copyright (C) 2023 Alexander Pyattaev 3 | * 4 | * This program is free software: you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License as published by 6 | * the Free Software Foundation, either version 3 of the License, or 7 | * (at your option) any later version. 8 | * 9 | * This program is distributed in the hope that it will be useful, 10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | * GNU General Public License for more details. 13 | * 14 | * You should have received a copy of the GNU General Public License 15 | * along with this program. If not, see . 16 | */ 17 | 18 | use crate::coords::*; 19 | use std::num::NonZeroU32; 20 | 21 | /// Utility function to cast random structures into arrays of bytes 22 | /// This is mostly for debugging purposes 23 | /// # Safety 24 | /// This is safe since returned slice is readonly (as long as you do not modify thing it is pointing into) 25 | pub unsafe fn any_as_u8_slice(p: &T) -> &[u8] { 26 | ::core::slice::from_raw_parts((p as *const T) as *const u8, ::core::mem::size_of::()) 27 | } 28 | 29 | /// Type for relative pointers to nodes in the tree. Kept 32bit for cache locality during lookups. 30 | /// Should you need > 4 billion nodes in the tree do let me know who sells you the RAM. 31 | pub type NodePtr = Option; 32 | 33 | /// Type for relative pointers to chunks in the tree. Kept 32bit for cache locality during lookups. 34 | /// Encodes "None" variant as -1, and Some(idx) as positive numbers 35 | /// This is not as fast as NonZeroU32, but close enough for our needs 36 | /// Should you need > 2 billion chunks in the tree do let me know who sells you the RAM. 37 | #[derive(PartialEq, Eq, Clone, Copy, Debug)] 38 | pub struct ChunkPtr(i32); 39 | impl core::fmt::Display for ChunkPtr { 40 | #[inline] 41 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 42 | f.write_fmt(format_args!("ChunkPtr({:?})", self.get())) 43 | } 44 | } 45 | 46 | impl ChunkPtr { 47 | #[inline] 48 | pub(crate) fn get(self) -> Option { 49 | match self.0 { 50 | -1 => None, 51 | _ => Some(self.0 as usize), 52 | } 53 | } 54 | 55 | #[inline] 56 | pub(crate) fn take(&mut self) -> Option { 57 | let rv = match self.0 { 58 | -1 => None, 59 | _ => Some(self.0 as usize), 60 | }; 61 | *self = Self::None; 62 | rv 63 | } 64 | 65 | #[inline] 66 | pub(crate) fn from(x: Option) -> Self { 67 | match x { 68 | Some(v) => Self(v as i32), 69 | None => Self::None, 70 | } 71 | } 72 | // Cheat for "compatibility" with option. 73 | #[allow(non_upper_case_globals)] 74 | pub const None: Self = ChunkPtr(-1); 75 | } 76 | 77 | //TODO: impl Try once stable 78 | /*impl std::ops::Try for ChunkPtr{ 79 | * type Output = usize; 80 | * 81 | * type Residual; 82 | * 83 | * fn from_output(output: Self::Output) -> Self { 84 | * todo!() 85 | * } 86 | * 87 | * fn branch(self) -> ControlFlow { 88 | * todo!() 89 | * } 90 | * }*/ 91 | 92 | //TODO - use struct of arrays? 93 | /// Tree node that encompasses multiple children at once. This just barely fits into one cache line for octree. 94 | /// For each possible child, the node has two relative pointers: 95 | /// * children will point to the TreeNode in a given branch direction 96 | /// * chunk will point to the data chunk in a given branch direction 97 | /// 98 | /// both pointers may be "None", indicating either no children, or no data 99 | #[derive(Clone, Debug)] 100 | pub struct TreeNode { 101 | /// children, these can't be the root (index 0), so we can use Some and Nonzero for slightly more compact memory 102 | pub children: [NodePtr; B], 103 | 104 | /// where the chunks for particular children is stored (if any) 105 | pub chunk: [ChunkPtr; B], 106 | } 107 | 108 | impl TreeNode { 109 | #[inline] 110 | pub(crate) fn new() -> Self { 111 | Self { 112 | children: [None; B], 113 | chunk: [ChunkPtr::None; B], 114 | } 115 | } 116 | 117 | #[inline] 118 | pub fn iter_existing_chunks(&self) -> impl Iterator + '_ { 119 | self.chunk.iter().filter_map(|c| c.get()).enumerate() 120 | } 121 | 122 | #[inline] 123 | pub fn is_empty(&self) -> bool { 124 | self.children.iter().all(|c| c.is_none()) && self.chunk.iter().all(|c| *c == ChunkPtr::None) 125 | } 126 | } 127 | 128 | #[inline] 129 | pub fn iter_treenode_children( 130 | children: &[NodePtr; N], 131 | ) -> impl Iterator + '_ { 132 | children 133 | .iter() 134 | .filter_map(|c| Some((*c)?.get() as usize)) 135 | .enumerate() 136 | } 137 | 138 | // utility struct for holding actual chunks and the node that owns them 139 | #[derive(Clone, Debug)] 140 | pub struct ChunkContainer> { 141 | /// actual data inside the chunk 142 | pub chunk: C, 143 | // where the chunk is (as this can not be easily recovered from node tree). 144 | pub(crate) position: L, 145 | // index of the node that holds this chunk. Do not modify unless you know what you are doing! 146 | pub(crate) node_idx: u32, 147 | // index of the child in the node. Do not modify unless you know what you are doing! 148 | pub(crate) child_idx: u8, 149 | } 150 | 151 | impl> ChunkContainer { 152 | /// get an mutable pointer to chunk which is not tied to the lifetime of the container 153 | /// this is only needed for iterators. 154 | #[inline(always)] 155 | pub fn chunk_ptr(&mut self) -> *mut C { 156 | &mut self.chunk as *mut C 157 | } 158 | /// where the chunk is. Modifying this 159 | /// will not move the chunk to a new position, so this is readonly 160 | #[inline(always)] 161 | pub fn position(&self) -> L { 162 | self.position 163 | } 164 | } 165 | 166 | /// utility struct for holding locations in the tree. 167 | #[derive(Clone, Debug, Copy)] 168 | pub struct TreePos> { 169 | /// node or chunk index 170 | pub idx: usize, 171 | /// and it's position 172 | pub pos: L, 173 | } 174 | -------------------------------------------------------------------------------- /examples/glium.rs: -------------------------------------------------------------------------------- 1 | /* Generic tree structures for storage of spatial data. 2 | * Copyright (C) 2023 Alexander Pyattaev 3 | * 4 | * This program is free software: you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License as published by 6 | * the Free Software Foundation, either version 3 of the License, or 7 | * (at your option) any later version. 8 | * 9 | * This program is distributed in the hope that it will be useful, 10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | * GNU General Public License for more details. 13 | * 14 | * You should have received a copy of the GNU General Public License 15 | * along with this program. If not, see . 16 | */ 17 | 18 | use glium::glutin::event_loop::EventLoop; 19 | use glium::index::PrimitiveType; 20 | use glium::{ 21 | glutin, implement_vertex, program, uniform, Display, IndexBuffer, Program, Surface, 22 | VertexBuffer, 23 | }; 24 | 25 | use spatialtree::*; 26 | 27 | // the chunk struct for the tree 28 | #[allow(dead_code)] 29 | struct Chunk { 30 | visible: bool, 31 | cache_state: i32, 32 | // 0 is new, 1 is merged, 2 is cached, 3 is both 33 | selected: bool, 34 | in_bounds: bool, 35 | } 36 | 37 | fn make_shaders(display: &Display) -> Program { 38 | program!(display, 39 | 140 => { 40 | vertex: " 41 | #version 140 42 | 43 | uniform vec2 offset; 44 | uniform float scale; 45 | 46 | in vec2 position; 47 | 48 | void main() { 49 | 50 | vec2 local_position = position * scale + 0.005; 51 | local_position.x = min(local_position.x, scale) - 0.0025; 52 | local_position.y = min(local_position.y, scale) - 0.0025; 53 | 54 | gl_Position = vec4(local_position + (offset + scale * 0.5) * 2.0 - 1.0, 0.0, 1.0); 55 | } 56 | ", 57 | 58 | fragment: " 59 | #version 140 60 | 61 | uniform int state; 62 | uniform int selected; 63 | uniform int in_bounds; 64 | 65 | void main() { 66 | 67 | if (state == 0) gl_FragColor = vec4(0.2, 0.2, 0.2, 1.0); // new, white 68 | if (state == 1) gl_FragColor = vec4(0.0, 0.2, 0.0, 1.0); // merged, green 69 | if (state == 2) gl_FragColor = vec4(0.2, 0.0, 0.0, 1.0); // from cache, red 70 | if (state == 3) gl_FragColor = vec4(0.4, 0.2, 0.0, 1.0); // both, yellow 71 | 72 | if (selected != 0) gl_FragColor = vec4(0.0, 0.2, 0.2, 1.0); // selected, so blue 73 | if (in_bounds != 0) gl_FragColor = vec4(0.0, 0.2, 0.2, 1.0); // in bounds, so purple 74 | 75 | } 76 | " 77 | } 78 | ) 79 | .unwrap() 80 | } 81 | 82 | #[derive(Copy, Clone)] 83 | struct Vertex { 84 | // only need a 2d position 85 | position: [f32; 2], 86 | } 87 | implement_vertex!(Vertex, position); 88 | 89 | struct RenderContext { 90 | display: Display, 91 | vertex_buffer: VertexBuffer, 92 | shaders: Program, 93 | index_buffer: IndexBuffer, 94 | } 95 | 96 | impl RenderContext { 97 | pub fn new(event_loop: &EventLoop<()>) -> Self { 98 | let wb = glutin::window::WindowBuilder::new().with_title("Quadtree demo"); 99 | let cb = glutin::ContextBuilder::new().with_vsync(true); 100 | let display = Display::new(wb, cb, event_loop).unwrap(); 101 | // make a vertex buffer 102 | // we'll reuse it as we only need to draw one quad multiple times anyway 103 | let vertex_buffer = { 104 | VertexBuffer::new( 105 | &display, 106 | &[ 107 | Vertex { 108 | position: [-1.0, -1.0], 109 | }, 110 | Vertex { 111 | position: [-1.0, 1.0], 112 | }, 113 | Vertex { 114 | position: [1.0, -1.0], 115 | }, 116 | Vertex { 117 | position: [1.0, 1.0], 118 | }, 119 | ], 120 | ) 121 | .unwrap() 122 | }; 123 | // and the index buffer to form the triangle 124 | let index_buffer = IndexBuffer::new( 125 | &display, 126 | PrimitiveType::TrianglesList, 127 | &[0_u16, 1, 2, 1, 2, 3], 128 | ) 129 | .unwrap(); 130 | 131 | let shaders = make_shaders(&display); 132 | Self { 133 | display, 134 | vertex_buffer, 135 | index_buffer, 136 | shaders, 137 | } 138 | } 139 | } 140 | 141 | fn draw(mouse_pos: (f32, f32), tree: &mut QuadTree, ctx: &RenderContext) { 142 | //function for adding chunks to their respective position, and also set their properties 143 | fn chunk_creator(_position: QuadVec) -> Chunk { 144 | Chunk { 145 | visible: true, 146 | cache_state: 0, 147 | selected: false, 148 | in_bounds: false, 149 | } 150 | } 151 | 152 | let qv = QuadVec::from_float_coords([mouse_pos.0, (1.0 - mouse_pos.1)], 6); 153 | tree.lod_update(&[qv], 2, chunk_creator, |_, _| {}); 154 | // make sure there are no holes in chunks array for fast iteration 155 | tree.defragment_chunks(); 156 | // and select the chunk at the mouse position 157 | if let Some(chunk) = tree.get_chunk_by_position_mut(qv) { 158 | chunk.selected = true; 159 | } 160 | 161 | // and select a number of chunks in a region when the mouse buttons are selected 162 | 163 | // and, Redraw! 164 | let mut target = ctx.display.draw(); 165 | target.clear_color(0.6, 0.6, 0.6, 1.0); 166 | 167 | // go over all chunks, iterator version 168 | for (_, container) in tree.iter_chunks() { 169 | let (chunk, position) = (&container.chunk, container.position()); 170 | if chunk.visible { 171 | // draw it if it's visible 172 | // here we get the chunk position and size 173 | let uniforms = uniform! { 174 | offset: position.float_coords(), 175 | scale: position.float_size(), 176 | state: chunk.cache_state, 177 | selected: chunk.selected as i32, 178 | }; 179 | 180 | // draw it with glium 181 | target 182 | .draw( 183 | &ctx.vertex_buffer, 184 | &ctx.index_buffer, 185 | &ctx.shaders, 186 | &uniforms, 187 | &Default::default(), 188 | ) 189 | .unwrap(); 190 | } 191 | } 192 | target.finish().unwrap(); 193 | 194 | // deselect the chunk at the mouse position 195 | if let Some(chunk) = tree.get_chunk_by_position_mut(qv) { 196 | chunk.selected = false; 197 | } 198 | } 199 | 200 | fn main() { 201 | // set up the tree 202 | let mut tree = QuadTree::::with_capacity(32, 32); 203 | // start the glium event loop 204 | let event_loop = glutin::event_loop::EventLoop::new(); 205 | let context = RenderContext::new(&event_loop); 206 | draw((0.5, 0.5), &mut tree, &context); 207 | 208 | // the mouse cursor position 209 | let mut mouse_pos = (0.5, 0.5); 210 | 211 | // last time redraw was done 212 | let mut last_redraw = std::time::Instant::now(); 213 | 214 | // run the main loop 215 | event_loop.run(move |event, _, control_flow| { 216 | *control_flow = match event { 217 | glutin::event::Event::RedrawRequested(_) => { 218 | // and draw, if enough time elapses 219 | if last_redraw.elapsed().as_millis() > 16 { 220 | draw(mouse_pos, &mut tree, &context); 221 | last_redraw = std::time::Instant::now(); 222 | } 223 | 224 | glutin::event_loop::ControlFlow::Wait 225 | } 226 | glutin::event::Event::WindowEvent { event, .. } => match event { 227 | // stop if the window is closed 228 | glutin::event::WindowEvent::CloseRequested => glutin::event_loop::ControlFlow::Exit, 229 | glutin::event::WindowEvent::CursorMoved { position, .. } => { 230 | // get the mouse position 231 | mouse_pos = ( 232 | position.x as f32 / context.display.get_framebuffer_dimensions().0 as f32, 233 | position.y as f32 / context.display.get_framebuffer_dimensions().1 as f32, 234 | ); 235 | 236 | // request a redraw 237 | context.display.gl_window().window().request_redraw(); 238 | 239 | glutin::event_loop::ControlFlow::Wait 240 | } 241 | _ => glutin::event_loop::ControlFlow::Wait, 242 | }, 243 | _ => glutin::event_loop::ControlFlow::Wait, 244 | } 245 | }); 246 | } 247 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Crates.io](https://img.shields.io/crates/v/spatialtree)](https://crates.io/crates/spatialtree) 2 | [![Documentation](https://docs.rs/spatialtree/badge.svg)](https://docs.rs/spatialtree) 3 | 4 | # Spatial trees 5 | Spatial trees, (aka QuadTrees, OctTrees, LodTrees) are a family of fast tree data structures that supports complex spatial queries at various level of detail. They are particularly well suited for sparse data storage and neighbor queries. 6 | 7 | ## Acknowledgements 8 | Internals are partially based on: 9 | * 10 | * 11 | 12 | 13 | ## Goals 14 | The aim of this crate is to provide a generic, easy to use tree data structure that can be used to make Quadtrees, Octrees for various realtime applications (e.g. games or GIS software). 15 | 16 | Internally, the tree tries to keep all needed memory allocated in slab arenas to avoid the memory fragmentation and allocator pressure. All operations, where possible, use either stack allocations or allocate at most once. 17 | 18 | 19 | ## Features 20 | - Highly tunable for different scales (from 8 bit to 64 bit coordinates), 2D, 3D, N-D if desired. 21 | - Minimized memory (re)allocations and moves 22 | - Provides a selection iterators for finding chunks in certain bounds 23 | - Supports online defragmentation for data chunks to optimize sequential operations on all chunks 24 | - External chunk cache can be used to allow reusing chunks at a memory tradeoff 25 | 26 | ## Accepted design compromises 27 | 28 | - Data chunks that are nearby in space do not necessarily land in nearby locations in the tree's memory. 29 | - There is no way to defragment node storage memory short of rebuilding the tree from scratch (which means doubling memory usage) 30 | - Like any tree, this will become less efficient with depth. Consider using at most 8 levels of depth, and stitching larger areas with a [spatial hash](https://crates.io/crates/spatial_hash_3d). 31 | 32 | 33 | ### Examples: 34 | - [rayon](examples/rayon.rs): shows how to use the tree with rayon to generate new chunks in parallel, and cache chunks already made. 35 | - [glium](examples/glium.rs): shows how a basic drawing setup would work, with glium to do the drawing. 36 | 37 | ## Usage: 38 | Import the crate 39 | ```rust 40 | use spatialtree::*; 41 | ``` 42 | 43 | The tree is it's own struct, and accepts a chunk (anything that implements Sized) and the coordinate vector (Anything that implements the LodVec trait). 44 | ```rust 45 | # use spatialtree::*; 46 | struct Chunk { 47 | //important useful fileds go here 48 | } 49 | // a new OctTree with no capacity 50 | let mut tree = OctTree::::new(); 51 | // a new OctTree with 32 slots for nodes and 64 slots for data chunks 52 | let mut tree = QuadTree::::with_capacity(32, 64); 53 | ``` 54 | 55 | The given LodVec implementations (OctVec and QuadVec) take in 4 and 3 arguments respectively. 56 | The first 3/2 are the position in the tree, which is dependant on the lod level. 57 | and the last parameter is the lod level. No lods smaller than this will be generated for this target. 58 | 59 | ```rust 60 | # use spatialtree::*; 61 | // QuadVec takes x,y and depth 62 | let qv1 = QuadVec::build(1u8, 2, 3); 63 | let qv2 = QuadVec::new([1u8, 2], 3); 64 | assert_eq!(qv1, qv2); 65 | // OctVec takes x,y,z and depth 66 | let ov1 = OctVec::build(1u8, 2, 3, 3); 67 | let ov2 = OctVec::new([1u8, 2, 3], 3); 68 | assert_eq!(ov1, ov2); 69 | ``` 70 | 71 | 72 | Inserts are most efficient when performed in large batches, as this minimizes tree traverse overhead. 73 | ```rust 74 | # use spatialtree::*; 75 | # struct Chunk {} 76 | // create a tree 77 | let mut tree = QuadTree::::with_capacity(32, 64); 78 | // create a few targets 79 | let targets = [ 80 | QuadVec::build(1u8, 1, 3), 81 | QuadVec::build(2, 2, 3), 82 | QuadVec::build(3, 3, 3), 83 | ]; 84 | // ask tree to populate given positions, calling a function to construct new data as needed. 85 | tree.insert_many(targets.iter().copied(), |_| Chunk {}); 86 | ``` 87 | 88 | Alternatively, if you want to insert data one chunk at a time: 89 | ```rust 90 | # use spatialtree::*; 91 | // create a tree with usize as data 92 | let mut tree = QuadTree::::with_capacity(32, 64); 93 | // insert/replace a chunk at selected location, provided lambda builds the content 94 | // we get chunk index back 95 | let idx = tree.insert(QuadVec::new([1u8,2], 3), |p| {p.pos.iter().sum::() as usize} ); 96 | // we can access chunks by index (in this case to make sure insert worked ok) 97 | assert_eq!(tree.get_chunk(idx).chunk, 3); 98 | ``` 99 | 100 | Lookups in the tree can be efficiently done over a wide area using an axis-aligned bounding box (AABB) to select the desired region as follows: 101 | ```rust 102 | # use spatialtree::*; 103 | let mut tree = OctTree::::new(); 104 | let min = OctVec::new([0u8, 0, 0], 3); 105 | let max = OctVec::new([7u8, 7, 7], 3); 106 | 107 | // create iterator over all possible positions in the tree 108 | let pos_iter = iter_all_positions_in_bounds(min, max); 109 | // fill tree with important data 110 | tree.insert_many(pos_iter, |_| 42 ); 111 | // iterateing over data in AABB yields both positions and associated data chunks 112 | // only populated positions are yielded, empty ones are quietly skipped. 113 | for (pos, data) in tree.iter_chunks_in_aabb(min, max) { 114 | dbg!(pos, data); 115 | } 116 | ``` 117 | Selecting chunks this way will never traverse deeper than the deepest chunk in the AABB limits provided. Both limits should have the same depth. 118 | 119 | ## Advanced usage 120 | This structure can be used for purposes such as progressive LOD. 121 | 122 | If you want to update chunks due to the camera being moved, you can do so with lod_update. 123 | It takes in 3 parameters. 124 | 125 | Targets: is the array of locations around which to generate the most detail. 126 | 127 | Detail: The amount of detail for the targets. 128 | The default implementation defines this as the amount of chunks at the target lod level surrounding the target chunk. 129 | 130 | chunk_creator: the function to call when new chunk is needed 131 | evict_callback: function to call when chunk is evicted from data structure 132 | 133 | The purpose of evict_callback is to enable things such as caching, object reuse etc. If this is done it may be wise 134 | to keep chunks fairly small such that moving them between tree and cache is not too expensive. 135 | 136 | ```rust 137 | # use spatialtree::*; 138 | # use std::collections::HashMap; 139 | # use std::cell::RefCell; 140 | # use std::borrow::BorrowMut; 141 | // Tree with "active" data 142 | let mut tree = QuadTree::, QuadVec>::with_capacity(32, 64); 143 | // Cache for "inactive" data 144 | let mut cache: RefCell>> = RefCell::new(HashMap::new()); 145 | # fn expensive_init(c:QuadVec, d:&mut Vec){ } 146 | 147 | //function to populate new chunks. Will read from cache if possible 148 | let mut chunk_creator = |c:QuadVec|->Vec { 149 | match cache.borrow_mut().remove(&c){ 150 | Some(d)=>d, 151 | None => { 152 | let mut d = Vec::new(); 153 | // run whatever mystery function may be needed to populate new chunk with reasonable data 154 | expensive_init(c, &mut d); 155 | d 156 | } 157 | } 158 | }; 159 | 160 | //Function to deal with evicted chunks. Will move them to cache. 161 | let mut chunk_evict = |c:QuadVec, d:Vec|{ 162 | println!("Chunk {d:?} at position {c:?} evicted"); 163 | cache.borrow_mut().insert(c,d); 164 | }; 165 | 166 | // construct vector pointing to location that we want to detail 167 | let qv = QuadVec::from_float_coords([1.1, 2.4], 6); 168 | // run the actual update rebuilding the tree 169 | tree.lod_update(&[qv], 2, chunk_creator, chunk_evict); 170 | ``` 171 | Internally, lod_update will rebuild the tree to match needed node structure that reflects locations of all targets. 172 | Thus, defragment_nodes is never needed after lod_update. You may want to defragment_chunks if you are going to iterate over them. 173 | 174 | ### Optimize memory layout 175 | 176 | For best performance, memory compactness, you may wish to ensure that chunks are stored in a 177 | contigous array. While tree will try to ensure this at all times, it will not move data it does not 178 | have to, unless explicitly instructed to do so. Thus, after multiple deletions it may be necessary to 179 | defragment the storage. 180 | 181 | ```rust 182 | # use spatialtree::*; 183 | # let mut tree = QuadTree::::with_capacity(32, 64); 184 | 185 | // make sure there are no holes in chunks array for fast iteration 186 | tree.defragment_chunks(); 187 | ``` 188 | Note that defragment_chunks will not do anything if chunks array has no holes already, so it is safe to call it every time 189 | you suspect you might need to. 190 | 191 | Similarly, nodes storage can be rebuilt and defragmented, though this is a substantially more costly operation, and needs to allocate 192 | memory. Thus, call this only when you have strong reasons (i.e. benchmarks) to do so. 193 | ```rust 194 | # use spatialtree::*; 195 | # let mut tree = QuadTree::::with_capacity(32, 64); 196 | 197 | // make sure there are no holes in nodes array for fast iteration 198 | tree.defragment_nodes(); 199 | ``` 200 | 201 | Once structures are defragmented, any memory that was freed can be reclaimed with 202 | ```rust 203 | # use spatialtree::*; 204 | # let mut tree = QuadTree::::with_capacity(32, 64); 205 | 206 | tree.shrink_to_fit(); 207 | ``` 208 | 209 | 210 | ## Roadmap 211 | ### 0.2.0: 212 | - There is no way to prune nodes (yet). They do not eat much RAM, but it may become a problem. 213 | - Organize benchmarks better 214 | 215 | ### 0.3.0: 216 | - Swap L and C, so the key (position) is before the chunk, which is consistent with other key-value datatypes in rust 217 | - Use generic const expressions to improve templating 218 | 219 | 220 | ## License 221 | Licensed under either 222 | * GPL, Version 3.0 223 | ([LICENSE.txt](LICENSE.txt) ) 224 | * Proprietary license for commercial use (contact author to arrange licensing) 225 | 226 | 227 | ## Contribution 228 | Unless you explicitly state otherwise, any contribution intentionally submitted 229 | for inclusion in the work by you, shall be licensed as above, without any additional terms or conditions. 230 | -------------------------------------------------------------------------------- /src/coords.rs: -------------------------------------------------------------------------------- 1 | /* Generic tree structures for storage of spatial data. 2 | Copyright (C) 2023 Alexander Pyattaev 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with this program. If not, see . 16 | */ 17 | 18 | //! Contains coordinate structs, QuadVec for quadtrees, and OctVec for octrees, as well as their LodVec implementation 19 | 20 | use std::cmp::Ordering; 21 | 22 | pub const MAX_DEPTH: u8 = 60; 23 | 24 | /// External interface into coordinates used by the Tree implementations. 25 | pub trait LodVec: 26 | std::hash::Hash + Eq + Sized + Copy + Clone + Send + Sync + std::fmt::Debug + PartialOrd 27 | { 28 | const MAX_CHILDREN: usize = 1 << N; 29 | 30 | /// gets one of the child node position of this node, defined by it's index. 31 | fn get_child(self, index: usize) -> Self; 32 | 33 | /// returns index of child for a given child position (reciprocal of get_child) 34 | fn get_child_index(self, child: Self) -> usize; 35 | 36 | /// tests if given node is a child of self. 37 | fn contains_child_node(self, child: Self) -> bool; 38 | 39 | /// returns the lod vector as if it's at the root of the tree. 40 | fn root() -> Self; 41 | 42 | /// wether a target with this position can subdivide a given node, allowing for required "detail" region. 43 | /// 44 | /// Assumes self is the target position for a lod. 45 | /// 46 | /// self.depth determines the max lod level allowed, detail determines the amount of chunks around the target. 47 | /// 48 | /// if the detail is 0, this may only return true if self is inside the node. 49 | /// 50 | fn can_subdivide(self, node: Self, detail: u32) -> bool; 51 | 52 | /// check if this chunk is inside of a bounding box 53 | /// where min is the lowest corner of the box, and max is the highest corner 54 | /// max_depth controls the depth at which the BB checking is done. 55 | fn is_inside_bounds(self, min: Self, max: Self, max_depth: u8) -> bool; 56 | 57 | /// Retrieve current depth 58 | fn depth(self) -> u8; 59 | } 60 | 61 | /// Trait for data types suitable for use in CoordVec. 62 | /// Implemented for builtin unsigned integers, implement for other types 63 | /// at your own risk! 64 | pub trait ReasonableIntegerLike: 65 | Default 66 | + Copy 67 | + core::cmp::Eq 68 | + core::cmp::Ord 69 | + std::marker::Send 70 | + std::marker::Sync 71 | + std::fmt::Debug 72 | + std::hash::Hash 73 | { 74 | fn fromusize(value: usize) -> Self; 75 | fn tousize(self) -> usize; 76 | } 77 | 78 | #[macro_export] 79 | macro_rules! reasonable_int_impl { 80 | ( $x:ty ) => { 81 | impl ReasonableIntegerLike for $x { 82 | #[inline(always)] 83 | fn fromusize(value: usize) -> Self { 84 | value as $x 85 | } 86 | #[inline(always)] 87 | fn tousize(self) -> usize { 88 | self as usize 89 | } 90 | } 91 | }; 92 | } 93 | 94 | reasonable_int_impl!(u8); 95 | reasonable_int_impl!(u16); 96 | reasonable_int_impl!(u32); 97 | reasonable_int_impl!(u64); 98 | 99 | /// "Default" data structure for use as coordinate vector in a tree. 100 | #[derive(Debug, Copy, Clone, PartialEq, Eq, std::hash::Hash)] 101 | pub struct CoordVec 102 | where 103 | DT: ReasonableIntegerLike, 104 | { 105 | pub pos: [DT; N], 106 | pub depth: u8, 107 | } 108 | 109 | impl CoordVec 110 | where 111 | DT: ReasonableIntegerLike, 112 | { 113 | /// creates a new coordinate vector from components 114 | /// # Args 115 | /// * `coord` The position in the tree. Allowed range scales with the depth (doubles as the depth increases by one) 116 | /// * `depth` the depth the coord is at. This is hard limited at 60 to preserve sanity. 117 | #[inline(always)] 118 | pub fn new(pos: [DT; N], depth: u8) -> Self { 119 | debug_assert!(depth <= MAX_DEPTH); 120 | debug_assert!( 121 | pos.iter().all(|e| { e.tousize() < (1 << depth) }), 122 | "All components of position should be < 2^depth" 123 | ); 124 | 125 | Self { pos, depth } 126 | } 127 | 128 | /// creates a new vector from floating point coords. 129 | /// mapped so that e.g. (0, 0, 0) is the front bottom left corner and (1, 1, 1) is the back top right. 130 | /// # Args 131 | /// * `pos` coordinates of the float vector, from 0 to 1 132 | /// * `depth` The lod depth of the coord 133 | #[inline(always)] 134 | pub fn from_float_coords(pos: [f32; N], depth: u8) -> Self { 135 | // scaling factor due to the lod depth 136 | let scale_factor = (1 << depth) as f32; 137 | 138 | // and get the actual coord 139 | Self { 140 | pos: pos.map(|e| DT::fromusize((e * scale_factor) as usize)), 141 | depth, 142 | } 143 | } 144 | 145 | /// converts the coord into float coords. 146 | /// Returns a slice of f32 to represent the coordinates, at the front bottom left corner. 147 | #[inline(always)] 148 | pub fn float_coords(self) -> [f32; N] { 149 | // scaling factor to scale the coords down with 150 | let scale_factor = 1.0 / (1 << self.depth) as f32; 151 | self.pos.map(|e| e.tousize() as f32 * scale_factor) 152 | } 153 | 154 | /// gets the size the chunk of this lod vector takes up, with the root taking up the entire area. 155 | #[inline(always)] 156 | pub fn float_size(self) -> f32 { 157 | 1.0 / (1 << self.depth) as f32 158 | } 159 | } 160 | 161 | impl LodVec for CoordVec 162 | where 163 | DT: ReasonableIntegerLike, 164 | { 165 | #[inline(always)] 166 | fn root() -> Self { 167 | Self { 168 | pos: [DT::default(); N], 169 | depth: 0, 170 | } 171 | } 172 | #[inline(always)] 173 | fn depth(self) -> u8 { 174 | self.depth 175 | } 176 | 177 | #[inline(always)] 178 | fn get_child(self, index: usize) -> Self { 179 | debug_assert!(index < as LodVec>::MAX_CHILDREN); 180 | let mut new = Self::root(); 181 | //println!("GetChild for {:?} idx {}", self,index); 182 | for i in 0..N { 183 | let p_doubled = self.pos[i].tousize() << 1; 184 | 185 | let p = p_doubled + ((index & (1 << i)) >> i); 186 | //dbg!(i, p_doubled, p); 187 | new.pos[i] = DT::fromusize(p); 188 | } 189 | new.depth = self.depth + 1; 190 | debug_assert!(new.depth < MAX_DEPTH); 191 | new 192 | } 193 | #[inline] 194 | fn get_child_index(self, child: Self) -> usize { 195 | debug_assert!(self.depth < child.depth); 196 | let level_difference = child.depth - self.depth; 197 | //let one = DT::fromusize(1 as usize); 198 | let mut idx: usize = 0; 199 | for i in 0..N { 200 | //scale up own base pos 201 | let sp = self.pos[i].tousize() << level_difference; 202 | let pi = (child.pos[i].tousize() - sp) >> (level_difference - 1); 203 | //dbg!(i, sp, pi); 204 | idx |= pi << i; 205 | } 206 | idx 207 | } 208 | #[inline] 209 | fn contains_child_node(self, child: Self) -> bool { 210 | if self.depth >= child.depth { 211 | return false; 212 | } 213 | // basically, move the child node up to this level and check if they're equal 214 | let level_difference = child.depth as isize - self.depth as isize; 215 | 216 | self.pos 217 | .iter() 218 | .zip(child.pos) 219 | .all(|(s, c)| s.tousize() == (c.tousize() >> level_difference)) 220 | } 221 | #[inline(always)] 222 | fn is_inside_bounds(self, min: Self, max: Self, max_depth: u8) -> bool { 223 | // get the lowest lod level 224 | let level = *[self.depth, min.depth, max.depth] 225 | .iter() 226 | .min() 227 | .expect("Starting array not empty") as isize; 228 | //dbg!(level); 229 | // bring all coords to the lowest level 230 | let self_difference: isize = self.depth as isize - level; 231 | let min_difference: isize = min.depth as isize - level; 232 | let max_difference: isize = max.depth as isize - level; 233 | //println!("diff {:?}, {:?}, {:?}", self_difference, min_difference, max_difference); 234 | // get the coords to that level 235 | 236 | let self_lowered = self.pos.iter().map(|e| e.tousize() >> self_difference); 237 | let min_lowered = min.pos.iter().map(|e| e.tousize() >> min_difference); 238 | let max_lowered = max.pos.iter().map(|e| e.tousize() >> max_difference); 239 | //println!("lowered {self_lowered:?}, {min_lowered:?}, {max_lowered:?}"); 240 | // then check if we are inside the AABB 241 | self.depth <= max_depth 242 | && self_lowered 243 | .zip(min_lowered.zip(max_lowered)) 244 | .all(|(slf, (min, max))| slf >= min && slf <= max) 245 | } 246 | 247 | #[inline(always)] 248 | fn can_subdivide(self, node: Self, detail: u32) -> bool { 249 | let detail = detail as usize; 250 | // return early if the level of this chunk is too high 251 | if node.depth >= self.depth { 252 | return false; 253 | } 254 | 255 | // difference in lod level between the target and the node 256 | let level_difference = self.depth - node.depth; 257 | 258 | // size of bounding box 259 | let bb_size = (detail + 1) << level_difference; 260 | let offset = 1 << level_difference; 261 | 262 | // minimum corner of the bounding box 263 | let min = node.pos.iter().map(|e| { 264 | let x = e.tousize(); 265 | (x << (level_difference + 1)).saturating_sub(bb_size - offset) 266 | }); 267 | 268 | // maximum corner of the bounding box 269 | let max = node.pos.iter().map(|e| { 270 | let x = e.tousize(); 271 | (x << (level_difference + 1)).saturating_add(bb_size + offset) 272 | }); 273 | 274 | // iterator over bounding boxes 275 | let minmax = min.zip(max); 276 | 277 | // local position of the target, moved one lod level higher to allow more detail 278 | let local = self.pos.iter().map(|e| e.tousize() << 1); 279 | //println!("Check tgt {self:?} wrt {node:?}"); 280 | // check if the target is inside of the bounding box 281 | local.zip(minmax).all(|(c, (min, max))| { 282 | // println!("{min:?} <= {c:?} < {max:?}"); 283 | min <= c && c < max 284 | }) 285 | } 286 | } 287 | 288 | pub type OctVec
= CoordVec<3, DT>; 289 | pub type QuadVec
= CoordVec<2, DT>; 290 | 291 | impl
OctVec
292 | where 293 | DT: ReasonableIntegerLike, 294 | { 295 | #[inline(always)] 296 | pub fn build(x: DT, y: DT, z: DT, depth: u8) -> Self { 297 | Self::new([x, y, z], depth) 298 | } 299 | } 300 | 301 | impl
QuadVec
302 | where 303 | DT: ReasonableIntegerLike, 304 | { 305 | #[inline(always)] 306 | pub fn build(x: DT, y: DT, depth: u8) -> Self { 307 | Self::new([x, y], depth) 308 | } 309 | } 310 | 311 | impl PartialOrd for CoordVec 312 | where 313 | DT: ReasonableIntegerLike, 314 | { 315 | #[inline] 316 | fn partial_cmp(&self, other: &Self) -> Option { 317 | if self.depth != other.depth { 318 | return None; 319 | } 320 | 321 | if self.pos == other.pos { 322 | return Some(Ordering::Equal); 323 | } 324 | 325 | if self.pos.iter().zip(other.pos).all(|(s, o)| *s < o) { 326 | return Some(Ordering::Less); 327 | } else if self.pos.iter().zip(other.pos).all(|(s, o)| *s > o) { 328 | return Some(Ordering::Greater); 329 | } 330 | None 331 | } 332 | } 333 | 334 | impl std::ops::Add for CoordVec 335 | where 336 | DT: ReasonableIntegerLike + std::ops::AddAssign, 337 | { 338 | type Output = Self; 339 | #[inline] 340 | fn add(self, rhs: Self) -> Self::Output { 341 | debug_assert_eq!(self.depth, rhs.depth); 342 | let mut res = self; 343 | for (e1, e2) in res.pos.iter_mut().zip(rhs.pos) { 344 | *e1 += e2; 345 | } 346 | res 347 | } 348 | } 349 | 350 | impl Default for CoordVec 351 | where 352 | DT: ReasonableIntegerLike, 353 | { 354 | #[inline] 355 | fn default() -> Self { 356 | Self::root() 357 | } 358 | } 359 | 360 | #[inline] 361 | pub fn get_chunk_count_at_max_depth(a: CoordVec, b: CoordVec) -> usize { 362 | assert_eq!(a.depth, b.depth); 363 | b.pos 364 | .iter() 365 | .zip(a.pos) 366 | .fold(1, |acc, (e1, e2)| acc * (e1 - e2 + 1) as usize) 367 | } 368 | 369 | #[cfg(feature = "rand")] 370 | #[inline] 371 | pub fn rand_cv( 372 | rng: &mut R, 373 | min: CoordVec, 374 | max: CoordVec, 375 | ) -> CoordVec 376 | where 377 | T: ReasonableIntegerLike + rand::distr::uniform::SampleUniform, 378 | { 379 | debug_assert_eq!(min.depth, max.depth); 380 | let mut zz = [T::fromusize(0); N]; 381 | #[allow(clippy::needless_range_loop)] 382 | for i in 0..N { 383 | zz[i] = rng.random_range(min.pos[i]..max.pos[i]); 384 | } 385 | CoordVec::new(zz, min.depth) 386 | } 387 | 388 | #[cfg(test)] 389 | mod tests { 390 | use crate::coords::*; 391 | use std::mem::size_of; 392 | 393 | #[test] 394 | fn sizes() { 395 | assert_eq!(3, size_of::()); 396 | assert_eq!(4, size_of::()); 397 | } 398 | #[test] 399 | fn find_child_idx() { 400 | // create root 401 | let z = OctVec::::root(); 402 | // loop over possible children 403 | for i in 0..OctVec::::MAX_CHILDREN { 404 | // get child of z with index i 405 | let c = z.get_child(i); 406 | // recover its index based on coords 407 | let ci = z.get_child_index(c); 408 | // make sure they are identical 409 | assert_eq!(ci, i); 410 | 411 | for j in 0..OctVec::::MAX_CHILDREN { 412 | // get child of c 413 | let cc = c.get_child(j); 414 | // and its index 415 | let cci = c.get_child_index(cc); 416 | println!("{}->{} ({}->{}): {:?}->{:?} ", i, j, ci, cci, c, cc); 417 | assert_eq!(cci, j); 418 | // we can also get index w.r.t. previous levels 419 | let czi = z.get_child_index(cc); 420 | assert_eq!(czi, i); 421 | // and we can go deeper too... 422 | for k in 0..OctVec::::MAX_CHILDREN { 423 | let ccc = cc.get_child(k); 424 | assert_eq!(z.get_child_index(ccc), i); 425 | assert_eq!(c.get_child_index(ccc), j); 426 | assert_eq!(cc.get_child_index(ccc), k); 427 | } 428 | } 429 | } 430 | } 431 | 432 | #[test] 433 | fn can_subdivide() { 434 | let z: QuadVec = QuadVec::root(); 435 | let c1 = z.get_child(0); 436 | let c12 = c1.get_child(0); 437 | let tgt = QuadVec::build(0, 0, 2); 438 | 439 | println!("{tgt:?}, {c12:?}, {}", tgt.can_subdivide(c12, 3)); 440 | println!("{tgt:?}, {c1:?}, {}", tgt.can_subdivide(c1, 3)); 441 | } 442 | } 443 | -------------------------------------------------------------------------------- /src/iter.rs: -------------------------------------------------------------------------------- 1 | /* Generic tree structures for storage of spatial data. 2 | Copyright (C) 2023 Alexander Pyattaev 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with this program. If not, see . 16 | */ 17 | 18 | //! Iterators over tree data and over coordinates 19 | use crate::coords::*; 20 | use crate::tree::*; 21 | use crate::util_funcs::*; 22 | 23 | /// iterator for all coordinates that are inside given bounds 24 | pub struct CoordsInBoundsIter> { 25 | // internal stack for which coordinates are next 26 | stack: Vec, 27 | 28 | // and maximum depth to go to 29 | max_depth: u8, 30 | 31 | // and the min of the bound 32 | bound_min: L, 33 | 34 | // and max of the bound 35 | bound_max: L, 36 | } 37 | 38 | impl> CoordsInBoundsIter { 39 | /// Returns the amount of heap allocation to run this iterator. 40 | #[inline] 41 | pub fn stack_size(cv: L) -> usize { 42 | (cv.depth() as usize * L::MAX_CHILDREN) - (cv.depth() as usize - 1) 43 | } 44 | } 45 | 46 | impl> Iterator for CoordsInBoundsIter { 47 | type Item = L; 48 | 49 | #[inline] 50 | fn next(&mut self) -> Option { 51 | let current = self.stack.pop()?; 52 | if current.depth() != self.max_depth { 53 | // go over all child nodes 54 | for i in 0..L::MAX_CHILDREN { 55 | let position = current.get_child(i); 56 | // if they are in bounds, add them to the stack 57 | if position.is_inside_bounds(self.bound_min, self.bound_max, self.max_depth) { 58 | //We really do not want this to EVER allocate... 59 | debug_assert_ne!(self.stack.capacity(), self.stack.len()); 60 | self.stack.push(position); 61 | } 62 | } 63 | } 64 | // and return this item from the stack 65 | Some(current) 66 | } 67 | } 68 | 69 | ///Iterator over positions and indices of chunks in a given AABB. 70 | pub struct ChunkIdxInAABBIter<'a, const N: usize, const B: usize, L> 71 | where 72 | L: LodVec, 73 | { 74 | /// the reference to tree's nodes 75 | nodes: &'a NodeStorage, 76 | 77 | /// internal stack for tree traverse 78 | to_visit: Vec>, 79 | 80 | /// index of child to return 81 | to_return: arrayvec::ArrayVec, B>, 82 | /// and maximum depth to go to 83 | max_depth: u8, 84 | 85 | /// the min of the bound box 86 | bound_min: L, 87 | 88 | /// max of the bound box 89 | bound_max: L, 90 | 91 | #[cfg(test)] 92 | pub max_stack: usize, 93 | } 94 | 95 | impl<'a, const N: usize, const B: usize, L> ChunkIdxInAABBIter<'a, N, B, L> 96 | where 97 | L: LodVec, 98 | { 99 | pub fn new(nodes: &'a NodeStorage, bound_min: L, bound_max: L) -> Self { 100 | debug_assert_eq!(bound_min.depth(), bound_max.depth()); 101 | 102 | // TODO: Smallvec? 103 | let mut to_visit = Vec::with_capacity(Self::stack_size(bound_min)); 104 | 105 | to_visit.push(TreePos { 106 | idx: 0, 107 | pos: L::root(), 108 | }); 109 | 110 | ChunkIdxInAABBIter { 111 | to_visit, 112 | to_return: arrayvec::ArrayVec::new(), 113 | nodes, 114 | max_depth: bound_min.depth(), 115 | bound_min, 116 | bound_max, 117 | #[cfg(test)] 118 | max_stack: 1, 119 | } 120 | } 121 | #[inline] 122 | pub fn stack_size(cv: L) -> usize { 123 | (cv.depth().saturating_sub(1) as usize) * (L::MAX_CHILDREN - 1) + 1 124 | } 125 | } 126 | 127 | impl Iterator for ChunkIdxInAABBIter<'_, N, B, L> 128 | where 129 | L: LodVec, 130 | { 131 | type Item = TreePos; 132 | 133 | #[inline] 134 | fn next(&mut self) -> Option { 135 | // if we have nothing in to_return stack, traverse the tree. 136 | while self.to_return.is_empty() { 137 | // try to traverse more nodes, if nothing to traverse we are done 138 | let current = self.to_visit.pop()?; 139 | // dbg!(current); 140 | //if we are allowed to dive deeper, do so 141 | if current.pos.depth() != self.max_depth { 142 | let cur_node = &self.nodes[current.idx]; 143 | // go over all child nodes 144 | for i in 0..L::MAX_CHILDREN { 145 | let child_position = current.pos.get_child(i); 146 | 147 | if !child_position.is_inside_bounds( 148 | self.bound_min, 149 | self.bound_max, 150 | self.max_depth, 151 | ) { 152 | //dbg!(self.bound_min,self.bound_max); 153 | //println!("Tried child {i} pos {child_position:?} got OOB!"); 154 | continue; 155 | } 156 | //println!("Use child {i} pos {child_position:?}"); 157 | // if child is present at given location add it to the visit list 158 | //dbg!(cur_node.children); 159 | if let Some(child_idx) = cur_node.children[i] { 160 | // make sure this push never allocates 161 | debug_assert!(self.to_visit.capacity() > 0); 162 | self.to_visit.push(TreePos { 163 | pos: child_position, 164 | idx: child_idx.get() as usize, 165 | }); 166 | #[cfg(test)] 167 | { 168 | self.max_stack = self.max_stack.max(self.to_visit.len()); 169 | } 170 | } 171 | if let Some(chunk_idx) = cur_node.chunk[i].get() { 172 | //println!("Return chunk {}",chunk_idx); 173 | self.to_return.push(TreePos { 174 | pos: child_position, 175 | idx: chunk_idx, 176 | }); 177 | } 178 | } 179 | //dbg!(&self.to_visit); 180 | } 181 | } 182 | match self.to_return.pop() { 183 | Some(rv) => Some(rv), 184 | // SAFETY: the only way to get here is by having stuf in the to_return vec 185 | _ => unsafe { core::hint::unreachable_unchecked() }, 186 | } 187 | } 188 | } 189 | 190 | duplicate::duplicate! { 191 | [ 192 | StructName reference(lt, type) getter(p); 193 | [ChunksInAABBIter] [& 'lt type] [ &self.chunks[p.idx].chunk ]; 194 | // SAFETY: we attach the lifetime of the iterator to this when returning so 195 | // nobody can destroy the tree when we are not looking. 196 | [ChunksInAABBIterMut] [& 'lt mut type] [unsafe{self.chunks[p.idx].chunk_ptr().as_mut().unwrap_unchecked()}]; 197 | ] 198 | 199 | ///Iterator over positions and chunks in the AABB 200 | pub struct StructName<'a, const N:usize, const B:usize, C, L> 201 | where 202 | L:LodVec, 203 | C:Sized, 204 | { 205 | // the chunks storage reference 206 | chunks: reference([a],[ChunkStorage]), 207 | // iterator over indices in chunk storage 208 | chunk_idx_iter: ChunkIdxInAABBIter<'a, N,B,L>, 209 | } 210 | impl <'a, const N:usize, const B:usize, C, L> Iterator for StructName<'a,N,B, C, L> where 211 | L:LodVec, 212 | C:Sized, 213 | { 214 | type Item = (TreePos, reference([a], [C])); 215 | 216 | #[inline] 217 | fn next(&mut self) -> Option { 218 | // fetch next position from position iterator 219 | let pos = self.chunk_idx_iter.next()?; 220 | // return appropriate reference to the chunk 221 | Some((pos, getter([pos]))) 222 | } 223 | } 224 | 225 | } 226 | 227 | /// Iterate over all positions inside a certain AABB. 228 | /// Important - this returns all intermediate depths, but does not return root node. 229 | #[inline] 230 | pub fn iter_all_positions_in_bounds>( 231 | bound_min: L, 232 | bound_max: L, 233 | ) -> CoordsInBoundsIter { 234 | debug_assert!( 235 | bound_min < bound_max, 236 | "Bounds must select a non-empty region" 237 | ); 238 | 239 | let mut stack = Vec::with_capacity(CoordsInBoundsIter::::stack_size(bound_min)); 240 | stack.push(L::root()); 241 | let mut ite = CoordsInBoundsIter { 242 | stack, 243 | max_depth: bound_min.depth(), 244 | bound_min, 245 | bound_max, 246 | }; 247 | //discard root node as we never want it. 248 | ite.next(); 249 | ite 250 | } 251 | 252 | impl<'a, const N: usize, const B: usize, C, L> Tree 253 | where 254 | C: Sized, 255 | L: LodVec, 256 | Self: 'a, 257 | { 258 | /// Iterate over references to all chunks of the tree in the bounding box. Also returns chunk positions. 259 | #[inline(always)] 260 | pub fn iter_chunk_indices_in_aabb( 261 | &'a self, 262 | bound_min: L, 263 | bound_max: L, 264 | ) -> ChunkIdxInAABBIter<'a, N, B, L> { 265 | ChunkIdxInAABBIter::new(&self.nodes, bound_min, bound_max) 266 | } 267 | 268 | /// Iterate over references to all chunks of the tree in the bounding box. Also returns chunk positions. 269 | #[inline(always)] 270 | pub fn iter_chunks_in_aabb( 271 | &'a self, 272 | bound_min: L, 273 | bound_max: L, 274 | ) -> ChunksInAABBIter<'a, N, B, C, L> { 275 | ChunksInAABBIter { 276 | chunks: &self.chunks, 277 | chunk_idx_iter: ChunkIdxInAABBIter::new(&self.nodes, bound_min, bound_max), 278 | } 279 | } 280 | /// Iterate over mutable references to all chunks of the tree in the bounding box. Also returns chunk positions. 281 | #[inline(always)] 282 | pub fn iter_chunks_in_aabb_mut( 283 | &'a mut self, 284 | bound_min: L, 285 | bound_max: L, 286 | ) -> ChunksInAABBIterMut<'a, N, B, C, L> { 287 | ChunksInAABBIterMut { 288 | chunks: &mut self.chunks, 289 | chunk_idx_iter: ChunkIdxInAABBIter::new(&self.nodes, bound_min, bound_max), 290 | } 291 | } 292 | } 293 | 294 | #[cfg(test)] 295 | mod tests { 296 | use super::*; 297 | use rand::rngs::SmallRng; 298 | use rand::{Rng, SeedableRng}; 299 | 300 | const NUM_QUERIES: usize = 1; 301 | 302 | struct Chunk { 303 | visible: bool, 304 | } 305 | 306 | ///Tests generation of coordinates in bounds over QuadTree 307 | #[test] 308 | fn bounds_quadtree() { 309 | let mut rng = SmallRng::seed_from_u64(42); 310 | 311 | for _i in 0..NUM_QUERIES { 312 | let depth = rng.random_range(4u8..8u8); 313 | let cmax = 1 << depth; 314 | let min = rand_cv( 315 | &mut rng, 316 | QuadVec::new([0, 0], depth), 317 | QuadVec::new([cmax - 2, cmax - 2], depth), 318 | ); 319 | let max = rand_cv( 320 | &mut rng, 321 | min + QuadVec::new([1, 1], depth), 322 | QuadVec::new([cmax - 1, cmax - 1], depth), 323 | ); 324 | 325 | println!("Generated min {:?}", min); 326 | println!("Generated max {:?}", max); 327 | 328 | let mut count = 0; 329 | for pos in iter_all_positions_in_bounds(min, max) { 330 | //println!("{:?}", pos); 331 | 332 | if pos.depth == depth { 333 | count += 1; 334 | } 335 | } 336 | assert_eq!(count, get_chunk_count_at_max_depth(min, max)); 337 | } 338 | } 339 | 340 | ///Tests generation of coordinates in bounds over OctTree 341 | #[test] 342 | fn bounds_octree() { 343 | let mut rng = SmallRng::seed_from_u64(42); 344 | 345 | for _i in 0..NUM_QUERIES { 346 | let depth = rng.random_range(4u8..8u8); 347 | let cmax = 1 << depth; 348 | let min = rand_cv( 349 | &mut rng, 350 | OctVec::new([0, 0, 0], depth), 351 | OctVec::new([cmax - 2, cmax - 2, cmax - 2], depth), 352 | ); 353 | let max = rand_cv( 354 | &mut rng, 355 | min + OctVec::new([1, 1, 1], depth), 356 | OctVec::new([cmax - 1, cmax - 1, cmax - 1], depth), 357 | ); 358 | let mut count = 0; 359 | for pos in iter_all_positions_in_bounds(min, max) { 360 | //println!("{:?}", pos); 361 | 362 | if pos.depth == depth { 363 | count += 1; 364 | } 365 | } 366 | assert_eq!(count, get_chunk_count_at_max_depth(min, max)); 367 | } 368 | } 369 | #[test] 370 | fn aabb_iterator_stack_size() { 371 | println!("Testing OctTree"); 372 | 373 | for d in 1..6 { 374 | println!("Depth {d}"); 375 | let mut tree = OctTree::::new(); 376 | let cmax = (1u8 << d) - 1; 377 | let min = OctVec::new([0u8, 0, 0], d); 378 | let max = OctVec::new([cmax, cmax, cmax], d); 379 | let pos_iter = iter_all_positions_in_bounds(min, max); 380 | 381 | tree.insert_many(pos_iter, |_| Chunk { visible: false }); 382 | let mut ite = tree.iter_chunks_in_aabb(min, max); 383 | while ite.next().is_some() {} 384 | 385 | let expected_maxstack = ChunkIdxInAABBIter::<3, 8, OctVec>::stack_size(min); 386 | 387 | assert_eq!(ite.chunk_idx_iter.max_stack, expected_maxstack); 388 | } 389 | 390 | println!("Testing QuadTree"); 391 | for d in 1..10 { 392 | println!("Depth {d}"); 393 | let mut tree = QuadTree::>::new(); 394 | let cmax = (1u16 << d) - 1; 395 | let min = QuadVec::new([0u16, 0], d); 396 | let max = QuadVec::new([cmax, cmax], d); 397 | let pos_iter = iter_all_positions_in_bounds(min, max); 398 | 399 | tree.insert_many(pos_iter, |_| Chunk { visible: false }); 400 | let mut ite = tree.iter_chunks_in_aabb(min, max); 401 | while ite.next().is_some() {} 402 | let expected_maxstack = ChunkIdxInAABBIter::<2, 4, QuadVec>::stack_size(min); 403 | 404 | assert_eq!(ite.chunk_idx_iter.max_stack, expected_maxstack); 405 | } 406 | } 407 | #[test] 408 | fn iterate_over_chunks_in_aabb() { 409 | const D: u8 = 4; 410 | const R: u8 = 3; 411 | 412 | let mut counter: usize = 0; 413 | let mut counter_created: usize = 0; 414 | let mut chunk_creator = |position: OctVec| -> Chunk { 415 | let r = (R * R) as i32 - 2; 416 | 417 | let visible = match position.depth { 418 | D => position 419 | .pos 420 | .iter() 421 | .fold(true, |acc, e| acc & ((*e as i32 - R as i32).pow(2) < r)), 422 | _ => false, 423 | }; 424 | counter += visible as usize; 425 | counter_created += 1; 426 | //println!("create {:?} {:?}", position, visible); 427 | Chunk { visible } 428 | }; 429 | let cmax = 2u8 * R; 430 | let mut tree = OctTree::::new(); 431 | let pos_iter = iter_all_positions_in_bounds( 432 | OctVec::new([0u8, 0, 0], D), 433 | OctVec::new([cmax, cmax, cmax], D), 434 | ) 435 | .filter(|p| p.depth == D); 436 | 437 | tree.insert_many(pos_iter, &mut chunk_creator); 438 | 439 | // query the whole region for filled voxels 440 | let mut filled_voxels: usize = 0; 441 | let mut total_voxels: usize = 0; 442 | let min = OctVec::new([0, 0, 0], D); 443 | let max = OctVec::new([cmax, cmax, cmax], D); 444 | for (l, c) in tree.iter_chunks_in_aabb(min, max) { 445 | filled_voxels += c.visible as usize; 446 | total_voxels += 1; 447 | //println!("visit {:?} {:?}", l, c.visible); 448 | assert_eq!( 449 | l.pos.depth, D, 450 | "All chunks must be at max depth (as we did not insert any others)" 451 | ); 452 | } 453 | assert_eq!( 454 | filled_voxels, counter, 455 | " we should have found all voxels that were inserted and marked visible" 456 | ); 457 | assert_eq!( 458 | total_voxels, counter_created, 459 | "we should have found all voxels that were inserted" 460 | ); 461 | assert_eq!( 462 | total_voxels, 463 | get_chunk_count_at_max_depth(min, max), 464 | "we should have found all voxels in AABB" 465 | ); 466 | 467 | // query a bunch of random regions 468 | let mut rng = SmallRng::seed_from_u64(42); 469 | for _ite in 0..NUM_QUERIES { 470 | let cmax = 2u8 * R; 471 | let min = rand_cv( 472 | &mut rng, 473 | OctVec::new([0, 0, 0], D), 474 | OctVec::new([cmax - 2, cmax - 2, cmax - 2], D), 475 | ); 476 | let max = rand_cv( 477 | &mut rng, 478 | min + OctVec::new([1, 1, 1], D), 479 | OctVec::new([cmax, cmax, cmax], D), 480 | ); 481 | // println!("Generated min {:?}", min); 482 | // println!("Generated max {:?}", max); 483 | assert!(max > min); 484 | 485 | let mut filled_voxels: usize = 0; 486 | //println!("{:?} {:?} {:?}", _ite, min, max); 487 | for (_l, c) in tree.iter_chunks_in_aabb(min, max) { 488 | if c.visible { 489 | //println!(" Sphere chunk {:?}", _l); 490 | filled_voxels += 1; 491 | } 492 | } 493 | //println!(" filled {:?}", filled_voxels); 494 | assert!( 495 | filled_voxels <= counter, 496 | "No way we see more voxels than were inserted!" 497 | ) 498 | } 499 | } 500 | 501 | #[test] 502 | fn edit_chunks_in_aabb() { 503 | const D: u8 = 4; 504 | const R: u8 = 3; 505 | let mut counter: usize = 0; 506 | let mut chunk_creator = |position: OctVec| -> Chunk { 507 | let r = (R * R) as i32 - 2; 508 | 509 | let visible = match position.depth { 510 | D => position 511 | .pos 512 | .iter() 513 | .fold(true, |acc, e| acc & ((*e as i32 - R as i32).pow(2) < r)), 514 | _ => false, 515 | }; 516 | counter += visible as usize; 517 | println!("create {:?} {:?}", position, visible); 518 | Chunk { visible } 519 | }; 520 | 521 | let mut tree = OctTree::::new(); 522 | let pos_iter = iter_all_positions_in_bounds( 523 | OctVec::build(0, 0, 0, D), 524 | OctVec::build(2 * R, 2 * R, 2 * R, D), 525 | ) 526 | .filter(|p| p.depth == D); 527 | tree.insert_many(pos_iter, &mut chunk_creator); 528 | // query the whole region for filled voxels 529 | let cmax = 2u8 * R; 530 | let min = OctVec::build(0, 0, 0, D); 531 | let max = OctVec::new([cmax, cmax, cmax], D); 532 | let mut filled_voxels: usize = 0; 533 | for (l, c) in tree.iter_chunks_in_aabb_mut(min, max) { 534 | if c.visible { 535 | filled_voxels += 1; 536 | c.visible = false; 537 | } 538 | 539 | assert_eq!( 540 | l.pos.depth, D, 541 | "All chunks must be at max depth (as we did not insert any others)" 542 | ); 543 | } 544 | 545 | assert_eq!( 546 | filled_voxels, counter, 547 | " we should have found all voxels that were inserted and marked visible" 548 | ); 549 | 550 | let mut rng = SmallRng::seed_from_u64(42); 551 | 552 | for _ite in 0..NUM_QUERIES { 553 | let cmax = 2u8 * R; 554 | let min = rand_cv( 555 | &mut rng, 556 | OctVec::new([0, 0, 0], D), 557 | OctVec::new([cmax - 2, cmax - 2, cmax - 2], D), 558 | ); 559 | let max = rand_cv( 560 | &mut rng, 561 | min + OctVec::new([1, 1, 1], D), 562 | OctVec::new([cmax, cmax, cmax], D), 563 | ); 564 | 565 | for (l, c) in tree.iter_chunks_in_aabb_mut(min, max) { 566 | assert!(!c.visible, "no way any voxel is still visible"); 567 | assert_eq!( 568 | l.pos.depth, D, 569 | "All chunks must be at max depth (as we did not insert any others)" 570 | ); 571 | } 572 | } 573 | } 574 | } 575 | -------------------------------------------------------------------------------- /src/tree.rs: -------------------------------------------------------------------------------- 1 | /* Generic tree structures for storage of spatial data. 2 | * Copyright (C) 2023 Alexander Pyattaev 3 | * 4 | * This program is free software: you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License as published by 6 | * the Free Software Foundation, either version 3 of the License, or 7 | * (at your option) any later version. 8 | * 9 | * This program is distributed in the hope that it will be useful, 10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | * GNU General Public License for more details. 13 | * 14 | * You should have received a copy of the GNU General Public License 15 | * along with this program. If not, see . 16 | */ 17 | 18 | //! Contains the tree struct, which is used to hold all chunks 19 | 20 | use crate::coords::*; 21 | use crate::util_funcs::*; 22 | use slab::Slab; 23 | use std::fmt::Debug; 24 | use std::num::NonZeroU32; 25 | use std::ops::ControlFlow; 26 | 27 | // type aliases to make iterators more readable 28 | pub(crate) type ChunkStorage = Slab>; 29 | pub(crate) type NodeStorage = Slab>; 30 | 31 | /// Tree holding the actual data permanently in memory. 32 | /// This is arguably "too generic", and one should use provided OctTree and QuadTree types when possible. 33 | /// 34 | /// 35 | /// Template parameters are: 36 | /// * N is the number bits needed to encode B, i.e. 3 for octrees and 4 for quadtrees. 37 | /// * B is the branch count per node, i.e. 8 for octrees and 4 for quadtrees. Has to be power of two. 38 | /// 39 | /// An invariant between the two has to be ensured where 1<> { 43 | /// All data chunks in the tree 44 | pub(crate) chunks: ChunkStorage, 45 | /// All nodes of the Tree 46 | pub(crate) nodes: NodeStorage, 47 | /// Temporary buffer for nodes used during rebuilds 48 | new_nodes: Slab>, 49 | } 50 | 51 | pub enum Entry<'a, C: Sized> { 52 | Occupied(&'a mut C), 53 | Vacant(&'a mut C), 54 | } 55 | 56 | impl Tree 57 | where 58 | C: Sized, 59 | L: LodVec, 60 | { 61 | /// create a tree with preallocated memory for chunks and nodes 62 | /// NOTE this function does runtime asserts to make sure Tree is templated correctly. 63 | /// this runtime check will become compiletime check once generic_const_exprs matures. 64 | pub fn with_capacity_unsafe(nodes_capacity: usize, chunks_capacity: usize) -> Self { 65 | // TODO: once feature(generic_const_exprs) is mature, make this look nicer 66 | assert_eq!(1<= 1); 69 | debug_assert!(chunks_capacity >= 1); 70 | let mut nodes = Slab::with_capacity(nodes_capacity); 71 | // create root node right away, no point having a tree without a root. 72 | let r = nodes.insert(TreeNode::new()); 73 | //Slab always returns 0 for index of first inserted element, right? Better check... 74 | debug_assert_eq!(r, 0); 75 | 76 | Self { 77 | chunks: Slab::with_capacity(chunks_capacity), 78 | nodes, 79 | new_nodes: Slab::new(), 80 | } 81 | } 82 | //TODO: use duplicate! on this 83 | 84 | /// Gets the node "controlling" the desired position. This means node that is one depth level above target. 85 | /// Returns the index of child entry and mutable reference to the node. 86 | /// If exact match is found, returns Ok variant, else Err variant with nearest match (at lower depth). 87 | fn follow_nodes_to_position_mut( 88 | &mut self, 89 | position: L, 90 | ) -> Result<(usize, &mut TreeNode), (usize, &mut TreeNode)> { 91 | // start in root 92 | let mut addr = TreePos { 93 | idx: 0, 94 | pos: L::root(), 95 | }; 96 | // make sure target is not root (else we will be stuck here) 97 | debug_assert_ne!(position, addr.pos); 98 | // then loop 99 | loop { 100 | // SAFETY: the node hierarchy should be sound. If it is not we are doomed. 101 | let current = unsafe { 102 | (self.nodes.get_unchecked_mut(addr.idx) as *mut TreeNode) 103 | .as_mut() 104 | .unwrap_unchecked() 105 | }; 106 | // compute child index & position towards target 107 | let child_idx = addr.pos.get_child_index(position); 108 | let child_pos = addr.pos.get_child(child_idx); 109 | // if the current node is the one we are looking for, return it 110 | if child_pos == position { 111 | return Ok((child_idx, current)); 112 | } 113 | 114 | // assuming the child index points to an existing child node, follow it. 115 | addr = match current.children[child_idx] { 116 | Some(idx) => TreePos { 117 | idx: idx.get() as usize, 118 | pos: addr.pos.get_child(child_idx), 119 | }, 120 | None => { 121 | return Err((child_idx, current)); 122 | } 123 | }; 124 | } 125 | } 126 | 127 | /// Gets the node "controlling" the desired position. This means node that is one depth level above target. 128 | /// Returns the index of child entry and mutable reference to the node. 129 | /// If exact match is found, returns Ok variant, else Err variant with nearest match (at lower depth). 130 | fn follow_nodes_to_position( 131 | &self, 132 | position: L, 133 | ) -> Result<(usize, &TreeNode), (usize, &TreeNode)> { 134 | // start in root 135 | let mut addr = TreePos { 136 | idx: 0, 137 | pos: L::root(), 138 | }; 139 | // make sure target is not root (else we will be stuck here) 140 | debug_assert_ne!(position, addr.pos); 141 | 142 | // then loop 143 | loop { 144 | // SAFETY: the node hierarchy should be sound. If it is not we are doomed. 145 | let current = unsafe { self.nodes.get_unchecked(addr.idx) }; 146 | // compute child index & position towards target 147 | let child_idx = addr.pos.get_child_index(position); 148 | let child_pos = addr.pos.get_child(child_idx); 149 | // if the current node is the one we are looking for, return it 150 | if child_pos == position { 151 | return Ok((child_idx, current)); 152 | } 153 | 154 | // assuming the child index points to an existing child node, follow it. 155 | addr = match current.children[child_idx] { 156 | Some(idx) => TreePos { 157 | idx: idx.get() as usize, 158 | pos: addr.pos.get_child(child_idx), 159 | }, 160 | None => { 161 | return Err((child_idx, current)); 162 | } 163 | }; 164 | } 165 | } 166 | 167 | /// get the number of chunks in the tree 168 | #[inline] 169 | pub fn get_num_chunks(&self) -> usize { 170 | self.chunks.len() 171 | } 172 | 173 | /// get a reference to chunk by index 174 | #[inline] 175 | pub fn get_chunk(&self, index: usize) -> &ChunkContainer { 176 | &self.chunks[index] 177 | } 178 | 179 | /// get a mutable reference to chunk container by index 180 | #[inline] 181 | pub fn get_chunk_mut(&mut self, index: usize) -> &mut ChunkContainer { 182 | &mut self.chunks[index] 183 | } 184 | 185 | /// get a chunk by position if it's in the tree 186 | #[inline] 187 | pub fn get_chunk_by_position(&self, position: L) -> Option<&C> { 188 | // get the index of the chunk 189 | let (idx, node) = self.follow_nodes_to_position(position).ok()?; 190 | let chunk_index = node.chunk[idx].get()?; 191 | // and return the chunk 192 | Some(&self.chunks[chunk_index].chunk) 193 | } 194 | 195 | /// get a mutable chunk by position if it's in the tree 196 | #[inline] 197 | pub fn get_chunk_by_position_mut(&mut self, position: L) -> Option<&mut C> { 198 | // get the index of the chunk 199 | let (idx, node) = self.follow_nodes_to_position(position).ok()?; 200 | let chunk_index = node.chunk[idx].get()?; 201 | // and return the chunk 202 | Some(&mut self.chunks[chunk_index].chunk) 203 | } 204 | 205 | /// get an Entry handle to modify existing or insert a new chunk. 206 | /// this is WIP 207 | #[inline] 208 | pub fn entry(&mut self, _position: L, mut _chunk_creator: V) -> Entry 209 | where 210 | V: FnMut(L) -> C, 211 | { 212 | todo!() 213 | /*match self.follow_nodes_to_position(position){ 214 | Ok((idx, node))=>{(idx, node)} 215 | Err((idx, node))=>{todo!()} 216 | } 217 | 218 | let chunk_index = node.chunk[idx].get()?; 219 | // and return the chunk 220 | Some(&mut self.chunks[chunk_index].chunk)*/ 221 | } 222 | 223 | /// get the position of a chunk, if it exists 224 | #[inline] 225 | pub fn get_chunk_position(&self, index: usize) -> Option { 226 | Some(self.chunks.get(index)?.position) 227 | } 228 | 229 | /// Inserts/replaces chunks at specified locations. 230 | /// This operation will create necessary intermediate nodes to meet datastructure 231 | /// constraints. 232 | /// This operation may allocate memory more than once if targets is long enough 233 | /// 234 | /// If targets are nearby, we could save quite a bit of resources by 235 | /// reducing walking needed to insert data. 236 | pub fn insert_many(&mut self, mut targets: T, mut chunk_creator: V) 237 | where 238 | T: Iterator, 239 | V: FnMut(L) -> C, 240 | { 241 | debug_assert!(!self.nodes.is_empty()); 242 | 243 | // Internal queue for batch processing, it will be as long as maximal depth of the tree. 244 | // Stack allocated since it is only ~200 bytes, and this keeps things cache-friendly. 245 | let mut queue = arrayvec::ArrayVec::, { MAX_DEPTH as usize }>::new(); 246 | 247 | // start at the root node 248 | let mut addr = TreePos { 249 | pos: L::root(), 250 | idx: 0, 251 | }; 252 | 253 | let mut tgt = targets.next().expect("Expected at least one target"); 254 | loop { 255 | debug_assert_ne!(tgt, L::root(), "Root node is not a valid target!"); 256 | //println!("===Inserting target {tgt:?}==="); 257 | 258 | loop { 259 | addr = match self.insert_inner(addr, tgt, &mut chunk_creator) { 260 | ControlFlow::Break(_) => { 261 | break; 262 | } 263 | ControlFlow::Continue(a) => { 264 | queue.push(addr); 265 | a 266 | } 267 | }; 268 | } 269 | // insert done, fetch us the next target 270 | tgt = match targets.next() { 271 | Some(t) => t, 272 | None => { 273 | break; 274 | } 275 | }; 276 | debug_assert_ne!(tgt, L::root(), "Root node is not a valid target!"); 277 | // walk up the tree until we are high enough to work on next target 278 | //dbg!(&self.processing_queue); 279 | while !addr.pos.contains_child_node(tgt) { 280 | addr = queue 281 | .pop() 282 | .expect("This should not happen, as we keep root in the stack"); 283 | //println!("Going up the stack to {addr:?} for target {tgt:?}"); 284 | } 285 | } 286 | } 287 | 288 | /// Removes chunk at specified position, and returns its content (if any) 289 | #[inline] 290 | pub fn pop_chunk_by_position(&mut self, pos: L) -> Option { 291 | let (child, node) = self.follow_nodes_to_position_mut(pos).ok()?; 292 | let chunk_idx = node.chunk[child].take()?; 293 | 294 | let chunk_rec = self.chunks.remove(chunk_idx); 295 | Some(chunk_rec.chunk) 296 | } 297 | 298 | // Common part of various insert operations 299 | #[inline] 300 | fn insert_inner( 301 | &mut self, 302 | addr: TreePos, 303 | tgt: L, 304 | chunk_creator: &mut V, 305 | ) -> ControlFlow> 306 | where 307 | V: FnMut(L) -> C, 308 | { 309 | //dbg!(addr, tgt); 310 | let child_idx = addr.pos.get_child_index(tgt); 311 | let child_pos = addr.pos.get_child(child_idx); 312 | let current_node = self.nodes.get_mut(addr.idx).expect("Node index broken!"); 313 | //println!("Current node {addr:?}"); 314 | if child_pos == tgt { 315 | //println!("Found child {child_pos:?}, id {child_idx:?}"); 316 | let chunk = chunk_creator(tgt); 317 | //perform actual insertion at this location 318 | let inserted = match current_node.chunk[child_idx].get() { 319 | Some(ci) => { 320 | self.chunks[ci].chunk = chunk; 321 | //println!("Found target, replacing existing chunk at {}", ci.get()); 322 | ci 323 | } 324 | None => { 325 | let chunk_idx = self.chunks.insert(ChunkContainer { 326 | chunk, 327 | position: child_pos, 328 | node_idx: addr.idx as u32, 329 | child_idx: child_idx as u8, 330 | }); 331 | //println!("Found target, inserting chunk at new index {chunk_idx}"); 332 | current_node.chunk[child_idx] = ChunkPtr::from(Some(chunk_idx)); 333 | chunk_idx 334 | } 335 | }; 336 | return ControlFlow::Break(inserted); 337 | } 338 | 339 | let idx = match current_node.children[child_idx] { 340 | Some(idx) => idx.get() as usize, 341 | None => { 342 | //println!("Inserting new node"); 343 | // modify nodes slab 344 | let idx = self.nodes.insert(TreeNode::new()); 345 | // update pointer in parent node 346 | self.nodes[addr.idx].children[child_idx] = NonZeroU32::new(idx as u32); 347 | idx 348 | } 349 | }; 350 | ControlFlow::Continue(TreePos { 351 | idx, 352 | pos: child_pos, 353 | }) 354 | } 355 | 356 | /// Inserts/replaces a single chunk at specified location. 357 | /// This operation will create necessary intermediate nodes to meet datastructure 358 | /// constraints. 359 | /// This operation may allocate memory. 360 | /// 361 | /// If you need to insert lots of chunks, use insert_many instead, it will probably be faster on deep trees. 362 | /// returns index of inserted chunk. 363 | pub fn insert(&mut self, tgt: L, mut chunk_creator: V) -> usize 364 | where 365 | V: FnMut(L) -> C, 366 | { 367 | debug_assert!(!self.nodes.is_empty()); 368 | debug_assert_ne!(tgt, L::root(), "Root node is not a valid target!"); 369 | 370 | // start at the root node 371 | let mut addr = TreePos { 372 | pos: L::root(), 373 | idx: 0, 374 | }; 375 | 376 | //println!("===Inserting target {tgt:?}==="); 377 | loop { 378 | addr = match self.insert_inner(addr, tgt, &mut chunk_creator) { 379 | ControlFlow::Continue(a) => a, 380 | ControlFlow::Break(idx) => { 381 | break idx; 382 | } 383 | }; 384 | } 385 | } 386 | 387 | #[inline] 388 | pub fn iter_chunks_mut(&mut self) -> slab::IterMut> { 389 | self.chunks.iter_mut() 390 | } 391 | 392 | #[inline] 393 | pub fn iter_chunks(&mut self) -> slab::Iter> { 394 | self.chunks.iter() 395 | } 396 | 397 | /// clears the tree, removing all nodes, chunks and internal buffers 398 | #[inline] 399 | pub fn clear(&mut self) { 400 | self.chunks.clear(); 401 | let root = self.nodes.remove(0); 402 | self.nodes.clear(); 403 | self.nodes.insert(root); 404 | } 405 | 406 | /// Defragments the chunks array to enable fast iteration. 407 | /// This will have zero cost if array does not need defragmentation. 408 | /// The next update might take longer due to memory allocations. 409 | #[inline] 410 | pub fn defragment_chunks(&mut self) { 411 | let nodes = &mut self.nodes; 412 | self.chunks.compact(|chunk, cur, new| { 413 | assert_eq!( 414 | nodes[chunk.node_idx as usize].chunk[chunk.child_idx as usize] 415 | .get() 416 | .unwrap(), 417 | cur 418 | ); 419 | nodes[chunk.node_idx as usize].chunk[chunk.child_idx as usize] = 420 | ChunkPtr::from(Some(new)); 421 | true 422 | }); 423 | } 424 | 425 | /// Prunes the nodes array to delete all nodes that have no chunks. 426 | /// This requires nodes to be traversed in a depth-first manner, so this is somewhat slow on larger trees 427 | /// You only really need this if you have deleted a whole bunch of chunks and really need the nodes memory back 428 | pub fn prune_nodes(&mut self) { 429 | todo!() 430 | } 431 | 432 | /// Defragments the nodes array to enable faster operation and prune dead leaves. 433 | /// This requires nodes to be copied, so this will allocate. Many unsafes would be needed otherwise. 434 | /// The next update might take longer due to memory allocations. 435 | pub fn defragment_nodes(&mut self) { 436 | let num_nodes = self.nodes.len(); 437 | // allocate for all nodes since we know their exact number 438 | self.new_nodes.reserve(num_nodes); 439 | 440 | // move the root node to kick things off 441 | self.new_nodes.insert(self.nodes.remove(0)); 442 | 443 | // for every index in new slab, move its children immediately after itself, keep doing that until all are moved. 444 | // this will produce a breadth-first traverse of original nodes laid out in new memory, which should keep 445 | // nearby nodes close in memory locations. 446 | for n in 0..num_nodes { 447 | // clone children array to keep it safe while we mess with it 448 | let children = self.new_nodes[n].children; 449 | // now go over node's children and move them over 450 | for (i, old_idx) in iter_treenode_children(&children) { 451 | let old_node = self.nodes.remove(old_idx); 452 | //eliminate empty nodes 453 | if old_node.is_empty() { 454 | self.new_nodes[n].children[i] = None; 455 | continue; 456 | } 457 | // move the child into new slab 458 | let new_idx = self.new_nodes.insert(old_node); 459 | // ensure slab is not doing anything fishy, and actually gives us correct indices 460 | debug_assert_eq!(new_idx, n + i + 1); 461 | // fix our reference to that child 462 | self.new_nodes[n].children[i] = Some(NonZeroU32::new(new_idx as u32).unwrap()); 463 | 464 | // if the position of the node has changed 465 | if new_idx != old_idx { 466 | // update node index of all chunks we are referring to 467 | for (_, chunk_idx) in self.new_nodes[new_idx].iter_existing_chunks() { 468 | self.chunks[chunk_idx].node_idx = new_idx as u32; 469 | } 470 | } 471 | } 472 | } 473 | std::mem::swap(&mut self.nodes, &mut self.new_nodes); 474 | self.new_nodes.clear(); 475 | } 476 | 477 | /// Prepares the tree for an LOD update. This operation reorganizes the nodes and 478 | /// adds chunks around specified locations (targets) while also erasing all other chunks. 479 | /// A side-effect of this is that nodes are defragmented. 480 | /// # Params 481 | /// * `targets` the target positions to generate the maximal level of detail around, e.g. players 482 | /// * `detail` the size of the region which will be filled with max level of detail 483 | /// * `chunk_creator` function to create a new chunk from a given position 484 | /// * `evict_callback` function to dispose of unneeded chunks (can move them into cache or whatever) 485 | pub fn lod_update( 486 | &mut self, 487 | targets: &[L], 488 | detail: u32, 489 | mut chunk_creator: V, 490 | mut evict_callback: W, 491 | ) where 492 | V: FnMut(L) -> C, 493 | W: FnMut(L, C), 494 | { 495 | let num_nodes = self.nodes.len(); 496 | // allocate room for new nodes (assuming it is about same amount as before update) 497 | // better to overallocate here than to allocate twice. 498 | //let mut new_nodes = Slab::with_capacity(num_nodes); 499 | self.new_nodes.reserve(num_nodes); 500 | let mut new_positions = std::collections::VecDeque::with_capacity(B); 501 | 502 | // move the root node to kick things off 503 | self.new_nodes.insert(self.nodes.remove(0)); 504 | new_positions.push_back(L::root()); 505 | 506 | // for every index in new slab, move its children immediately after itself, keep doing that until all are moved. 507 | // this will produce a breadth-first traverse of original nodes laid out in new memory, which should keep 508 | // nearby nodes close in memory locations. 509 | for n in 0..usize::MAX { 510 | let pos = match new_positions.pop_front() { 511 | Some(p) => p, 512 | None => break, 513 | }; 514 | // copy children array to keep it safe while we mess with it 515 | let children = self.new_nodes[n].children; 516 | 517 | // now go over node's children 518 | for (b, maybe_child) in children.iter().enumerate() { 519 | // figure out position of child node 520 | let child_pos = pos.get_child(b); 521 | // figure if any of the targets needs it subdivided 522 | let subdivide = targets.iter().any(|x| x.can_subdivide(child_pos, detail)); 523 | //println!("{child_pos:?}, {subdivide:?}"); 524 | 525 | // if child is subdivided we do not want a chunk there, 526 | // and in other case we need one, so we make one if necessary 527 | match (self.new_nodes[n].chunk[b].get(), subdivide) { 528 | (None, true) => { 529 | //println!("No chunks present"); 530 | } 531 | (Some(chunk_idx), true) => { 532 | let cont = self.chunks.remove(chunk_idx); 533 | debug_assert_eq!(cont.position, child_pos); 534 | evict_callback(child_pos, cont.chunk); 535 | self.new_nodes[n].chunk[b] = ChunkPtr::None; 536 | } 537 | (None, false) => { 538 | let chunk_idx = self.chunks.insert(ChunkContainer { 539 | chunk: chunk_creator(child_pos), 540 | position: child_pos, 541 | node_idx: n as u32, 542 | child_idx: b as u8, 543 | }); 544 | 545 | self.new_nodes[n].chunk[b] = ChunkPtr::from(Some(chunk_idx)); 546 | } 547 | (Some(chunk_idx), false) => { 548 | //println!("Preserve chunk at index {chunk_idx}"); 549 | self.chunks[chunk_idx].node_idx = n as u32; 550 | } 551 | } 552 | 553 | // make sure a child is present if we are going to subdivide 554 | match (maybe_child, subdivide) { 555 | // no node present but we need one 556 | (None, true) => { 557 | let new_idx = self.new_nodes.insert(TreeNode::new()); 558 | // keep track of positions 559 | new_positions.push_back(child_pos); 560 | self.new_nodes[n].children[b] = 561 | Some(NonZeroU32::new(new_idx as u32).unwrap()); 562 | } 563 | // no node present and we do not need one 564 | (None, false) => {} 565 | //existing node needed, keep it (same logic as in defragment_nodes) 566 | (Some(child_idx), true) => { 567 | // move the child into new slab 568 | let new_idx = self 569 | .new_nodes 570 | .insert(self.nodes.remove(child_idx.get() as usize)); 571 | // keep track of positions 572 | new_positions.push_back(child_pos); 573 | // fix our reference to that child 574 | self.new_nodes[n].children[b] = 575 | Some(NonZeroU32::new(new_idx as u32).unwrap()); 576 | } 577 | // existing node not needed, delete its chunks and do not copy over the node itself 578 | (Some(child_idx), false) => { 579 | for node in traverse(&self.nodes, &self.nodes[child_idx.get() as usize]) { 580 | for (_, cid) in node.iter_existing_chunks() { 581 | let cont = self.chunks.remove(cid); 582 | debug_assert!(child_pos.contains_child_node(cont.position)); 583 | evict_callback(cont.position, cont.chunk); 584 | } 585 | } 586 | self.new_nodes[n].children[b] = None; 587 | } 588 | }; 589 | } 590 | } 591 | std::mem::swap(&mut self.nodes, &mut self.new_nodes); 592 | self.new_nodes.clear(); 593 | } 594 | 595 | /// Shrinks all internal buffers to fit actual need, reducing memory usage. 596 | /// Calling defragment_chunks() and defragment_nodes() before this is advisable. 597 | /// The next update might take longer due to memory allocations. 598 | #[inline] 599 | pub fn shrink_to_fit(&mut self) { 600 | self.chunks.shrink_to_fit(); 601 | self.nodes.shrink_to_fit(); 602 | self.new_nodes.shrink_to_fit(); 603 | } 604 | } 605 | 606 | /// Construct an itreator that traverses a subtree in nodes that begins in start (including start itself). 607 | #[inline] 608 | pub fn traverse<'a, const B: usize>( 609 | nodes: &'a NodeStorage, 610 | start: &'a TreeNode, 611 | ) -> TraverseIter<'a, B> { 612 | //TODO use better logic here (DFS)! 613 | let mut to_visit = Vec::with_capacity(8 * B); //arrayvec::ArrayVec::new(); 614 | to_visit.push(start); 615 | TraverseIter { nodes, to_visit } 616 | } 617 | 618 | ///Helper to perform breadth-first traverse of tree's nodes. 619 | pub struct TraverseIter<'a, const B: usize> { 620 | nodes: &'a NodeStorage, 621 | to_visit: Vec<&'a TreeNode>, 622 | //to_visit: arrayvec::ArrayVec<&'a TreeNode, B>, 623 | } 624 | 625 | impl<'a, const B: usize> Iterator for TraverseIter<'a, B> { 626 | type Item = &'a TreeNode; 627 | 628 | #[inline] 629 | fn next(&mut self) -> Option { 630 | let current = self.to_visit.pop()?; 631 | for (_, c) in iter_treenode_children(¤t.children) { 632 | self.to_visit.push(&self.nodes[c]); 633 | } 634 | Some(current) 635 | } 636 | } 637 | 638 | pub type OctTree = Tree<3, 8, C, L>; 639 | impl OctTree 640 | where 641 | C: Sized, 642 | L: LodVec<3>, 643 | { 644 | /// creates a new, empty OctTree, with no cache 645 | pub fn new() -> Self { 646 | Self::with_capacity(1, 1) 647 | } 648 | /// Creates a OctTree with given capacity for nodes and chunks. Capacities should be > 1 both. 649 | pub fn with_capacity(nodes_capacity: usize, chunks_capacity: usize) -> Self { 650 | Tree::with_capacity_unsafe(nodes_capacity, chunks_capacity) 651 | } 652 | } 653 | 654 | pub type QuadTree = Tree<2, 4, C, L>; 655 | impl QuadTree 656 | where 657 | C: Sized, 658 | L: LodVec<2>, 659 | { 660 | /// creates a new, empty QuadTree, with no cache 661 | pub fn new() -> Self { 662 | Self::with_capacity(1, 1) 663 | } 664 | /// Creates a QuadTree with given capacity for nodes and chunks. Capacities should be > 1 both. 665 | pub fn with_capacity(nodes_capacity: usize, chunks_capacity: usize) -> Self { 666 | Tree::with_capacity_unsafe(nodes_capacity, chunks_capacity) 667 | } 668 | } 669 | 670 | impl Default for OctTree 671 | where 672 | C: Sized, 673 | L: LodVec<3>, 674 | { 675 | /// creates a new, empty tree 676 | fn default() -> Self { 677 | Self::new() 678 | } 679 | } 680 | 681 | impl Default for QuadTree 682 | where 683 | C: Sized, 684 | L: LodVec<2>, 685 | { 686 | /// creates a new, empty tree 687 | fn default() -> Self { 688 | Self::new() 689 | } 690 | } 691 | 692 | #[cfg(test)] 693 | mod tests { 694 | 695 | use super::*; 696 | 697 | struct TestChunk; 698 | 699 | #[test] 700 | fn lod_update() { 701 | // make a tree 702 | let mut tree = QuadTree::::new(); 703 | // as long as we need to update, do so 704 | //let targets = [QuadVec::build(1, 1, 2), QuadVec::build(2, 3, 2)]; 705 | let targets = [QuadVec::build((1 << 2) - 1, (1 << 2) - 1, 2)]; 706 | println!("=====> Update with targets {targets:?}"); 707 | tree.lod_update( 708 | &targets, 709 | 0, 710 | |p| { 711 | println!("Creating chunk at {p:?}"); 712 | TestChunk {} 713 | }, 714 | |p, _| { 715 | println!("Evicting chunk at {p:?}"); 716 | }, 717 | ); 718 | 719 | let targets = [QuadVec::build(0, 0, 2)]; 720 | println!("=====> Update with targets {targets:?}"); 721 | tree.lod_update( 722 | &targets, 723 | 0, 724 | |p| { 725 | println!("Creating chunk at {p:?}"); 726 | TestChunk {} 727 | }, 728 | |p, _| { 729 | println!("Evicting chunk at {p:?}"); 730 | }, 731 | ); 732 | } 733 | #[test] 734 | fn insert_into_tree() { 735 | // make a tree 736 | let mut tree = QuadTree::::new(); 737 | // as long as we need to update, do so 738 | let targets = [ 739 | QuadVec::build(1u8, 1u8, 1u8), 740 | QuadVec::build(2u8, 3u8, 2u8), 741 | QuadVec::build(2u8, 2u8, 2u8), 742 | QuadVec::build(0u8, 1u8, 1u8), 743 | ]; 744 | 745 | tree.insert_many(targets.iter().copied(), |_| TestChunk {}); 746 | 747 | let mut tree2 = QuadTree::::new(); 748 | for t in targets { 749 | tree2.insert(t, |_| TestChunk {}); 750 | } 751 | } 752 | 753 | #[test] 754 | pub fn defragment() { 755 | let mut tree = QuadTree::::new(); 756 | let targets = [ 757 | QuadVec::build(0u8, 0u8, 2u8), 758 | QuadVec::build(0u8, 1u8, 2u8), 759 | QuadVec::build(3u8, 3u8, 2u8), 760 | QuadVec::build(2u8, 2u8, 2u8), 761 | ]; 762 | tree.insert_many(targets.iter().copied(), |_| TestChunk {}); 763 | // slab is a Vec, so it should have binary exponential growth. With 4 entires it should have capacity = len. 764 | assert_eq!(tree.chunks.capacity(), tree.chunks.len()); 765 | tree.pop_chunk_by_position(targets[1]); 766 | assert_eq!(tree.chunks.capacity(), 4); 767 | assert_eq!(tree.chunks.len(), 3); 768 | tree.defragment_chunks(); 769 | tree.shrink_to_fit(); 770 | assert_eq!(tree.chunks.capacity(), tree.chunks.len()); 771 | dbg!(tree.nodes.len()); 772 | tree.pop_chunk_by_position(targets[0]); 773 | //TODO! 774 | //tree.prune(); 775 | dbg!(tree.nodes.len()); 776 | } 777 | 778 | #[test] 779 | pub fn alignment() { 780 | assert_eq!( 781 | std::mem::size_of::>(), 782 | 64, 783 | "Octree node should be 64 bytes" 784 | ); 785 | assert_eq!( 786 | std::mem::size_of::>(), 787 | 32, 788 | "Quadtree node should be 32 bytes" 789 | ); 790 | } 791 | } 792 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------