rm2k-lib 1.2.0

Reads and writes the RPG Maker 2000/2003 LCF binary formats (LDB, LMU, LMT, LSD).
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
//! Allocation-free iteration over event and move-route command lists.
//!
//! [`EventCommandIter`] and [`MoveCommandIter`] walk a command list, handing back each command as
//! a borrowed view into the input buffer: no `Vec`, no string copies, no allocator. For embedded
//! consumers that walk a map's events, match command codes, and read strings.
//!
//! Event command lists are the format's oddest corner. They carry **no element count and no
//! length prefix of their own** - the list ends at four consecutive zero bytes, which is what a
//! command with `code == 0` looks like. Each command is:
//!
//! ```text
//! varint(code) varint(indent) varint(len) len*u8 varint(n) n*varint
//! ```
//!
//! Move routes are framed differently again: no terminator and no count, they simply run to the
//! end of the enclosing chunk, and each command's payload shape depends on its own code.

use crate::{
    cursor::{ChunkIter, Ctx, Cursor, ListWalker},
    diag::DiagKind,
    wire,
};

/// One event command, borrowed from the input buffer.
#[derive(Clone, Debug)]
pub struct EventCommandRef<'a> {
    /// The command code.
    pub code: i32,
    /// Nesting depth inside conditional branches and loops.
    pub indent: i32,
    /// The command's string operand, **verbatim**. Never transcoded; see the crate docs.
    pub string: &'a [u8],
    /// The raw parameter bytes, decoded lazily by [`params`](EventCommandRef::params).
    params: &'a [u8],
    /// How many parameters are actually in `params`: the header's count, or fewer if the payload
    /// ran out first.
    param_count: u32,
}

impl<'a> EventCommandRef<'a> {
    /// Iterate the command's integer parameters.
    ///
    /// Decoded on demand, not collected: most consumers read one or two parameters of the few
    /// codes they care about, and never touch the rest.
    #[must_use]
    #[inline]
    pub const fn params(&self) -> ParamIter<'a> {
        ParamIter {
            cur: Cursor::new(self.params),
            left: self.param_count,
        }
    }

    /// The parameter at `index`, or `None` if the command has fewer.
    ///
    /// `O(index)`: compressed integers are not fixed width, so there is no direct indexing. Fine
    /// for the small indices real code uses; iterate [`params`](EventCommandRef::params) for all.
    #[must_use]
    #[inline]
    pub fn param(&self, index: usize) -> Option<i32> {
        self.params().nth(index)
    }

    /// How many parameters the command holds. A header declaring more than the payload has room
    /// for reports only those present (plus a [`DiagKind::ShortChunk`]),
    /// so this is always safe to size a buffer from.
    #[must_use]
    #[inline]
    pub const fn param_count(&self) -> u32 {
        self.param_count
    }

    /// The undecoded parameter bytes.
    ///
    /// For carrying the parameters somewhere before decoding them. The C API returns this span so
    /// `rm2k_event_command_param` can decode on demand without keeping the iterator alive.
    #[must_use]
    #[inline]
    pub const fn raw_params(&self) -> &'a [u8] {
        self.params
    }
}

/// Lazily decodes an event command's integer parameters.
#[derive(Clone, Debug)]
pub struct ParamIter<'a> {
    cur: Cursor<'a>,
    left: u32,
}

impl Iterator for ParamIter<'_> {
    type Item = i32;

    #[inline]
    fn next(&mut self) -> Option<i32> {
        if self.left == 0 {
            return None;
        }
        self.left -= 1;
        // `left` never exceeds what the payload holds (see `EventCommandIter::next`), so the
        // varint is always there.
        Some(self.cur.varint().map_or(0, |v| v.value as i32))
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        (self.left as usize, Some(self.left as usize))
    }
}

impl ExactSizeIterator for ParamIter<'_> {}

/// Walks an event command list.
///
/// Not an [`Iterator`], for the same reason as
/// [`ChunkIter`]: advancing needs a [`Ctx`] to report recovery into,
/// and `Iterator::next` has nowhere to put one.
#[derive(Clone, Debug)]
pub struct EventCommandIter<'a> {
    cur: Cursor<'a>,
    done: bool,
}

impl<'a> EventCommandIter<'a> {
    /// Walk the command list in a chunk payload beginning at file offset `base`.
    #[must_use]
    #[inline]
    pub const fn new(data: &'a [u8], base: u32) -> Self {
        Self {
            cur: Cursor::with_base(data, base),
            done: false,
        }
    }

