plozone 0.1.2

3D spatial zone engine: geofencing, octree hole-scanning, realtime sync (WebSocket + QUIC + io_uring), voxel pathfinding, and AV sensor fusion.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
//! Game-map coordinate systems and world containers (feature `game`).
//!
//! Real-world tracking uses geodetic lat/lon via [`EnuConverter`](crate::coord::EnuConverter). Games use
//! arbitrary XYZ — different units, axis conventions, and origins. The
//! [`CoordSystem`] trait abstracts both so
//! [`ZoneStore`] and [`OctreeNode`] work unchanged; this module supplies the
//! common game-space implementations plus a few world containers built on top.

use std::collections::{HashMap, VecDeque};

use crate::coord::CoordSystem;
use crate::octree::OctreeNode;
use crate::store::ZoneStore;
use crate::zone::{Zone, ZoneEntry};

// ── Coordinate systems ──────────────────────────────────────────────────────

/// 1 unit = 1 metre, Z-up — a zero-cost passthrough.
#[derive(Clone, Copy, Debug, Default)]
pub struct DirectCartesian;

impl CoordSystem for DirectCartesian {
    fn to_internal(&self, p: [f64; 3]) -> [f64; 3] {
        p
    }
    fn from_internal(&self, p: [f64; 3]) -> [f64; 3] {
        p
    }
}

/// Uniformly scaled, Z-up, with an optional origin offset. E.g. Unreal Engine
/// (1 unit = 1 cm) uses `scale_to_meters = 0.01`.
#[derive(Clone, Copy, Debug)]
pub struct ScaledCartesian {
    pub scale_to_meters: f64,
    pub origin: [f64; 3],
}

impl CoordSystem for ScaledCartesian {
    fn to_internal(&self, p: [f64; 3]) -> [f64; 3] {
        std::array::from_fn(|i| (p[i] - self.origin[i]) * self.scale_to_meters)
    }
    fn from_internal(&self, p: [f64; 3]) -> [f64; 3] {
        std::array::from_fn(|i| p[i] / self.scale_to_meters + self.origin[i])
    }
}

/// Y-up game space (e.g. Unity) remapped to the internal Z-up frame.
#[derive(Clone, Copy, Debug)]
pub struct YUpCartesian {
    pub scale: f64,
}

impl CoordSystem for YUpCartesian {
    fn to_internal(&self, p: [f64; 3]) -> [f64; 3] {
        // (x, y_up, z_depth) → (x, z_depth, y_up)
        [p[0] * self.scale, p[2] * self.scale, p[1] * self.scale]
    }
    fn from_internal(&self, p: [f64; 3]) -> [f64; 3] {
        [p[0] / self.scale, p[2] / self.scale, p[1] / self.scale]
    }
}

/// 2D game (top-down / side-scroller): Z collapses onto a fixed layer.
#[derive(Clone, Copy, Debug)]
pub struct Cartesian2D {
    pub scale: f64,
    pub layer: f64,
}

impl CoordSystem for Cartesian2D {
    fn to_internal(&self, p: [f64; 3]) -> [f64; 3] {
        [p[0] * self.scale, p[1] * self.scale, self.layer]
    }
    fn from_internal(&self, p: [f64; 3]) -> [f64; 3] {
        [p[0] / self.scale, p[1] / self.scale, 0.0]
    }
}

// ── Multi-instance world ────────────────────────────────────────────────────

/// One isolated instance ("room") of a shared map template.
pub struct GameInstance {
    pub instance_id: u32,
    pub store: ZoneStore,
    pub octree: OctreeNode,
    pub coord: Box<dyn CoordSystem>,
}

/// A world of independent instances that all share a set of zone templates.
pub struct GameWorld {
    instances: HashMap<u32, GameInstance>,
    zone_templates: Vec<ZoneEntry>,
}

impl GameWorld {
    /// New world with the given shared zone templates.
    pub fn new(templates: Vec<ZoneEntry>) -> Self {
        Self { instances: HashMap::new(), zone_templates: templates }
    }

    /// Spawn an instance with its own coordinate system and world half-extent.
    pub fn spawn_instance(&mut self, id: u32, coord: Box<dyn CoordSystem>, world_half: f64) {
        let store = ZoneStore::from_entries(&self.zone_templates, coord.as_ref());
        self.instances.insert(
            id,
            GameInstance {
                instance_id: id,
                store,
                octree: OctreeNode::new([0.0; 3], world_half),
                coord,
            },
        );
    }

    /// Remove an instance.
    pub fn despawn_instance(&mut self, id: u32) {
        self.instances.remove(&id);
    }

    /// Number of live instances.
    pub fn instance_count(&self) -> usize {
        self.instances.len()
    }

