project-wormhole-esm 0.1.0

ESM file format parser for Project Wormhole
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
use std::{fmt::Debug, io::Read};


use crate::{dev::*, records::all::*};
use bitflags::bitflags;


// ====================================================================================================

#[derive(Debug, NomLE)]
pub struct RecordHeader {
    pub iden: FourCC,
    pub size: u32, // Size NOT INCLUDING header, unlike GroupHeader
    pub flags: RecordFlags2,
    pub form_id: FormId,
    pub version_control: VersionControl,
}

// ====================================================================================================

// The information contained in the version control structure appears to be used by a custom Perforce VCM
#[derive(Debug, NomLE)]
pub struct VersionControl {
    pub timestamp: ESMTimestamp,
    pub users: [u8; 2],
    pub form: u16,
    pub revision: u16,
}

impl From<[u8; 8]> for VersionControl {
    fn from(value: [u8; 8]) -> Self {
        Self {
            timestamp: ESMTimestamp(u16::from_le_bytes([value[0], value[1]])),
            users: [value[2], value[3]],
            form: u16::from_le_bytes([value[4], value[5]]),
            revision: u16::from_le_bytes([value[6], value[7]]),
        }
    }
}


// ====================================================================================================



// Assuming the timestamp is the same in Fallout 4 as SkyrimSE
#[derive(NomLE)]
pub struct ESMTimestamp(pub u16);

impl std::fmt::Debug for ESMTimestamp {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {

        // Shift over to keep only the year
        let year = self.0   >>   9;

        // Shift over to keep only the month
        // Not working properly, some months are showing as 0
        let month = self.0  >> 5 & 0b00000001111;

        // Mask to keep only the day
        let day = self.0    &   0b0000000000011111;

        write!(f, "{:04}/{:02}/{:02}", year + 2000, month, day)
    }
}

// ====================================================================================================

// Flag positions

// 0x00000001	(TES4) Master (ESM) file
pub const TES4_MASTER: u32 = 0x1;

// 0x00000002
pub const UNKNOWN_FLAG_2: u32 = 0x2;

// 0x00000004
pub const UNKNOWN_FLAG_4: u32 = 0x4;

// 0x00000010	Deleted Group (bugged, see Groups)]
pub const DELETED_GROUP: u32 = 0x10;

// 0x00000020	Deleted Record
pub const DELETED_RECORD: u32 = 0x20;

// 0x00000040
// (GLOB) Constant
// (REFR) Hidden From Local Map (Needs Confirmation: Related to shields)
pub const GLOB_CONSTANT: u32 = 0x40;
pub const REFR_HIDDEN: u32 = 0x40;

// 0x00000080	(TES4) Localized - this will make Skyrim load the .STRINGS, .DLSTRINGS, and .ILSTRINGS files associated with the mod. If this flag is not set, lstrings are treated as zstrings.
pub const TES4_LOCALIZED: u32 = 0x80;

// 0x00000100	Must Update Anims
// (REFR) Inaccessible
pub const MUST_UPDATE_ANIMS: u32 = 0x100;
pub const REFR_INACCESSIBLE: u32 = 0x100;

// 0x00000200
// (TES4) Light Master (ESL) File. Data File
// (REFR) Hidden from local map
// (ACHR) Starts dead
// (REFR) MotionBlurCastsShadows
pub const TES4_LIGHT_MASTER: u32 = 0x200;
pub const REFR_HIDDEN2: u32 = 0x200;
pub const ACHR_STARTS_DEAD: u32 = 0x200;
pub const REFR_MOTION_BLUR_CASTS_SHADOWS: u32 = 0x200;

// 0x00000400
// Quest item
// Persistent reference
// (LSCR) Displays in Main Menu
pub const QUEST_ITEM: u32 = 0x400;
pub const PERSISTENT_REFERENCE: u32 = 0x400;
pub const LSCR_DISPLAYS_IN_MAIN_MENU: u32 = 0x400;

// 0x00000800	Initially disabled
pub const INITIALLY_DISABLED: u32 = 0x800;

