Skip to main content

sm64_binds/sm64/
game_state.rs

1use std::fmt;
2
3/// Layout produced by the `get_game_state` WASM export.
4///
5/// Mirrors `struct GameState` in `sm64-port/src/pc/pc_main.c`: every scalar is
6/// an `s32`, so the struct is 13 * 4 = 76 bytes with no padding.
7pub const GAME_STATE_SIZE: usize = 76;
8
9#[derive(Debug, Clone, PartialEq)]
10pub struct GameState {
11    pub num_stars: i32,
12    pub pos: [f32; 3],
13    pub vel: [f32; 3],
14    pub lakitu_pos: [f32; 3],
15    pub lakitu_yaw: i32,
16    pub in_credits: i32,
17    pub course_num: i32,
18    pub act_num: i32,
19    pub area_index: i32,
20    pub level_num: i32,
21    pub lives: i32,
22    pub coins: i32,
23    pub health: i32,
24}
25
26impl GameState {
27    /// Decodes the 76 byte little endian struct written by the WASM export.
28    ///
29    /// # Panics
30    ///
31    /// Panics if `data` is shorter than [`GAME_STATE_SIZE`].
32    pub fn new(data: &[u8]) -> GameState {
33        assert!(
34            data.len() >= GAME_STATE_SIZE,
35            "game state needs {GAME_STATE_SIZE} bytes, got {}",
36            data.len()
37        );
38
39        let mut offset = 0;
40        GameState {
41            num_stars: read_i32(data, &mut offset),
42            pos: read_vec3(data, &mut offset),
43            vel: read_vec3(data, &mut offset),
44            lakitu_pos: read_vec3(data, &mut offset),
45            lakitu_yaw: read_i32(data, &mut offset),
46            in_credits: read_i32(data, &mut offset),
47            course_num: read_i32(data, &mut offset),
48            act_num: read_i32(data, &mut offset),
49            area_index: read_i32(data, &mut offset),
50            level_num: read_i32(data, &mut offset),
51            lives: read_i32(data, &mut offset),
52            coins: read_i32(data, &mut offset),
53            health: read_i32(data, &mut offset),
54        }
55    }
56
57    pub fn has_won(&self) -> bool {
58        self.num_stars > 0
59    }
60}
61
62fn read_i32(data: &[u8], offset: &mut usize) -> i32 {
63    let value = i32::from_le_bytes(data[*offset..*offset + 4].try_into().unwrap());
64    *offset += 4;
65    value
66}
67
68fn read_vec3(data: &[u8], offset: &mut usize) -> [f32; 3] {
69    let vec = [
70        f32::from_le_bytes(data[*offset..*offset + 4].try_into().unwrap()),
71        f32::from_le_bytes(data[*offset + 4..*offset + 8].try_into().unwrap()),
72        f32::from_le_bytes(data[*offset + 8..*offset + 12].try_into().unwrap()),
73    ];
74    *offset += 12;
75    vec
76}
77
78impl fmt::Display for GameState {
79    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
80        write!(
81            f,
82            "GameState {{\n\
83                numStars: {},\n\
84                position: ({}, {}, {}),\n\
85                velocity: ({}, {}, {}),\n\
86                lakituPosition: ({}, {}, {}),\n\
87                lakituYaw: {},\n\
88                inCredits: {},\n\
89                courseNum: {},\n\
90                actNum: {},\n\
91                areaIndex: {},\n\
92                levelNum: {},\n\
93                lives: {},\n\
94                coins: {},\n\
95                health: {},\n\
96            }}",
97            self.num_stars,
98            self.pos[0],
99            self.pos[1],
100            self.pos[2],
101            self.vel[0],
102            self.vel[1],
103            self.vel[2],
104            self.lakitu_pos[0],
105            self.lakitu_pos[1],
106            self.lakitu_pos[2],
107            self.lakitu_yaw,
108            self.in_credits,
109            self.course_num,
110            self.act_num,
111            self.area_index,
112            self.level_num,
113            self.lives,
114            self.coins,
115            self.health,
116        )
117    }
118}
119
120#[cfg(test)]
121mod tests {
122    use super::*;
123
124    /// Builds the little endian byte image the WASM export would write.
125    fn encode(state: &GameState) -> Vec<u8> {
126        fn push_i32(out: &mut Vec<u8>, v: i32) {
127            out.extend_from_slice(&v.to_le_bytes());
128        }
129        fn push_vec3(out: &mut Vec<u8>, v: &[f32; 3]) {
130            for f in v {
131                push_i32(out, f.to_bits() as i32);
132            }
133        }
134
135        let mut out = Vec::with_capacity(GAME_STATE_SIZE);
136        push_i32(&mut out, state.num_stars);
137        push_vec3(&mut out, &state.pos);
138        push_vec3(&mut out, &state.vel);
139        push_vec3(&mut out, &state.lakitu_pos);
140        push_i32(&mut out, state.lakitu_yaw);
141        push_i32(&mut out, state.in_credits);
142        push_i32(&mut out, state.course_num);
143        push_i32(&mut out, state.act_num);
144        push_i32(&mut out, state.area_index);
145        push_i32(&mut out, state.level_num);
146        push_i32(&mut out, state.lives);
147        push_i32(&mut out, state.coins);
148        push_i32(&mut out, state.health);
149        out
150    }
151
152    fn sample() -> GameState {
153        GameState {
154            num_stars: 7,
155            pos: [1.0, 2.0, 3.0],
156            vel: [-1.5, 0.25, 100.0],
157            lakitu_pos: [-64.0, 512.0, 0.5],
158            lakitu_yaw: 4096,
159            in_credits: 1,
160            course_num: 5,
161            act_num: 2,
162            area_index: 3,
163            level_num: 11,
164            lives: 4,
165            coins: 42,
166            health: 255,
167        }
168    }
169
170    #[test]
171    fn struct_is_seventy_six_bytes() {
172        // Every field is an s32 or three of them, so 13 * 4 with no padding.
173        assert_eq!(GAME_STATE_SIZE, 76);
174        assert_eq!(encode(&sample()).len(), GAME_STATE_SIZE);
175    }
176
177    #[test]
178    fn round_trips_every_field() {
179        let state = sample();
180        assert_eq!(GameState::new(&encode(&state)), state);
181    }
182
183    #[test]
184    fn reads_fields_at_their_documented_offsets() {
185        let bytes = encode(&sample());
186
187        assert_eq!(&bytes[0..4], &7i32.to_le_bytes(), "numStars");
188        assert_eq!(
189            GameState::new(&bytes).pos,
190            [1.0, 2.0, 3.0],
191            "pos occupies bytes 4..16"
192        );
193        assert_eq!(
194            GameState::new(&bytes).level_num,
195            11,
196            "level_num sits after area_index"
197        );
198        assert_eq!(
199            GameState::new(&bytes).health,
200            255,
201            "health is the last field"
202        );
203    }
204
205    #[test]
206    fn ignores_trailing_bytes() {
207        // The memory view is larger than the struct, so a short read must work.
208        let mut bytes = encode(&sample());
209        bytes.extend_from_slice(&[0xAA; 64]);
210        assert_eq!(GameState::new(&bytes), sample());
211    }
212
213    #[test]
214    #[should_panic(expected = "game state needs 76 bytes")]
215    fn rejects_short_buffers() {
216        GameState::new(&[0u8; 60]);
217    }
218
219    #[test]
220    fn has_won_tracks_num_stars() {
221        let mut state = sample();
222        state.num_stars = 0;
223        assert!(!state.has_won());
224        state.num_stars = 1;
225        assert!(state.has_won());
226    }
227
228    #[test]
229    fn display_includes_every_field() {
230        let text = sample().to_string();
231        for field in [
232            "numStars",
233            "lakituYaw",
234            "inCredits",
235            "courseNum",
236            "actNum",
237            "areaIndex",
238            "levelNum",
239            "lives",
240            "coins",
241            "health",
242        ] {
243            assert!(text.contains(field), "Display is missing {field}");
244        }
245    }
246}