libgm 0.8.1

A tool for unpacking and modding GameMaker games
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
// SPDX-License-Identifier: GPL-3.0-only
use std::fmt::Display;
use std::fmt::Formatter;

use crate::prelude::*;
use crate::util::fmt::hexdump;
use crate::wad::GMVersion;
use crate::wad::elem::GMElement;
use crate::wad::elem::string::Strings;

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ChunkName {
    ACRV,
    AGRP,
    AUDO,
    BGND,
    CODE,
    DAFL,
    EMBI,
    EXTN,
    FEAT,
    FEDS,
    FONT,
    FUNC,
    GEN8,
    GLOB,
    GMEN,
    LANG,
    OBJT,
    OPTN,
    PATH,
    PSEM,
    PSYS,
    ROOM,
    SCPT,
    SEQN,
    SHDR,
    SOND,
    SPRT,
    STRG,
    TAGS,
    TGIN,
    TMLN,
    TPAG,
    TXTR,
    UILR,
    VARI,
}

impl ChunkName {
    pub fn from_bytes(bytes: [u8; 4]) -> Result<Self> {
        Ok(match &bytes {
            b"ACRV" => Self::ACRV,
            b"AGRP" => Self::AGRP,
            b"AUDO" => Self::AUDO,
            b"BGND" => Self::BGND,
            b"CODE" => Self::CODE,
            b"DAFL" => Self::DAFL,
            b"EMBI" => Self::EMBI,
            b"EXTN" => Self::EXTN,
            b"FEAT" => Self::FEAT,
            b"FEDS" => Self::FEDS,
            b"FONT" => Self::FONT,
            b"FUNC" => Self::FUNC,
            b"GEN8" => Self::GEN8,
            b"GLOB" => Self::GLOB,
            b"GMEN" => Self::GMEN,
            b"LANG" => Self::LANG,
            b"OBJT" => Self::OBJT,
            b"OPTN" => Self::OPTN,
            b"PATH" => Self::PATH,
            b"PSEM" => Self::PSEM,
            b"PSYS" => Self::PSYS,
            b"ROOM" => Self::ROOM,
            b"SCPT" => Self::SCPT,
            b"SEQN" => Self::SEQN,
            b"SHDR" => Self::SHDR,
            b"SOND" => Self::SOND,
            b"SPRT" => Self::SPRT,
            b"STRG" => Self::STRG,
            b"TAGS" => Self::TAGS,
            b"TGIN" => Self::TGIN,
            b"TMLN" => Self::TMLN,
            b"TPAG" => Self::TPAG,
            b"TXTR" => Self::TXTR,
            b"UILR" => Self::UILR,
            b"VARI" => Self::VARI,
            // unused / weird chunks
            b"GEN7" => bail!("Found GEN7 chunk, please report this"), // alternative unusd GEN8
            b"GENL" => bail!("Found GENL chunk, please report this"), // alternative unusd GEN8
            b"PSPS" => bail!("PlayStation 3 chunk PSPS is not supported"),
            b"STAT" => bail!("Xbox One chunk STAT is not supported"),
            b"DBGI" => bail!("Debug chunk DBGI is not supported for normal data files"),
            b"INST" => bail!("Debug chunk INST is not supported for normal data files"),
            b"LOCL" => bail!("Debug chunk LOCL is not supported for normal data files"),
            _ => {
                let hex = hexdump(&bytes);
                if let Ok(string) = str::from_utf8(&bytes) {
                    bail!("Invalid chunk name {string:?} [{hex}]");
                }
                bail!("Invalid chunk name [{hex}]");
            }
        })
    }