// 0x00001000	Ignored
pub const IGNORED: u32 = 0x1000;

// 0x00002000
pub const UNKNOWN_FLAG_2000: u32 = 0x2000;

// 0x00008000	Visible when distant
pub const VISIBLE_WHEN_DISTANT: u32 = 0x8000;

// 0x00010000	(ACTI) Random Animation Start
pub const ACTI_RANDOM_ANIMATION_START: u32 = 0x10000;

// 0x00020000
// (ACTI) Dangerous
// Off limits (Interior cell)
// Dangerous Can't be set without Ignore Object Interaction
pub const ACTI_DANGEROUS: u32 = 0x20000;
pub const OFF_LIMITS: u32 = 0x20000;

// 0x00040000	Data is compressed
pub const COMPRESSED: u32 = 0x40000;

// 0x00080000	Can't wait
pub const CANT_WAIT: u32 = 0x80000;

// 0x00100000
// (ACTI) Ignore Object Interaction
// Ignore Object Interaction Sets Dangerous Automatically
pub const ACTI_IGNORE_OBJECT_INTERACTION: u32 = 0x100000;

// 0x00800000	Is Marker
pub const IS_MARKER: u32 = 0x800000;

// 0x02000000
// (ACTI) Obstacle
// (REFR) No AI Acquire
pub const ACTI_OBSTACLE: u32 = 0x2000000;
pub const REFR_NO_AI_ACQUIRE: u32 = 0x2000000;

// 0x04000000	NavMesh Gen - Filter
pub const NAVMESH_GEN_FILTER: u32 = 0x4000000;

// 0x08000000	NavMesh Gen - Bounding Box
pub const NAVMESH_GEN_BOUNDING_BOX: u32 = 0x8000000;

// 0x10000000
// (FURN) Must Exit to Talk
// (REFR) Reflected By Auto Water
pub const FURN_MUST_EXIT_TO_TALK: u32 = 0x10000000;
pub const REFR_REFLECTED_BY_AUTO_WATER: u32 = 0x10000000;

// 0x20000000
// (FURN/IDLM) Child Can Use
// (REFR) Don't Havok Settle
pub const FURN_CHILD_CAN_USE: u32 = 0x20000000;
pub const IDLM_CHILD_CAN_USE: u32 = 0x20000000;
pub const REFR_DONT_HAVOK_SETTLE: u32 = 0x20000000;

// 0x40000000
// NavMesh Gen - Ground
// (REFR) NoRespawn
pub const NAVMESH_GEN_GROUND: u32 = 0x40000000;
pub const REFR_NORESPAWN: u32 = 0x40000000;

// 0x80000000	(REFR) MultiBound
pub const REFR_MULTIBOUND: u32 = 0x80000000;

// #[derive(Clone, Copy, NomLE)]
// pub struct RecordFlags2(pub u32);

