brdb 0.5.0

A library for reading and writing Brickadia's World files.
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
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
mod reader_trait;

use indexmap::IndexSet;
pub use reader_trait::{BrFsReader, FoundFile};
use std::{
    collections::{BTreeMap, HashSet},
    fmt::Display,
    ops::Deref,
    sync::{Arc, RwLock},
};

use crate::{
    AsBrdbValue, BString, BrFsError, BrdbComponent, BrickChunkSoA, ChunkIndex, ComponentChunkSoA,
    Entity, EntityChunkIndexSoA, EntityChunkSoA, IntVector,
    assets::LiteralComponent,
    errors::{BrError, BrdbSchemaError},
    lookup_entity_struct_name,
    pending::BrPendingFs,
    schema::{BrdbSchema, BrdbSchemaGlobalData, BrdbStruct, BrdbValue, ReadBrdbSchema},
    schemas::{BRICK_COMPONENT_SOA, BRICK_WIRE_SOA, ENTITY_CHUNK_SOA},
    wrapper::schemas::{
        BRICK_CHUNK_INDEX_SOA, BRICK_CHUNK_SOA, ENTITY_CHUNK_INDEX_SOA, GLOBAL_DATA_SOA,
        OWNER_TABLE_SOA,
    },
};

pub struct BrReader<T> {
    reader: T,
    global_data: RwLock<Option<Arc<BrdbSchemaGlobalData>>>,
    owners_schema: RwLock<BTreeMap<i64, Arc<BrdbSchema>>>,
    components_schema: RwLock<BTreeMap<i64, Arc<BrdbSchema>>>,
    wires_schema: RwLock<BTreeMap<i64, Arc<BrdbSchema>>>,
    bricks_schema: RwLock<BTreeMap<i64, Arc<BrdbSchema>>>,
    brick_chunk_index_schema: RwLock<BTreeMap<i64, Arc<BrdbSchema>>>,
    entity_chunk_index_schema: RwLock<BTreeMap<i64, Arc<BrdbSchema>>>,
    entities_schema: RwLock<BTreeMap<i64, Arc<BrdbSchema>>>,
}
impl<T> Deref for BrReader<T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        &self.reader
    }
}

pub trait IntoReader {
    type Inner;
    fn into_reader(self) -> BrReader<Self::Inner>
    where
        Self: Sized;
}

impl<T> IntoReader for T
where
    T: BrFsReader,
{
    type Inner = Self;
    fn into_reader(self) -> BrReader<Self> {
        BrReader::new(self)
    }
}

#[derive(Debug, Clone, Copy)]
pub struct ChunkMeta {
    pub index: ChunkIndex,
    pub chunk_offset: IntVector,
    pub chunk_size: i32,
    pub num_bricks: u32,
    pub num_wires: u32,
    pub num_components: u32,
}
impl Deref for ChunkMeta {
    type Target = ChunkIndex;

    fn deref(&self) -> &Self::Target {
        &self.index
    }
}
impl AsRef<ChunkIndex> for ChunkMeta {
    fn as_ref(&self) -> &ChunkIndex {
        &self.index
    }
}
impl From<ChunkMeta> for ChunkIndex {
    fn from(value: ChunkMeta) -> Self {
        value.index
    }
}
impl Display for ChunkMeta {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.index)
    }
}

impl<T> BrReader<T> {
    /// Fallback name used when type/struct names are not found in global data
    const ILLEGAL_NAME: &'static str = "illegal";

    pub fn new(brdb: T) -> Self
    where
        T: BrFsReader,
    {
        Self {
            reader: brdb,
            global_data: Default::default(),
            owners_schema: Default::default(),
            components_schema: Default::default(),
            wires_schema: Default::default(),
            bricks_schema: Default::default(),
            brick_chunk_index_schema: Default::default(),
            entity_chunk_index_schema: Default::default(),
            entities_schema: Default::default(),
        }
    }

