1use anyhow::{Result, bail};
15
16use super::MupenState;
17use super::layout::{Counts, convert, named, var};
18use super::tables::{BUILD_ID, N64_ONLY, TARGETS, VARS};
19use super::translate::Translator;
20use crate::sm64::SM64Game;
21
22#[derive(Debug, Clone, Default)]
24pub struct MupenLoadReport {
25 pub level: i16,
26 pub area: i16,
27 pub vars_copied: usize,
29 pub pointers: u32,
32 pub pointers_kept: u32,
33 pub pairs_learned: usize,
35 pub static_surfaces: (u32, u32, u32),
39 pub dynamic_surfaces: (u32, u32),
42 pub objects_differing: u32,
46 pub kept: Vec<(String, u32, u32)>,
49 pub notes: Vec<String>,
50 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 p32(m: &[u8], a: u32) -> u32 {
89 m.get(a as usize..a as usize + 4)
90 .map_or(0, |b| u32::from_le_bytes(b.try_into().unwrap()))
91}
92fn p16(m: &[u8], a: u32) -> u16 {
93 m.get(a as usize..a as usize + 2)
94 .map_or(0, |b| u16::from_le_bytes(b.try_into().unwrap()))
95}
96
97fn n64_int(st: &MupenState, name: &str) -> Option<i64> {
99 let v = var(name)?;
100 Some(match v.size {
101 1 => st.u8(v.n64)? as i8 as i64,
102 2 => st.s16(v.n64)? as i64,
103 _ => st.u32(v.n64)? as i32 as i64,
104 })
105}
106fn port_int(m: &[u8], name: &str) -> Option<i64> {
107 let v = var(name)?;
108 Some(match v.size {
109 1 => *m.get(v.port as usize)? as i8 as i64,
110 2 => p16(m, v.port) as i16 as i64,
111 _ => p32(m, v.port) as i32 as i64,
112 })
113}
114
115fn describe(a: u32) -> String {
117 let i = VARS.partition_point(|v| v.n64 <= a);
118 if let Some(v) = i.checked_sub(1).map(|i| &VARS[i])
119 && a - v.n64 < v.size
120 {
121 return format!("{}+{:#x}", v.name, a - v.n64);
122 }
123 format!("heap {a:#010x}")
124}
125
126const OBJECT_SIZE: u32 = 0x260;
127const POOL_CAPACITY: u32 = 240;
128const OBJ_BEHAVIOR: u32 = 0x20C;
129const OBJ_ANIMATIONS: u32 = 0x88 + 0x26 * 4;
130const OBJ_COLLISION: u32 = 0x218;
131const OBJ_CUR_ANIM: u32 = 0x3C;
132const OBJ_ANIM_ID: u32 = 0x38;
133const OBJ_SHARED_CHILD: u32 = 0x14;
134const OBJ_SPAWN_INFO: u32 = 0x4C;
135const OBJ_RESPAWN_INFO: u32 = 0x25C;
136
137impl MupenState {
138 pub fn level(&self) -> Option<i16> {
140 self.s16(var("gCurrLevelNum")?.n64)
141 }
142 pub fn area(&self) -> Option<i16> {
144 self.s16(var("gCurrAreaIndex")?.n64)
145 }
146 pub fn global_timer(&self) -> Option<u32> {
148 self.u32(var("gGlobalTimer")?.n64)
149 }
150 pub fn mario_state_bytes(&self) -> Option<Vec<u8>> {
154 let v = var("gMarioStates")?;
155 let src = self.bytes(v.n64, v.size as usize)?;
156 let mut out = vec![0u8; v.size as usize];
157 let mut tr = Translator::new(self, None, None);
158 convert(
159 v.layout,
160 src,
161 &mut out,
162 v.n64,
163 &mut tr,
164 &mut Counts::default(),
165 );
166 for (&at, &val) in &tr.failures {
169 let o = (at - v.n64) as usize;
170 out[o..o + 4].copy_from_slice(&val.to_le_bytes());
171 }
172 Some(out)
173 }
174}
175
176impl SM64Game {
177 pub fn load_mupen_state(&mut self, st: &MupenState) -> Result<MupenLoadReport> {
187 let id: String = self.build_id.iter().map(|b| format!("{b:02x}")).collect();
188 if id != BUILD_ID {
189 bail!("Mupen state tables are for build {BUILD_ID}, this game is build {id}");
190 }
191 let mut report = MupenLoadReport::default();
192 if !st.is_us_rom() {
193 report.notes.push(format!(
194 "state is for ROM MD5 {}, not the US ROM",
195 st.rom_md5
196 ));
197 }
198 let snap: Vec<u8> = self.with_memory(|m| m.to_vec());
199 let (Some(level), Some(area)) = (st.level(), st.area()) else {
200 bail!("state has no level/area");
201 };
202 let port_level = port_int(&snap, "gCurrLevelNum").unwrap_or(-1) as i16;
203 let port_area = port_int(&snap, "gCurrAreaIndex").unwrap_or(-1) as i16;
204 if (level, area) != (port_level, port_area) {
205 bail!(
206 "the state is in level {level} area {area}, this game is in level {port_level} area {port_area}: \
207 bring the game to the same area first"
208 );
209 }
210 report.level = level;
211 report.area = area;
212
213 let mut tr = Translator::new(st, n64_only("sSegmentTable"), Some(&snap));
214 learn_behaviors(&mut tr, &snap);
215 let level_copies = learn_tables(&mut tr, st, &snap, &mut report);
216 let surfaces = learn_surfaces(&mut tr, st, &snap, &mut report);
217 let object_pool = learn_object_pool(&mut tr, st, &snap, &mut report);
218 let object_heap = learn_objects(
219 &mut tr,
220 st,
221 &snap,
222 &mut report,
223 object_pool.as_ref().map(|p| p.space),
224 );
225 let paintings = learn_paintings(&mut tr, st, &snap, level);
226 report.pairs_learned = tr.pair_count();
227
228 let mut writes: Vec<(u32, Vec<u8>)> = Vec::new();
230 let mut counts = Counts::default();
231 for v in VARS.iter().filter(|v| v.copy) {
232 let (Some(src), Some(dst)) = (
233 st.bytes(v.n64, v.size as usize),
234 snap.get(v.port as usize..(v.port + v.size) as usize),
235 ) else {
236 continue;
237 };
238 let mut out = dst.to_vec();
239 convert(v.layout, src, &mut out, v.n64, &mut tr, &mut counts);
240 writes.push((v.port, out));
241 report.vars_copied += 1;
242 }
243
244 fix_s16_fields(st, &mut writes, &tr);
245
246 if let (Some((nb, pb, count)), Some((size, layout))) =
247 (report.envfx, named("EnvFxParticle"))
248 {
249 for k in 0..count {
250 heap_struct(
251 &mut writes,
252 &mut tr,
253 &mut counts,
254 st,
255 &snap,
256 nb + k * size,
257 pb + k * size,
258 size,
259 layout,
260 );
261 }
262 }
263
264 let read_only = self.read_only_memory();
267 for &(n, p, size, unit) in &level_copies {
268 if read_only.contains(&(p as usize)) {
269 continue;
270 }
271 if let Some(src) = st.bytes(n, size as usize) {
272 let out: Vec<u8> = src
273 .chunks_exact(unit)
274 .flat_map(|h| h.iter().rev().copied())
275 .collect();
276 writes.push((p, out));
277 }
278 }
279
280 if let Some((size, layout)) = named("Painting") {
282 for &(n, p) in &paintings {
283 heap_struct(
284 &mut writes,
285 &mut tr,
286 &mut counts,
287 st,
288 &snap,
289 n,
290 p,
291 size,
292 layout,
293 );
294 }
295 }
296
297 if let Some(pool) = object_pool {
300 writes.extend(pool.writes);
301 }
302 if let Some((size, layout)) = named("ChainSegment") {
303 for &(n, p, len) in &object_heap {
304 debug_assert_eq!(len, size);
305 heap_struct(
306 &mut writes,
307 &mut tr,
308 &mut counts,
309 st,
310 &snap,
311 n,
312 p,
313 size,
314 layout,
315 );
316 }
317 }
318
319 if let (Some(gc), Some((size, layout))) = (var("gCamera"), named("Camera")) {
321 let (n, p) = (st.u32(gc.n64).unwrap_or(0), p32(&snap, gc.port));
322 if n != 0 && p != 0 {
323 heap_struct(
324 &mut writes,
325 &mut tr,
326 &mut counts,
327 st,
328 &snap,
329 n,
330 p,
331 size,
332 layout,
333 );
334 }
335 }
336
337 if let Some(s) = &surfaces {
342 for (kind, n64, port, capacity, live, statics) in [
343 (
344 "Surface",
345 s.n64_surfaces,
346 s.port_surfaces,
347 SURFACE_POOL_SIZE,
348 s.surfaces,
349 s.static_surfaces,
350 ),
351 (
352 "SurfaceNode",
353 s.n64_nodes,
354 s.port_nodes,
355 SURFACE_NODE_POOL_SIZE,
356 s.nodes,
357 s.static_nodes,
358 ),
359 ] {
360 let Some((size, layout)) = named(kind) else {
361 continue;
362 };
363 let mut stale = Counts::default();
364 for i in 0..capacity {
365 let (n, p) = (n64 + i * size, port + i * size);
366 if i < statics {
367 let mut out = snap[p as usize..(p + size) as usize].to_vec();
368 let mut c = Counts::default();
369 convert(
370 layout,
371 st.bytes(n, size as usize).unwrap_or(&[]),
372 &mut out,
373 n,
374 &mut tr,
375 &mut c,
376 );
377 if kind == "Surface" && out != snap[p as usize..(p + size) as usize] {
378 report.static_surfaces.2 += 1;
379 }
380 continue;
381 }
382 let c = if i < live { &mut counts } else { &mut stale };
385 heap_struct(&mut writes, &mut tr, c, st, &snap, n, p, size, layout);
386 if kind == "Surface" && i < live {
387 report.dynamic_surfaces.1 += 1;
388 }
389 }
390 }
391 }
392
393 report.pointers = counts.pointers;
394 report.pointers_kept = counts.kept;
395 report.kept = tr
396 .failures
397 .iter()
398 .take(400)
399 .map(|(&at, &v)| (describe(at), at, v))
400 .collect();
401
402 let (ptr, len) = self.mem_mut();
404 let mem = unsafe { std::slice::from_raw_parts_mut(ptr, len) };
407 for (addr, bytes) in &writes {
408 let a = *addr as usize;
409 if let Some(dst) = mem.get_mut(a..a + bytes.len()) {
410 dst.copy_from_slice(bytes);
411 }
412 }
413 fix_mario_animation(st, mem, &mut report);
414 Ok(report)
415 }
416}
417
418impl SM64Game {
419 pub fn warp_to_mupen_area(&mut self, st: &MupenState, max_frames: u32) -> Result<u32> {
428 let (Some(level), Some(area)) = (st.level(), st.area()) else {
429 bail!("state has no level/area");
430 };
431 let here = |g: &SM64Game| {
432 g.with_memory(|m| {
433 (
434 port_int(m, "gCurrLevelNum").unwrap_or(-1) as i16,
435 port_int(m, "gCurrAreaIndex").unwrap_or(-1) as i16,
436 port_int(m, "sCurrPlayMode").unwrap_or(-1),
437 p32(m, var("gMarioStates").map_or(0, |v| v.port) + 0x0C),
438 )
439 })
440 };
441 let transition = |g: &SM64Game| {
442 g.with_memory(|m| p32(m, var("sTransitionUpdate").map_or(0, |v| v.port)))
443 };
444 if here(self).0 == level && here(self).1 == area {
445 return Ok(0);
446 }
447 let mut waited = 0;
449 loop {
450 let (l, a, mode, action) = here(self);
451 if (l, a) == (level, area) && mode == 0 && action != 0 {
452 return Ok(waited);
453 }
454 if l > 1 && mode == 0 && action != 0 && transition(self) == 0 {
455 break;
456 }
457 if waited >= max_frames || l <= 1 {
458 bail!(
459 "the game must be playing a level to warp (it is in level {l}, play mode {mode})"
460 );
461 }
462 self.step_game(crate::GamePad::default())?;
463 waited += 1;
464 }
465 let areas = var("gAreaData").ok_or_else(|| anyhow::anyhow!("no gAreaData"))?;
468 let mut node = st.u32(areas.n64 + 60 * area as u32 + 0x14).unwrap_or(0);
469 let mut ids = Vec::new();
470 while node != 0 && ids.len() < 256 {
471 ids.push(st.u8(node).unwrap_or(0));
472 node = st.u32(node + 8).unwrap_or(0);
473 }
474 let Some(&first) = ids.first() else {
475 bail!("the state's area has no warp nodes to arrive at");
476 };
477 let id = if ids.contains(&0x0A) { 0x0A } else { first };
478 let writes: Vec<(&str, Vec<u8>)> = vec![
479 (
480 "gCurrSaveFileNum",
481 (st.s16(var("gCurrSaveFileNum").unwrap().n64).unwrap_or(1))
482 .to_le_bytes()
483 .to_vec(),
484 ),
485 (
486 "gCurrActNum",
487 (st.s16(var("gCurrActNum").unwrap().n64).unwrap_or(1))
488 .to_le_bytes()
489 .to_vec(),
490 ),
491 ("sWarpCheckpointActive", vec![1]),
492 ("sTransitionTimer", 0i16.to_le_bytes().to_vec()),
493 ("sDelayedWarpOp", 0i16.to_le_bytes().to_vec()),
494 (
495 "sWarpDest",
496 vec![1, level as u8, area as u8, id, 0, 0, 0, 0],
497 ),
498 ("sCurrPlayMode", 4i16.to_le_bytes().to_vec()),
501 ];
502 {
503 let (ptr, len) = self.mem_mut();
504 let mem = unsafe { std::slice::from_raw_parts_mut(ptr, len) };
506 for (name, bytes) in writes {
507 let v = var(name).unwrap();
508 mem[v.port as usize..v.port as usize + bytes.len()].copy_from_slice(&bytes);
509 }
510 }
511 for frame in 1..=max_frames {
512 self.step_game(crate::GamePad::default())?;
513 let (l, a, mode, action) = here(self);
514 if (l, a) == (level, area) && mode == 0 && action != 0 {
515 return Ok(waited + frame);
516 }
517 }
518 bail!("the warp to level {level} area {area} did not finish in {max_frames} frames")
519 }
520}
521
522#[allow(clippy::too_many_arguments)]
523fn heap_struct(
524 writes: &mut Vec<(u32, Vec<u8>)>,
525 tr: &mut Translator,
526 counts: &mut Counts,
527 st: &MupenState,
528 snap: &[u8],
529 n64: u32,
530 port: u32,
531 size: u32,
532 layout: u16,
533) {
534 let (Some(src), Some(dst)) = (
535 st.bytes(n64, size as usize),
536 snap.get(port as usize..(port + size) as usize),
537 ) else {
538 return;
539 };
540 let mut out = dst.to_vec();
541 convert(layout, src, &mut out, n64, tr, counts);
542 writes.push((port, out));
543}
544
545fn fix_s16_fields(st: &MupenState, writes: &mut [(u32, Vec<u8>)], tr: &Translator) {
551 use super::tables::{POINTER_SLOTS, S16_SLOTS, S16_SLOTS_ALL};
552 let Some((n_pool, p_pool, _)) = super::translate::target_by_name("gObjectPool") else {
553 return;
554 };
555 let Some(w) = writes.iter_mut().find(|w| w.0 == p_pool) else {
556 return;
557 };
558 for i in 0..POOL_CAPACITY {
559 let no = n_pool + i * OBJECT_SIZE;
560 let bhv = st.u32(no + OBJ_BEHAVIOR).unwrap_or(0);
561 let mut mask = S16_SLOTS_ALL;
562 if let Some(name) = bhv_name(tr, bhv)
563 && let Some((_, m)) = S16_SLOTS.iter().find(|(n, _)| *n == name)
564 {
565 mask |= m;
566 }
567 for slot in 0..0x50u32 {
568 let at = no + 0x88 + 4 * slot;
569 let Some(v) = st.u32(at) else { continue };
570 let o = (i * OBJECT_SIZE + 0x88 + 4 * slot) as usize;
571 if mask >> slot & 1 == 0 {
572 if POINTER_SLOTS >> slot & 1 == 0 && super::layout::looks_like_segmented(v) {
575 w.1[o..o + 4].copy_from_slice(&v.to_le_bytes());
576 }
577 continue;
578 }
579 let (hi, lo) = ((v >> 16) as u16, v as u16);
581 w.1[o..o + 2].copy_from_slice(&hi.to_le_bytes());
582 w.1[o + 2..o + 4].copy_from_slice(&lo.to_le_bytes());
583 }
584 }
585}
586
587fn learn_behaviors(tr: &mut Translator, snap: &[u8]) {
592 let mut anim_tables = Vec::new();
593 for t in TARGETS.iter().filter(|t| t.0 >> 24 == 0x13) {
594 let Some(base) = tr.segmented_to_virtual(t.0) else {
595 continue;
596 };
597 let words = t.2 / 4;
598 let mut prev_cmd = 0u32;
599 for i in 0..words {
600 let (Some(n), p) = (tr.st.u32(base + 4 * i), p32(snap, t.1 + 4 * i)) else {
601 break;
602 };
603 if n != p {
604 if (0x0100_0000..0x2000_0000).contains(&n) {
605 if let Some(v) = tr.segmented_to_virtual(n) {
606 tr.pair(v, p);
607 if prev_cmd >> 24 == 0x27 {
608 anim_tables.push((v, p));
609 }
610 }
611 } else if super::layout::looks_like_pointer(n) {
612 tr.pair(n, p);
613 }
614 }
615 prev_cmd = n;
616 }
617 }
618 for (n, p) in anim_tables {
619 pair_anim_table(tr, snap, n, p);
620 }
621}
622
623fn pair_anim_table(tr: &mut Translator, snap: &[u8], n: u32, p: u32) {
625 for i in 0..64 {
626 let (Some(ne), pe) = (tr.st.u32(n + 4 * i), p32(snap, p + 4 * i)) else {
627 break;
628 };
629 if ne == 0 || pe == 0 {
630 break;
631 }
632 let Some(nv) = tr
633 .segmented_to_virtual(ne)
634 .or_else(|| super::layout::looks_like_pointer(ne).then_some(ne))
635 else {
636 break;
637 };
638 tr.pair(nv, pe);
639 }
640}
641
642type LevelCopies = Vec<(u32, u32, u32, usize)>;
647
648fn learn_tables(
649 tr: &mut Translator,
650 st: &MupenState,
651 snap: &[u8],
652 report: &mut MupenLoadReport,
653) -> LevelCopies {
654 let mut copies = Vec::new();
655 learn_envfx(tr, st, snap, report);
656 if let Some(v) = var("gLoadedGraphNodes") {
657 let (n, p) = (st.u32(v.n64).unwrap_or(0), p32(snap, v.port));
658 if n != 0 && p != 0 {
659 for i in 0..256 {
660 tr.pair(st.u32(n + 4 * i).unwrap_or(0), p32(snap, p + 4 * i));
661 }
662 }
663 }
664 for (name, len) in [
665 ("gMarioAnimsMemAlloc", 0x4000),
666 ("gDemoInputsMemAlloc", 0x800),
667 ] {
668 if let Some(v) = var(name) {
669 tr.region(st.u32(v.n64).unwrap_or(0), len, p32(snap, v.port));
670 }
671 }
672 let camera = named("Camera").map_or(0, |c| c.0);
673 let spawn = named("SpawnInfo").map_or(32, |c| c.0);
674 let warp = named("ObjectWarpNode").map_or(12, |c| c.0);
675 if let Some(v) = var("gCamera") {
676 tr.region(st.u32(v.n64).unwrap_or(0), camera, p32(snap, v.port));
677 }
678 let Some(areas) = var("gAreaData") else {
679 return copies;
680 };
681 if named("Area").map(|a| a.0) != Some(60) {
682 report
683 .notes
684 .push("struct Area is not 60 bytes; areas not paired".into());
685 return copies;
686 }
687 for i in 0..areas.size / 60 {
688 let (na, pa) = (areas.n64 + 60 * i, areas.port + 60 * i);
689 let n = |o: u32| st.u32(na + o).unwrap_or(0);
690 let p = |o: u32| p32(snap, pa + o);
691 tr.pair(n(0x04), p(0x04));
692 tr.region(n(0x24), camera, p(0x24));
693 tr.region(n(0x1C), 32, p(0x1C));
694 for o in [0x2C, 0x30] {
695 tr.region(n(o), 8, p(o));
696 }
697 let (nm, pm) = (n(0x10), p(0x10));
699 if nm != 0 && pm != 0 {
700 let mut len = 0;
701 while len < 0x8000 && p16(snap, pm + len) != 0x1E {
702 len += 10;
703 }
704 tr.region(nm, len + 2, pm);
705 copies.push((nm, pm, len + 2, 2));
707 }
708 for (head, size, next) in [(0x20, spawn, 0x1C), (0x14, warp, 0x08)] {
710 let (mut ns, mut ps) = (n(head), p(head));
711 let mut k = 0;
712 while ns != 0 && ps != 0 && k < 1024 {
713 tr.region(ns, size, ps);
714 if head == 0x20 {
717 copies.push((ns + 0x10, ps + 0x10, 4, 4));
718 }
719 ns = st.u32(ns + next).unwrap_or(0);
720 ps = p32(snap, ps + next);
721 k += 1;
722 }
723 if (ns == 0) != (ps == 0) {
724 report.notes.push(format!(
725 "area {i}: lists at {head:#x} have different lengths"
726 ));
727 }
728 }
729 }
730 copies
731}
732
733fn learn_paintings(
737 tr: &mut Translator,
738 st: &MupenState,
739 snap: &[u8],
740 level: i16,
741) -> Vec<(u32, u32)> {
742 let list = match level {
743 6 => "sInsideCastlePaintings",
744 7 => "sHmcPaintings",
745 36 => "sTtmPaintings",
746 _ => return Vec::new(),
747 };
748 let (Some(v), Some((size, _))) = (var(list), named("Painting")) else {
749 return Vec::new();
750 };
751 let mut out = Vec::new();
752 for i in 0..v.size / 4 {
753 let (n, p) = (
754 st.u32(v.n64 + 4 * i).unwrap_or(0),
755 p32(snap, v.port + 4 * i),
756 );
757 let n = if super::layout::looks_like_pointer(n) {
758 Some(n)
759 } else {
760 tr.segmented_to_virtual(n)
761 };
762 if let Some(n) = n
763 && p != 0
764 {
765 tr.region(n, size, p);
766 out.push((n, p));
767 }
768 }
769 out
770}
771
772fn learn_envfx(tr: &mut Translator, st: &MupenState, snap: &[u8], report: &mut MupenLoadReport) {
775 let (Some(buf), Some(mode), Some((size, _))) = (
776 var("gEnvFxBuffer"),
777 n64_int(st, "gEnvFxMode"),
778 named("EnvFxParticle"),
779 ) else {
780 return;
781 };
782 let count = if mode == 0 {
783 return;
784 } else if mode < 10 {
785 "gSnowParticleMaxCount"
786 } else {
787 "sBubbleParticleCount"
788 };
789 let n = n64_int(st, count)
790 .unwrap_or(0)
791 .min(port_int(snap, count).unwrap_or(0));
792 let (nb, pb) = (st.u32(buf.n64).unwrap_or(0), p32(snap, buf.port));
793 if n > 0 && nb != 0 && pb != 0 && port_int(snap, "gEnvFxMode") == Some(mode) {
794 tr.region(nb, n as u32 * size, pb);
795 report.envfx = Some((nb, pb, n as u32));
796 }
797}
798
799const SURFACE_POOL_SIZE: u32 = 2300;
803const SURFACE_NODE_POOL_SIZE: u32 = 7000;
804
805struct Surfaces {
806 n64_surfaces: u32,
807 port_surfaces: u32,
808 surfaces: u32,
810 static_surfaces: u32,
811 n64_nodes: u32,
812 port_nodes: u32,
813 nodes: u32,
814 static_nodes: u32,
815}
816
817fn learn_surfaces(
821 tr: &mut Translator,
822 st: &MupenState,
823 snap: &[u8],
824 report: &mut MupenLoadReport,
825) -> Option<Surfaces> {
826 let n_pool = st.u32(n64_only("sSurfacePool")?)?;
827 let n_nodes = st.u32(n64_only("sSurfaceNodePool")?)?;
828 let (p_pool, p_nodes) = (
829 p32(snap, var("sSurfacePool")?.port),
830 p32(snap, var("sSurfaceNodePool")?.port),
831 );
832 let get = |name: &str| {
833 (
834 n64_int(st, name).unwrap_or(0) as u32,
835 port_int(snap, name).unwrap_or(0) as u32,
836 )
837 };
838 let (n_static, p_static) = get("gNumStaticSurfaces");
839 let (n_all, _) = get("gSurfacesAllocated");
840 let (n_static_nodes, p_static_nodes) = get("gNumStaticSurfaceNodes");
841 let (n_all_nodes, _) = get("gSurfaceNodesAllocated");
842 report.static_surfaces = (n_static, p_static, 0);
843 report.dynamic_surfaces = (n_all.saturating_sub(n_static), 0);
844 if n_pool == 0 || n_nodes == 0 || p_pool == 0 || p_nodes == 0 {
845 report
846 .notes
847 .push("no surface pools (not in a level)".into());
848 return None;
849 }
850 if n_static != p_static || n_static_nodes != p_static_nodes {
851 report.notes.push(format!(
852 "static collision differs (surfaces {n_static} vs {p_static}, nodes {n_static_nodes} vs {p_static_nodes}): \
853 surfaces not paired"
854 ));
855 return None;
856 }
857 if n_all > SURFACE_POOL_SIZE || n_all_nodes > SURFACE_NODE_POOL_SIZE {
858 report.notes.push(format!(
859 "the state has {n_all} surfaces and {n_all_nodes} nodes: the N64 wrote those past its pools \
860 over other memory, they are not copied"
861 ));
862 }
863 tr.region(n_pool, SURFACE_POOL_SIZE * 48, p_pool);
864 tr.region(n_nodes, SURFACE_NODE_POOL_SIZE * 8, p_nodes);
865 Some(Surfaces {
866 n64_surfaces: n_pool,
867 port_surfaces: p_pool,
868 surfaces: n_all.min(SURFACE_POOL_SIZE),
869 static_surfaces: n_static,
870 n64_nodes: n_nodes,
871 port_nodes: p_nodes,
872 nodes: n_all_nodes.min(SURFACE_NODE_POOL_SIZE),
873 static_nodes: n_static_nodes,
874 })
875}
876
877struct ObjectPool {
882 space: (u32, u32, u32),
884 writes: Vec<(u32, Vec<u8>)>,
886}
887
888fn learn_object_pool(
896 tr: &mut Translator,
897 st: &MupenState,
898 snap: &[u8],
899 report: &mut MupenLoadReport,
900) -> Option<ObjectPool> {
901 let v = var("gObjectMemoryPool")?;
902 let (n_pool, p_pool) = (st.u32(v.n64)?, p32(snap, v.port));
903 let (size, _) = named("MemoryPool")?;
904 if n_pool == 0 || p_pool == 0 {
905 return None;
906 }
907 let fixed = p_pool + size - 16;
910 let n_total = st.u32(n_pool)?;
911 let n_space = st.u32(n_pool + 4)?;
912 let (p_total, p_first) = (p32(snap, fixed), p32(snap, fixed + 4));
913 if n_total != p_total || n_total == 0 || n_space != n_pool + 16 || p_first != size {
914 report.notes.push(format!(
915 "object memory pool not copied: N64 {n_total:#x} bytes at {n_space:#x}, port {p_total:#x} at offset {p_first:#x}"
916 ));
917 return None;
918 }
919 let p_space = p_pool + p_first;
920 let offset = |a: u32| {
921 if a >= n_space && a - n_space < n_total {
922 a - n_space + p_first
923 } else {
924 0
925 }
926 };
927 let mut free = std::collections::HashSet::new();
928 let mut at = st.u32(n_pool + 8)?;
929 while at != 0 && free.len() < 1024 {
930 if offset(at) == 0 || !free.insert(at - n_space) {
931 break;
932 }
933 at = st.u32(at)?;
934 }
935 let mut space = vec![0u8; n_total as usize];
936 let mut off = 0u32;
937 while off < n_total {
938 let (next, len) = (st.u32(n_space + off)?, st.u32(n_space + off + 4)?);
939 if len < 8 || len % 4 != 0 || off + len > n_total {
940 report.notes.push(format!(
941 "object memory pool not copied: a block of {len:#x} bytes at offset {off:#x}"
942 ));
943 return None;
944 }
945 let o = off as usize;
946 space[o..o + 4].copy_from_slice(&offset(next).to_le_bytes());
947 space[o + 4..o + 8].copy_from_slice(&len.to_le_bytes());
948 if !free.contains(&off) {
949 for w in (8..len).step_by(4) {
950 space[o + w as usize..o + w as usize + 4]
951 .copy_from_slice(&st.u32(n_space + off + w)?.to_le_bytes());
952 }
953 }
954 off += len;
955 }
956 let mut head = Vec::with_capacity(12);
958 for w in [n_total, p_first, offset(st.u32(n_pool + 8)?)] {
959 head.extend_from_slice(&w.to_le_bytes());
960 }
961 tr.region(n_space, n_total, p_space);
962 Some(ObjectPool {
963 space: (n_space, n_total, p_space),
964 writes: vec![(fixed, head), (p_space, space)],
965 })
966}
967
968fn learn_objects(
969 tr: &mut Translator,
970 st: &MupenState,
971 snap: &[u8],
972 report: &mut MupenLoadReport,
973 pool: Option<(u32, u32, u32)>,
974) -> Vec<(u32, u32, u32)> {
975 let mut heap = Vec::new();
976 let Some((n_pool, p_pool, _)) = super::translate::target_by_name("gObjectPool") else {
977 return heap;
978 };
979 for i in 0..POOL_CAPACITY {
980 let (no, po) = (n_pool + i * OBJECT_SIZE, p_pool + i * OBJECT_SIZE);
981 let nb = st.u32(no + OBJ_BEHAVIOR).unwrap_or(0);
982 let pb = p32(snap, po + OBJ_BEHAVIOR);
983 learn_path(tr, st, snap, no, nb);
984 if tr.lookup(nb) != Some(pb) {
985 report.objects_differing += 1;
986 continue;
987 }
988 if nb == 0 {
989 continue;
990 }
991 let n = |o: u32| st.u32(no + o).unwrap_or(0);
992 let p = |o: u32| p32(snap, po + o);
993 for o in [
994 OBJ_ANIMATIONS,
995 OBJ_COLLISION,
996 OBJ_SHARED_CHILD,
997 OBJ_RESPAWN_INFO,
998 ] {
999 if super::layout::looks_like_pointer(n(o)) && p(o) != 0 && tr.lookup(n(o)).is_none() {
1000 tr.pair(n(o), p(o));
1001 }
1002 }
1003 if n(OBJ_ANIMATIONS) != 0 && p(OBJ_ANIMATIONS) != 0 {
1004 pair_anim_table(tr, snap, n(OBJ_ANIMATIONS), p(OBJ_ANIMATIONS));
1005 }
1006 if st.u16(no + OBJ_ANIM_ID) == Some(p16(snap, po + OBJ_ANIM_ID))
1007 && tr.lookup(n(OBJ_CUR_ANIM)).is_none()
1008 {
1009 tr.pair(n(OBJ_CUR_ANIM), p(OBJ_CUR_ANIM));
1010 }
1011 if let Some((size, _)) = named("SpawnInfo")
1012 && tr.lookup(n(OBJ_SPAWN_INFO)).is_none()
1013 {
1014 tr.region(n(OBJ_SPAWN_INFO), size, p(OBJ_SPAWN_INFO));
1015 }
1016 let name = bhv_name(tr, nb);
1017 for &(bhv, slot, count) in CHAIN_SEGMENTS {
1022 let o = 0x88 + 4 * slot;
1023 if name != Some(bhv) || !super::layout::looks_like_pointer(n(o)) {
1024 continue;
1025 }
1026 let len = count * CHAIN_SEGMENT_SIZE;
1027 let at = match pool {
1028 Some((ns, nl, ps)) if n(o) >= ns && n(o) - ns + len <= nl => ps + (n(o) - ns),
1029 _ if p(o) != 0 => {
1030 tr.region(n(o), len, p(o));
1031 p(o)
1032 }
1033 _ => continue,
1034 };
1035 for k in 0..count {
1036 heap.push((
1037 n(o) + k * CHAIN_SEGMENT_SIZE,
1038 at + k * CHAIN_SEGMENT_SIZE,
1039 CHAIN_SEGMENT_SIZE,
1040 ));
1041 }
1042 }
1043 }
1044 heap
1045}
1046
1047fn learn_path(tr: &mut Translator, st: &MupenState, snap: &[u8], no: u32, nb: u32) {
1051 let start = st.u32(no + 0x88 + 4 * WAYPOINT_START_SLOT).unwrap_or(0);
1052 if !super::layout::looks_like_pointer(start)
1053 || !bhv_name(tr, nb).is_some_and(|b| super::tables::PATH_BEHAVIORS.contains(&b))
1054 {
1055 return;
1056 }
1057 let mut want = Vec::new();
1058 loop {
1059 let Some(w) = st.bytes(start + want.len() as u32, 8) else {
1060 return;
1061 };
1062 if w[0] == 0xFF && w[1] == 0xFF {
1064 want.extend_from_slice(&[0xFF, 0xFF]);
1065 break;
1066 }
1067 for k in 0..4 {
1068 want.extend_from_slice(&[w[2 * k + 1], w[2 * k]]);
1069 }
1070 if want.len() > 0x1000 {
1071 return;
1072 }
1073 }
1074 let at = tr
1077 .lookup(start)
1078 .filter(|&p| snap.get(p as usize..p as usize + want.len()) == Some(&want[..]));
1079 if let Some(p) = at.or_else(|| find_first(snap, &want)) {
1080 tr.region(start, want.len() as u32, p);
1081 }
1082}
1083
1084fn find_first(mem: &[u8], want: &[u8]) -> Option<u32> {
1087 let mut at = 0;
1088 while at + want.len() <= mem.len() {
1089 if mem[at] == want[0] && mem[at + 1] == want[1] && mem[at..at + want.len()] == *want {
1090 return Some(at as u32);
1091 }
1092 at += 2;
1093 }
1094 None
1095}
1096
1097const WAYPOINT_START_SLOT: u32 = 0x1D;
1099
1100const CHAIN_SEGMENTS: &[(&str, u32, u32)] =
1103 &[("bhvChainChomp", 0x1B, 5), ("bhvWigglerHead", 0x1C, 4)];
1104const CHAIN_SEGMENT_SIZE: u32 = 0x14;
1105
1106fn bhv_name(tr: &Translator, bhv: u32) -> Option<&'static str> {
1108 let seg = tr.virtual_to_segmented(bhv)?;
1109 TARGETS.iter().find(|t| t.0 == seg).map(|t| t.3)
1110}
1111
1112fn fix_mario_animation(st: &MupenState, mem: &mut [u8], report: &mut MupenLoadReport) {
1116 let Some(v) = var("gMarioAnimsBuf") else {
1117 return;
1118 };
1119 let rd = |m: &[u8], a: u32| p32(m, a);
1120 let (Some(n_table), Some(n_current)) = (st.u32(v.n64), st.u32(v.n64 + 4)) else {
1122 return;
1123 };
1124 let n_count = st.u32(n_table).unwrap_or(0);
1125 let n_src = st.u32(n_table + 4).unwrap_or(0);
1126 let index = (0..n_count.min(1024))
1127 .find(|&i| st.u32(n_table + 8 + 8 * i).map(|o| n_src.wrapping_add(o)) == Some(n_current));
1128 let Some(index) = index else {
1129 report
1130 .notes
1131 .push("could not tell which Mario animation the state has loaded".into());
1132 return;
1133 };
1134 let (p_table, p_current, p_buf) = (rd(mem, v.port), rd(mem, v.port + 4), rd(mem, v.port + 8));
1135 if p_table == 0 || p_buf == 0 || index >= rd(mem, p_table) {
1136 return;
1137 }
1138 let src = rd(mem, p_table + 4).wrapping_add(rd(mem, p_table + 8 + 8 * index));
1139 let size = rd(mem, p_table + 12 + 8 * index);
1140 if src == p_current {
1141 return;
1142 }
1143 let (s, d, n) = (src as usize, p_buf as usize, size as usize);
1144 if s + n > mem.len() || d + n > mem.len() || n > 0x4000 {
1145 report
1146 .notes
1147 .push("Mario's animation is out of bounds; not loaded".into());
1148 return;
1149 }
1150 mem.copy_within(s..s + n, d);
1151 for o in [0x0C, 0x10] {
1153 let off = rd(mem, p_buf + o);
1154 mem[d + o as usize..d + o as usize + 4]
1155 .copy_from_slice(&p_buf.wrapping_add(off).to_le_bytes());
1156 }
1157 mem[v.port as usize + 4..v.port as usize + 8].copy_from_slice(&src.to_le_bytes());
1158}