// impl std::fmt::Debug for RecordFlags2 {
//     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
//         if self.has_flags() {
//             let mut flags = Vec::new();
//             if self.has_flag(TES4_MASTER) {
//                 flags.push("TES4_MASTER")
//             }
//             if self.has_flag(UNKNOWN_FLAG_2) {
//                 flags.push("UNKNOWN_FLAG_2")
//             }
//             if self.has_flag(UNKNOWN_FLAG_4) {
//                 flags.push("UNKNOWN_FLAG_4")
//             }
//             if self.has_flag(DELETED_GROUP) {
//                 flags.push("DELETED_GROUP")
//             }
//             if self.has_flag(DELETED_RECORD) {
//                 flags.push("DELETED_RECORD")
//             }
//             if self.has_flag(GLOB_CONSTANT) {
//                 flags.push("GLOB_CONSTANT")
//             }
//             if self.has_flag(REFR_HIDDEN) {
//                 flags.push("REFR_HIDDEN")
//             }
//             if self.has_flag(TES4_LOCALIZED) {
//                 flags.push("TES4_LOCALIZED")
//             }
//             if self.has_flag(MUST_UPDATE_ANIMS) {
//                 flags.push("MUST_UPDATE_ANIMS")
//             }
//             if self.has_flag(REFR_INACCESSIBLE) {
//                 flags.push("REFR_INACCESSIBLE")
//             }
//             if self.has_flag(TES4_LIGHT_MASTER) {
//                 flags.push("TES4_LIGHT_MASTER")
//             }
//             if self.has_flag(REFR_HIDDEN2) {
//                 flags.push("REFR_HIDDEN2")
//             }
//             if self.has_flag(ACHR_STARTS_DEAD) {
//                 flags.push("ACHR_STARTS_DEAD")
//             }
//             if self.has_flag(REFR_MOTION_BLUR_CASTS_SHADOWS) {
//                 flags.push("REFR_MOTION_BLUR_CASTS_SHADOWS")
//             }
//             if self.has_flag(QUEST_ITEM) {
//                 flags.push("QUEST_ITEM")
//             }
//             if self.has_flag(PERSISTENT_REFERENCE) {
//                 flags.push("PERSISTENT_REFERENCE")
//             }
//             if self.has_flag(LSCR_DISPLAYS_IN_MAIN_MENU) {
//                 flags.push("LSCR_DISPLAYS_IN_MAIN_MENU")
//             }
//             if self.has_flag(INITIALLY_DISABLED) {
//                 flags.push("INITIALLY_DISABLED")
//             }
//             if self.has_flag(IGNORED) {
//                 flags.push("IGNORED")
//             }
//             if self.has_flag(UNKNOWN_FLAG_2000) {
//                 flags.push("UNKNOWN_FLAG_2000")
//             }
//             if self.has_flag(VISIBLE_WHEN_DISTANT) {
//                 flags.push("VISIBLE_WHEN_DISTANT")
//             }
//             if self.has_flag(ACTI_RANDOM_ANIMATION_START) {
//                 flags.push("ACTI_RANDOM_ANIMATION_START")
//             }
//             if self.has_flag(ACTI_DANGEROUS) {
//                 flags.push("ACTI_DANGEROUS")
//             }
//             if self.has_flag(OFF_LIMITS) {
//                 flags.push("OFF_LIMITS")
//             }
//             if self.has_flag(COMPRESSED) {
//                 flags.push("COMPRESSED")
//             }
//             if self.has_flag(CANT_WAIT) {
//                 flags.push("CANT_WAIT")
//             }
//             if self.has_flag(ACTI_IGNORE_OBJECT_INTERACTION) {
//                 flags.push("ACTI_IGNORE_OBJECT_INTERACTION")
//             }

//             if self.has_flag(IS_MARKER) {
//                 flags.push("IS_MARKER")
//             }
//             if self.has_flag(ACTI_OBSTACLE) {
//                 flags.push("ACTI_OBSTACLE")
//             }
//             if self.has_flag(REFR_NO_AI_ACQUIRE) {
//                 flags.push("REFR_NO_AI_ACQUIRE")
//             }
//             if self.has_flag(NAVMESH_GEN_FILTER) {
//                 flags.push("NAVMESH_GEN_FILTER")
//             }
//             if self.has_flag(NAVMESH_GEN_BOUNDING_BOX) {
//                 flags.push("NAVMESH_GEN_BOUNDING_BOX")
//             }
//             if self.has_flag(FURN_MUST_EXIT_TO_TALK) {
//                 flags.push("FURN_MUST_EXIT_TO_TALK")
//             }
//             if self.has_flag(REFR_REFLECTED_BY_AUTO_WATER) {
//                 flags.push("REFR_REFLECTED_BY_AUTO_WATER")
//             }
//             if self.has_flag(FURN_CHILD_CAN_USE) {
//                 flags.push("FURN_CHILD_CAN_USE")
//             }
//             if self.has_flag(IDLM_CHILD_CAN_USE) {
//                 flags.push("IDLM_CHILD_CAN_USE")
//             }
//             if self.has_flag(REFR_DONT_HAVOK_SETTLE) {
//                 flags.push("REFR_DONT_HAVOK_SETTLE")
//             }
//             if self.has_flag(NAVMESH_GEN_GROUND) {
//                 flags.push("NAVMESH_GEN_GROUND")
//             }
//             if self.has_flag(REFR_NORESPAWN) {
//                 flags.push("REFR_NORESPAWN")
//             }
//             if self.has_flag(REFR_MULTIBOUND) {
//                 flags.push("REFR_MULTIBOUND")
//             }
//             if flags.is_empty() {
//                 panic!("Unrecognized flags: {:x}", self.0)
//             } else {
//                 write!(f, "{}", flags.join(", "))
//             }
//         } else {
//             write!(f, "NONE")
//         }
//     }
// }