    /// Helper method to load a schema at a specific revision
    fn load_schema_rev(
        &self,
        cache: &RwLock<BTreeMap<i64, Arc<BrdbSchema>>>,
        revision: i64,
        path: &str,
        parse_fn: impl FnOnce(&mut &[u8]) -> Result<Arc<BrdbSchema>, BrError>,
    ) -> Result<Arc<BrdbSchema>, BrError>
    where
        T: BrFsReader,
    {
        // Check if we have this revision cached
        if let Some(schema) = cache.read().unwrap().get(&revision) {
            return Ok(schema.clone());
        }

        // Load the schema file
        let schema_file = self
            .find_file_by_path(path)?
            .ok_or(BrError::Fs(BrFsError::NotFound(path.to_string())))?;

        let schema_data = self.find_blob(schema_file.blob_id)?.read()?;
        let schema = parse_fn(&mut schema_data.as_slice())?;

        cache.write().unwrap().insert(revision, schema.clone());
        Ok(schema)
    }

    /// Helper method to get the latest schema, calling schema_rev if not cached
    fn get_latest_schema(
        &self,
        cache: &RwLock<BTreeMap<i64, Arc<BrdbSchema>>>,
        path: &str,
        schema_rev_fn: impl FnOnce(i64) -> Result<Arc<BrdbSchema>, BrError>,
    ) -> Result<Arc<BrdbSchema>, BrError>
    where
        T: BrFsReader,
    {
        // Check if we have the latest revision cached
        if let Some((_, schema)) = cache.read().unwrap().iter().next_back() {
            return Ok(schema.clone());
        }

        // Find the schema file to get its created_at timestamp
        let found = self
            .find_file_by_path(path)?
            .ok_or(BrError::Fs(BrFsError::NotFound(path.to_string())))?;

        schema_rev_fn(found.created_at)
    }

    /// Helper method to find a file, get its schema at the file's revision, and read the data
    fn read_mps_with_schema(
        &self,
        path: &str,
        schema_getter: impl FnOnce(i64) -> Result<Arc<BrdbSchema>, BrError>,
        struct_name: &str,
    ) -> Result<BrdbValue, BrError>
    where
        T: BrFsReader,
    {
        // Find the file and get its created_at timestamp
        let found = self
            .find_file_by_path(path)?
            .ok_or(BrError::Fs(BrFsError::NotFound(path.to_string())))?;

        // Get the schema at the file's revision
        let schema = schema_getter(found.created_at)?;

        // Read and parse the data
        let data = self.find_blob(found.blob_id)?.read()?;
        Ok(data.as_slice().read_brdb(&schema, struct_name)?)
    }

    /// Convert this filesystem to a pending filesystem with all files present
    pub fn to_pending(&self) -> Result<BrPendingFs, BrFsError>
    where
        T: BrFsReader,
    {
        self.reader.get_fs()?.to_pending(&self.reader)
    }

    /// Convert this filesystem to a pending filesystem all files in Patch mode (None for unchanged)
    pub fn to_pending_patch(&self) -> Result<BrPendingFs, BrFsError>
    where
        T: BrFsReader,
    {
        self.reader.get_fs()?.to_pending_patch()
    }