    /// Query zones at a user-space position within one instance.
    pub fn query(&self, instance_id: u32, pos: [f64; 3]) -> Option<Vec<u32>> {
        let inst = self.instances.get(&instance_id)?;
        Some(inst.store.query_enu(inst.coord.to_internal(pos)).to_vec())
    }

    /// Add a zone to a single instance only.
    pub fn add_zone_to_instance(&mut self, instance_id: u32, entry: ZoneEntry) -> bool {
        let Some(inst) = self.instances.get_mut(&instance_id) else {
            return false;
        };
        inst.store.add_zone(entry.id, &entry.zone, inst.coord.as_ref());
        true
    }
}

// ── Layered (multi-floor) map ───────────────────────────────────────────────

/// Multiple floors stacked on the same XY plane — dungeons, buildings, etc.
pub struct LayeredMap {
    pub layers: HashMap<i32, ZoneStore>,
    pub coord: ScaledCartesian,
    pub floor_height: f64,
}

impl LayeredMap {
    /// New empty layered map.
    pub fn new(coord: ScaledCartesian, floor_height: f64) -> Self {
        Self { layers: HashMap::new(), coord, floor_height }
    }

    /// Which floor a user-space Z lands on.
    pub fn floor_of(&self, z_game: f64) -> i32 {
        let z_m = z_game * self.coord.scale_to_meters;
        (z_m / self.floor_height).floor() as i32
    }

    /// Add a zone to a specific floor.
    pub fn add_zone(&mut self, floor: i32, entry: ZoneEntry) {
        let coord = self.coord;
        self.layers
            .entry(floor)
            .or_insert_with(|| ZoneStore::from_entries(&[], &coord))
            .add_zone(entry.id, &entry.zone, &coord);
    }

    /// Query the current floor plus its immediate neighbours (handles the
    /// boundary case of standing on a floor seam). Each result is
    /// `(floor, zone ids on that floor)`.
    pub fn query(&self, pos: [f64; 3]) -> Vec<(i32, Vec<u32>)> {
        let floor = self.floor_of(pos[2]);
        let p = self.coord.to_internal(pos);
        [floor - 1, floor, floor + 1]
            .iter()
            .filter_map(|&f| {
                let hits = self.layers.get(&f)?.query_enu(p);
                (!hits.is_empty()).then_some((f, hits.to_vec()))
            })
            .collect()
    }
}

// ── Chunked (Minecraft-style) world ─────────────────────────────────────────

/// Integer chunk coordinate in internal metric space.
#[derive(Hash, PartialEq, Eq, Clone, Copy, Debug)]
pub struct ChunkKey {
    pub cx: i32,
    pub cy: i32,
    pub cz: i32,
}

impl ChunkKey {
    /// Which chunk an internal-space point belongs to.
    pub fn from_pos(pos: [f64; 3], chunk_size: f64) -> Self {
        Self {
            cx: (pos[0] / chunk_size).floor() as i32,
            cy: (pos[1] / chunk_size).floor() as i32,
            cz: (pos[2] / chunk_size).floor() as i32,
        }
    }

    /// Self plus the 26 surrounding chunks.
    pub fn neighbors(&self) -> Vec<ChunkKey> {
        let mut v = Vec::with_capacity(27);
        for dz in -1i32..=1 {
            for dy in -1i32..=1 {
                for dx in -1i32..=1 {
                    v.push(ChunkKey { cx: self.cx + dx, cy: self.cy + dy, cz: self.cz + dz });
                }
            }
        }
        v
    }
}

/// One loaded chunk's spatial data.
pub struct GameChunk {
    pub store: ZoneStore,
    pub octree: OctreeNode,
}

/// A lazily-loaded, LRU-evicted chunked world.
pub struct ChunkedGameWorld {
    pub chunk_size: f64,
    pub coord: Box<dyn CoordSystem>,
    pub max_chunks: usize,
    chunks: HashMap<ChunkKey, GameChunk>,
    access_order: VecDeque<ChunkKey>,
}

impl ChunkedGameWorld {
    /// New world with the given chunk edge length, coordinate system, and LRU cap.
    pub fn new(chunk_size: f64, coord: Box<dyn CoordSystem>, max_chunks: usize) -> Self {
        Self {
            chunk_size,
            coord,
            max_chunks: max_chunks.max(1),
            chunks: HashMap::new(),
            access_order: VecDeque::new(),
        }
    }

    /// Number of currently resident chunks.
    pub fn loaded_chunks(&self) -> usize {
        self.chunks.len()
    }

    fn touch(&mut self, key: ChunkKey) {
        if let Some(pos) = self.access_order.iter().position(|&k| k == key) {
            self.access_order.remove(pos);
        }
        self.access_order.push_back(key);
    }