// impl RecordFlags2 {
//     pub fn has_flags(&self) -> bool {
//         self.0 != 0
//     }
//     pub fn has_flag(&self, flag: u32) -> bool {
//         (self.0 & flag) != 0
//     }
//     pub fn is_compressed(&self) -> bool {
//         self.has_flag(COMPRESSED)
//     }
// }

bitflags! {
    /// Represents a set of flags.
    #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
    pub struct RecordFlags2: u32 {
        /// The value `A`, at bit position `0`.
        
        /// The data is compressed.
        const COMPRESSED = 0x00040000;

        const TES4_MASTER = 0x1;
        const UNKNOWN_FLAG_2 = 0x2;
        const UNKNOWN_FLAG_4 = 0x4;
        const DELETED_GROUP = 0x10;
        const DELETED_RECORD = 0x20;
        const GLOB_CONSTANT = 0x40;
        const REFR_HIDDEN = 0x40;
        const TES4_LOCALIZED = 0x80;
        const MUST_UPDATE_ANIMS = 0x100;
        const REFR_INACCESSIBLE = 0x100;
        const TES4_LIGHT_MASTER = 0x200;
        const REFR_HIDDEN2 = 0x200;
        const ACHR_STARTS_DEAD = 0x200;
        const REFR_MOTION_BLUR_CASTS_SHADOWS = 0x200;
        const QUEST_ITEM = 0x400;
        const PERSISTENT_REFERENCE = 0x400;
        const LSCR_DISPLAYS_IN_MAIN_MENU = 0x400;
        const INITIALLY_DISABLED = 0x800;
        const IGNORED = 0x1000;
        const UNKNOWN_FLAG_2000 = 0x2000;
        const VISIBLE_WHEN_DISTANT = 0x8000;
        const ACTI_RANDOM_ANIMATION_START = 0x10000;
        const ACTI_DANGEROUS = 0x20000;
        const OFF_LIMITS = 0x20000;
        const CANT_WAIT = 0x80000;
        const ACTI_IGNORE_OBJECT_INTERACTION = 0x100000;
        const IS_MARKER = 0x800000;
        const ACTI_OBSTACLE = 0x2000000;
        const REFR_NO_AI_ACQUIRE = 0x2000000;
        const NAVMESH_GEN_FILTER = 0x4000000;
        const NAVMESH_GEN_BOUNDING_BOX = 0x8000000;
        const FURN_MUST_EXIT_TO_TALK = 0x10000000;
        const REFR_REFLECTED_BY_AUTO_WATER = 0x10000000;
        const FURN_CHILD_CAN_USE = 0x20000000;
        const IDLM_CHILD_CAN_USE = 0x20000000;
        const REFR_DONT_HAVOK_SETTLE = 0x20000000;
        const NAVMESH_GEN_GROUND = 0x40000000;
        const REFR_NORESPAWN = 0x40000000;
        const REFR_MULTIBOUND = 0x80000000;
    }
}

impl<'esm> Parse<&'esm[u8]> for RecordFlags2 {
    fn parse(i: &'esm[u8]) -> IResult<&'esm[u8], Self, nom::error::Error<&'esm[u8]>> {
        let (i, raw_flags) = le_u32::<&'esm[u8], nom::error::Error<&'esm[u8]>>(i)?;
        Ok((i, RecordFlags2::from_bits_retain(raw_flags)))
    }
}

