libgm 0.5.0

A tool for modding, unpacking and decompiling 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
//! This is THE module. All GameMaker elements are contained in these
//! submodules. There are some traits as well which can help you with dynamic
//! programming.

use std::collections::HashMap;

use crate::prelude::*;
use crate::util::fmt::typename;
use crate::wad::chunk::ChunkName;
use crate::wad::deserialize::reader::DataReader;
use crate::wad::reference::GMRef;
use crate::wad::serialize::builder::DataBuilder;

pub mod animation_curve;
pub mod audio;
pub mod audio_group;
pub mod background;
pub mod code;
pub(crate) mod data_file;
pub mod embedded_image;
pub mod extension;
pub mod feature_flag;
pub mod filter_effect;
pub mod font;
pub mod function;
pub mod game_end;
pub mod game_object;
pub mod general_info;
pub mod global_init;
pub mod language;
pub mod options;
pub mod particle_emitter;
pub mod particle_system;
pub mod path;
pub mod room;
pub mod script;
pub mod sequence;
pub mod shader;
pub mod sound;
pub mod sprite;
pub(crate) mod string;
pub mod tag;
pub mod texture_group_info;
pub mod texture_page;
pub mod texture_page_item;
pub mod timeline;
pub mod ui_node;
pub mod variable;

/// All GameMaker elements that can be deserialized
/// from a data file should implement this trait.
#[allow(unused_variables)]
pub trait GMElement: Sized {
    /// Deserializes this element from the current position of the reader.
    ///
    /// Implementations should read the exact binary representation of this
    /// element and return a fully constructed instance.
    #[doc(hidden)]
    fn deserialize(reader: &mut DataReader) -> Result<Self>;

    /// Serializes this element to the current position of the builder.
    ///
    /// Implementations should write the exact binary representation of this
    /// element in the format expected by the GameMaker runtime.
    #[doc(hidden)]
    fn serialize(&self, builder: &mut DataBuilder) -> Result<()>;

    /// Handles padding bytes that may appear before this element in pointer
    /// lists.
    ///
    /// This is called before [`GMElement::deserialize`] when reading from
    /// structured data. The default implementation does nothing - override
    /// if your element requires alignment padding in specific contexts.
    #[doc(hidden)]
    fn deserialize_pre_padding(reader: &mut DataReader) -> Result<()> {
        Ok(())
    }

    /// Writes padding bytes that may be required before this element in pointer
    /// lists.
    ///
    /// This is called before [`GMElement::serialize`] when writing to
    /// structured data. The default implementation does nothing - override
    /// if your element requires alignment padding in specific contexts.
    #[doc(hidden)]
    fn serialize_pre_padding(&self, builder: &mut DataBuilder) -> Result<()> {
        Ok(())
    }

    /// Handles padding bytes that may appear after this element in pointer
    /// lists.
    ///
    /// This is called after [`GMElement::deserialize`] when reading from
    /// structured data. The `is_last` parameter indicates if this is the
    /// final element in a list, which may affect padding requirements.
    #[doc(hidden)]
    fn deserialize_post_padding(reader: &mut DataReader, is_last: bool) -> Result<()> {
        Ok(())
    }

    /// Writes padding bytes that may be required after this element in pointer
    /// lists.
    ///
    /// This is called after [`GMElement::serialize`] when writing to structured
    /// data. The `is_last` parameter indicates if this is the final element
    /// in a list, which may affect padding requirements.
    #[doc(hidden)]
    fn serialize_post_padding(&self, builder: &mut DataBuilder, is_last: bool) -> Result<()> {
        Ok(())
    }
}

impl GMElement for u8 {
    fn deserialize(reader: &mut DataReader) -> Result<Self> {
        reader.read_u8()
    }

    fn serialize(&self, builder: &mut DataBuilder) -> Result<()> {
        builder.write_u8(*self);
        Ok(())
    }
}

impl GMElement for i8 {
    fn deserialize(reader: &mut DataReader) -> Result<Self> {
        reader.read_i8()
    }

    fn serialize(&self, builder: &mut DataBuilder) -> Result<()> {
        builder.write_i8(*self);
        Ok(())
    }
}

impl GMElement for u16 {
    fn deserialize(reader: &mut DataReader) -> Result<Self> {
        reader.read_u16()
    }