    /// Bytes left after the list terminated.
    #[must_use]
    #[inline]
    pub fn tail(&self) -> &'a [u8] {
        self.cur.remaining()
    }

    /// Yield the next command, or `None` at the terminator or end of payload.
    #[must_use]
    pub fn next(&mut self, ctx: &mut Ctx<'_>) -> Option<EventCommandRef<'a>> {
        if self.done || self.cur.is_empty() {
            self.done = true;
            return None;
        }

        // A zero code is the terminator. The list ends with four zero bytes, being a command
        // whose code, indent, string length and parameter count are all zero.
        if self.cur.peek() == Some(0) {
            self.cur.skip(4);
            self.done = true;
            return None;
        }

        let offset = self.cur.offset();
        let Some(code) = self.cur.varint() else {
            self.recover(ctx, offset);
            return None;
        };
        // Only the terminator carries code 0, and it was caught above by its first byte. Any other
        // route to 0 (an overlong or non-canonical encoding) would be written back as that
        // terminator and cut the list short on the next load, so the list ends here instead.
        if code.value == 0 {
            self.recover(ctx, offset);
            return None;
        }
        let Some(indent) = self.cur.varint() else {
            self.recover(ctx, offset);
            return None;
        };
        let Some(string) = self.cur.lstring() else {
            self.recover(ctx, offset);
            return None;
        };
        let Some(param_count) = self.cur.varint() else {
            self.recover(ctx, offset);
            return None;
        };

        // Parameters are compressed integers, so their extent is found by scanning, once here. That
        // keeps `ParamIter` a plain decode with no bounds bookkeeping.
        //
        // The count is the file's claim: a command can declare billions of parameters in a few
        // bytes, and `ParamIter` is exact-size, so collecting it would allocate for all of them.
        // Only parameters actually present are counted.
        let params_start = self.cur.pos();
        let mut present = 0;
        while present < param_count.value {
            if self.cur.varint().is_none() {
                ctx.report("EventCommand", 0, offset, DiagKind::ShortChunk);
                break;
            }
            present += 1;
        }
        let params_end = self.cur.pos();
        let params = self.cur.buf().get(params_start..params_end).unwrap_or(&[]);

        Some(EventCommandRef {
            code: code.value as i32,
            indent: indent.value as i32,
            string,
            params,
            param_count: present,
        })
    }

    /// Resynchronize after a malformed command.
    ///
    /// The list has no framing to fall back on, so scan forward for 4 zero bytes.
    fn recover(&mut self, ctx: &mut Ctx<'_>, offset: u32) {
        ctx.report("EventCommand", 0, offset, DiagKind::EventListCorrupt);
        let mut zeros = 0;
        while let Some(byte) = self.cur.u8() {
            zeros = if byte == 0 { zeros + 1 } else { 0 };
            if zeros == 4 {
                break;
            }
        }
        self.done = true;
    }
}

/// One move-route command, borrowed from the input buffer.
///
/// Unlike an event command, a move command's payload shape depends on its own code: most codes
/// carry nothing, two carry one integer, and two carry a string followed by one or three integers.
#[derive(Clone, Debug, Default)]
pub struct MoveCommandRef<'a> {
    /// The command code. See [`move_code`] for the ones that carry operands.
    pub code: i32,
    /// The string operand, verbatim. Empty for every code that does not carry one.
    pub string: &'a [u8],
    /// First integer operand, or `0`.
    pub parameter_a: i32,
    /// Second integer operand, or `0`.
    pub parameter_b: i32,
    /// Third integer operand, or `0`.
    pub parameter_c: i32,
}

/// The move-route command codes whose payload is not empty.
///
/// Only these four change how many bytes a move command occupies, so they are the only ones the
/// codec names.
pub mod move_code {
    /// Turns a switch on; carries one integer.
    pub const SWITCH_ON: i32 = 32;
    /// Turns a switch off; carries one integer.
    pub const SWITCH_OFF: i32 = 33;
    /// Changes the event's sprite; carries a string and one integer.
    pub const CHANGE_GRAPHIC: i32 = 34;
    /// Plays a sound effect; carries a string and three integers.
    pub const PLAY_SOUND_EFFECT: i32 = 35;
}

/// Walks a move route's command list.
///
/// The list has neither a count nor a terminator: it runs to the end of the enclosing chunk.
#[derive(Clone, Debug)]
pub struct MoveCommandIter<'a> {
    cur: Cursor<'a>,
}

impl<'a> MoveCommandIter<'a> {
    /// Walk the move commands in a chunk payload beginning at file offset `base`.
    #[must_use]
    #[inline]
    pub const fn new(data: &'a [u8], base: u32) -> Self {
        Self {
            cur: Cursor::with_base(data, base),
        }
    }