    /// Read the GlobalData
    pub fn read_global_data(&self) -> Result<Arc<BrdbSchemaGlobalData>, BrError>
    where
        T: BrFsReader,
    {
        // Parse the GlobalData schema
        let schema = self
            .read_file("World/0/GlobalData.schema")?
            .as_slice()
            .read_brdb_schema()
            .map_err(|e| e.wrap("Read GlobalData Schema"))?;

        // Parse the GlobalData struct of arrays
        let mps = self
            .read_file("World/0/GlobalData.mps")?
            .as_slice()
            .read_brdb(&schema, GLOBAL_DATA_SOA)
            .map_err(|e| e.wrap("Read BRSavedGlobalDataSoA"))?;

        let mps_struct = mps.as_struct()?;

        let str_set = |prop| {
            mps_struct
                .prop(prop)?
                .as_array()?
                .into_iter()
                .map(|s| Ok(s.as_str()?.to_owned()))
                .collect::<Result<IndexSet<String>, BrdbSchemaError>>()
        };
        let str_vec = |prop| {
            mps_struct
                .prop(prop)?
                .as_array()?
                .into_iter()
                .map(|s| Ok(s.as_str()?.to_owned()))
                .collect::<Result<Vec<String>, BrdbSchemaError>>()
        };

        // Extract the asset names and types from the data
        let mut external_asset_types = HashSet::new();
        let external_asset_references = mps_struct
            .prop("ExternalAssetReferences")?
            .as_array()?
            .into_iter()
            .map(|s| {
                let s = s.as_struct()?;
                let asset_type = s.prop("PrimaryAssetType")?.as_str()?;
                let asset_name = s.prop("PrimaryAssetName")?.as_str()?;
                external_asset_types.insert(asset_type.to_owned());
                Ok((asset_type.to_owned(), asset_name.to_owned()))
            })
            .collect::<Result<IndexSet<_>, BrdbSchemaError>>()?;

        let entity_type_names = str_set("EntityTypeNames")?;

        Ok(Arc::new(BrdbSchemaGlobalData {
            external_asset_types,
            external_asset_references,
            // Handle entity data class names fallback
            entity_data_class_names: if mps_struct.contains_key("EntityDataClassNames") {
                str_set("EntityDataClassNames")?
            } else {
                entity_type_names
                    .iter()
                    .map(|n| lookup_entity_struct_name(n).unwrap_or("Unknown").to_owned())
                    .collect()
            },
            entity_type_names,
            basic_brick_asset_names: str_set("BasicBrickAssetNames")?,
            procedural_brick_asset_names: str_set("ProceduralBrickAssetNames")?,
            material_asset_names: str_set("MaterialAssetNames")?,
            component_type_names: str_set("ComponentTypeNames")?,
            component_data_struct_names: str_vec("ComponentDataStructNames")?,
            component_wire_port_names: str_set("ComponentWirePortNames")?,
        }))
    }

    /// Read and cache the GlobalData
    pub fn global_data(&self) -> Result<Arc<BrdbSchemaGlobalData>, BrError>
    where
        T: BrFsReader,
    {
        if let Some(data) = self.global_data.read().unwrap().as_ref() {
            return Ok(data.clone());
        }
        let data = self.read_global_data()?;
        self.global_data.write().unwrap().replace(data.clone());
        Ok(data)
    }
    /// Read the Owners table
    pub fn owners_soa(&self) -> Result<BrdbStruct, BrError>
    where
        T: BrFsReader,
    {
        let owners_data = self.read_mps_with_schema(
            "World/0/Owners.mps",
            |rev| self.owners_schema_rev(rev),
            OWNER_TABLE_SOA,
        )?;
        match owners_data {
            BrdbValue::Struct(s) => Ok(*s),
            ty => Err(BrError::Schema(BrdbSchemaError::ExpectedType(
                "Struct".to_string(),
                ty.get_type().to_owned(),
            ))),
        }
    }
    /// Read the Owners schema at a specific revision
    pub fn owners_schema_rev(&self, revision: i64) -> Result<Arc<BrdbSchema>, BrError>
    where
        T: BrFsReader,
    {
        self.load_schema_rev(
            &self.owners_schema,
            revision,
            "World/0/Owners.schema",
            |data| Ok(data.read_brdb_schema()?),
        )
    }

    /// Read the Owners schema (latest revision)
    pub fn owners_schema(&self) -> Result<Arc<BrdbSchema>, BrError>
    where
        T: BrFsReader,
    {
        self.get_latest_schema(&self.owners_schema, "World/0/Owners.schema", |rev| {
            self.owners_schema_rev(rev)
        })
    }
    /// Read the shared components chunk schema at a specific revision
    pub fn components_schema_rev(&self, revision: i64) -> Result<Arc<BrdbSchema>, BrError>
    where
        T: BrFsReader,
    {
        let global_data = self.global_data()?;
        self.load_schema_rev(
            &self.components_schema,
            revision,
            "World/0/Bricks/ComponentsShared.schema",
            |data| Ok(data.read_brdb_schema_with_data(global_data)?),
        )
    }