impl RecordFlags2 {

    pub fn is_compressed(&self) -> bool {
        self.contains(RecordFlags2::COMPRESSED)
    }
}


// ====================================================================================================

pub struct RawRecord<'esm> {
    pub header: RecordHeader,
    pub data: RawRecordData<'esm>,
}

impl<'esm> Parse<&'esm [u8]> for RawRecord<'esm> {
    fn parse(i: &'esm[u8]) -> IResult<&'esm[u8], Self> {
        let (i, (header, data)) = alloc_record(i)?;

        if header.flags.is_compressed() {
            if let Ok(dec) = decompress_record(data) {
                Ok((i, Self{ header, data: RawRecordData::Decompressed(dec) }))
            } else {
                panic!("Could not decompress record: {:?}", header);
            }
            
        } else {
            Ok((i, Self{ header, data: RawRecordData::Pointer(data) }))
        }
    }
}


impl Debug for RawRecord<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "RawRecord {{ header: {:?}, data: [{} bytes]}}",
            self.header,
            self.data.len()
        )
    }
}

impl RawRecord<'_> {
    pub fn get_raw_fields(&self) -> IResult<&[u8], Vec<RawField<'_>>, nom::error::Error<&[u8]>> {
        match &self.data {
            RawRecordData::Pointer(data) => {
                many0(RawField::parse)(data)
            }
            RawRecordData::Decompressed(data) => {
                many0(RawField::parse)(data)
            }
        }
    }   
}

#[derive(Debug)]
pub enum RawRecordData<'esm> {
    Pointer(&'esm[u8]),
    Decompressed(Vec<u8>)
}

impl RawRecordData<'_> {
    pub fn len(&self) -> usize {
        match self {
            RawRecordData::Pointer(items) => items.len(),
            RawRecordData::Decompressed(items) => items.len(),
        }
    }
}



// ====================================================================================================

pub fn alloc_record(i: &[u8]) -> IResult<&[u8], (RecordHeader, &[u8]), nom::error::Error<&[u8]>> {
    let orig = i;
    let (i, header) = RecordHeader::parse(i)?;
    let (i, raw) = take(header.size)(i)?;
    if &header.iden.0 == b"GRUP" {
        let (_, gheader) = GroupHeader::parse(orig)?;
        panic!("alloc_record(): function encountered a group: {:?}", gheader);
    } else {
        Ok((i, (header, raw)))
    }
    
}


// ====================================================================================================


#[derive(Debug)]
pub struct Record<T> {
    pub header: RecordHeader,
    pub fields: Vec<T>
}


impl<T: for<'esm> Parse<&'esm[u8]>> Parse<&[u8]> for Record<T> {
    fn parse(i: &[u8]) -> IResult<&[u8], Self, nom::error::Error<&[u8]>> {
        let (i, (header, raw)) = alloc_record(i)?;

        if header.flags.is_compressed() {
            if let Ok(dec) = decompress_record(raw) {
                
                if let Ok((_, fields)) = many0(T::parse)(&dec) {
                    Ok((i, Self { header, fields }))
                } else {
                    Err(nom::Err::Error(nom::error::Error::new(i, nom::error::ErrorKind::Complete)))
                }
                
            } else {
                panic!("Could not decompress record: {:?}", header);
            }
            
        } else if let Ok((_, fields)) = many0(T::parse)(raw) {
            Ok((i, Self { header, fields }))
        } else {
            Err(nom::Err::Error(nom::error::Error::new(i, nom::error::ErrorKind::Complete)))
        }       
    }
}


// ====================================================================================================

/// Parse the u32 for the real size, then decompress the zlib
pub fn decompress_record(i: &[u8]) -> Result<Vec<u8>, std::io::Error> {
    
    if let Ok((i, real_size)) = le_u32::<&[u8], nom::error::Error<&[u8]>>(i) {
        let mut buf = Vec::with_capacity(real_size as usize);
        let mut dec = flate2::bufread::ZlibDecoder::new(i);
        dec.read_to_end(&mut buf)?;

        Ok(buf)
    } else {
        Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "decompress_record(): could not get real size"))
    }

}


