mirui 0.46.3

A lightweight, no_std ECS-driven UI framework for embedded, mobile, desktop, and WebAssembly
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
use crate::gallery::play::change::ChangeSet;
#[cfg(any(feature = "persistence", test))]
use crate::gallery::play::expeditions::{
    ACTION_BYTES, ExpeditionSaveError, RECORD_BYTES, finish_packet, read_records, validate_packet,
    write_records,
};
use crate::gallery::play::expeditions::{
    Direction4, EXPEDITION_LEVELS, ExpeditionHintWorkspace, ExpeditionModal, LevelRecord,
    PackedDirections, TwinCell, TwinLevelRef, accepted_change, movement_stars, twin_level,
    unlocked_level,
};

#[cfg(any(feature = "persistence", test))]
const SAVE_MAGIC: [u8; 4] = *b"TWB1";
#[cfg(any(feature = "persistence", test))]
const SAVE_VERSION: u8 = 1;
#[cfg(any(feature = "persistence", test))]
const SAVE_PAYLOAD: usize = 10 + RECORD_BYTES + ACTION_BYTES;
#[cfg(any(feature = "persistence", test))]
pub(crate) const SAVE_LEN: usize = SAVE_PAYLOAD + 4;

pub(crate) const CHAPTER_NAMES: [&str; 6] = [
    "FIRST RESPONSE",
    "MIRROR ROUTE",
    "REVERSE TIDE",
    "KEY PROTOCOL",
    "RIGHT ANGLE",
    "TWIN FINALE",
];