    fn serialize(&self, builder: &mut DataBuilder) -> Result<()> {
        builder.write_u16(*self);
        Ok(())
    }
}

impl GMElement for i16 {
    fn deserialize(reader: &mut DataReader) -> Result<Self> {
        reader.read_i16()
    }

    fn serialize(&self, builder: &mut DataBuilder) -> Result<()> {
        builder.write_i16(*self);
        Ok(())
    }
}

impl GMElement for u32 {
    fn deserialize(reader: &mut DataReader) -> Result<Self> {
        reader.read_u32()
    }

    fn serialize(&self, builder: &mut DataBuilder) -> Result<()> {
        builder.write_u32(*self);
        Ok(())
    }
}

impl GMElement for i32 {
    fn deserialize(reader: &mut DataReader) -> Result<Self> {
        reader.read_i32()
    }

    fn serialize(&self, builder: &mut DataBuilder) -> Result<()> {
        builder.write_i32(*self);
        Ok(())
    }
}

impl GMElement for u64 {
    fn deserialize(reader: &mut DataReader) -> Result<Self> {
        reader.read_u64()
    }

    fn serialize(&self, builder: &mut DataBuilder) -> Result<()> {
        builder.write_u64(*self);
        Ok(())
    }
}

impl GMElement for i64 {
    fn deserialize(reader: &mut DataReader) -> Result<Self> {
        reader.read_i64()
    }

    fn serialize(&self, builder: &mut DataBuilder) -> Result<()> {
        builder.write_i64(*self);
        Ok(())
    }
}

impl GMElement for f32 {
    fn deserialize(reader: &mut DataReader) -> Result<Self> {
        reader.read_f32()
    }

    fn serialize(&self, builder: &mut DataBuilder) -> Result<()> {
        builder.write_f32(*self);
        Ok(())
    }
}

impl GMElement for f64 {
    fn deserialize(reader: &mut DataReader) -> Result<Self> {
        reader.read_f64()
    }

    fn serialize(&self, builder: &mut DataBuilder) -> Result<()> {
        builder.write_f64(*self);
        Ok(())
    }
}

impl GMElement for bool {
    fn deserialize(reader: &mut DataReader) -> Result<Self> {
        reader.read_bool32()
    }

    fn serialize(&self, builder: &mut DataBuilder) -> Result<()> {
        builder.write_bool32(*self);
        Ok(())
    }
}

impl GMElement for String {
    fn deserialize(reader: &mut DataReader) -> Result<Self> {
        reader.read_gm_string()
    }

    fn serialize(&self, builder: &mut DataBuilder) -> Result<()> {
        builder.write_gm_string(self);
        Ok(())
    }
}

impl GMElement for Option<String> {
    fn deserialize(reader: &mut DataReader) -> Result<Self> {
        reader.read_gm_string_opt()
    }

    fn serialize(&self, builder: &mut DataBuilder) -> Result<()> {
        builder.write_gm_string_opt(self);
        Ok(())
    }
}

impl<T> GMElement for GMRef<T> {
    fn deserialize(reader: &mut DataReader) -> Result<Self> {
        reader.read_resource_by_id()
    }

    fn serialize(&self, builder: &mut DataBuilder) -> Result<()> {
        builder.write_resource_id(*self);
        Ok(())
    }
}

impl<T> GMElement for Option<GMRef<T>> {
    fn deserialize(reader: &mut DataReader) -> Result<Self> {
        reader.read_resource_by_id_opt()
    }

    fn serialize(&self, builder: &mut DataBuilder) -> Result<()> {
        builder.write_resource_id_opt(*self);
        Ok(())
    }
}

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

    /// Returns `true` if this chunk is present in the data file.
    ///
    /// This differs from simply checking if the chunk is empty:
    /// - A list chunk may exist and contain zero elements.
    ///   > Chunk name + chunk length (four) + element count (zero).
    /// - A chunk may exist but contain no data.
    ///   > Chunk name + chunk length (zero).
    /// - A chunk may be absent entirely from the file format.
    ///   > Completely gone.
    ///
    /// Use this to distinguish between "present but empty" and "not present at
    /// all".
    fn exists(&self) -> bool;
}

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

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

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

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

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

    fn push(&mut self, element: Self::Element) {
        self.elements_mut().push(element);
    }

    #[must_use]
    fn len(&self) -> usize {
        self.elements().len()
    }

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

    fn iter(&self) -> core::slice::Iter<'_, Self::Element>;
    fn iter_mut(&mut self) -> core::slice::IterMut<'_, Self::Element>;
    #[must_use]
    fn into_iter(self) -> std::vec::IntoIter<Self::Element>;
}