    #[must_use]
    pub const fn as_bytes(self) -> [u8; 4] {
        *match self {
            Self::ACRV => b"ACRV",
            Self::AGRP => b"AGRP",
            Self::AUDO => b"AUDO",
            Self::BGND => b"BGND",
            Self::CODE => b"CODE",
            Self::DAFL => b"DAFL",
            Self::EMBI => b"EMBI",
            Self::EXTN => b"EXTN",
            Self::FEAT => b"FEAT",
            Self::FEDS => b"FEDS",
            Self::FONT => b"FONT",
            Self::FUNC => b"FUNC",
            Self::GEN8 => b"GEN8",
            Self::GLOB => b"GLOB",
            Self::GMEN => b"GMEN",
            Self::LANG => b"LANG",
            Self::OBJT => b"OBJT",
            Self::OPTN => b"OPTN",
            Self::PATH => b"PATH",
            Self::PSEM => b"PSEM",
            Self::PSYS => b"PSYS",
            Self::ROOM => b"ROOM",
            Self::SCPT => b"SCPT",
            Self::SEQN => b"SEQN",
            Self::SHDR => b"SHDR",
            Self::SOND => b"SOND",
            Self::SPRT => b"SPRT",
            Self::STRG => b"STRG",
            Self::TAGS => b"TAGS",
            Self::TGIN => b"TGIN",
            Self::TMLN => b"TMLN",
            Self::TPAG => b"TPAG",
            Self::TXTR => b"TXTR",
            Self::UILR => b"UILR",
            Self::VARI => b"VARI",
        }
    }
}

impl Display for ChunkName {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "{self:?}")
    }
}

/// The number of all known GameMaker chunks (excluding debug chunks).
pub const KNOWN_CHUNK_COUNT: usize = 35;

/// The order of chunks in a data file.
/// Also determines which chunks exist.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ChunkOrder(pub(crate) Vec<ChunkName>);

impl ChunkOrder {
    /// Creates a new empty chunk order.
    ///
    /// This will throw an error when serializing, so make sure to fill it with chunks.
    #[must_use]
    pub const fn new_empty() -> Self {
        Self(Vec::new())
    }

    #[must_use]
    pub fn new_by_version(version: GMVersion) -> Self {
        use ChunkName::*;
        // based on https://discord.com/channels/1505850303600394270/1505850575231914024/1531238205133815831
        let mut chunks = Vec::with_capacity(35);
        chunks.push(GEN8);
        chunks.push(OPTN);
        if version >= GMVersion::GMS2_0_6 {
            chunks.push(LANG);
        }
        chunks.push(EXTN);
        chunks.push(SOND);
        if version >= GMVersion::Wad14 {
            chunks.push(AGRP);
        }
        chunks.push(SPRT);
        chunks.push(BGND);
        chunks.push(PATH);
        chunks.push(SCPT);
        if version >= GMVersion::GMS2 {
            chunks.push(GLOB);
        }
        chunks.push(SHDR);
        chunks.push(FONT);
        chunks.push(TMLN);
        chunks.push(OBJT);
        if version >= GMVersion::GMS2_3_6 {
            chunks.push(FEDS);
        }
        if version >= GMVersion::GMS2_3 {
            chunks.push(ACRV);
            chunks.push(SEQN);
            chunks.push(TAGS);
        }
        chunks.push(ROOM);
        if version >= GMVersion::GM2024_13 {
            chunks.push(UILR);
        }
        chunks.push(DAFL);
        if version >= GMVersion::GMS2 {
            chunks.push(EMBI);
        }
        if version >= GMVersion::GM2023_2 {
            // TODO: also found in 2022.6
            chunks.push(PSEM);
            chunks.push(PSYS);
        }
        chunks.push(TPAG);
        if version >= GMVersion::GMS2_2_1 {
            chunks.push(TGIN);
        }
        chunks.push(CODE);
        chunks.push(VARI);
        chunks.push(FUNC);
        if version >= GMVersion::GM2022_8 {
            // TODO: also found in 2022.6
            chunks.push(FEAT);
        }
        chunks.push(STRG);
        chunks.push(TXTR);
        chunks.push(AUDO);
        Self(chunks)
    }