    /// Read the shared components chunk schema (latest revision)
    pub fn components_schema(&self) -> Result<Arc<BrdbSchema>, BrError>
    where
        T: BrFsReader,
    {
        self.get_latest_schema(
            &self.components_schema,
            "World/0/Bricks/ComponentsShared.schema",
            |rev| self.components_schema_rev(rev),
        )
    }

    /// Read the shared component chunks
    pub fn component_chunk_soa(
        &self,
        grid_id: usize,
        chunk: ChunkIndex,
    ) -> Result<(ComponentChunkSoA, Vec<BrdbStruct>), BrError>
    where
        T: BrFsReader,
    {
        self.component_chunk(grid_id, chunk)
    }

    /// Read the shared component chunks
    pub fn component_chunk(
        &self,
        grid_id: usize,
        chunk: ChunkIndex,
    ) -> Result<(ComponentChunkSoA, Vec<BrdbStruct>), BrError>
    where
        T: BrFsReader,
    {
        let global_data = self.global_data()?;

        let path = format!("World/0/Bricks/Grids/{grid_id}/Components/{chunk}.mps");
        let found = self
            .find_file_by_path(&path)?
            .ok_or(BrError::Fs(BrFsError::NotFound(path.clone())))?;

        let schema = self.components_schema_rev(found.created_at)?;
        let buf = self.find_blob(found.blob_id)?.read()?;
        let buf = &mut buf.as_slice();

        let mps = buf.read_brdb(&schema, BRICK_COMPONENT_SOA)?;
        let soa = ComponentChunkSoA::try_from(&mps)
            .map_err(|e| e.wrap(format!("Read component chunk {chunk}")))?;

        let mut component_data = Vec::new();
        for counter in &soa.component_type_counters {
            let type_idx = counter.type_index as usize;
            let type_name = global_data
                .component_type_names
                .get_index(type_idx)
                .cloned()
                .unwrap_or_else(|| Self::ILLEGAL_NAME.to_string());
            let struct_name = global_data
                .component_data_struct_names
                .get(type_idx)
                .cloned()
                .unwrap_or_else(|| Self::ILLEGAL_NAME.to_string());

            if struct_name == "None" {
                continue;
            }

            for i in 0..counter.num_instances {
                let BrdbValue::Struct(s) = buf
                    .read_brdb(&schema, &struct_name)
                    .map_err(|e| e.wrap(format!("Read component {i} {type_name}/{struct_name}")))?
                else {
                    continue;
                };
                component_data.push(*s);
            }
        }
        Ok((soa, component_data))
    }

    /// Read the shared wires chunk schema at a specific revision
    pub fn wires_schema_rev(&self, revision: i64) -> Result<Arc<BrdbSchema>, BrError>
    where
        T: BrFsReader,
    {
        self.load_schema_rev(
            &self.wires_schema,
            revision,
            "World/0/Bricks/WiresShared.schema",
            |data| Ok(data.read_brdb_schema()?),
        )
    }