    fn ensure_loaded(&mut self, key: ChunkKey) {
        if self.chunks.contains_key(&key) {
            self.touch(key);
            return;
        }
        if self.chunks.len() >= self.max_chunks
            && let Some(old) = self.access_order.pop_front()
        {
            self.chunks.remove(&old);
        }
        let h = self.chunk_size / 2.0;
        let origin =
            std::array::from_fn(|i| [key.cx, key.cy, key.cz][i] as f64 * self.chunk_size + h);
        self.chunks.insert(
            key,
            GameChunk {
                store: ZoneStore::from_entries(&[], self.coord.as_ref()),
                octree: OctreeNode::new(origin, h),
            },
        );
        self.access_order.push_back(key);
    }

    /// Query zones at a user-space position, loading the surrounding chunks.
    pub fn query(&mut self, pos: [f64; 3]) -> Vec<u32> {
        let p = self.coord.to_internal(pos);
        let key = ChunkKey::from_pos(p, self.chunk_size);
        key.neighbors()
            .into_iter()
            .flat_map(|k| {
                self.ensure_loaded(k);
                self.chunks.get(&k).unwrap().store.query_enu(p)
            })
            .collect()
    }

    /// Insert a point into the chunk that owns it.
    pub fn insert_point(&mut self, pos: [f64; 3]) {
        let p = self.coord.to_internal(pos);
        let key = ChunkKey::from_pos(p, self.chunk_size);
        self.ensure_loaded(key);
        self.chunks.get_mut(&key).unwrap().octree.insert(p, 8);
    }

    /// Add a zone (already in user space) to the chunk containing a reference
    /// position. Useful for attaching a zone to a known chunk.
    pub fn add_zone_at(&mut self, ref_pos: [f64; 3], entry: ZoneEntry) {
        let p = self.coord.to_internal(ref_pos);
        let key = ChunkKey::from_pos(p, self.chunk_size);
        self.ensure_loaded(key);
        let coord = &self.coord;
        self.chunks
            .get_mut(&key)
            .unwrap()
            .store
            .add_zone(entry.id, &entry.zone, coord.as_ref());
    }
}

// ── Portals ─────────────────────────────────────────────────────────────────

/// A trigger zone that teleports an entity into another space.
#[derive(Debug, Clone)]
pub struct Portal {
    pub id: u32,
    pub trigger_zone: Zone,
    pub dest_instance: u32,
    pub dest_pos: [f64; 3],
    pub dest_yaw_deg: f32,
}

/// An R-tree-indexed set of portal trigger zones.
pub struct PortalSystem {
    portals: Vec<Portal>,
    portal_store: ZoneStore,
}

impl PortalSystem {
    /// Build the system, indexing every portal's trigger zone.
    pub fn build<C: CoordSystem + ?Sized>(portals: Vec<Portal>, coord: &C) -> Self {
        let entries: Vec<ZoneEntry> = portals
            .iter()
            .map(|p| ZoneEntry::new(p.id, p.trigger_zone.clone()))
            .collect();
        Self { portal_store: ZoneStore::from_entries(&entries, coord), portals }
    }

