use anyhow::{Context, Result};
use base64::Engine;
use clap::Parser;
use rayon::prelude::*;
use serde_json::{Map, Value, json};
use std::path::{Path, PathBuf};
use std::process::Child;
use std::sync::atomic::{AtomicUsize, Ordering};
use log::{error, info};
use wz_reader::property::{Vector2D, WzSoundType, WzSubProperty, WzValue};
use wz_reader::util::node_util;
use wz_reader::{WzNode, WzNodeArc, WzObjectType};
#[derive(Parser)]
#[command(name = "wz-export", version)]
struct Cli {
#[arg(long)]
base: PathBuf,
#[arg(long)]
output: PathBuf,
#[arg(long)]
img: Option<String>,
#[arg(short = 'j', long)]
jobs: Option<usize>,
}
fn parse_img_filter(filter: &Option<String>) -> (Option<String>, Option<String>) {
match filter {
Some(f) if f.contains('/') => {
let mut parts = f.splitn(2, '/');
let wz = parts.next().unwrap().to_string();
let img = parts.next().unwrap().to_string();
(Some(wz), Some(img))
}
Some(f) => (None, Some(f.clone())),
None => (None, None),
}
}
fn main() -> anyhow::Result<()> {
let (_guard, _err_guard) = wz_export::log::init_tracing("info", true)?;
log::info!("start ...");
let cli = Cli::parse();
if let Some(n) = cli.jobs {
rayon::ThreadPoolBuilder::new()
.num_threads(n)
.build_global()
.map_err(|e| anyhow::anyhow!("Failed to set rayon threads: {}", e))?;
}
std::fs::create_dir_all(&cli.output)?;
let (wz_filter, img_filter) = parse_img_filter(&cli.img);
if cli.base.is_dir() {
for entry in std::fs::read_dir(&cli.base)? {
let path = entry?.path();
if path.extension().map_or(false, |e| e == "wz") {
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
process_wz_file(&path, &cli.output, &wz_filter, &img_filter)
}));
match result {
Ok(Ok(())) => {}
Ok(Err(e)) => error!("Error processing {}: {:#}", path.display(), e),
Err(_) => error!("Skipped {} (unsupported WZ format or panic)", path.display()),
}
}
}
} else {
process_wz_file(&cli.base, &cli.output, &wz_filter, &img_filter)?;
}
log::info!("success ...");
Ok(())
}
fn is_sound_wz(name: &str) -> bool {
name.eq_ignore_ascii_case("Sound")
}
fn remove_empty_dirs(dir: &Path) {
if let Ok(entries) = std::fs::read_dir(dir) {
for entry in entries.flatten() {
let path = entry.path();
if path.is_dir() {
remove_empty_dirs(&path);
let _ = std::fs::remove_dir(&path);
}
}
}
}
struct ImgJob {
node: WzNodeArc,
output_dir: PathBuf,
img_name: String,
is_sound: bool,
}
fn process_wz_file(input: &Path, output: &Path, wz_filter: &Option<String>, img_filter: &Option<String>) -> Result<()> {
let root: WzNodeArc = WzNode::from_wz_file(input, None)
.with_context(|| format!("Failed to open: {}", input.display()))?
.into();
let wz_name = {
let mut w = root.write().unwrap();
w.parse(&root)?;
w.name.to_string()
};
if let Some(wz) = wz_filter {
if !wz.eq_ignore_ascii_case(&wz_name) {
return Ok(());
}
}
let wz_dir = output.join(&wz_name);
std::fs::create_dir_all(&wz_dir)?;
let root_children: Vec<WzNodeArc> = root.read().unwrap().children.values().cloned().collect();
let is_sound = is_sound_wz(&wz_name);
let mut jobs: Vec<ImgJob> = Vec::new();
for child in &root_children {
collect_img_jobs(child, &wz_dir, is_sound, &mut jobs, img_filter.as_deref())?;
}
if jobs.is_empty() {
if img_filter.is_some() {
info!("=== {} (filter: not found) ===", wz_name);
}
remove_empty_dirs(&wz_dir);
return Ok(());
}
let total = jobs.len();
info!("=== {} ({} imgs) ===", wz_name, total);
let remaining = AtomicUsize::new(total);
jobs.par_iter().for_each(|job| {
let left = remaining.fetch_sub(1, Ordering::Relaxed);
if let Err(e) = process_single_img_job(job) {
error!("[{}] Error processing {}: {:#}", wz_name, job.img_name, e);
}
if left % 100 == 0 || left <= 10 {
info!("[{}] [{} left] {}", wz_name, left - 1, job.img_name);
}
});
remove_empty_dirs(&wz_dir);
info!("Done: {}", wz_dir.display());
Ok(())
}
fn collect_img_jobs(
node: &WzNodeArc,
output_dir: &Path,
is_sound: bool,
jobs: &mut Vec<ImgJob>,
img_filter: Option<&str>,
) -> Result<()> {
let _ = node_util::parse_node(node);
let (name, is_dir, is_img, children) = {
let node_read = node.read().unwrap();
let name = node_read.name.to_string();
let is_dir = matches!(node_read.object_type, WzObjectType::Directory(_));
let is_img = matches!(node_read.object_type, WzObjectType::Image(_));
let children: Vec<WzNodeArc> = node_read.children.values().cloned().collect();
(name, is_dir, is_img, children)
};
if is_dir {
let sub_dir = output_dir.join(&name);
std::fs::create_dir_all(&sub_dir)?;
for child in children {
collect_img_jobs(&child, &sub_dir, is_sound, jobs, img_filter)?;
}
} else if is_img {
let match_name = name.trim_end_matches(".img").to_string();
if let Some(filter) = img_filter {
if name != filter && format!("{}.img", match_name) != filter {
return Ok(());
}
}
jobs.push(ImgJob {
node: node.clone(),
output_dir: output_dir.to_path_buf(),
img_name: name,
is_sound,
});
}
Ok(())
}
fn process_single_img_job(job: &ImgJob) -> Result<()> {
let base = job.img_name.strip_suffix(".img").unwrap_or(&job.img_name);
if job.is_sound {
let img_dir = job.output_dir.join(&job.img_name);
std::fs::create_dir_all(&img_dir)?;
extract_sounds(&job.node, &img_dir, "")?;
} else {
let sound_dir = job.output_dir.join(format!("{}.img", base));
let json = node_to_json(&job.node, &sound_dir)?;
let json_str = serde_json::to_string(&json)?;
let out_path = job.output_dir.join(format!("{}.img.json", base));
std::fs::write(&out_path, json_str)?;
}
Ok(())
}
fn extract_sounds(node: &WzNodeArc, sound_dir: &Path, wz_name: &str) -> Result<()> {
let _ = node_util::parse_node(node);
let node_read = node.read().unwrap();
for (key, child) in &node_read.children {
let child_read = child.read().unwrap();
if let WzObjectType::Property(WzSubProperty::Sound(sound)) = &child_read.object_type {
let ext = match sound.sound_type {
WzSoundType::Mp3 => "mp3",
WzSoundType::Wav => "wav",
_ => "bin",
};
let filename = format!("{}.{}", key, ext);
sound
.save(sound_dir.join(&filename))
.map_err(|e| anyhow::anyhow!("Sound error: {}", e))?;
info!("[sound] {}/{}", wz_name, filename);
}
}
Ok(())
}
fn node_to_json(node: &WzNodeArc, sound_dir: &Path) -> Result<Value> {
node_to_json_with_path(node, sound_dir, "")
}
fn node_to_json_with_path(node: &WzNodeArc, sound_dir: &Path, img_path: &str) -> Result<Value> {
let _ = node_util::parse_node(node);
let node_read = node.read().unwrap();
let name = node_read.name.to_string();
let current_path = if img_path.is_empty() {
name.clone()
} else {
format!("{}/{}", img_path, name)
};
let children: Vec<(String, WzNodeArc)> = node_read
.children
.iter()
.map(|(k, v)| (k.to_string(), v.clone()))
.collect();
let needs_wrapper = !children.is_empty() || is_special(&node_read.object_type);
if !needs_wrapper {
if let WzObjectType::Value(value) = &node_read.object_type {
return wz_value_to_json(value);
}
return Ok(Value::Null);
}
let mut obj = Map::new();
obj.insert("name".to_string(), Value::String(name.clone()));
match &node_read.object_type {
WzObjectType::Value(WzValue::Vector(Vector2D(x, y))) => {
obj.insert("type".to_string(), Value::String("vector".to_string()));
obj.insert("X".to_string(), Value::Number((*x).into()));
obj.insert("Y".to_string(), Value::Number((*y).into()));
}
WzObjectType::Value(WzValue::UOL(s)) => {
obj.insert("type".to_string(), Value::String("uol".to_string()));
obj.insert(
"path".to_string(),
Value::String(s.get_string().unwrap_or_default()),
);
}
WzObjectType::Property(WzSubProperty::PNG(png)) => {
obj.insert("type".to_string(), Value::String("canvas".to_string()));
match png.extract_png() {
Ok(img) => {
let mut png_bytes = Vec::new();
if img.write_to(
&mut std::io::Cursor::new(&mut png_bytes),
image::ImageFormat::Png,
).is_ok() {
let uri = base64::engine::general_purpose::STANDARD.encode(&png_bytes);
let mut image_obj = Map::new();
image_obj.insert("width".to_string(), Value::Number(png.width.into()));
image_obj.insert("height".to_string(), Value::Number(png.height.into()));
image_obj.insert(
"uri".to_string(),
Value::String(uri),
);
obj.insert("_image".to_string(), Value::Object(image_obj));
} else {
error!("PNG encode error at {}", current_path);
obj.insert("_image".to_string(), Value::Null);
}
}
Err(e) => {
error!("PNG decode error at {}: {}", current_path, e);
obj.insert("_image".to_string(), Value::Null);
}
}
}
WzObjectType::Property(WzSubProperty::Sound(sound)) => {
obj.insert("type".to_string(), Value::String("sound".to_string()));
let ext = match sound.sound_type {
WzSoundType::Mp3 => "mp3",
WzSoundType::Wav => "wav",
_ => "bin",
};
std::fs::create_dir_all(sound_dir)?;
let sound_name = format!("{}.{}", name, ext);
sound
.save(sound_dir.join(&sound_name))
.map_err(|e| anyhow::anyhow!("Sound error: {}", e))?;
info!("[sound] {}/{}", current_path, sound_name);
obj.insert("_sound".to_string(), Value::String(sound_name));
}
_ => {}
}
let mut valid_keys: Vec<Value> = Vec::new();
for (key, child) in &children {
let child_json = node_to_json_with_path(child, sound_dir, ¤t_path)?;
if !child_json.is_null() {
obj.insert(key.clone(), child_json);
}
else{
let child_json=json!({"_keys":[]});
obj.insert(key.clone(), child_json);
}
valid_keys.push(Value::String(key.clone()));
}
let has_type = obj.contains_key("type");
if valid_keys.is_empty() && !has_type {
if let WzObjectType::Value(value) = &node_read.object_type {
return wz_value_to_json(value);
}
}
obj.insert("_keys".to_string(), Value::Array(valid_keys));
Ok(Value::Object(obj))
}
fn is_special(obj_type: &WzObjectType) -> bool {
matches!(
obj_type,
WzObjectType::Value(WzValue::Vector(_))
| WzObjectType::Value(WzValue::UOL(_))
| WzObjectType::Property(WzSubProperty::PNG(_))
| WzObjectType::Property(WzSubProperty::Sound(_))
)
}
fn wz_value_to_json(value: &WzValue) -> Result<Value> {
match value {
WzValue::Short(v) => Ok(Value::Number((*v).into())),
WzValue::Int(v) => Ok(Value::Number((*v).into())),
WzValue::Long(v) => Ok(Value::Number((*v).into())),
WzValue::Float(v) => Ok(serde_json::Number::from_f64((*v).into())
.map(Value::Number)
.unwrap_or(Value::Null)),
WzValue::Double(v) => Ok(serde_json::Number::from_f64(*v)
.map(Value::Number)
.unwrap_or(Value::Null)),
WzValue::String(s) => Ok(Value::String(s.get_string().unwrap_or_default())),
WzValue::ParsedString(s) => Ok(Value::String(s.clone())),
_ => Ok(Value::Null),
}
}