    /// Read the shared wires chunk schema (latest revision)
    pub fn wires_schema(&self) -> Result<Arc<BrdbSchema>, BrError>
    where
        T: BrFsReader,
    {
        self.get_latest_schema(
            &self.wires_schema,
            "World/0/Bricks/WiresShared.schema",
            |rev| self.wires_schema_rev(rev),
        )
    }
    pub fn wire_chunk_soa(&self, grid_id: usize, chunk: ChunkIndex) -> Result<BrdbStruct, BrError>
    where
        T: BrFsReader,
    {
        let path = format!("World/0/Bricks/Grids/{grid_id}/Wires/{chunk}.mps");
        let mps =
            self.read_mps_with_schema(&path, |rev| self.wires_schema_rev(rev), BRICK_WIRE_SOA)?;
        match mps {
            BrdbValue::Struct(s) => Ok(*s),
            ty => Err(BrError::Schema(BrdbSchemaError::ExpectedType(
                "Struct".to_string(),
                ty.get_type().to_owned(),
            ))),
        }
    }
    /// Read the shared brick-chunk-index schema at a specific revision
    pub fn brick_chunk_index_schema_rev(&self, revision: i64) -> Result<Arc<BrdbSchema>, BrError>
    where
        T: BrFsReader,
    {
        self.load_schema_rev(
            &self.brick_chunk_index_schema,
            revision,
            "World/0/Bricks/ChunkIndexShared.schema",
            |data| Ok(data.read_brdb_schema()?),
        )
    }

    /// Read the shared brick-chunk-index schema (latest revision)
    pub fn brick_chunk_index_schema(&self) -> Result<Arc<BrdbSchema>, BrError>
    where
        T: BrFsReader,
    {
        self.get_latest_schema(
            &self.brick_chunk_index_schema,
            "World/0/Bricks/ChunkIndexShared.schema",
            |rev| self.brick_chunk_index_schema_rev(rev),
        )
    }
    /// Read the shared bricks chunk schema at a specific revision
    pub fn bricks_schema_rev(&self, revision: i64) -> Result<Arc<BrdbSchema>, BrError>
    where
        T: BrFsReader,
    {
        self.load_schema_rev(
            &self.bricks_schema,
            revision,
            "World/0/Bricks/ChunksShared.schema",
            |data| Ok(data.read_brdb_schema()?),
        )
    }

    /// Read the shared bricks chunk schema (latest revision)
    pub fn bricks_schema(&self) -> Result<Arc<BrdbSchema>, BrError>
    where
        T: BrFsReader,
    {
        self.get_latest_schema(
            &self.bricks_schema,
            "World/0/Bricks/ChunksShared.schema",
            |rev| self.bricks_schema_rev(rev),
        )
    }
    /// Read the brick chunk indices for a specific grid
    pub fn brick_chunk_index(&self, grid_id: usize) -> Result<Vec<ChunkMeta>, BrError>
    where
        T: BrFsReader,
    {
        let path = format!("World/0/Bricks/Grids/{grid_id}/ChunkIndex.mps");
        let brick_index = self.read_mps_with_schema(
            &path,
            |rev| self.brick_chunk_index_schema_rev(rev),
            BRICK_CHUNK_INDEX_SOA,
        )?;
        let num_bricks = brick_index.prop("NumBricks")?;
        let num_wires = brick_index.prop("NumWires")?;
        let num_components = brick_index.prop("NumComponents")?;
        let chunk_offsets = brick_index
            .contains_key("ChunkOffsets")
            .then(|| brick_index.prop("ChunkOffsets"))
            .transpose()?;
        let chunk_sizes = brick_index
            .contains_key("ChunkSizes")
            .then(|| brick_index.prop("ChunkSizes"))
            .transpose()?;

        let chunk_indices = brick_index
            .prop("Chunk3DIndices")?
            .as_array()?
            .into_iter()
            .enumerate()
            .map(|(i, s)| {
                Ok(ChunkMeta {
                    index: s.try_into()?,
                    chunk_offset: chunk_offsets
                        .map(|f| f.index_unwrap(i)?.try_into())
                        .transpose()?
                        // Defaults for old worlds
                        .unwrap_or_else(|| IntVector::new(1024, 1024, 1024)),
                    chunk_size: chunk_sizes
                        .map(|f| f.index_unwrap(i)?.as_brdb_i32())
                        .transpose()?
                        // Defaults for old worlds
                        .unwrap_or(2048),
                    num_bricks: num_bricks.index_unwrap(i)?.as_brdb_u32()?,
                    num_wires: num_wires.index_unwrap(i)?.as_brdb_u32()?,
                    num_components: num_components.index_unwrap(i)?.as_brdb_u32()?,
                })
            })
            .collect::<Result<Vec<_>, BrdbSchemaError>>()?;
        Ok(chunk_indices)
    }
    pub fn brick_chunk_soa(
        &self,
        grid_id: usize,
        chunk: ChunkIndex,
    ) -> Result<BrickChunkSoA, BrError>
    where
        T: BrFsReader,
    {
        let path = format!("World/0/Bricks/Grids/{grid_id}/Chunks/{chunk}.mps");
        let mps =
            self.read_mps_with_schema(&path, |rev| self.bricks_schema_rev(rev), BRICK_CHUNK_SOA)?;
        Ok((&mps).try_into()?)
    }
    /// Read the shared entity chunk schema at a specific revision
    pub fn entities_schema_rev(&self, revision: i64) -> Result<Arc<BrdbSchema>, BrError>
    where
        T: BrFsReader,
    {
        let global_data = self.global_data()?;
        self.load_schema_rev(
            &self.entities_schema,
            revision,
            "World/0/Entities/ChunksShared.schema",
            |data| Ok(data.read_brdb_schema_with_data(global_data)?),
        )
    }

