use crate::{
cursor::{ChunkIter, Ctx, Cursor, ListWalker},
diag::DiagKind,
wire,
};
#[derive(Clone, Debug)]
pub struct EventCommandRef<'a> {
pub code: i32,
pub indent: i32,
pub string: &'a [u8],
params: &'a [u8],
param_count: u32,
}
impl<'a> EventCommandRef<'a> {
#[must_use]
#[inline]
pub const fn params(&self) -> ParamIter<'a> {
ParamIter {
cur: Cursor::new(self.params),
left: self.param_count,
}
}
#[must_use]
#[inline]
pub fn param(&self, index: usize) -> Option<i32> {
self.params().nth(index)
}
#[must_use]
#[inline]
pub const fn param_count(&self) -> u32 {
self.param_count
}
#[must_use]
#[inline]
pub const fn raw_params(&self) -> &'a [u8] {
self.params
}
}
#[derive(Clone, Debug)]
pub struct ParamIter<'a> {
cur: Cursor<'a>,
left: u32,
}
impl Iterator for ParamIter<'_> {
type Item = i32;
#[inline]
fn next(&mut self) -> Option<i32> {
if self.left == 0 {
return None;
}
self.left -= 1;
Some(self.cur.varint().map_or(0, |v| v.value as i32))
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
(self.left as usize, Some(self.left as usize))
}
}
impl ExactSizeIterator for ParamIter<'_> {}
#[derive(Clone, Debug)]
pub struct EventCommandIter<'a> {
cur: Cursor<'a>,
done: bool,
}
impl<'a> EventCommandIter<'a> {
#[must_use]
#[inline]
pub const fn new(data: &'a [u8], base: u32) -> Self {
Self {
cur: Cursor::with_base(data, base),
done: false,
}
}
#[must_use]
#[inline]
pub fn tail(&self) -> &'a [u8] {
self.cur.remaining()
}
#[must_use]
pub fn next(&mut self, ctx: &mut Ctx<'_>) -> Option<EventCommandRef<'a>> {
if self.done || self.cur.is_empty() {
self.done = true;
return None;
}
if self.cur.peek() == Some(0) {
self.cur.skip(4);
self.done = true;
return None;
}
let offset = self.cur.offset();
let Some(code) = self.cur.varint() else {
self.recover(ctx, offset);
return None;
};
if code.value == 0 {
self.recover(ctx, offset);
return None;
}
let Some(indent) = self.cur.varint() else {
self.recover(ctx, offset);
return None;
};
let Some(string) = self.cur.lstring() else {
self.recover(ctx, offset);
return None;
};
let Some(param_count) = self.cur.varint() else {
self.recover(ctx, offset);
return None;
};
let params_start = self.cur.pos();
let mut present = 0;
while present < param_count.value {
if self.cur.varint().is_none() {
ctx.report("EventCommand", 0, offset, DiagKind::ShortChunk);
break;
}
present += 1;
}
let params_end = self.cur.pos();
let params = self.cur.buf().get(params_start..params_end).unwrap_or(&[]);
Some(EventCommandRef {
code: code.value as i32,
indent: indent.value as i32,
string,
params,
param_count: present,
})
}
fn recover(&mut self, ctx: &mut Ctx<'_>, offset: u32) {
ctx.report("EventCommand", 0, offset, DiagKind::EventListCorrupt);
let mut zeros = 0;
while let Some(byte) = self.cur.u8() {
zeros = if byte == 0 { zeros + 1 } else { 0 };
if zeros == 4 {
break;
}
}
self.done = true;
}
}
#[derive(Clone, Debug, Default)]
pub struct MoveCommandRef<'a> {
pub code: i32,
pub string: &'a [u8],
pub parameter_a: i32,
pub parameter_b: i32,
pub parameter_c: i32,
}
pub mod move_code {
pub const SWITCH_ON: i32 = 32;
pub const SWITCH_OFF: i32 = 33;
pub const CHANGE_GRAPHIC: i32 = 34;
pub const PLAY_SOUND_EFFECT: i32 = 35;
}
#[derive(Clone, Debug)]
pub struct MoveCommandIter<'a> {
cur: Cursor<'a>,
}
impl<'a> MoveCommandIter<'a> {
#[must_use]
#[inline]
pub const fn new(data: &'a [u8], base: u32) -> Self {
Self {
cur: Cursor::with_base(data, base),
}
}
#[must_use]
pub fn next(&mut self, ctx: &mut Ctx<'_>) -> Option<MoveCommandRef<'a>> {
if self.cur.is_empty() {
return None;
}
let offset = self.cur.offset();
let code = self.cur.varint()?.value as i32;
let mut out = MoveCommandRef {
code,
..MoveCommandRef::default()
};
let ok = match code {
move_code::SWITCH_ON | move_code::SWITCH_OFF => self.read_ints(&mut out, 1),
move_code::CHANGE_GRAPHIC => self.read_string(&mut out) && self.read_ints(&mut out, 1),
move_code::PLAY_SOUND_EFFECT => self.read_string(&mut out) && self.read_ints(&mut out, 3),
_ => true,
};
if !ok {
ctx.report("MoveCommand", 0, offset, DiagKind::ShortChunk);
}
Some(out)
}
fn read_string(&mut self, out: &mut MoveCommandRef<'a>) -> bool {
match self.cur.lstring() {
Some(s) => {
out.string = s;
true
}
None => false,
}
}
fn read_ints(&mut self, out: &mut MoveCommandRef<'a>, count: usize) -> bool {
for slot in [&mut out.parameter_a, &mut out.parameter_b, &mut out.parameter_c]
.into_iter()
.take(count)
{
match self.cur.varint() {
Some(v) => *slot = v.value as i32,
None => return false,
}
}
true
}
}
#[must_use]
pub fn event_command_len(code: i32, indent: i32, string_len: usize, params: &[i32]) -> u32 {
let mut total = wire::varint_len(code as u32)
+ wire::varint_len(indent as u32)
+ wire::varint_len(string_len as u32)
+ string_len as u32
+ wire::varint_len(params.len() as u32);
for &p in params {
total += wire::varint_len(p as u32);
}
total
}
pub mod path {
pub const MAP_EVENTS: u32 = 0x51;
pub const EVENT_PAGES: u32 = 0x05;
pub const EVENT_PAGE_COMMANDS: u32 = 0x34;
pub const DATABASE_COMMON_EVENTS: u32 = 0x19;
pub const COMMON_EVENT_COMMANDS: u32 = 0x16;
pub const DATABASE_TROOPS: u32 = 0x0F;
pub const TROOP_PAGES: u32 = 0x0B;
pub const TROOP_PAGE_COMMANDS: u32 = 0x0C;
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct CommandListAt<'a> {
pub owner_id: i32,
pub page_id: i32,
pub commands: &'a [u8],
pub offset: u32,
}
impl<'a> CommandListAt<'a> {
#[must_use]
#[inline]
pub const fn commands(&self) -> EventCommandIter<'a> {
EventCommandIter::new(self.commands, self.offset)
}
}
#[derive(Clone, Copy, Debug)]
enum Shape {
Paged { outer: u32, pages: u32, commands: u32 },
Flat { outer: u32, commands: u32 },
}
#[derive(Clone, Debug)]
pub struct CommandLists<'a> {
shape: Shape,
outer: Option<ListWalker<'a>>,
inner: Option<ListWalker<'a>>,
owner_id: i32,
name: &'static str,
}
impl<'a> CommandLists<'a> {
#[must_use]
pub fn in_map(body: &'a [u8], base: u32, ctx: &mut Ctx<'_>) -> Self {
Self::start(
body,
base,
ctx,
"Map",
Shape::Paged {
outer: path::MAP_EVENTS,
pages: path::EVENT_PAGES,
commands: path::EVENT_PAGE_COMMANDS,
},
)
}
#[must_use]
pub fn in_common_events(body: &'a [u8], base: u32, ctx: &mut Ctx<'_>) -> Self {
Self::start(
body,
base,
ctx,
"CommonEvent",
Shape::Flat {
outer: path::DATABASE_COMMON_EVENTS,
commands: path::COMMON_EVENT_COMMANDS,
},
)
}
#[must_use]
pub fn in_battle_events(body: &'a [u8], base: u32, ctx: &mut Ctx<'_>) -> Self {
Self::start(
body,
base,
ctx,
"Troop",
Shape::Paged {
outer: path::DATABASE_TROOPS,
pages: path::TROOP_PAGES,
commands: path::TROOP_PAGE_COMMANDS,
},
)
}
fn start(body: &'a [u8], base: u32, ctx: &mut Ctx<'_>, name: &'static str, shape: Shape) -> Self {
let outer_id = match shape {
Shape::Paged { outer, .. } | Shape::Flat { outer, .. } => outer,
};
let outer = ChunkIter::find(body, base, outer_id, ctx, name)
.map(|chunk| ListWalker::new(chunk.data, chunk.offset, ctx, name));
Self {
shape,
outer,
inner: None,
owner_id: 0,
name,
}
}
#[must_use]
pub fn next(&mut self, ctx: &mut Ctx<'_>) -> Option<CommandListAt<'a>> {
loop {
if let Some(inner) = self.inner.as_mut() {
if let Some(page) = inner.next(ctx) {
let Shape::Paged { commands, .. } = self.shape else {
unreachable!("inner walker only exists for a paged shape")
};
if let Some(chunk) = page.find(commands, ctx, self.name) {
return Some(CommandListAt {
owner_id: self.owner_id,
page_id: page.id,
commands: chunk.data,
offset: chunk.offset,
});
}
continue;
}
self.inner = None;
}
let owner = self.outer.as_mut()?.next(ctx)?;
self.owner_id = owner.id;
match self.shape {
Shape::Flat { commands, .. } => {
if let Some(chunk) = owner.find(commands, ctx, self.name) {
return Some(CommandListAt {
owner_id: owner.id,
page_id: 0,
commands: chunk.data,
offset: chunk.offset,
});
}
}
Shape::Paged { pages, .. } => {
if let Some(chunk) = owner.find(pages, ctx, self.name) {
self.inner = Some(ListWalker::new(chunk.data, chunk.offset, ctx, self.name));
}
}
}
}
}
}