    /// Yield the next command, or `None` at the end of the payload.
    #[must_use]
    pub fn next(&mut self, ctx: &mut Ctx<'_>) -> Option<MoveCommandRef<'a>> {
        if self.cur.is_empty() {
            return None;
        }

        let offset = self.cur.offset();
        let code = self.cur.varint()?.value as i32;
        let mut out = MoveCommandRef {
            code,
            ..MoveCommandRef::default()
        };

        let ok = match code {
            move_code::SWITCH_ON | move_code::SWITCH_OFF => self.read_ints(&mut out, 1),
            move_code::CHANGE_GRAPHIC => self.read_string(&mut out) && self.read_ints(&mut out, 1),
            move_code::PLAY_SOUND_EFFECT => self.read_string(&mut out) && self.read_ints(&mut out, 3),
            _ => true,
        };

        if !ok {
            ctx.report("MoveCommand", 0, offset, DiagKind::ShortChunk);
        }
        Some(out)
    }

    fn read_string(&mut self, out: &mut MoveCommandRef<'a>) -> bool {
        match self.cur.lstring() {
            Some(s) => {
                out.string = s;
                true
            }
            None => false,
        }
    }

    fn read_ints(&mut self, out: &mut MoveCommandRef<'a>, count: usize) -> bool {
        for slot in [&mut out.parameter_a, &mut out.parameter_b, &mut out.parameter_c]
            .into_iter()
            .take(count)
        {
            match self.cur.varint() {
                Some(v) => *slot = v.value as i32,
                None => return false,
            }
        }
        true
    }
}

/// Encoded length of one event command.
///
/// Exposed so a caller sizing a buffer for [`SliceSink`](crate::sink::SliceSink) can do it
/// without allocating.
#[must_use]
pub fn event_command_len(code: i32, indent: i32, string_len: usize, params: &[i32]) -> u32 {
    let mut total = wire::varint_len(code as u32)
        + wire::varint_len(indent as u32)
        + wire::varint_len(string_len as u32)
        + string_len as u32
        + wire::varint_len(params.len() as u32);
    for &p in params {
        total += wire::varint_len(p as u32);
    }
    total
}

/// The chunk ids on the route from a file root down to a command list.
///
/// Reaching an event command means walking `Map` -> `Event` -> `EventPage` -> commands. The core
/// tier has no typed structs for that (they need `alloc`), so the few ids on the route are named
/// here rather than hardcoded by callers.
///
/// Deliberately not the full set: liblcf generates 2 960 lines of chunk-id enums across four
/// `chunks.h` files, and nothing in the core tier needs the other ~1 190 ids. For any other chunk,
/// use the `alloc` tier's typed structs.
pub mod path {
    /// `Map::events` - a list of `Event`.
    pub const MAP_EVENTS: u32 = 0x51;
    /// `Event::pages` - a list of `EventPage`.
    pub const EVENT_PAGES: u32 = 0x05;
    /// `EventPage::event_commands`.
    pub const EVENT_PAGE_COMMANDS: u32 = 0x34;

    /// `Database::commonevents` - a list of `CommonEvent`.
    pub const DATABASE_COMMON_EVENTS: u32 = 0x19;
    /// `CommonEvent::event_commands`.
    pub const COMMON_EVENT_COMMANDS: u32 = 0x16;

    /// `Database::troops` - a list of `Troop`.
    pub const DATABASE_TROOPS: u32 = 0x0F;
    /// `Troop::pages` - a list of `TroopPage`.
    pub const TROOP_PAGES: u32 = 0x0B;
    /// `TroopPage::event_commands`.
    pub const TROOP_PAGE_COMMANDS: u32 = 0x0C;
}

/// Where a command list was found.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct CommandListAt<'a> {
    /// Id of the owning event, common event or troop.
    pub owner_id: i32,
    /// Id of the owning page, or `0` for a common event, which has no pages.
    pub page_id: i32,
    /// The command list's payload.
    pub commands: &'a [u8],
    /// File-absolute offset of `commands`.
    pub offset: u32,
}

impl<'a> CommandListAt<'a> {
    /// Walk the commands.
    ///
    /// Not `iter`: the result is not an [`Iterator`], since advancing needs a [`Ctx`] to report
    /// recovery into.
    #[must_use]
    #[inline]
    pub const fn commands(&self) -> EventCommandIter<'a> {
        EventCommandIter::new(self.commands, self.offset)
    }
}

/// Which nesting shape a root's command lists have.
#[derive(Clone, Copy, Debug)]
enum Shape {
    /// Root -> list -> page -> commands (maps, troops).
    Paged { outer: u32, pages: u32, commands: u32 },
    /// Root -> list -> commands (common events).
    Flat { outer: u32, commands: u32 },
}