/// All chunk elements that represent a collection of elements **with a unique
/// name** should implement this trait.
pub trait GMNamedListChunk: GMListChunk<Element: GMNamedElement> {
    fn ref_by_name(&self, name: &str) -> Result<GMRef<Self::Element>>;
    fn by_name(&self, name: &str) -> Result<&Self::Element>;
    fn by_name_mut(&mut self, name: &str) -> Result<&mut Self::Element>;
}

/// Validates all names of the root elements in this chunk.
///
/// This checks for duplicates as well as names not following the proper
/// charset.
pub fn validate_names<T: GMNamedListChunk>(chunk: &T) -> Result<()> {
    // TODO(perf): this can probably be optimised or something
    let elements = chunk.elements();
    let mut seen: HashMap<&String, usize> = HashMap::new();

    for (i, item) in elements.iter().enumerate() {
        let name = item.name();

        item.validate_name().with_context(|| {
            format!(
                "validating {} with name {:?}",
                typename::<T::Element>(),
                name,
            )
        })?;

        let Some(first_index) = seen.insert(name, i) else {
            continue;
        };

        bail!(
            "There are multiple {} with the same name ({:?}): First at index {} and now at index \
             {}",
            typename::<T::Element>(),
            name,
            first_index,
            i,
        );
    }
    Ok(())
}

/// All GameMaker elements with a unique name (to the list
/// they're contained in) should implement this trait.
#[allow(unused_variables)]
pub trait GMNamedElement: GMElement {
    /// The name of this element.
    #[must_use]
    fn name(&self) -> &String;

    /// A mutable reference to the name of this element.
    #[must_use]
    fn name_mut(&mut self) -> &mut String;

    /// Whether the name of this element is valid.
    /// This method respects this element type's specific rules.
    fn validate_name(&self) -> Result<()> {
        validate_identifier(self.name())
    }
}

/// Generic check whether an identifier / asset name is valid.
/// Some element types might have different rules.
/// These should be defined in [`GMNamedElement::validate_name`].
///
/// ## Rules:
/// - At least one character long
/// - First character is not a digit
/// - Letters and underscores are allowed
/// - Only ascii characters
/// - Special `@@MyIdentifier@@` syntax covered
pub(crate) fn validate_identifier(name: &str) -> Result<()> {
    let orig_name = name;
    let mut name = name;

    // i hate this function
    if name.len() > 4 && name.starts_with("@@") && name.ends_with("@@") {
        name = &name[2..name.len() - 2];
    }

    let mut chars = name.chars();
    let first_char = chars.next().ok_or("Identifier is empty")?;

    if !matches!(first_char, 'a'..='z' | '_' | 'A'..='Z') {
        if first_char.is_ascii_digit() {
            bail!("Identifier {orig_name:?} starts with a digit ({first_char})");
        }
        bail!("Identifier {orig_name:?} starts with invalid character {first_char:?}");
    }

    for ch in chars {
        if !matches!(ch, 'a'..='z'| '0'..='9' | '_' | 'A'..='Z') {
            bail!("Identifier {orig_name:?} contains invalid character {ch:?}");
        }
    }

    Ok(())
}

macro_rules! element_stub {
    ($type:ty) => {
        impl $crate::wad::elements::GMElement for $type {
            fn deserialize(_: &mut $crate::wad::deserialize::reader::DataReader) -> Result<Self> {
                unimplemented!(
                    "Using {0}::deserialize is not supported, use {0}s::deserialize instead",
                    stringify!($type),
                );
            }

            fn serialize(
                &self,
                _: &mut $crate::wad::serialize::builder::DataBuilder,
            ) -> Result<()> {
                unimplemented!(
                    "Using {0}::serialize is not supported, use {0}s::serialize instead",
                    stringify!($type),
                );
            }
        }
    };
}

pub(crate) use element_stub;