    /// Tries to create a chunk order from a vector of chunk names.
    ///
    /// This can fail if there are duplicate chunks.
    pub fn from_vec(vector: Vec<ChunkName>) -> Result<Self> {
        let count = vector.len();
        let known = KNOWN_CHUNK_COUNT;
        if count > known {
            bail!("Vector has {count} elements which is larger than the known chunk count {known}");
        }

        // check for duplicates
        let mut seen: u64 = 0;
        for &chunk in &vector {
            // this works because there's less than 65 ChunkName variants
            let bit = 1u64 << (chunk as u32);
            if seen & bit != 0 {
                bail!("Duplicate chunk {chunk} in vector");
            }
            seen |= bit;
        }

        // ok you're fine to go
        Ok(Self(vector))
    }

    /// Turns this chunk order into a vector of chunk names, consuming it.
    #[must_use]
    pub fn into_vec(self) -> Vec<ChunkName> {
        self.0
    }

    /// The count/length of chunks in this chunk order.
    ///
    /// This can never be greater than the amount of chunks
    /// (variant count of [`Chunk`]).
    ///
    /// Usually, it will also be non-zero, as data files with no chunks are invalid.
    /// However, it is possible to artificially create an empty
    /// chunk order using [`Self::new_empty`] or [`Self::from_vec`].
    #[doc(alias = "len")]
    #[must_use]
    pub const fn count(&self) -> usize {
        self.0.len()
    }

    /// Whether this chunk order contains no chunks.
    ///
    /// This will usually be false, as data files with no chunks are invalid.
    /// However, it is possible to artificially create an empty
    /// chunk order using [`Self::new_empty`] or [`Self::from_vec`].
    #[must_use]
    pub const fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    /// Whether the given chunk exists in this chunk order.
    #[doc(alias = "contains")]
    #[must_use]
    pub fn has(&self, chunk: ChunkName) -> bool {
        self.0.contains(&chunk)
    }

    /// The index of given chunk in this chunk order, if it exists.
    #[must_use]
    pub fn find(&self, chunk: ChunkName) -> Option<usize> {
        self.0.iter().position(|&c| c == chunk)
    }

    /// The chunk at the specified index of this chunk order, if it exists.
    #[must_use]
    pub fn get(&self, index: usize) -> Option<ChunkName> {
        self.0.get(index).copied()
    }

    /// Adds a chunk to the end of the chunk order.
    ///
    /// Returns whether the operation was successful:
    /// If the chunk already exists, it will not be inserted and `false` will be returned.
    #[doc(alias = "add")]
    pub fn push(&mut self, chunk: ChunkName) -> bool {
        if self.has(chunk) {
            false
        } else {
            self.0.push(chunk);
            true
        }
    }

    /// Removes a chunk from the chunk order.
    ///
    /// Returns whether the operation was successful:
    /// If the chunk did not exist in the first place, `false` will be returned.
    pub fn remove(&mut self, chunk: ChunkName) -> bool {
        if let Some(idx) = self.find(chunk) {
            self.0.remove(idx);
            true
        } else {
            false
        }
    }

    /// Inserts a chunk into the chunk order at the specified index.
    ///
    /// Returns whether the operation was successful:
    /// If the chunk already exists, it will not be inserted and `false` will be returned.
    ///
    /// Note that the index logic is saturating:
    /// If you provide an index out of bounds, it will clamp to the end of the chunk order.
    #[must_use]
    pub fn insert(&mut self, index: usize, chunk: ChunkName) -> bool {
        if self.has(chunk) {
            false
        } else {
            let idx: usize = self.count().min(index);
            self.0.insert(idx, chunk);
            true
        }
    }

    /// Moves a chunk from its current position in the chunk order to the specified index.
    ///
    /// Returns whether the operation was successful:
    /// If the chunk exists and could therefore be moved around, `true` will be returned.
    ///
    /// Note that the index logic is saturating:
    /// If you provide an index out of bounds, it will clamp to the end of the chunk order.
    pub fn move_to(&mut self, chunk: ChunkName, index: usize) -> bool {
        let Some(old_idx) = self.find(chunk) else {
            return false;
        };
        self.0.remove(old_idx);

        let index = if old_idx < index { index - 1 } else { index };
        let index = self.count().min(index);
        self.0.insert(index, chunk);
        true
    }

