rpgmxp_project/commands/
init.rs

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
use anyhow::ensure;
use anyhow::Context;
use std::fmt::Write;
use std::path::Path;
use std::path::PathBuf;

#[derive(Debug, argh::FromArgs)]
#[argh(name = "init", subcommand, description = "init a new project")]
pub struct Options {
    #[argh(
        option,
        description = "the path to the game or archive to init a project from"
    )]
    pub from: PathBuf,

    #[argh(option, description = "the output path", default = "PathBuf::new()")]
    pub output: PathBuf,
}

pub fn exec(options: Options) -> anyhow::Result<()> {
    copy_data(&options.from, &options.output)?;
    copy_graphics(&options.from, &options.output)?;
    Ok(())
}

fn copy_data(base_in_path: &Path, base_out_path: &Path) -> anyhow::Result<()> {
    let data_path = base_in_path.join("Data");
    ensure!(
        data_path.exists(),
        "missing folder at \"{}\"",
        data_path.display()
    );
    let out_dir = base_out_path.join("Data");
    for entry in std::fs::read_dir(data_path)? {
        let entry = entry?;

        let file_type = entry.file_type()?;
        ensure!(file_type.is_file());

        let in_path = entry.path();
        ensure!(in_path.extension() == Some("rxdata".as_ref()));

        let file_stem = in_path
            .file_stem()
            .context("missing file stem")?
            .to_str()
            .context("file stem is not valid unicode")?;

        let map_number = file_stem.strip_prefix("Map").and_then(|file_stem| {
            if file_stem.len() != 3 {
                return None;
            }

            if !file_stem.chars().all(|c| c.is_ascii_digit()) {
                return None;
            }

            Some(file_stem)
        });

        if let Some(map_number) = map_number {
            let map_data = std::fs::read(&in_path)?;
            let value_arena = ruby_marshal::load(&*map_data)?;
            let ctx = ruby_marshal::FromValueContext::new(&value_arena);

            let maybe_map: Result<rpgmxp_types::Map, _> = ctx.from_value(value_arena.root());

            if let Err(ruby_marshal::FromValueError::UnexpectedValueKind { kind, trace }) =
                maybe_map.as_ref()
            {
                dbg!(kind);
                for handle in trace.iter().copied() {
                    let value = value_arena.get(handle).unwrap();
                    dbg!(DebugValue::new(&value_arena, value, 10));
                }
            }

            let map = maybe_map
                .with_context(|| format!("failed to extract data from Map{map_number:03}"))?;

            let out_path = out_dir.join(format!("Map{map_number}.json"));
            std::fs::write(&out_path, &serde_json::to_string_pretty(&map)?)?;

            continue;
        }

        // We will add more later.
        #[allow(clippy::single_match)]
        match file_stem {
            "Scripts" => {
                let out_dir = out_dir.join("Scripts");
                std::fs::create_dir_all(&out_dir)?;
                extract_scripts(&in_path, &out_dir)?;
            }
            _ => {}
        }
    }

    Ok(())
}

fn copy_graphics(base_in_path: &Path, base_out_path: &Path) -> anyhow::Result<()> {
    let graphics_path = base_in_path.join("Graphics");

    ensure!(
        graphics_path.exists(),
        "missing folder at \"{}\"",
        graphics_path.display()
    );
    let out_dir = base_out_path.join("Graphics");
    for entry in std::fs::read_dir(graphics_path)? {
        let entry = entry?;

        // TODO: Should we allow files in non-standard places?
        let file_type = entry.file_type()?;
        ensure!(file_type.is_dir());

        let dir_name = entry.file_name();
        let out_dir = out_dir.join(dir_name);

        std::fs::create_dir_all(&out_dir)?;

        for entry in std::fs::read_dir(entry.path())? {
            let entry = entry?;

            let file_type = entry.file_type()?;
            ensure!(file_type.is_file());

            let in_path = entry.path();
            let out_path = out_dir.join(entry.file_name());
            std::fs::copy(&in_path, &out_path).with_context(|| {
                format!(
                    "failed to copy \"{}\" to \"{}\"",
                    in_path.display(),
                    out_path.display()
                )
            })?;
        }
    }

    Ok(())
}

fn extract_scripts(in_path: &Path, out_dir: &Path) -> anyhow::Result<()> {
    let scripts_data = std::fs::read(in_path)?;
    let value_arena = ruby_marshal::load(&*scripts_data)?;
    let ctx = ruby_marshal::FromValueContext::new(&value_arena);

    let script_list: rpgmxp_types::ScriptList = ctx.from_value(value_arena.root())?;

    for (script_index, script) in script_list.scripts.iter().enumerate() {
        let escaped_script_name = escape_file_name(&script.name);

        let out_path = out_dir.join(format!("{script_index}-{escaped_script_name}.rb"));
        std::fs::write(&out_path, &script.data)?;
    }

    Ok(())
}

fn escape_file_name(file_name: &str) -> String {
    let mut escaped = String::with_capacity(file_name.len());
    for c in file_name.chars() {
        match c {
            '%' | ':' => {
                let c = u32::from(c);
                write!(&mut escaped, "%{c:02x}").unwrap();
            }
            _ => {
                escaped.push(c);
            }
        }
    }
    escaped
}

struct DebugValue<'a> {
    arena: &'a ruby_marshal::ValueArena,
    value: &'a ruby_marshal::Value,
    limit: usize,
}

impl<'a> DebugValue<'a> {
    fn new(
        arena: &'a ruby_marshal::ValueArena,
        value: &'a ruby_marshal::Value,
        limit: usize,
    ) -> Self {
        Self {
            arena,
            value,
            limit,
        }
    }
}

impl std::fmt::Debug for DebugValue<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if self.limit == 0 {
            return self.value.fmt(f);
        }

        match &self.value {
            ruby_marshal::Value::Bool(value) => value.value().fmt(f),
            ruby_marshal::Value::Fixnum(value) => value.value().fmt(f),
            ruby_marshal::Value::String(value) => {
                let value = value.value();
                match std::str::from_utf8(value) {
                    Ok(value) => value.fmt(f),
                    Err(_error) => value.fmt(f),
                }
            }
            ruby_marshal::Value::Array(value) => {
                let mut f = f.debug_list();
                for handle in value.value().iter().copied() {
                    match self.arena.get(handle) {
                        Some(value) => {
                            f.entry(&DebugValue::new(self.arena, value, self.limit - 1));
                        }
                        None => {
                            f.entry(&handle);
                        }
                    }
                }
                f.finish()
            }
            ruby_marshal::Value::Object(value) => {
                let name = value.name();
                let name = match self
                    .arena
                    .get_symbol(name)
                    .and_then(|value| std::str::from_utf8(value.value()).ok())
                {
                    Some(name) => name,
                    None => {
                        return value.fmt(f);
                    }
                };

                let instance_variables = value.instance_variables();

                let mut f = f.debug_struct(name);

                for (key, value) in instance_variables.iter().copied() {
                    let key = self.arena.get_symbol(key).unwrap().value();
                    let key = std::str::from_utf8(key).unwrap();

                    let value = self.arena.get(value).unwrap();

                    f.field(key, &DebugValue::new(self.arena, value, self.limit - 1));
                }

                f.finish()
            }
            _ => self.value.fmt(f),
        }
    }
}