Untitled

mail@pastecode.io avatar
unknown
rust
a year ago
2.2 kB
1
Indexable
Never
use serde_json::Value;
use std::fs::File;
use std::io::{BufReader, Write};


fn fix_points(points: &mut Vec<(f64, f64)>) {
    let mut s = 0.0;
    for i in 0..points.len() {
        let (px, py) = points[i];
        let (qx, qy) = points[(i + 1) % points.len()];
        s += (qx - px) * (qy + py);
    }
    if s < 0.0 {
        points.reverse();
    }
}

fn main() -> Result<(), std::io::Error> {
    let args: Vec<String> = std::env::args().collect();

    if args.len() != 3 {
        eprintln!("Usage: {} <input_file> <output_file>", args[0]);
        std::process::exit(1);
    }

    let in_name = &args[1];
    let out_name = &args[2];

    let in_file = File::open(in_name)?;
    let reader = BufReader::new(in_file);
    let json: Value = serde_json::from_reader(reader)?;
    let mut out_file = File::create(&out_name)?;

    for layer in json["layers"].as_array().unwrap() {
        let name = layer["name"].as_str().unwrap();
        if name == "walls" {
            for o in layer["objects"].as_array().unwrap() {
                let mut points = Vec::new();
                let x = o["x"].as_f64().unwrap();
                let y = o["y"].as_f64().unwrap();
                for p in o["polygon"].as_array().unwrap() {
                    let px = p["x"].as_f64().unwrap();
                    let py = p["y"].as_f64().unwrap();
                    points.push((x + px, y + py));
                }
                fix_points(&mut points);
                let s = points
                    .iter()
                    .map(|(x, y)| format!("({} {})", x, y))
                    .collect::<Vec<_>>()
                    .join(" ");
                out_file
                    .write_all(format!("wall [{}]\n", s).as_bytes())
                    .unwrap()
            }
        } else if name == "objects" {
            for o in layer["objects"].as_array().unwrap() {
                let name = o["name"].as_str().unwrap();
                let x = o["x"].as_f64().unwrap();
                let y = o["y"].as_f64().unwrap();
                out_file
                    .write_all(format!("{} ({} {})\n", name, x, y).as_bytes())
                    .unwrap()
            }
        }
    }

    Ok(())
}