Skip to main content

sm64_binds/sm64/mupen/
load.rs

1//! Loading a Mupen64 savestate into a port game.
2//!
3//! The port is not an N64: it is the decomp compiled to WASM, with its own
4//! memory layout, its own heap (system malloc instead of the N64's pools) and
5//! no ROM segments (assets are linked in). So a state cannot be copied in
6//! byte for byte. Instead the port game is first brought to the same level
7//! and area (by playing to it, as the N64 did), and then the game state
8//! variables are carried over one by one (`tables.rs` says which, where on
9//! each side, and how they are laid out), byte-swapped, with every pointer
10//! translated (`translate.rs`). What the port builds when it loads a level
11//! (geometry, the static collision, spawn lists, the model table) stays the
12//! port's own, and serves to translate pointers into the N64's.
13
14use anyhow::{Result, bail};
15
16use super::MupenState;
17use super::layout::{Counts, convert, named, var};
18use super::tables::{BUILD_ID, N64_ONLY, PORT_ONLY, TARGETS, VARS};
19use super::translate::Translator;
20use crate::sm64::SM64Game;
21
22/// What [`SM64Game::load_mupen_state`] did.
23#[derive(Debug, Clone, Default)]
24pub struct MupenLoadReport {
25    pub level: i16,
26    pub area: i16,
27    /// Variables copied (out of those both builds have).
28    pub vars_copied: usize,
29    /// Pointer values met, and how many could not be translated (the port's
30    /// value was kept).
31    pub pointers: u32,
32    pub pointers_kept: u32,
33    /// Pointers learned from memory both sides hold (scripts, pools, tables).
34    pub pairs_learned: usize,
35    /// Static surfaces: (N64 count, port count, how many differ after
36    /// conversion). They come from the level's collision, so they should be
37    /// identical; a mismatch means the two games did not load the same area.
38    pub static_surfaces: (u32, u32, u32),
39    /// Dynamic surfaces (rebuilt every frame from objects): (N64 count,
40    /// copied into the port's slots).
41    pub dynamic_surfaces: (u32, u32),
42    /// Object slots whose behavior differs between the state and the port
43    /// before loading (objects the port had not spawned, or had in another
44    /// slot): their pointers into level data may not translate.
45    pub objects_differing: u32,
46    /// Untranslated pointers, as (where, N64 address holding it, value), at
47    /// most a few hundred.
48    pub kept: Vec<(String, u32, u32)>,
49    pub notes: Vec<String>,
50    /// Environment effect particles copied: (N64 buffer, port buffer, count).
51    pub envfx: Option<(u32, u32, u32)>,
52}
53
54impl std::fmt::Display for MupenLoadReport {
55    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
56        writeln!(
57            f,
58            "level {} area {}: {} variables, {} pointers ({} kept as the port's), {} learned pairs",
59            self.level,
60            self.area,
61            self.vars_copied,
62            self.pointers,
63            self.pointers_kept,
64            self.pairs_learned
65        )?;
66        writeln!(
67            f,
68            "static surfaces n64 {} port {} differing {}; dynamic surfaces n64 {} copied {}; objects differing {}",
69            self.static_surfaces.0,
70            self.static_surfaces.1,
71            self.static_surfaces.2,
72            self.dynamic_surfaces.0,
73            self.dynamic_surfaces.1,
74            self.objects_differing
75        )?;
76        for n in &self.notes {
77            writeln!(f, "note: {n}")?;
78        }
79        Ok(())
80    }
81}
82
83fn n64_only(name: &str) -> Option<u32> {
84    N64_ONLY.iter().find(|(n, _)| *n == name).map(|(_, a)| *a)
85}
86
87fn port_only(name: &str) -> Option<u32> {
88    PORT_ONLY.iter().find(|(n, _)| *n == name).map(|(_, a)| *a)
89}
90
91/// Little-endian reads of a port memory snapshot.
92fn p32(m: &[u8], a: u32) -> u32 {
93    m.get(a as usize..a as usize + 4)
94        .map_or(0, |b| u32::from_le_bytes(b.try_into().unwrap()))
95}
96fn p16(m: &[u8], a: u32) -> u16 {
97    m.get(a as usize..a as usize + 2)
98        .map_or(0, |b| u16::from_le_bytes(b.try_into().unwrap()))
99}
100
101/// A variable's value, as an integer, on each side (2 or 4 bytes).
102fn n64_int(st: &MupenState, name: &str) -> Option<i64> {
103    let v = var(name)?;
104    Some(match v.size {
105        1 => st.u8(v.n64)? as i8 as i64,
106        2 => st.s16(v.n64)? as i64,
107        _ => st.u32(v.n64)? as i32 as i64,
108    })
109}
110fn port_int(m: &[u8], name: &str) -> Option<i64> {
111    let v = var(name)?;
112    Some(match v.size {
113        1 => *m.get(v.port as usize)? as i8 as i64,
114        2 => p16(m, v.port) as i16 as i64,
115        _ => p32(m, v.port) as i32 as i64,
116    })
117}
118
119/// The items of an alloc-only pool (the port's surface pools), in
120/// allocation order. Blocks are 100, 200, 400... bytes, each item in one
121/// block, and the newest block is the pool's `lastBlock`.
122fn pool_items(m: &[u8], pool: u32, item: u32, count: u32) -> Vec<u32> {
123    let mut blocks = Vec::new();
124    let mut b = p32(m, pool);
125    while b != 0 && blocks.len() < 64 {
126        blocks.push(b);
127        b = p32(m, b);
128    }
129    blocks.reverse();
130    let mut out = Vec::with_capacity(count as usize);
131    let mut size = 100u32;
132    for (i, &blk) in blocks.iter().enumerate() {
133        let n = if i + 1 == blocks.len() {
134            p32(m, pool + 8) / item
135        } else {
136            size / item
137        };
138        for j in 0..n {
139            out.push(blk + 8 + j * item);
140        }
141        size = size.saturating_mul(2).max(item);
142    }
143    out.truncate(count as usize);
144    out
145}
146
147/// Where an N64 address is, for reports: a variable and offset, or heap.
148fn describe(a: u32) -> String {
149    let i = VARS.partition_point(|v| v.n64 <= a);
150    if let Some(v) = i.checked_sub(1).map(|i| &VARS[i])
151        && a - v.n64 < v.size
152    {
153        return format!("{}+{:#x}", v.name, a - v.n64);
154    }
155    format!("heap {a:#010x}")
156}
157
158const OBJECT_SIZE: u32 = 0x260;
159const POOL_CAPACITY: u32 = 240;
160const OBJ_BEHAVIOR: u32 = 0x20C;
161const OBJ_ANIMATIONS: u32 = 0x88 + 0x26 * 4;
162const OBJ_COLLISION: u32 = 0x218;
163const OBJ_CUR_ANIM: u32 = 0x3C;
164const OBJ_ANIM_ID: u32 = 0x38;
165const OBJ_SHARED_CHILD: u32 = 0x14;
166const OBJ_SPAWN_INFO: u32 = 0x4C;
167const OBJ_RESPAWN_INFO: u32 = 0x25C;
168
169impl MupenState {
170    /// The current level number (`gCurrLevelNum`) in a US state.
171    pub fn level(&self) -> Option<i16> {
172        self.s16(var("gCurrLevelNum")?.n64)
173    }
174    /// The current area index (`gCurrAreaIndex`) in a US state.
175    pub fn area(&self) -> Option<i16> {
176        self.s16(var("gCurrAreaIndex")?.n64)
177    }
178    /// `gGlobalTimer`: frames since the game started.
179    pub fn global_timer(&self) -> Option<u32> {
180        self.u32(var("gGlobalTimer")?.n64)
181    }
182    /// Mario's `MarioState` (`gMarioStates[0]`) as the port lays it out,
183    /// byte-swapped but with its pointers left as N64 addresses: offsets as
184    /// in `include/types.h`.
185    pub fn mario_state_bytes(&self) -> Option<Vec<u8>> {
186        let v = var("gMarioStates")?;
187        let src = self.bytes(v.n64, v.size as usize)?;
188        let mut out = vec![0u8; v.size as usize];
189        let mut tr = Translator::new(self, None, None);
190        convert(
191            v.layout,
192            src,
193            &mut out,
194            v.n64,
195            &mut tr,
196            &mut Counts::default(),
197        );
198        // Untranslated pointers kept "the port's" value, zero here: put the
199        // raw N64 values back.
200        for (&at, &val) in &tr.failures {
201            let o = (at - v.n64) as usize;
202            out[o..o + 4].copy_from_slice(&val.to_le_bytes());
203        }
204        Some(out)
205    }
206}
207
208impl SM64Game {
209    /// Loads the game state of a Mupen64 savestate (US ROM) into this game.
210    ///
211    /// This game must already be in the state's level and area (play or
212    /// replay to it first): the level's geometry, collision and spawn lists
213    /// stay this game's own, and everything that changes while playing is
214    /// copied over (Mario, objects, camera, save file, HUD, timers, RNG, ...).
215    /// Fails, without changing anything, if the state is from another level
216    /// or area, or this game is not the build the tables were made for.
217    /// [`MupenLoadReport`] says what could not be translated.
218    pub fn load_mupen_state(&mut self, st: &MupenState) -> Result<MupenLoadReport> {
219        let id: String = self.build_id.iter().map(|b| format!("{b:02x}")).collect();
220        if id != BUILD_ID {
221            bail!("Mupen state tables are for build {BUILD_ID}, this game is build {id}");
222        }
223        let mut report = MupenLoadReport::default();
224        if !st.is_us_rom() {
225            report.notes.push(format!(
226                "state is for ROM MD5 {}, not the US ROM",
227                st.rom_md5
228            ));
229        }
230        let snap: Vec<u8> = self.with_memory(|m| m.to_vec());
231        let (Some(level), Some(area)) = (st.level(), st.area()) else {
232            bail!("state has no level/area");
233        };
234        let port_level = port_int(&snap, "gCurrLevelNum").unwrap_or(-1) as i16;
235        let port_area = port_int(&snap, "gCurrAreaIndex").unwrap_or(-1) as i16;
236        if (level, area) != (port_level, port_area) {
237            bail!(
238                "the state is in level {level} area {area}, this game is in level {port_level} area {port_area}: \
239                 bring the game to the same area first"
240            );
241        }
242        report.level = level;
243        report.area = area;
244
245        // Room for the state's dynamic surfaces (rebuilt every frame from
246        // objects, but Mario's floor can be one of last frame's): a fresh
247        // block in each of the port's dynamic pools, from the game's malloc.
248        let dynamic = |all: &str, stat: &str| {
249            (n64_int(st, all).unwrap_or(0) - n64_int(st, stat).unwrap_or(0)).max(0) as u32
250        };
251        let (d_surfaces, d_nodes) = (
252            dynamic("gSurfacesAllocated", "gNumStaticSurfaces"),
253            dynamic("gSurfaceNodesAllocated", "gNumStaticSurfaceNodes"),
254        );
255        let mut fresh = None;
256        if d_surfaces > 0 && d_nodes > 0 && self.has_export("malloc") {
257            let sb = self.malloc(8 + 48 * d_surfaces)?;
258            let nb = self.malloc(8 + 8 * d_nodes)?;
259            if sb != 0 && nb != 0 {
260                fresh = Some((sb, d_surfaces, nb, d_nodes));
261            }
262        }
263        let snap: Vec<u8> = self.with_memory(|m| m.to_vec());
264
265        let mut tr = Translator::new(st, n64_only("sSegmentTable"), Some(&snap));
266        learn_behaviors(&mut tr, &snap);
267        let level_copies = learn_tables(&mut tr, st, &snap, &mut report);
268        let surfaces = learn_surfaces(&mut tr, st, &snap, &mut report, fresh);
269        let object_heap = learn_objects(&mut tr, st, &snap, &mut report);
270        let paintings = learn_paintings(&mut tr, st, &snap, level);
271        report.pairs_learned = tr.pair_count();
272
273        // The variables.
274        let mut writes: Vec<(u32, Vec<u8>)> = Vec::new();
275        let mut counts = Counts::default();
276        for v in VARS.iter().filter(|v| v.copy) {
277            let (Some(src), Some(dst)) = (
278                st.bytes(v.n64, v.size as usize),
279                snap.get(v.port as usize..(v.port + v.size) as usize),
280            ) else {
281                continue;
282            };
283            let mut out = dst.to_vec();
284            convert(v.layout, src, &mut out, v.n64, &mut tr, &mut counts);
285            writes.push((v.port, out));
286            report.vars_copied += 1;
287        }
288
289        fix_s16_fields(st, &mut writes, &tr);
290
291        if let (Some((nb, pb, count)), Some((size, layout))) =
292            (report.envfx, named("EnvFxParticle"))
293        {
294            for k in 0..count {
295                heap_struct(
296                    &mut writes,
297                    &mut tr,
298                    &mut counts,
299                    st,
300                    &snap,
301                    nb + k * size,
302                    pb + k * size,
303                    size,
304                    layout,
305                );
306            }
307        }
308
309        // Respawn flags in the spawn lists and macro object lists, of every
310        // area (they decide what spawns when an area is entered again).
311        let read_only = self.read_only_memory();
312        for &(n, p, size, unit) in &level_copies {
313            if read_only.contains(&(p as usize)) {
314                continue;
315            }
316            if let Some(src) = st.bytes(n, size as usize) {
317                let out: Vec<u8> = src
318                    .chunks_exact(unit)
319                    .flat_map(|h| h.iter().rev().copied())
320                    .collect();
321                writes.push((p, out));
322            }
323        }
324
325        // The level's paintings (their ripple state is level data).
326        if let Some((size, layout)) = named("Painting") {
327            for &(n, p) in &paintings {
328                heap_struct(
329                    &mut writes,
330                    &mut tr,
331                    &mut counts,
332                    st,
333                    &snap,
334                    n,
335                    p,
336                    size,
337                    layout,
338                );
339            }
340        }
341
342        // What objects allocated (chain segments).
343        if let Some((size, layout)) = named("ChainSegment") {
344            for &(n, p, len) in &object_heap {
345                debug_assert_eq!(len, size);
346                heap_struct(
347                    &mut writes,
348                    &mut tr,
349                    &mut counts,
350                    st,
351                    &snap,
352                    n,
353                    p,
354                    size,
355                    layout,
356                );
357            }
358        }
359
360        // The camera, which the area allocates.
361        if let (Some(gc), Some((size, layout))) = (var("gCamera"), named("Camera")) {
362            let (n, p) = (st.u32(gc.n64).unwrap_or(0), p32(&snap, gc.port));
363            if n != 0 && p != 0 {
364                heap_struct(
365                    &mut writes,
366                    &mut tr,
367                    &mut counts,
368                    st,
369                    &snap,
370                    n,
371                    p,
372                    size,
373                    layout,
374                );
375            }
376        }
377
378        // Dynamic surfaces and nodes into the port's slots; static ones are
379        // compared, not written.
380        if let Some(s) = surfaces {
381            writes.extend(s.writes.iter().cloned());
382            for (kind, n64s, ports, statics, item) in [
383                (
384                    "Surface",
385                    &s.n64_surfaces,
386                    &s.port_surfaces,
387                    s.static_surfaces,
388                    48u32,
389                ),
390                (
391                    "SurfaceNode",
392                    &s.n64_nodes,
393                    &s.port_nodes,
394                    s.static_nodes,
395                    8u32,
396                ),
397            ] {
398                let Some((size, layout)) = named(kind) else {
399                    continue;
400                };
401                debug_assert_eq!(size, item);
402                for (i, (&n, &p)) in n64s.iter().zip(ports.iter()).enumerate() {
403                    if (i as u32) < statics {
404                        let mut out = snap[p as usize..(p + size) as usize].to_vec();
405                        let mut c = Counts::default();
406                        convert(
407                            layout,
408                            st.bytes(n, size as usize).unwrap_or(&[]),
409                            &mut out,
410                            n,
411                            &mut tr,
412                            &mut c,
413                        );
414                        if kind == "Surface" && out != snap[p as usize..(p + size) as usize] {
415                            report.static_surfaces.2 += 1;
416                        }
417                    } else {
418                        heap_struct(
419                            &mut writes,
420                            &mut tr,
421                            &mut counts,
422                            st,
423                            &snap,
424                            n,
425                            p,
426                            size,
427                            layout,
428                        );
429                        if kind == "Surface" {
430                            report.dynamic_surfaces.1 += 1;
431                        }
432                    }
433                }
434            }
435        }
436
437        report.pointers = counts.pointers;
438        report.pointers_kept = counts.kept;
439        report.kept = tr
440            .failures
441            .iter()
442            .take(400)
443            .map(|(&at, &v)| (describe(at), at, v))
444            .collect();
445
446        // Everything was computed from the snapshot; now write.
447        let (ptr, len) = self.mem_mut();
448        // SAFETY: linear memory is `len` bytes at `ptr` while self is
449        // borrowed mutably; nothing else touches it meanwhile.
450        let mem = unsafe { std::slice::from_raw_parts_mut(ptr, len) };
451        for (addr, bytes) in &writes {
452            let a = *addr as usize;
453            if let Some(dst) = mem.get_mut(a..a + bytes.len()) {
454                dst.copy_from_slice(bytes);
455            }
456        }
457        fix_mario_animation(st, mem, &mut report);
458        Ok(report)
459    }
460}
461
462impl SM64Game {
463    /// `size` bytes from the game's own malloc (its exported `malloc`).
464    fn malloc(&mut self, size: u32) -> Result<u32> {
465        let (store, exports) = self.parts_mut();
466        let f: wasmer::TypedFunction<i32, i32> = exports
467            .instance
468            .exports
469            .get_typed_function(store, "malloc")?;
470        Ok(f.call(store, size as i32)? as u32)
471    }
472
473    /// Brings this game to the level and area of `st`, so that
474    /// [`SM64Game::load_mupen_state`] can load it, by starting the warp the
475    /// game itself would use (a level change to one of the area's warp
476    /// nodes, as a checkpoint so no act select interrupts it) and playing
477    /// with no input until the area has loaded. The game must be playing a
478    /// level (past the file select); if it is in the middle of a transition
479    /// (a fade, an area change) it plays on with no input until that ends.
480    /// Returns the frames played: 0 if the game was already there.
481    pub fn warp_to_mupen_area(&mut self, st: &MupenState, max_frames: u32) -> Result<u32> {
482        let (Some(level), Some(area)) = (st.level(), st.area()) else {
483            bail!("state has no level/area");
484        };
485        let here = |g: &SM64Game| {
486            g.with_memory(|m| {
487                (
488                    port_int(m, "gCurrLevelNum").unwrap_or(-1) as i16,
489                    port_int(m, "gCurrAreaIndex").unwrap_or(-1) as i16,
490                    port_int(m, "sCurrPlayMode").unwrap_or(-1),
491                    p32(m, var("gMarioStates").map_or(0, |v| v.port) + 0x0C),
492                )
493            })
494        };
495        let transition = |g: &SM64Game| {
496            g.with_memory(|m| p32(m, var("sTransitionUpdate").map_or(0, |v| v.port)))
497        };
498        if here(self).0 == level && here(self).1 == area {
499            return Ok(0);
500        }
501        // Mid-transition (an area change, a fade): play on until it ends.
502        let mut waited = 0;
503        loop {
504            let (l, a, mode, action) = here(self);
505            if (l, a) == (level, area) && mode == 0 && action != 0 {
506                return Ok(waited);
507            }
508            if l > 1 && mode == 0 && action != 0 && transition(self) == 0 {
509                break;
510            }
511            if waited >= max_frames || l <= 1 {
512                bail!(
513                    "the game must be playing a level to warp (it is in level {l}, play mode {mode})"
514                );
515            }
516            self.step_game(crate::GamePad::default())?;
517            waited += 1;
518        }
519        // A warp node of the destination area, from the state's own list
520        // (node 0x0A, the usual entry, if it has one).
521        let areas = var("gAreaData").ok_or_else(|| anyhow::anyhow!("no gAreaData"))?;
522        let mut node = st.u32(areas.n64 + 60 * area as u32 + 0x14).unwrap_or(0);
523        let mut ids = Vec::new();
524        while node != 0 && ids.len() < 256 {
525            ids.push(st.u8(node).unwrap_or(0));
526            node = st.u32(node + 8).unwrap_or(0);
527        }
528        let Some(&first) = ids.first() else {
529            bail!("the state's area has no warp nodes to arrive at");
530        };
531        let id = if ids.contains(&0x0A) { 0x0A } else { first };
532        let writes: Vec<(&str, Vec<u8>)> = vec![
533            (
534                "gCurrSaveFileNum",
535                (st.s16(var("gCurrSaveFileNum").unwrap().n64).unwrap_or(1))
536                    .to_le_bytes()
537                    .to_vec(),
538            ),
539            (
540                "gCurrActNum",
541                (st.s16(var("gCurrActNum").unwrap().n64).unwrap_or(1))
542                    .to_le_bytes()
543                    .to_vec(),
544            ),
545            ("sWarpCheckpointActive", vec![1]),
546            ("sTransitionTimer", 0i16.to_le_bytes().to_vec()),
547            ("sDelayedWarpOp", 0i16.to_le_bytes().to_vec()),
548            (
549                "sWarpDest",
550                vec![1, level as u8, area as u8, id, 0, 0, 0, 0],
551            ),
552            // PLAY_MODE_CHANGE_LEVEL: with the timer at 0 the next frame
553            // leaves for sWarpDest's level (play_mode_change_level).
554            ("sCurrPlayMode", 4i16.to_le_bytes().to_vec()),
555        ];
556        {
557            let (ptr, len) = self.mem_mut();
558            // SAFETY: as in load_mupen_state.
559            let mem = unsafe { std::slice::from_raw_parts_mut(ptr, len) };
560            for (name, bytes) in writes {
561                let v = var(name).unwrap();
562                mem[v.port as usize..v.port as usize + bytes.len()].copy_from_slice(&bytes);
563            }
564        }
565        for frame in 1..=max_frames {
566            self.step_game(crate::GamePad::default())?;
567            let (l, a, mode, action) = here(self);
568            if (l, a) == (level, area) && mode == 0 && action != 0 {
569                return Ok(waited + frame);
570            }
571        }
572        bail!("the warp to level {level} area {area} did not finish in {max_frames} frames")
573    }
574}
575
576#[allow(clippy::too_many_arguments)]
577fn heap_struct(
578    writes: &mut Vec<(u32, Vec<u8>)>,
579    tr: &mut Translator,
580    counts: &mut Counts,
581    st: &MupenState,
582    snap: &[u8],
583    n64: u32,
584    port: u32,
585    size: u32,
586    layout: u16,
587) {
588    let (Some(src), Some(dst)) = (
589        st.bytes(n64, size as usize),
590        snap.get(port as usize..(port + size) as usize),
591    ) else {
592        return;
593    };
594    let mut out = dst.to_vec();
595    convert(layout, src, &mut out, n64, tr, counts);
596    writes.push((port, out));
597}
598
599/// Object fields that hold two s16s were swapped as one 32-bit value by
600/// the generic layout (the field union cannot say): swap their halves back,
601/// for the slots every object uses that way and those its behavior does.
602/// And numbers that look like segmented addresses, in slots that never
603/// hold pointers, go back to being numbers.
604fn fix_s16_fields(st: &MupenState, writes: &mut [(u32, Vec<u8>)], tr: &Translator) {
605    use super::tables::{POINTER_SLOTS, S16_SLOTS, S16_SLOTS_ALL};
606    let Some((n_pool, p_pool, _)) = super::translate::target_by_name("gObjectPool") else {
607        return;
608    };
609    let Some(w) = writes.iter_mut().find(|w| w.0 == p_pool) else {
610        return;
611    };
612    for i in 0..POOL_CAPACITY {
613        let no = n_pool + i * OBJECT_SIZE;
614        let bhv = st.u32(no + OBJ_BEHAVIOR).unwrap_or(0);
615        let mut mask = S16_SLOTS_ALL;
616        if let Some(name) = bhv_name(tr, bhv)
617            && let Some((_, m)) = S16_SLOTS.iter().find(|(n, _)| *n == name)
618        {
619            mask |= m;
620        }
621        for slot in 0..0x50u32 {
622            let at = no + 0x88 + 4 * slot;
623            let Some(v) = st.u32(at) else { continue };
624            let o = (i * OBJECT_SIZE + 0x88 + 4 * slot) as usize;
625            if mask >> slot & 1 == 0 {
626                // A segmented-looking number in a slot no behavior keeps a
627                // pointer in is a number (behavior params, for one).
628                if POINTER_SLOTS >> slot & 1 == 0 && super::layout::looks_like_segmented(v) {
629                    w.1[o..o + 4].copy_from_slice(&v.to_le_bytes());
630                }
631                continue;
632            }
633            // Two big-endian halves: each swapped on its own.
634            let (hi, lo) = ((v >> 16) as u16, v as u16);
635            w.1[o..o + 2].copy_from_slice(&hi.to_le_bytes());
636            w.1[o + 2..o + 4].copy_from_slice(&lo.to_le_bytes());
637        }
638    }
639}
640
641/// Pairs the pointers in the two builds' behavior scripts: the commands are
642/// the same words, so where they differ both hold the same pointer
643/// (collision data, animation tables, native functions). Animation tables
644/// are then paired entry by entry.
645fn learn_behaviors(tr: &mut Translator, snap: &[u8]) {
646    let mut anim_tables = Vec::new();
647    for t in TARGETS.iter().filter(|t| t.0 >> 24 == 0x13) {
648        let Some(base) = tr.segmented_to_virtual(t.0) else {
649            continue;
650        };
651        let words = t.2 / 4;
652        let mut prev_cmd = 0u32;
653        for i in 0..words {
654            let (Some(n), p) = (tr.st.u32(base + 4 * i), p32(snap, t.1 + 4 * i)) else {
655                break;
656            };
657            if n != p {
658                if (0x0100_0000..0x2000_0000).contains(&n) {
659                    if let Some(v) = tr.segmented_to_virtual(n) {
660                        tr.pair(v, p);
661                        if prev_cmd >> 24 == 0x27 {
662                            anim_tables.push((v, p));
663                        }
664                    }
665                } else if super::layout::looks_like_pointer(n) {
666                    tr.pair(n, p);
667                }
668            }
669            prev_cmd = n;
670        }
671    }
672    for (n, p) in anim_tables {
673        pair_anim_table(tr, snap, n, p);
674    }
675}
676
677/// An animation table: N64 entries are segmented, the port's are pointers.
678fn pair_anim_table(tr: &mut Translator, snap: &[u8], n: u32, p: u32) {
679    for i in 0..64 {
680        let (Some(ne), pe) = (tr.st.u32(n + 4 * i), p32(snap, p + 4 * i)) else {
681            break;
682        };
683        if ne == 0 || pe == 0 {
684            break;
685        }
686        let Some(nv) = tr
687            .segmented_to_virtual(ne)
688            .or_else(|| super::layout::looks_like_pointer(ne).then_some(ne))
689        else {
690            break;
691        };
692        tr.pair(nv, pe);
693    }
694}
695
696/// The model table, the areas' heap structs and Mario's animation buffer.
697/// What the level holds that changes while playing, to copy after the
698/// variables: (N64 address, port address, size, swapped as 2 or 4-byte
699/// values).
700type LevelCopies = Vec<(u32, u32, u32, usize)>;
701
702fn learn_tables(
703    tr: &mut Translator,
704    st: &MupenState,
705    snap: &[u8],
706    report: &mut MupenLoadReport,
707) -> LevelCopies {
708    let mut copies = Vec::new();
709    learn_envfx(tr, st, snap, report);
710    if let Some(v) = var("gLoadedGraphNodes") {
711        let (n, p) = (st.u32(v.n64).unwrap_or(0), p32(snap, v.port));
712        if n != 0 && p != 0 {
713            for i in 0..256 {
714                tr.pair(st.u32(n + 4 * i).unwrap_or(0), p32(snap, p + 4 * i));
715            }
716        }
717    }
718    for (name, len) in [
719        ("gMarioAnimsMemAlloc", 0x4000),
720        ("gDemoInputsMemAlloc", 0x800),
721    ] {
722        if let Some(v) = var(name) {
723            tr.region(st.u32(v.n64).unwrap_or(0), len, p32(snap, v.port));
724        }
725    }
726    let camera = named("Camera").map_or(0, |c| c.0);
727    let spawn = named("SpawnInfo").map_or(32, |c| c.0);
728    let warp = named("ObjectWarpNode").map_or(12, |c| c.0);
729    if let Some(v) = var("gCamera") {
730        tr.region(st.u32(v.n64).unwrap_or(0), camera, p32(snap, v.port));
731    }
732    let Some(areas) = var("gAreaData") else {
733        return copies;
734    };
735    if named("Area").map(|a| a.0) != Some(60) {
736        report
737            .notes
738            .push("struct Area is not 60 bytes; areas not paired".into());
739        return copies;
740    }
741    for i in 0..areas.size / 60 {
742        let (na, pa) = (areas.n64 + 60 * i, areas.port + 60 * i);
743        let n = |o: u32| st.u32(na + o).unwrap_or(0);
744        let p = |o: u32| p32(snap, pa + o);
745        tr.pair(n(0x04), p(0x04));
746        tr.region(n(0x24), camera, p(0x24));
747        tr.region(n(0x1C), 32, p(0x1C));
748        for o in [0x2C, 0x30] {
749            tr.region(n(o), 8, p(o));
750        }
751        // Macro objects: 5 s16 per object, ended by 0x1E.
752        let (nm, pm) = (n(0x10), p(0x10));
753        if nm != 0 && pm != 0 {
754            let mut len = 0;
755            while len < 0x8000 && p16(snap, pm + len) != 0x1E {
756                len += 10;
757            }
758            tr.region(nm, len + 2, pm);
759            // Their respawn flags (set when one is collected) are in the list.
760            copies.push((nm, pm, len + 2, 2));
761        }
762        // Spawn infos and warp nodes: lists, walked side by side.
763        for (head, size, next) in [(0x20, spawn, 0x1C), (0x14, warp, 0x08)] {
764            let (mut ns, mut ps) = (n(head), p(head));
765            let mut k = 0;
766            while ns != 0 && ps != 0 && k < 1024 {
767                tr.region(ns, size, ps);
768                // Spawn infos hold the respawn flags of what they spawned,
769                // in behaviorArg.
770                if head == 0x20 {
771                    copies.push((ns + 0x10, ps + 0x10, 4, 4));
772                }
773                ns = st.u32(ns + next).unwrap_or(0);
774                ps = p32(snap, ps + next);
775                k += 1;
776            }
777            if (ns == 0) != (ps == 0) {
778                report.notes.push(format!(
779                    "area {i}: lists at {head:#x} have different lengths"
780                ));
781            }
782        }
783    }
784    copies
785}
786
787/// The paintings of the current level: structs in level data (segment 7 on
788/// the N64) that hold the ripple state. The painting lists in the game's
789/// own data point at them on both sides.
790fn learn_paintings(
791    tr: &mut Translator,
792    st: &MupenState,
793    snap: &[u8],
794    level: i16,
795) -> Vec<(u32, u32)> {
796    let list = match level {
797        6 => "sInsideCastlePaintings",
798        7 => "sHmcPaintings",
799        36 => "sTtmPaintings",
800        _ => return Vec::new(),
801    };
802    let (Some(v), Some((size, _))) = (var(list), named("Painting")) else {
803        return Vec::new();
804    };
805    let mut out = Vec::new();
806    for i in 0..v.size / 4 {
807        let (n, p) = (
808            st.u32(v.n64 + 4 * i).unwrap_or(0),
809            p32(snap, v.port + 4 * i),
810        );
811        let n = if super::layout::looks_like_pointer(n) {
812            Some(n)
813        } else {
814            tr.segmented_to_virtual(n)
815        };
816        if let Some(n) = n
817            && p != 0
818        {
819            tr.region(n, size, p);
820            out.push((n, p));
821        }
822    }
823    out
824}
825
826/// The environment effect particles (snow, bubbles, flowers, lava): an
827/// allocation made when the area loads, paired whole and copied.
828fn learn_envfx(tr: &mut Translator, st: &MupenState, snap: &[u8], report: &mut MupenLoadReport) {
829    let (Some(buf), Some(mode), Some((size, _))) = (
830        var("gEnvFxBuffer"),
831        n64_int(st, "gEnvFxMode"),
832        named("EnvFxParticle"),
833    ) else {
834        return;
835    };
836    let count = if mode == 0 {
837        return;
838    } else if mode < 10 {
839        "gSnowParticleMaxCount"
840    } else {
841        "sBubbleParticleCount"
842    };
843    let n = n64_int(st, count)
844        .unwrap_or(0)
845        .min(port_int(snap, count).unwrap_or(0));
846    let (nb, pb) = (st.u32(buf.n64).unwrap_or(0), p32(snap, buf.port));
847    if n > 0 && nb != 0 && pb != 0 && port_int(snap, "gEnvFxMode") == Some(mode) {
848        tr.region(nb, n as u32 * size, pb);
849        report.envfx = Some((nb, pb, n as u32));
850    }
851}
852
853struct Surfaces {
854    n64_surfaces: Vec<u32>,
855    port_surfaces: Vec<u32>,
856    static_surfaces: u32,
857    n64_nodes: Vec<u32>,
858    port_nodes: Vec<u32>,
859    static_nodes: u32,
860    /// The port's pool and counter updates for fresh dynamic blocks.
861    writes: Vec<(u32, Vec<u8>)>,
862}
863
864/// Pairs the surfaces and surface nodes by allocation order: the N64 keeps
865/// them in two arrays, the port in alloc-only pools (static and dynamic).
866fn learn_surfaces(
867    tr: &mut Translator,
868    st: &MupenState,
869    snap: &[u8],
870    report: &mut MupenLoadReport,
871    fresh: Option<(u32, u32, u32, u32)>,
872) -> Option<Surfaces> {
873    let n_pool = st.u32(n64_only("sSurfacePool")?)?;
874    let n_nodes = st.u32(n64_only("sSurfaceNodePool")?)?;
875    let get = |name: &str| {
876        (
877            n64_int(st, name).unwrap_or(0) as u32,
878            port_int(snap, name).unwrap_or(0) as u32,
879        )
880    };
881    let (n_static, p_static_count) = get("gNumStaticSurfaces");
882    let (n_all, p_all) = get("gSurfacesAllocated");
883    let (n_static_nodes, p_static_nodes_count) = get("gNumStaticSurfaceNodes");
884    let (n_all_nodes, p_all_nodes) = get("gSurfaceNodesAllocated");
885    report.dynamic_surfaces = (n_all.saturating_sub(n_static), 0);
886    // The port's static pools hold what loading the area made. Its
887    // gNumStaticSurfaces can count a few more (allocations made while the
888    // area loaded), so the pools, not the counters, say how many there are.
889    let pool = |name| p32(snap, port_only(name).unwrap_or(0));
890    let mut port_surfaces = pool_items(snap, pool("sStaticSurfacePool"), 48, u32::MAX);
891    let mut port_nodes = pool_items(snap, pool("sStaticSurfaceNodePool"), 8, u32::MAX);
892    let (p_static, p_static_nodes) = (port_surfaces.len() as u32, port_nodes.len() as u32);
893    report.static_surfaces = (n_static, p_static, 0);
894    if n_static != p_static || n_static_nodes != p_static_nodes {
895        report.notes.push(format!(
896            "static collision differs (surfaces {n_static} vs {p_static}, nodes {n_static_nodes} vs {p_static_nodes}): \
897             surfaces not paired"
898        ));
899        return None;
900    }
901    let mut writes = Vec::new();
902    if let Some((sb, ns, nb, nn)) = fresh {
903        // The fresh blocks become the pools' newest blocks, holding all of
904        // the state's dynamic surfaces and nodes; the older blocks are freed
905        // with them when the next frame clears the pools.
906        for (pool_var, block, count, item, all, stat) in [
907            (
908                "sDynamicSurfacePool",
909                sb,
910                ns,
911                48,
912                "gSurfacesAllocated",
913                p_static_count,
914            ),
915            (
916                "sDynamicSurfaceNodePool",
917                nb,
918                nn,
919                8,
920                "gSurfaceNodesAllocated",
921                p_static_nodes_count,
922            ),
923        ] {
924            let pool_at = pool(pool_var);
925            if pool_at == 0 {
926                return None;
927            }
928            let mut header = p32(snap, pool_at).to_le_bytes().to_vec();
929            header.extend_from_slice(&[0; 4]);
930            writes.push((block, header));
931            let mut fields = block.to_le_bytes().to_vec();
932            fields.extend_from_slice(&(count * item).to_le_bytes());
933            fields.extend_from_slice(&(count * item).to_le_bytes());
934            writes.push((pool_at, fields));
935            if let Some(v) = var(all) {
936                writes.push((
937                    v.port,
938                    (stat + count).to_le_bytes()[..v.size as usize].to_vec(),
939                ));
940            }
941        }
942        port_surfaces.extend((0..ns).map(|j| sb + 8 + 48 * j));
943        port_nodes.extend((0..nn).map(|j| nb + 8 + 8 * j));
944    } else {
945        port_surfaces.extend(pool_items(
946            snap,
947            pool("sDynamicSurfacePool"),
948            48,
949            p_all.saturating_sub(p_static_count),
950        ));
951        port_nodes.extend(pool_items(
952            snap,
953            pool("sDynamicSurfaceNodePool"),
954            8,
955            p_all_nodes.saturating_sub(p_static_nodes_count),
956        ));
957    }
958    let n64_surfaces: Vec<u32> = (0..n_all).map(|i| n_pool + 48 * i).collect();
959    let n64_nodes: Vec<u32> = (0..n_all_nodes).map(|i| n_nodes + 8 * i).collect();
960    for (n, p) in n64_surfaces.iter().zip(&port_surfaces) {
961        tr.pair(*n, *p);
962    }
963    for (n, p) in n64_nodes.iter().zip(&port_nodes) {
964        tr.pair(*n, *p);
965    }
966    let n = n64_surfaces.len().min(port_surfaces.len());
967    let m = n64_nodes.len().min(port_nodes.len());
968    Some(Surfaces {
969        n64_surfaces: n64_surfaces[..n].to_vec(),
970        port_surfaces: port_surfaces[..n].to_vec(),
971        static_surfaces: n_static,
972        n64_nodes: n64_nodes[..m].to_vec(),
973        port_nodes: port_nodes[..m].to_vec(),
974        static_nodes: n_static_nodes,
975        writes,
976    })
977}
978
979/// Object slots running the same behavior on both sides pair their pointers
980/// into level data (animations, collision, model, spawn info), which other
981/// slots with the same objects can then use.
982fn learn_objects(
983    tr: &mut Translator,
984    st: &MupenState,
985    snap: &[u8],
986    report: &mut MupenLoadReport,
987) -> Vec<(u32, u32, u32)> {
988    let mut heap = Vec::new();
989    let Some((n_pool, p_pool, _)) = super::translate::target_by_name("gObjectPool") else {
990        return heap;
991    };
992    for i in 0..POOL_CAPACITY {
993        let (no, po) = (n_pool + i * OBJECT_SIZE, p_pool + i * OBJECT_SIZE);
994        let nb = st.u32(no + OBJ_BEHAVIOR).unwrap_or(0);
995        let pb = p32(snap, po + OBJ_BEHAVIOR);
996        learn_path(tr, st, snap, no, nb);
997        if tr.lookup(nb) != Some(pb) {
998            report.objects_differing += 1;
999            continue;
1000        }
1001        if nb == 0 {
1002            continue;
1003        }
1004        let n = |o: u32| st.u32(no + o).unwrap_or(0);
1005        let p = |o: u32| p32(snap, po + o);
1006        for o in [
1007            OBJ_ANIMATIONS,
1008            OBJ_COLLISION,
1009            OBJ_SHARED_CHILD,
1010            OBJ_RESPAWN_INFO,
1011        ] {
1012            if super::layout::looks_like_pointer(n(o)) && p(o) != 0 && tr.lookup(n(o)).is_none() {
1013                tr.pair(n(o), p(o));
1014            }
1015        }
1016        if n(OBJ_ANIMATIONS) != 0 && p(OBJ_ANIMATIONS) != 0 {
1017            pair_anim_table(tr, snap, n(OBJ_ANIMATIONS), p(OBJ_ANIMATIONS));
1018        }
1019        if st.u16(no + OBJ_ANIM_ID) == Some(p16(snap, po + OBJ_ANIM_ID))
1020            && tr.lookup(n(OBJ_CUR_ANIM)).is_none()
1021        {
1022            tr.pair(n(OBJ_CUR_ANIM), p(OBJ_CUR_ANIM));
1023        }
1024        if let Some((size, _)) = named("SpawnInfo")
1025            && tr.lookup(n(OBJ_SPAWN_INFO)).is_none()
1026        {
1027            tr.region(n(OBJ_SPAWN_INFO), size, p(OBJ_SPAWN_INFO));
1028        }
1029        let name = bhv_name(tr, nb);
1030        // Chain segments, which these objects allocate from the object
1031        // memory pool (the port: malloc): the same allocation on both sides,
1032        // whose contents are copied too.
1033        for &(bhv, slot, count) in CHAIN_SEGMENTS {
1034            let o = 0x88 + 4 * slot;
1035            if name == Some(bhv) && super::layout::looks_like_pointer(n(o)) && p(o) != 0 {
1036                tr.region(n(o), count * CHAIN_SEGMENT_SIZE, p(o));
1037                for k in 0..count {
1038                    heap.push((
1039                        n(o) + k * CHAIN_SEGMENT_SIZE,
1040                        p(o) + k * CHAIN_SEGMENT_SIZE,
1041                        CHAIN_SEGMENT_SIZE,
1042                    ));
1043                }
1044            }
1045        }
1046    }
1047    heap
1048}
1049
1050/// Paths (lists of 8-byte waypoints ended by a lone -1, in level data):
1051/// found in the port by their contents, so that the start field and the
1052/// current waypoint field both translate, whatever the port's slot holds.
1053fn learn_path(tr: &mut Translator, st: &MupenState, snap: &[u8], no: u32, nb: u32) {
1054    let start = st.u32(no + 0x88 + 4 * WAYPOINT_START_SLOT).unwrap_or(0);
1055    if !super::layout::looks_like_pointer(start)
1056        || !bhv_name(tr, nb).is_some_and(|b| super::tables::PATH_BEHAVIORS.contains(&b))
1057    {
1058        return;
1059    }
1060    let mut want = Vec::new();
1061    loop {
1062        let Some(w) = st.bytes(start + want.len() as u32, 8) else {
1063            return;
1064        };
1065        // The end is a lone -1 (TRAJECTORY_END), not a whole waypoint.
1066        if w[0] == 0xFF && w[1] == 0xFF {
1067            want.extend_from_slice(&[0xFF, 0xFF]);
1068            break;
1069        }
1070        for k in 0..4 {
1071            want.extend_from_slice(&[w[2 * k + 1], w[2 * k]]);
1072        }
1073        if want.len() > 0x1000 {
1074            return;
1075        }
1076    }
1077    // Where the start already translates (by name), the whole list follows
1078    // it; otherwise look for the list itself.
1079    let at = tr
1080        .lookup(start)
1081        .filter(|&p| snap.get(p as usize..p as usize + want.len()) == Some(&want[..]));
1082    if let Some(p) = at.or_else(|| find_first(snap, &want)) {
1083        tr.region(start, want.len() as u32, p);
1084    }
1085}
1086
1087/// Where `want` first occurs in `mem` (2-byte aligned). Read-only data
1088/// with the same contents is interchangeable, so a copy elsewhere is as good.
1089fn find_first(mem: &[u8], want: &[u8]) -> Option<u32> {
1090    let mut at = 0;
1091    while at + want.len() <= mem.len() {
1092        if mem[at] == want[0] && mem[at + 1] == want[1] && mem[at..at + want.len()] == *want {
1093            return Some(at as u32);
1094        }
1095        at += 2;
1096    }
1097    None
1098}
1099
1100/// oPathedStartWaypoint / oPlatformOnTrackStartWaypoint.
1101const WAYPOINT_START_SLOT: u32 = 0x1D;
1102
1103/// Objects that allocate chain segments: (behavior, field slot, count), as
1104/// in chain_chomp.inc.c and wiggler.inc.c.
1105const CHAIN_SEGMENTS: &[(&str, u32, u32)] =
1106    &[("bhvChainChomp", 0x1B, 5), ("bhvWigglerHead", 0x1C, 4)];
1107const CHAIN_SEGMENT_SIZE: u32 = 0x14;
1108
1109/// The name of the behavior script at N64 address `bhv`.
1110fn bhv_name(tr: &Translator, bhv: u32) -> Option<&'static str> {
1111    let seg = tr.virtual_to_segmented(bhv)?;
1112    TARGETS.iter().find(|t| t.0 == seg).map(|t| t.3)
1113}
1114
1115/// Mario's animation is loaded into a buffer from a table (the N64 by DMA
1116/// from ROM, the port by copying): load the one the state has loaded, the way
1117/// `load_patchable_table` and `set_mario_animation` do.
1118fn fix_mario_animation(st: &MupenState, mem: &mut [u8], report: &mut MupenLoadReport) {
1119    let Some(v) = var("gMarioAnimsBuf") else {
1120        return;
1121    };
1122    let rd = |m: &[u8], a: u32| p32(m, a);
1123    // N64: which animation is in the buffer.
1124    let (Some(n_table), Some(n_current)) = (st.u32(v.n64), st.u32(v.n64 + 4)) else {
1125        return;
1126    };
1127    let n_count = st.u32(n_table).unwrap_or(0);
1128    let n_src = st.u32(n_table + 4).unwrap_or(0);
1129    let index = (0..n_count.min(1024))
1130        .find(|&i| st.u32(n_table + 8 + 8 * i).map(|o| n_src.wrapping_add(o)) == Some(n_current));
1131    let Some(index) = index else {
1132        report
1133            .notes
1134            .push("could not tell which Mario animation the state has loaded".into());
1135        return;
1136    };
1137    let (p_table, p_current, p_buf) = (rd(mem, v.port), rd(mem, v.port + 4), rd(mem, v.port + 8));
1138    if p_table == 0 || p_buf == 0 || index >= rd(mem, p_table) {
1139        return;
1140    }
1141    let src = rd(mem, p_table + 4).wrapping_add(rd(mem, p_table + 8 + 8 * index));
1142    let size = rd(mem, p_table + 12 + 8 * index);
1143    if src == p_current {
1144        return;
1145    }
1146    let (s, d, n) = (src as usize, p_buf as usize, size as usize);
1147    if s + n > mem.len() || d + n > mem.len() || n > 0x4000 {
1148        report
1149            .notes
1150            .push("Mario's animation is out of bounds; not loaded".into());
1151        return;
1152    }
1153    mem.copy_within(s..s + n, d);
1154    // values and index are offsets from the animation until loaded.
1155    for o in [0x0C, 0x10] {
1156        let off = rd(mem, p_buf + o);
1157        mem[d + o as usize..d + o as usize + 4]
1158            .copy_from_slice(&p_buf.wrapping_add(off).to_le_bytes());
1159    }
1160    mem[v.port as usize + 4..v.port as usize + 8].copy_from_slice(&src.to_le_bytes());
1161}