pub(crate) const CHAPTER_MECHANICS: [&str; 6] = [
    "同向联动 · 撞墙的一位停住",
    "水平镜像 · 上下仍然同向",
    "完全反向 · 借障碍分离路线",
    "收齐钥片 · 打开两站闸门",
    "右侧旋转 90° · 重新理解方向",
    "钥片与变向 · 组合使用所有规则",
];

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum TwinMessage {
    Ready,
    Blocked,
    KeyCollected,
    Undone,
    Hint(Direction4, u16),
    Complete,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
struct TwinState {
    a: u8,
    b: u8,
    key: bool,
}

#[derive(Clone, Copy)]
pub(crate) struct TwinModel {
    level: u8,
    state: TwinState,
    actions: PackedDirections,
    records: [LevelRecord; EXPEDITION_LEVELS],
    hints: u16,
    last_hint: Option<(u8, u16, bool)>,
    modal: ExpeditionModal,
    message: TwinMessage,
}

impl Default for TwinModel {
    fn default() -> Self {
        let level = twin_level(0).expect("first Twin level");
        Self {
            level: 0,
            state: initial(level),
            actions: PackedDirections::default(),
            records: [LevelRecord::default(); EXPEDITION_LEVELS],
            hints: 0,
            last_hint: None,
            modal: ExpeditionModal::None,
            message: TwinMessage::Ready,
        }
    }
}

impl TwinModel {
    pub(crate) const fn level_index(&self) -> u8 {
        self.level
    }

    pub(crate) fn level(&self) -> TwinLevelRef {
        twin_level(self.level).expect("validated Twin level")
    }

    pub(crate) const fn position(&self, station: usize) -> u8 {
        if station == 0 {
            self.state.a
        } else {
            self.state.b
        }
    }

    pub(crate) const fn has_key(&self) -> bool {
        self.state.key
    }

    pub(crate) const fn steps(&self) -> u16 {
        self.actions.len()
    }

    pub(crate) const fn hints(&self) -> u16 {
        self.hints
    }

    pub(crate) const fn modal(&self) -> ExpeditionModal {
        self.modal
    }

    pub(crate) const fn message(&self) -> TwinMessage {
        self.message
    }

    pub(crate) const fn unlocked(&self) -> u8 {
        unlocked_level(&self.records)
    }

    pub(crate) const fn record(&self, level: u8) -> LevelRecord {
        self.records[level as usize]
    }

    pub(crate) fn won(&self) -> bool {
        won(self.level(), self.state)
    }

    pub(crate) fn move_direction(&mut self, direction: Direction4) -> ChangeSet {
        if self.modal != ExpeditionModal::None || self.won() || self.actions.is_full() {
            return ChangeSet::NONE;
        }
        let level = self.level();
        let Some(next) = moved(level, self.state, direction) else {
            self.message = TwinMessage::Blocked;
            return ChangeSet::MODEL | ChangeSet::VISUAL;
        };
        let collected = !self.state.key && next.key;
        self.state = next;
        let pushed = self.actions.push(direction);
        debug_assert!(pushed);
        self.last_hint = None;
        self.message = if collected {
            TwinMessage::KeyCollected
        } else {
            TwinMessage::Ready
        };
        if self.won() {
            let stars = movement_stars(self.hints, self.steps(), level.par());
            self.records[usize::from(self.level)].submit(self.steps(), stars);
            self.modal = if self.level as usize + 1 == EXPEDITION_LEVELS {
                ExpeditionModal::Final
            } else {
                ExpeditionModal::Result
            };
            self.message = TwinMessage::Complete;
        }
        accepted_change()
    }

    pub(crate) fn undo(&mut self) -> ChangeSet {
        if self.modal != ExpeditionModal::None || self.actions.pop().is_none() {
            return ChangeSet::NONE;
        }
        self.replay();
        self.last_hint = None;
        self.message = TwinMessage::Undone;
        accepted_change()
    }

    pub(crate) fn restart(&mut self) -> ChangeSet {
        self.actions.clear();
        self.state = initial(self.level());
        self.hints = 0;
        self.last_hint = None;
        self.modal = ExpeditionModal::None;
        self.message = TwinMessage::Ready;
        accepted_change()
    }

    pub(crate) fn select_level(&mut self, level: u8) -> ChangeSet {
        if level > self.unlocked() || twin_level(level).is_none() {
            return ChangeSet::NONE;
        }
        self.level = level;
        self.restart()
    }

    pub(crate) fn continue_campaign(&mut self) -> ChangeSet {
        if self.modal != ExpeditionModal::Result || self.level as usize + 1 >= EXPEDITION_LEVELS {
            return ChangeSet::NONE;
        }
        self.level += 1;
        self.restart()
    }

    pub(crate) fn request_hint(&mut self, workspace: &mut ExpeditionHintWorkspace) -> ChangeSet {
        if self.modal != ExpeditionModal::None || self.won() {
            return ChangeSet::NONE;
        }
        let signature = (self.state.a, u16::from(self.state.b), self.state.key);
        let Some((direction, remaining)) = solve(self.level(), self.state, workspace) else {
            return ChangeSet::NONE;
        };
        if self.last_hint != Some(signature) {
            self.hints = self.hints.saturating_add(1);
            self.last_hint = Some(signature);
        }
        self.message = TwinMessage::Hint(direction, remaining);
        accepted_change()
    }

    fn replay(&mut self) {
        let level = self.level();
        let mut state = initial(level);
        let mut index = 0;
        while let Some(direction) = self.actions.get(index) {
            state = moved(level, state, direction).expect("stored Twin action remains valid");
            index += 1;
        }
        self.state = state;
    }

    #[cfg(any(feature = "persistence", test))]
    pub(crate) fn encode_into(&self, output: &mut [u8]) -> Result<usize, ExpeditionSaveError> {
        if output.len() < SAVE_LEN {
            return Err(ExpeditionSaveError::BufferTooSmall);
        }
        output[..4].copy_from_slice(&SAVE_MAGIC);
        output[4] = SAVE_VERSION;
        output[5] = self.level;
        output[6..8].copy_from_slice(&self.actions.len().to_le_bytes());
        output[8..10].copy_from_slice(&self.hints.to_le_bytes());
        write_records(&self.records, &mut output[10..10 + RECORD_BYTES])?;
        output[10 + RECORD_BYTES..SAVE_PAYLOAD].copy_from_slice(self.actions.bytes());
        finish_packet(output, SAVE_PAYLOAD);
        Ok(SAVE_LEN)
    }

    #[cfg(any(feature = "persistence", test))]
    pub(crate) fn decode(input: &[u8]) -> Result<Self, ExpeditionSaveError> {
        validate_packet(input, SAVE_PAYLOAD)?;
        if input[..4] != SAVE_MAGIC {
            return Err(ExpeditionSaveError::InvalidMagic);
        }
        if input[4] != SAVE_VERSION {
            return Err(ExpeditionSaveError::UnsupportedVersion);
        }
        let level_index = input[5];
        let level = twin_level(level_index).ok_or(ExpeditionSaveError::InvalidLevel)?;
        let action_len = u16::from_le_bytes([input[6], input[7]]);
        let hints = u16::from_le_bytes([input[8], input[9]]);
        let records = read_records(&input[10..10 + RECORD_BYTES])?;
        let mut bytes = [0; ACTION_BYTES];
        bytes.copy_from_slice(&input[10 + RECORD_BYTES..SAVE_PAYLOAD]);
        let actions = PackedDirections::from_bytes(bytes, action_len)
            .ok_or(ExpeditionSaveError::InvalidState)?;
        let mut state = initial(level);
        let mut index = 0;
        while let Some(direction) = actions.get(index) {
            state = moved(level, state, direction).ok_or(ExpeditionSaveError::InvalidState)?;
            index += 1;
        }
        let modal = if won(level, state) {
            if level_index as usize + 1 == EXPEDITION_LEVELS {
                ExpeditionModal::Final
            } else {
                ExpeditionModal::Result
            }
        } else {
            ExpeditionModal::None
        };
        Ok(Self {
            level: level_index,
            state,
            actions,
            records,
            hints,
            last_hint: None,
            modal,
            message: if modal == ExpeditionModal::None {
                TwinMessage::Ready
            } else {
                TwinMessage::Complete
            },
        })
    }

    #[cfg(feature = "persistence")]
    pub(crate) fn encode_vec(&self) -> alloc::vec::Vec<u8> {
        let mut output = alloc::vec![0; SAVE_LEN];
        self.encode_into(&mut output)
            .expect("exact Twin save buffer");
        output
    }
}

fn initial(level: TwinLevelRef) -> TwinState {
    TwinState {
        a: level.start(0),
        b: level.start(1),
        key: level.key().is_none(),
    }
}

const fn mapped(direction: Direction4, mode: u8) -> Direction4 {
    match mode {
        1 => match direction {
            Direction4::Left => Direction4::Right,
            Direction4::Right => Direction4::Left,
            other => other,
        },
        2 => match direction {
            Direction4::Up => Direction4::Down,
            Direction4::Right => Direction4::Left,
            Direction4::Down => Direction4::Up,
            Direction4::Left => Direction4::Right,
        },
        3 => match direction {
            Direction4::Up => Direction4::Right,
            Direction4::Right => Direction4::Down,
            Direction4::Down => Direction4::Left,
            Direction4::Left => Direction4::Up,
        },
        _ => direction,
    }
}

fn moved_cell(
    level: TwinLevelRef,
    station: usize,
    position: u8,
    direction: Direction4,
    key: bool,
) -> u8 {
    let (dx, dy) = direction.delta();
    let x = (position % 6) as i8 + dx;
    let y = (position / 6) as i8 + dy;
    if x < 0 || y < 0 || x >= 6 || y >= 6 {
        return position;
    }
    let next = (y * 6 + x) as u8;
    match level.cell(station, next) {
        TwinCell::Wall => position,
        TwinCell::Door if !key => position,
        TwinCell::Floor | TwinCell::Door => next,
    }
}

fn moved(level: TwinLevelRef, state: TwinState, direction: Direction4) -> Option<TwinState> {
    let a = moved_cell(level, 0, state.a, direction, state.key);
    let b = moved_cell(
        level,
        1,
        state.b,
        mapped(direction, level.mode()),
        state.key,
    );
    if a == state.a && b == state.b {
        return None;
    }
    Some(TwinState {
        a,
        b,
        key: state.key || level.key() == Some(a),
    })
}

const fn won(level: TwinLevelRef, state: TwinState) -> bool {
    state.a == level.goal(0) && state.b == level.goal(1) && state.key
}

const fn state_id(state: TwinState) -> u16 {
    state.a as u16 + state.b as u16 * 36 + if state.key { 1296 } else { 0 }
}

const fn decode_state(id: u16) -> TwinState {
    TwinState {
        a: (id % 36) as u8,
        b: (id / 36 % 36) as u8,
        key: id >= 1296,
    }
}

fn solve(
    level: TwinLevelRef,
    start: TwinState,
    workspace: &mut ExpeditionHintWorkspace,
) -> Option<(Direction4, u16)> {
    debug_assert_eq!(level.solution_len(), level.par());
    debug_assert!(level.solution(0).is_some());
    workspace.clear();
    let start_id = state_id(start);
    workspace.visit(start_id, Direction4::Up);
    workspace.push(start_id);
    let mut depth = 0_u16;
    let mut level_end = workspace.tail();
    while let Some(id) = workspace.pop() {
        let state = decode_state(id);
        for direction in Direction4::ALL {
            let Some(next) = moved(level, state, direction) else {
                continue;
            };
            let next_id = state_id(next);
            let first = if id == start_id {
                direction
            } else {
                workspace.first(id)
            };
            if !workspace.visit(next_id, first) {
                continue;
            }
            if won(level, next) {
                return Some((first, depth + 1));
            }
            if !workspace.push(next_id) {
                return None;
            }
        }
        if workspace.head() == level_end {
            depth += 1;
            level_end = workspace.tail();
        }
    }
    None
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn all_reference_solutions_complete_at_par() {
        for index in 0..EXPEDITION_LEVELS as u8 {
            let level = twin_level(index).unwrap();
            let mut state = initial(level);
            for step in 0..level.solution_len() {
                state = moved(level, state, level.solution(step).unwrap()).unwrap();
            }
            assert!(won(level, state), "Twin level {index}");
            assert_eq!(level.solution_len(), level.par());
        }
    }

    #[test]
    fn key_opens_doors_only_after_the_collecting_move() {
        for index in 0..EXPEDITION_LEVELS as u8 {
            let level = twin_level(index).unwrap();
            if level.key().is_none() {
                continue;
            }
            let mut state = initial(level);
            for step in 0..level.solution_len() {
                let before = state;
                state = moved(level, state, level.solution(step).unwrap()).unwrap();
                if !before.key && state.key {
                    assert_eq!(level.key(), Some(state.a));
                    return;
                }
            }
        }
        panic!("no key was collected");
    }

    #[test]
    fn exact_hint_solves_every_initial_state() {
        let mut workspace = ExpeditionHintWorkspace::new();
        for index in 0..EXPEDITION_LEVELS as u8 {
            let level = twin_level(index).unwrap();
            let (_, remaining) = solve(level, initial(level), &mut workspace).unwrap();
            assert_eq!(remaining, u16::from(level.par()), "Twin level {index}");
        }
    }

    #[test]
    fn undo_replays_without_restoring_hint_usage() {
        let mut model = TwinModel::default();
        let direction = model.level().solution(0).unwrap();
        model.move_direction(direction);
        let before = model.state;
        model.request_hint(&mut ExpeditionHintWorkspace::new());
        assert_eq!(model.hints(), 1);
        model.undo();
        assert_ne!(model.state, before);
        assert_eq!(model.hints(), 1);
    }

    #[test]
    fn model_memory_is_bounded() {
        assert!(core::mem::size_of::<TwinModel>() <= 768);
        assert!(core::mem::size_of::<ExpeditionHintWorkspace>() <= 8_128);
    }

    #[test]
    fn save_round_trip_is_atomic_and_checksummed() {
        let mut model = TwinModel::default();
        model.move_direction(model.level().solution(0).unwrap());
        model.request_hint(&mut ExpeditionHintWorkspace::new());
        let mut bytes = [0; SAVE_LEN];
        model.encode_into(&mut bytes).unwrap();
        let restored = TwinModel::decode(&bytes).unwrap();
        assert_eq!(restored.level, model.level);
        assert_eq!(restored.state, model.state);
        assert_eq!(restored.actions.len(), model.actions.len());
        assert_eq!(restored.hints, model.hints);
        bytes[20] ^= 1;
        assert!(matches!(
            TwinModel::decode(&bytes),
            Err(ExpeditionSaveError::InvalidChecksum)
        ));
    }
}