    /// Read the shared entity chunk schema (latest revision)
    pub fn entities_schema(&self) -> Result<Arc<BrdbSchema>, BrError>
    where
        T: BrFsReader,
    {
        self.get_latest_schema(
            &self.entities_schema,
            "World/0/Entities/ChunksShared.schema",
            |rev| self.entities_schema_rev(rev),
        )
    }
    /// Read the entity chunk index schema at a specific revision
    pub fn entities_chunk_index_schema_rev(&self, revision: i64) -> Result<Arc<BrdbSchema>, BrError>
    where
        T: BrFsReader,
    {
        self.load_schema_rev(
            &self.entity_chunk_index_schema,
            revision,
            "World/0/Entities/ChunkIndex.schema",
            |data| Ok(data.read_brdb_schema()?),
        )
    }

    /// Read the entity chunk index schema (latest revision)
    pub fn entities_chunk_index_schema(&self) -> Result<Arc<BrdbSchema>, BrError>
    where
        T: BrFsReader,
    {
        self.get_latest_schema(
            &self.entity_chunk_index_schema,
            "World/0/Entities/ChunkIndex.schema",
            |rev| self.entities_chunk_index_schema_rev(rev),
        )
    }

    /// Read the entity chunk indices
    pub fn entity_chunk_index(&self) -> Result<Vec<ChunkIndex>, BrError>
    where
        T: BrFsReader,
    {
        let entities_index = self.read_mps_with_schema(
            "World/0/Entities/ChunkIndex.mps",
            |rev| self.entities_chunk_index_schema_rev(rev),
            ENTITY_CHUNK_INDEX_SOA,
        )?;
        Ok(entities_index.prop("Chunk3DIndices")?.try_into()?)
    }

    /// Read the entity chunk indices
    pub fn entity_chunk_index_soa(&self) -> Result<EntityChunkIndexSoA, BrError>
    where
        T: BrFsReader,
    {
        let entities_index = self.read_mps_with_schema(
            "World/0/Entities/ChunkIndex.mps",
            |rev| self.entities_chunk_index_schema_rev(rev),
            ENTITY_CHUNK_INDEX_SOA,
        )?;
        Ok((&entities_index).try_into()?)
    }