    pub fn iter(&'_ self) -> std::iter::Copied<std::slice::Iter<'_, ChunkName>> {
        self.0.iter().copied()
    }
}

impl IntoIterator for ChunkOrder {
    type IntoIter = std::vec::IntoIter<ChunkName>;
    type Item = ChunkName;

    fn into_iter(self) -> Self::IntoIter {
        self.0.into_iter()
    }
}

impl<'a> IntoIterator for &'a ChunkOrder {
    type IntoIter = std::iter::Copied<std::slice::Iter<'a, ChunkName>>;
    type Item = ChunkName;

    fn into_iter(self) -> Self::IntoIter {
        self.0.iter().copied()
    }
}

/// All chunk elements should implement this trait.
#[expect(private_bounds)]
pub trait GMChunk: GMElement + Default {
    /// The four character GameMaker chunk name (GEN8, STRG, VARI, etc.).
    const NAME: ChunkName;
}

/// All chunk elements that represent a collection of elements should implement
/// this trait. The only exceptions are `GEN8` and `OPTN`.
pub trait GMListChunk: GMChunk {
    // usually also GMElement
    type Element;

    fn elements(&self) -> impl Iterator<Item = &Self::Element> {
        self.element_refs().map(|(_ref, elem)| elem)
    }

    fn element_refs(&self) -> impl Iterator<Item = (GMRef<Self::Element>, &Self::Element)>;

    fn elements_mut(&mut self) -> impl Iterator<Item = &mut Self::Element> {
        self.element_refs_mut().map(|(_ref, elem)| elem)
    }

    fn element_refs_mut(
        &mut self,
    ) -> impl Iterator<Item = (GMRef<Self::Element>, &mut Self::Element)>;

    fn by_ref(&self, gm_ref: GMRef<Self::Element>) -> Result<&Self::Element>;

    fn by_ref_mut(&mut self, gm_ref: GMRef<Self::Element>) -> Result<&mut Self::Element>;

    fn push(&mut self, element: Self::Element) -> GMRef<Self::Element>;

    #[must_use]
    fn len(&self) -> usize;

    #[must_use]
    fn is_empty(&self) -> bool {
        self.len() == 0
    }
}

pub trait GMDirectListChunk: GMListChunk {
    #[must_use]
    fn all_elements(&self) -> &Vec<Self::Element>;

    #[must_use]
    fn all_elements_mut(&mut self) -> &mut Vec<Self::Element>;
}

/// Chunks that store assets.
///
/// Assets are high-level resources with a unique name.
/// They are globally referencable in GML source code.
/// Asset pointers in the chunk pointer list can be zero/null in 2024.14+ because GMAC removes (nulls out) unused assets.
pub trait GMAssetListChunk: GMListChunk<Element: GMNamedElement> {
    #[must_use]
    fn all_elements(&self) -> &Vec<Option<Self::Element>>;

    #[must_use]
    fn all_elements_mut(&mut self) -> &mut Vec<Option<Self::Element>>;

    fn ref_by_name(&self, name: &str, gm_strings: &Strings) -> Result<GMRef<Self::Element>> {
        for (gm_ref, elem) in self.element_refs() {
            let elem_name: &String = elem.name(gm_strings)?;
            if name == elem_name {
                return Ok(gm_ref);
            }
        }
        Err(err!(
            "Could not find {} with name {name:?}",
            crate::util::fmt::typename::<Self::Element>(),
        ))
    }

    fn by_name(&self, name: &str, gm_strings: &Strings) -> Result<&Self::Element> {
        self.ref_by_name(name, gm_strings).and_then(|elem| self.by_ref(elem))
    }