// ====================================================================================================

#[derive(Debug)]
pub struct RawCellRecord<'esm> {
    pub cell: RawRecord<'esm>,
    pub cell_children: Option<RawCellChildren<'esm>>
}

impl RawCellRecord<'_> {
    pub fn has_children(&self) -> bool {
        self.cell_children.is_some()
    }
}

impl <'esm> Parse<&'esm[u8]> for RawCellRecord<'esm> {
    fn parse(i: &'esm[u8]) -> IResult<&'esm[u8], Self, nom::error::Error<&'esm[u8]>> {
        let (i, cell) = RawRecord::parse(i)?;
        println!("{:?}", cell);
        let (_, ghead) = GroupHeader::parse(i)?;

        match ghead.label {
            GroupLabel::CellChildren(_) => {
                let (i, cell_children) = RawCellChildren::parse(i)?;
                Ok((i, Self { cell, cell_children: Some(cell_children) }))
            }
            _ => {
                Ok((i, Self { cell, cell_children: None }))
            }
        }

    }
}

// ====================================================================================================

#[derive(Debug)]
pub struct RawWorldRecord<'esm> {
    pub world: RawRecord<'esm>,
    pub world_children: Option<RawWorldChildren<'esm>>
}

impl RawWorldRecord<'_> {
    pub fn has_children(&self) -> bool {
        self.world_children.is_some()
    }
}


impl <'esm> Parse<&'esm[u8]> for RawWorldRecord<'esm>  {
    fn parse(i: &'esm[u8]) -> IResult<&'esm[u8], Self> {
        let (i, world) = RawRecord::parse(i)?;

        let (_, ghead) = GroupHeader::parse(i)?;

        match ghead.label {
            GroupLabel::WorldChildren(_) => {
                let (i, world_children) = RawWorldChildren::parse(i)?;
                Ok((i, Self { world, world_children: Some(world_children) }))
            }
            _ => {
                Ok((i, Self { world, world_children: None }))
            }
        }

    }
}

/*impl EditorId for RawWorldRecord<'_> {
    fn try_get_editor_id(&self) -> Option<ESMString> {
        let mut edid = None;
        let (_, fields) = many0(RawField::parse)(self.world.data).expect("Could not parse fields from world record.");
        for field in fields {
            match &field.header.iden().0 {
                b"EDID" => {
                    let (_, s) = ESMString::parse(field.data).unwrap();
                    edid = Some(s);
                }
                _ => {}
            }
        }
        edid
    }
}*/

// ====================================================================================================


#[derive(Debug)]
pub struct RawQuestRecord<'esm> {
    pub quest: RawRecord<'esm>,
    pub quest_children: Option<RawCellVisibleDistantChildren<'esm>>
}
impl RawQuestRecord<'_> {
    pub fn has_children(&self) -> bool {
        self.quest_children.is_some()
    }
}

impl <'esm> Parse<&'esm[u8]> for RawQuestRecord<'esm>  {
    fn parse(i: &'esm[u8]) -> IResult<&'esm[u8], Self> {

        // Parse the quest record first
        let (i, quest) = RawRecord::parse(i)?;
        


        // If the next thing isn't a group, return immediately
        let (_, next_id) = FourCC::parse(i)?;
        if &next_id.0 != b"GRUP" {
            return Ok((i, Self { quest, quest_children: None }));
        }

        // Treat next as a group and check if it belongs to this quest record
        let (_, ghead) = GroupHeader::parse(i)?;
        match ghead.label {
            GroupLabel::CellVisibleDistantChildren(_) => {
                let (i, quest_children) = RawCellVisibleDistantChildren::parse(i)?;
                Ok((i, Self { quest, quest_children: Some(quest_children) }))
            }
            _ => {
                Ok((i, Self { quest, quest_children: None }))
            }
        }
    }
}


// ====================================================================================================