    pub fn entity_chunk(&self, chunk: ChunkIndex) -> Result<Vec<Entity>, BrError>
    where
        T: BrFsReader,
    {
        let global_data = self.global_data()?;

        let path = format!("World/0/Entities/Chunks/{chunk}.mps");
        let found = self
            .find_file_by_path(&path)?
            .ok_or(BrError::Fs(BrFsError::NotFound(path.clone())))?;

        let schema = self.entities_schema_rev(found.created_at)?;
        let buf = self.find_blob(found.blob_id)?.read()?;
        let buf = &mut buf.as_slice();

        let mps = buf
            .read_brdb(&schema, ENTITY_CHUNK_SOA)
            .map_err(|e| e.wrap(format!("Read entity chunk {chunk}")))?;
        let soa = EntityChunkSoA::try_from(&mps)
            .map_err(|e| e.wrap(format!("Read entity chunk {chunk}")))?;

        let illegal = Self::ILLEGAL_NAME.to_string();
        let mut entity_data = Vec::new();
        let mut index = 0;

        for counter in soa.type_counters {
            let type_name = global_data
                .entity_type_names
                .get_index(counter.type_index as usize)
                .unwrap_or(&illegal);

            let struct_name = global_data
                .entity_data_class_names
                .get_index(counter.type_index as usize);

            for i in 0..counter.num_entities {
                let data: Arc<Box<dyn BrdbComponent>> = if let Some(struct_name) = struct_name {
                    let value = buf.read_brdb(&schema, struct_name).map_err(|e| {
                        e.wrap(format!("Read entity {i} {type_name}/{struct_name}"))
                    })?;
                    let component = LiteralComponent::new_from_data(
                        type_name,
                        struct_name,
                        None,
                        Arc::new(value.as_struct()?.as_hashmap()?),
                        [],
                    );
                    Arc::new(Box::new(component))
                } else {
                    Arc::new(Box::new(()))
                };

                entity_data.push(Entity {
                    asset: BString::from(type_name),
                    id: Some(soa.persistent_indices[index] as usize),
                    owner_index: Some(soa.owner_indices[index]),
                    location: soa.locations[index],
                    rotation: soa.rotations[index],
                    velocity: soa.linear_velocities[index],
                    angular_velocity: soa.angular_velocities[index],
                    color_and_alpha: soa.colors_and_alphas[index].clone(),
                    frozen: soa.physics_locked_flags.get(index),
                    sleeping: soa.physics_sleeping_flags.get(index),
                    data,
                });
                index += 1;
            }
        }
        Ok(entity_data)
    }

    pub fn entity_chunk_soa(
        &self,
        chunk: ChunkIndex,
    ) -> Result<(EntityChunkSoA, Vec<Option<BrdbStruct>>), BrError>
    where
        T: BrFsReader,
    {
        let path = format!("World/0/Entities/Chunks/{chunk}.mps");
        let found = self
            .find_file_by_path(&path)?
            .ok_or(BrError::Fs(BrFsError::NotFound(path.clone())))?;

        let schema = self.entities_schema_rev(found.created_at)?;
        let buf = self.find_blob(found.blob_id)?.read()?;
        let buf = &mut buf.as_slice();
        let mps = buf.read_brdb(&schema, ENTITY_CHUNK_SOA)?;
        let soa = EntityChunkSoA::try_from(&mps)
            .map_err(|e| e.wrap(format!("Read entity chunk {chunk}")))?;
        let global_data = self.global_data()?;
        let illegal = Self::ILLEGAL_NAME.to_string();

        let mut entity_data = Vec::new();

        for counter in &soa.type_counters {
            let type_name = global_data
                .entity_type_names
                .get_index(counter.type_index as usize)
                .unwrap_or(&illegal);

            let Some(struct_name) = global_data
                .entity_data_class_names
                .get_index(counter.type_index as usize)
            else {
                entity_data.push(None);
                continue;
            };
            if struct_name == "None" {
                entity_data.push(None);
                continue;
            }

            for i in 0..counter.num_entities {
                let BrdbValue::Struct(s) = buf
                    .read_brdb(&schema, struct_name)
                    .map_err(|e| e.wrap(format!("Read entity {i} {type_name}/{struct_name}")))?
                else {
                    continue;
                };

                entity_data.push(Some(*s));
            }
        }

        Ok((soa, entity_data))
    }
}