    fn by_name_mut(&mut self, name: &str, gm_strings: &Strings) -> Result<&mut Self::Element> {
        self.ref_by_name(name, gm_strings).and_then(|elem| self.by_ref_mut(elem))
    }
}

macro_rules! gm_list_chunk {
    ($name:ident, $chunk_struct:ident, $elem_type:ty) => {
        impl crate::wad::chunk::GMChunk for $chunk_struct {
            const NAME: crate::wad::chunk::ChunkName = crate::wad::chunk::ChunkName::$name;
        }

        impl crate::wad::chunk::GMListChunk for $chunk_struct {
            type Element = $elem_type;

            fn element_refs(&self) -> impl Iterator<Item = (GMRef<Self::Element>, &Self::Element)> {
                self.elems.iter().enumerate().map(|(idx, elem)| (idx.into(), elem))
            }

            fn element_refs_mut(
                &mut self,
            ) -> impl Iterator<Item = (GMRef<Self::Element>, &mut Self::Element)> {
                self.elems.iter_mut().enumerate().map(|(idx, elem)| (idx.into(), elem))
            }

            fn by_ref(&self, gm_ref: GMRef<Self::Element>) -> Result<&Self::Element> {
                gm_ref.resolve(&self.elems)
            }

            fn by_ref_mut(&mut self, gm_ref: GMRef<Self::Element>) -> Result<&mut Self::Element> {
                gm_ref.resolve_mut(&mut self.elems)
            }

            fn push(&mut self, element: Self::Element) -> GMRef<Self::Element> {
                self.elems.push(element);
                (self.elems.len() - 1).into()
            }

            fn len(&self) -> usize {
                self.elems.len()
            }
        }

        impl crate::wad::chunk::GMDirectListChunk for $chunk_struct {
            fn all_elements(&self) -> &Vec<Self::Element> {
                &self.elems
            }

            fn all_elements_mut(&mut self) -> &mut Vec<Self::Element> {
                &mut self.elems
            }
        }
    };
}

macro_rules! gm_asset_list_chunk {
    ($name:ident, $chunk_struct:ident, $elem_type:ty) => {
        impl crate::wad::chunk::GMChunk for $chunk_struct {
            const NAME: crate::wad::chunk::ChunkName = crate::wad::chunk::ChunkName::$name;
        }

        impl crate::wad::chunk::GMListChunk for $chunk_struct {
            type Element = $elem_type;

            fn element_refs(&self) -> impl Iterator<Item = (GMRef<Self::Element>, &Self::Element)> {
                self.elems
                    .iter()
                    .enumerate()
                    .filter_map(|(idx, elem)| Some((idx.into(), elem.as_ref()?)))
            }

            fn element_refs_mut(
                &mut self,
            ) -> impl Iterator<Item = (GMRef<Self::Element>, &mut Self::Element)> {
                self.elems
                    .iter_mut()
                    .enumerate()
                    .filter_map(|(idx, elem)| Some((idx.into(), elem.as_mut()?)))
            }

            fn by_ref(&self, gm_ref: GMRef<Self::Element>) -> Result<&Self::Element> {
                gm_ref.opt_resolve(&self.elems)
            }

            fn by_ref_mut(&mut self, gm_ref: GMRef<Self::Element>) -> Result<&mut Self::Element> {
                gm_ref.opt_resolve_mut(&mut self.elems)
            }

            fn push(&mut self, element: Self::Element) -> GMRef<Self::Element> {
                self.elems.push(Some(element));
                (self.elems.len() - 1).into()
            }

            fn len(&self) -> usize {
                self.elems.len()
            }
        }

        impl crate::wad::chunk::GMAssetListChunk for $chunk_struct {
            fn all_elements(&self) -> &Vec<Option<Self::Element>> {
                &self.elems
            }

            fn all_elements_mut(&mut self) -> &mut Vec<Option<Self::Element>> {
                &mut self.elems
            }
        }

        impl crate::wad::elem::GMNamedElement for $elem_type {
            fn name_ref(&self) -> crate::wad::GMRef<String> {
                self.name
            }
        }
    };
}

pub(crate) use gm_asset_list_chunk;
pub(crate) use gm_list_chunk;