/// Finds every event command list under a file root, without allocating.
///
/// What makes the core tier usable for real work. liblcf cannot express it: reaching one map's
/// commands means parsing the whole `rpg::Map` into `std::vector`s, copying every string. Here the
/// traversal is spans into the caller's buffer, so it runs on a microcontroller against a
/// memory-mapped file.
///
/// ```
/// # use rm2k::{event::CommandLists, Ctx, Engine, NullSink};
/// # let map_body: &[u8] = &[0];
/// let mut sink = NullSink;
/// let mut ctx = Ctx::new(Engine::R2K, &mut sink);
/// let mut lists = CommandLists::in_map(map_body, 0, &mut ctx);
/// while let Some(list) = lists.next(&mut ctx) {
///     let mut commands = list.commands();
///     while let Some(command) = commands.next(&mut ctx) {
///         let _ = (command.code, command.string);
///     }
/// }
/// ```
#[derive(Clone, Debug)]
pub struct CommandLists<'a> {
    shape: Shape,
    outer: Option<ListWalker<'a>>,
    inner: Option<ListWalker<'a>>,
    owner_id: i32,
    name: &'static str,
}

impl<'a> CommandLists<'a> {
    /// Every command list in a map, from its root chunk stream.
    ///
    /// `body` is the map's chunk stream: what [`load_map`](crate::file::load_map) parses, minus the
    /// file header.
    #[must_use]
    pub fn in_map(body: &'a [u8], base: u32, ctx: &mut Ctx<'_>) -> Self {
        Self::start(
            body,
            base,
            ctx,
            "Map",
            Shape::Paged {
                outer: path::MAP_EVENTS,
                pages: path::EVENT_PAGES,
                commands: path::EVENT_PAGE_COMMANDS,
            },
        )
    }

    /// Every common event's command list, from a database's chunk stream.
    #[must_use]
    pub fn in_common_events(body: &'a [u8], base: u32, ctx: &mut Ctx<'_>) -> Self {
        Self::start(
            body,
            base,
            ctx,
            "CommonEvent",
            Shape::Flat {
                outer: path::DATABASE_COMMON_EVENTS,
                commands: path::COMMON_EVENT_COMMANDS,
            },
        )
    }

    /// Every troop page's command list, from a database's chunk stream.
    #[must_use]
    pub fn in_battle_events(body: &'a [u8], base: u32, ctx: &mut Ctx<'_>) -> Self {
        Self::start(
            body,
            base,
            ctx,
            "Troop",
            Shape::Paged {
                outer: path::DATABASE_TROOPS,
                pages: path::TROOP_PAGES,
                commands: path::TROOP_PAGE_COMMANDS,
            },
        )
    }

    fn start(body: &'a [u8], base: u32, ctx: &mut Ctx<'_>, name: &'static str, shape: Shape) -> Self {
        let outer_id = match shape {
            Shape::Paged { outer, .. } | Shape::Flat { outer, .. } => outer,
        };
        let outer = ChunkIter::find(body, base, outer_id, ctx, name)
            .map(|chunk| ListWalker::new(chunk.data, chunk.offset, ctx, name));
        Self {
            shape,
            outer,
            inner: None,
            owner_id: 0,
            name,
        }
    }

    /// Yield the next command list.
    #[must_use]
    pub fn next(&mut self, ctx: &mut Ctx<'_>) -> Option<CommandListAt<'a>> {
        loop {
            // Drain the current owner's pages before advancing to the next owner.
            if let Some(inner) = self.inner.as_mut() {
                if let Some(page) = inner.next(ctx) {
                    let Shape::Paged { commands, .. } = self.shape else {
                        unreachable!("inner walker only exists for a paged shape")
                    };
                    if let Some(chunk) = page.find(commands, ctx, self.name) {
                        return Some(CommandListAt {
                            owner_id: self.owner_id,
                            page_id: page.id,
                            commands: chunk.data,
                            offset: chunk.offset,
                        });
                    }
                    continue;
                }
                self.inner = None;
            }

            let owner = self.outer.as_mut()?.next(ctx)?;
            self.owner_id = owner.id;

            match self.shape {
                Shape::Flat { commands, .. } => {
                    if let Some(chunk) = owner.find(commands, ctx, self.name) {
                        return Some(CommandListAt {
                            owner_id: owner.id,
                            page_id: 0,
                            commands: chunk.data,
                            offset: chunk.offset,
                        });
                    }
                }
                Shape::Paged { pages, .. } => {
                    if let Some(chunk) = owner.find(pages, ctx, self.name) {
                        self.inner = Some(ListWalker::new(chunk.data, chunk.offset, ctx, self.name));
                    }
                }
            }
        }
    }
}