    /// The portal a user-space position currently triggers, if any.
    pub fn check<C: CoordSystem + ?Sized>(&self, pos: [f64; 3], coord: &C) -> Option<&Portal> {
        let p = coord.to_internal(pos);
        let hits = self.portal_store.query_enu(p);
        hits.first().and_then(|&id| self.portals.iter().find(|p| p.id == id))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn scaled_cartesian_round_trip() {
        let c = ScaledCartesian { scale_to_meters: 0.01, origin: [100.0, 0.0, 0.0] };
        // 100 cm-units east of origin → (100-100)*0.01 = 0 m.
        assert_eq!(c.to_internal([100.0, 0.0, 0.0]), [0.0, 0.0, 0.0]);
        // 200 units → 1 m east.
        assert_eq!(c.to_internal([200.0, 0.0, 0.0])[0], 1.0);
        let back = c.from_internal(c.to_internal([350.0, 40.0, -8.0]));
        for i in 0..3 {
            assert!((back[i] - [350.0, 40.0, -8.0][i]).abs() < 1e-9);
        }
    }

    #[test]
    fn yup_remaps_axes() {
        let c = YUpCartesian { scale: 1.0 };
        // Unity Y-up (x=1, y=2 up, z=3 depth) → internal (1, 3, 2).
        assert_eq!(c.to_internal([1.0, 2.0, 3.0]), [1.0, 3.0, 2.0]);
        assert_eq!(c.from_internal([1.0, 3.0, 2.0]), [1.0, 2.0, 3.0]);
    }

    #[test]
    fn cartesian2d_pins_layer() {
        let c = Cartesian2D { scale: 2.0, layer: 7.0 };
        assert_eq!(c.to_internal([3.0, 4.0, 999.0]), [6.0, 8.0, 7.0]);
    }

fn unit_square_zone(id: u32) -> ZoneEntry {
    ZoneEntry::new(id, Zone::Aabb { min: [-5.0, -5.0, -100.0], max: [5.0, 5.0, 100.0] })
}

    #[test]
    fn game_world_instances_are_isolated() {
        let mut world = GameWorld::new(vec![unit_square_zone(1)]);
        world.spawn_instance(10, Box::new(DirectCartesian), 1000.0);
        world.spawn_instance(11, Box::new(DirectCartesian), 1000.0);
        assert_eq!(world.instance_count(), 2);

        // Template zone 1 is present in both instances.
        assert_eq!(world.query(10, [0.0, 0.0, 0.0]), Some(vec![1]));
        assert_eq!(world.query(11, [0.0, 0.0, 0.0]), Some(vec![1]));

        // Adding to one instance does not leak into the other.
        world.add_zone_to_instance(10, unit_square_zone(2));
        let mut a = world.query(10, [0.0, 0.0, 0.0]).unwrap();
        a.sort();
        assert_eq!(a, vec![1, 2]);
        assert_eq!(world.query(11, [0.0, 0.0, 0.0]), Some(vec![1]));

        world.despawn_instance(11);
        assert_eq!(world.instance_count(), 1);
        assert_eq!(world.query(11, [0.0, 0.0, 0.0]), None);
    }

    #[test]
    fn scaled_query_respects_units() {
        // 1 unit = 1 cm. Zone coordinates are in the same user units, so a box
        // spanning ±5 m internally must be defined at ±500 units.
        let mut world = GameWorld::new(vec![]);
        let coord = ScaledCartesian { scale_to_meters: 0.01, origin: [0.0; 3] };
        world.spawn_instance(1, Box::new(coord), 100_000.0);
        world.add_zone_to_instance(
            1,
        ZoneEntry::new(
            9,
            Zone::Aabb { min: [-500.0, -500.0, -500.0], max: [500.0, 500.0, 500.0] },
        ),
        );
        // 100 units = 1 m east → inside the ±5 m box.
        assert_eq!(world.query(1, [100.0, 0.0, 0.0]), Some(vec![9]));
        // 1000 units = 10 m east → outside.
        assert_eq!(world.query(1, [1000.0, 0.0, 0.0]), Some(vec![]));
    }

    #[test]
    fn layered_map_separates_floors() {
        let coord = ScaledCartesian { scale_to_meters: 1.0, origin: [0.0; 3] };
        let mut map = LayeredMap::new(coord, 3.0); // 3 m per floor
        map.add_zone(0, unit_square_zone(100));
        map.add_zone(1, unit_square_zone(101));

        // z = 1 m → floor 0.
        assert_eq!(map.floor_of(1.0), 0);
        // z = 4 m → floor 1.
        assert_eq!(map.floor_of(4.0), 1);

        // Standing at z=1 (floor 0) sees floor 0 and the adjacent floor 1.
        let hits = map.query([0.0, 0.0, 1.0]);
        let floors: Vec<i32> = hits.iter().map(|(f, _)| *f).collect();
        assert!(floors.contains(&0));
        assert!(floors.contains(&1));
        assert!(!floors.contains(&-1), "no zones two floors away");
    }

    #[test]
    fn chunked_world_loads_and_evicts() {
        let mut world =
            ChunkedGameWorld::new(16.0, Box::new(DirectCartesian), 4); // small LRU cap
        // Insert points spread far apart so each lands in a distinct chunk.
        for i in 0..10 {
            world.insert_point([i as f64 * 64.0, 0.0, 0.0]);
        }
        assert!(world.loaded_chunks() <= 4, "LRU cap honoured");
    }

    #[test]
    fn chunked_world_query_finds_zone() {
        let mut world = ChunkedGameWorld::new(32.0, Box::new(DirectCartesian), 64);
        world.add_zone_at([0.0, 0.0, 0.0], unit_square_zone(5));
        assert!(world.query([0.0, 0.0, 0.0]).contains(&5));
    }

    #[test]
    fn portal_triggers_inside_zone() {
        let coord = DirectCartesian;
        let portals = vec![Portal {
            id: 1,
            trigger_zone: Zone::Aabb { min: [-1.0, -1.0, -1.0], max: [1.0, 1.0, 1.0] },
            dest_instance: 99,
            dest_pos: [50.0, 0.0, 0.0],
            dest_yaw_deg: 90.0,
        }];
        let sys = PortalSystem::build(portals, &coord);
        let hit = sys.check([0.0, 0.0, 0.0], &coord).expect("inside trigger");
        assert_eq!(hit.dest_instance, 99);
        assert!(sys.check([10.0, 10.0, 10.0], &coord).is_none());
    }
}