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
 
49ec522
 
 
 
 
 
 
 
 
 
18d65b9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
//! Headless CLI; source-preserving conversion with atomic destination publication.
pub mod preflight;
use mb3_dat::{Document, Limits, Version, World};
use std::ffi::OsString;
use std::fmt;
use std::fs::{self, File, OpenOptions};
use std::io::{self, BufRead, BufReader, Write};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};

const HELP: &str = "nanobrush preflight INPUT --to txt|dat-201501280|dat-201512200|obj [LIMITS]\nnanobrush inspect INPUT [--from auto|txt|dat] [LIMITS]\nnanobrush validate INPUT [--from auto|txt|dat] [LIMITS]\nnanobrush convert INPUT OUTPUT --to txt|dat-201501280|dat-201512200|obj [--from auto|txt|dat] [--force] [LIMITS]\nLIMITS: --max-bytes N --max-items N --max-string-bytes N --max-owned-bytes N\nUse --compute with convert/preflight to regenerate native geometry.\nOBJ requires --allow-lossy when editable data is discarded.\nTXT option: --text-encoding utf8|latin1 (default utf8).\nUse -- before positional paths beginning with a dash. TXT input is UTF-8; output has a BOM.\nExit: 0 success/help, 1 invalid data or I/O failure, 2 usage error.\n";
#[derive(Debug)]
pub struct Error {
    pub usage: bool,
    message: String,
}
impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.message)
    }
}
impl std::error::Error for Error {}
impl From<io::Error> for Error {
    fn from(e: io::Error) -> Self {
        fail(e.to_string())
    }
}
fn fail(message: impl Into<String>) -> Error {
    Error {
        usage: false,
        message: message.into(),
    }
}
fn usage(message: impl Into<String>) -> Error {
    Error {
        usage: true,
        message: message.into(),
    }
}
type Result<T> = std::result::Result<T, Error>;
#[derive(Clone, Copy)]
enum InputFormat {
    Auto,
    Txt,
    Dat,
}
#[derive(Clone, Copy)]
enum To {
    Txt,
    Obj,
    Dat(Version),
}
struct Options {
    command: String,
    paths: Vec<PathBuf>,
    from: InputFormat,
    to: Option<To>,
    force: bool,
    allow_lossy: bool,
    compute: bool,
    limits: Limits,
    encoding: mb3_txt::Encoding,
}
fn parse(args: impl IntoIterator<Item = OsString>) -> Result<Option<Options>> {
    let mut args = args.into_iter();
    let command = args.next().ok_or_else(|| usage(HELP))?;
    if command == "--help" || command == "-h" {
        return Ok(None);
    }
    let command = command
        .into_string()
        .map_err(|_| usage("command must be UTF-8"))?;
    if !matches!(
        command.as_str(),
        "inspect" | "validate" | "convert" | "preflight"
    ) {
        return Err(usage(
            "expected inspect, validate, convert or preflight; use --help",
        ));
    }
    let mut options = Options {
        command,
        paths: Vec::new(),
        from: InputFormat::Auto,
        to: None,
        force: false,
        allow_lossy: false,
        compute: false,
        limits: Limits::default(),
        encoding: mb3_txt::Encoding::Utf8,
    };
    let mut positional = false;
    let mut seen = std::collections::HashSet::new();
    while let Some(arg) = args.next() {
        if !positional && arg == "--" {
            positional = true;
            continue;
        }
        if !positional && (arg == "--help" || arg == "-h") {
            return Ok(None);
        }
        if !positional && arg.as_encoded_bytes().starts_with(b"-") {
            let flag = arg.to_str().ok_or_else(|| usage("option must be UTF-8"))?;
            if !seen.insert(flag.to_owned()) {
                return Err(usage(format!("duplicate option {flag}")));
            }
            if flag == "--compute" {
                options.compute = true;
                continue;
            }
            if flag == "--allow-lossy" {
                options.allow_lossy = true;
                continue;
            }
            if flag == "--force" {
                options.force = true;
                continue;
            }
            if !matches!(
                flag,
                "--from"
                    | "--text-encoding"
                    | "--to"
                    | "--max-bytes"
                    | "--max-items"
                    | "--max-string-bytes"
                    | "--max-owned-bytes"
            ) {
                return Err(usage(format!("unknown option {flag}")));
            }
            let value = args
                .next()
                .ok_or_else(|| usage(format!("missing value for {flag}")))?;
            let value = value
                .to_str()
                .ok_or_else(|| usage("option value must be UTF-8"))?;
            match flag {
                "--text-encoding" => {
                    options.encoding = match value {
                        "utf8" => mb3_txt::Encoding::Utf8,
                        "latin1" => mb3_txt::Encoding::Latin1,
                        _ => return Err(usage("--text-encoding requires utf8 or latin1")),
                    }
                }
                "--from" => {
                    options.from = match value {
                        "auto" => InputFormat::Auto,
                        "txt" => InputFormat::Txt,
                        "dat" => InputFormat::Dat,
                        _ => return Err(usage("--from requires auto, txt or dat")),
                    }
                }
                "--to" => {
                    options.to = Some(match value {
                        "txt" => To::Txt,
                        "obj" => To::Obj,
                        "dat-201501280" => To::Dat(Version::V201501280),
                        "dat-201512200" => To::Dat(Version::V201512200),
                        _ => {
                            return Err(usage("--to requires txt, dat-201501280 or dat-201512200"));
                        }
                    })
                }
                _ => {
                    if value.is_empty() || !value.bytes().all(|b| b.is_ascii_digit()) {
                        return Err(usage("limits must be nonnegative decimal integers"));
                    }
                    let n = value
                        .parse::<usize>()
                        .map_err(|_| usage("limit outside platform usize range"))?;
                    match flag {
                        "--max-bytes" => options.limits.max_bytes = n,
                        "--max-items" => options.limits.max_items = n,
                        "--max-string-bytes" => options.limits.max_string_bytes = n,
                        _ => options.limits.max_owned_bytes = n,
                    }
                }
            }
        } else {
            options.paths.push(arg.into());
        }
    }
    if options.command == "preflight" {
        if options.paths.len() != 1 || options.to.is_none() || options.force {
            return Err(usage("preflight requires INPUT --to FORMAT"));
        }
    } else if options.command == "convert" {
        if options.paths.len() != 2 || options.to.is_none() {
            return Err(usage("convert requires INPUT OUTPUT --to FORMAT"));
        }
    } else if options.paths.len() != 1 || options.to.is_some() || options.force {
        return Err(usage(
            "inspect/validate require one INPUT and no --to/--force",
        ));
    }
    if options.allow_lossy && (options.command != "convert" || !matches!(options.to, Some(To::Obj)))
    {
        return Err(usage("--allow-lossy requires convert --to obj"));
    }
    if options.compute && !matches!(options.command.as_str(), "convert" | "preflight") {
        return Err(usage("--compute requires convert or preflight"));
    }
    Ok(Some(options))
}
struct Input {
    world: World,
    version: Option<Version>,
}
fn load(
    path: &Path,
    from: InputFormat,
    encoding: mb3_txt::Encoding,
    limits: &Limits,
) -> Result<Input> {
    let mut file =
        BufReader::new(File::open(path).map_err(|e| fail(format!("{}: {e}", path.display())))?);
    let dat = match from {
        InputFormat::Dat => true,
        InputFormat::Txt => false,
        InputFormat::Auto => file.fill_buf()?.starts_with(b"Mb3World"),
    };
    if dat {
        if encoding != mb3_txt::Encoding::Utf8 {
            return Err(fail("--text-encoding latin1 requires TXT input"));
        }
        let d =
            mb3_dat::read(file, limits).map_err(|e| fail(format!("{}: {e}", path.display())))?;
        Ok(Input {
            world: d.world,
            version: Some(d.version),
        })
    } else {
        let world = mb3_txt::read_with_encoding(file, encoding, limits)
            .map_err(|e| fail(format!("{}: {e}", path.display())))?;
        Ok(Input {
            world,
            version: None,
        })
    }
}
static NEXT_TEMP: AtomicU64 = AtomicU64::new(0);
struct Temp(PathBuf);
impl Drop for Temp {
    fn drop(&mut self) {
        let _ = fs::remove_file(&self.0);
    }
}
fn same_file(a: &fs::Metadata, b: &fs::Metadata) -> bool {
    #[cfg(unix)]
    {
        use std::os::unix::fs::MetadataExt;
        a.dev() == b.dev() && a.ino() == b.ino()
    }
    #[cfg(not(unix))]
    {
        let _ = (a, b);
        false
    }
}
fn save(input: &Path, output: &Path, bytes: &[u8], force: bool) -> Result<()> {
    let parent = output
        .parent()
        .filter(|p| !p.as_os_str().is_empty())
        .unwrap_or(Path::new("."));
    let parent = fs::canonicalize(parent)?;
    let name = output
        .file_name()
        .ok_or_else(|| fail("output requires a filename"))?;
    let output = parent.join(name);
    let input_meta = fs::metadata(input)?;
    match fs::symlink_metadata(&output) {
        Ok(meta) => {
            if !meta.is_file() || meta.file_type().is_symlink() {
                return Err(fail(
                    "output must be a regular file, not a symlink or directory",
                ));
            }
            if same_file(&input_meta, &meta)
                || fs::canonicalize(input)? == fs::canonicalize(&output)?
            {
                return Err(fail(
                    "input and output must be different files (including hard links)",
                ));
            }
            if !force {
                return Err(fail("output exists; use --force to replace it"));
            }
        }
        Err(e) if e.kind() == io::ErrorKind::NotFound => (),
        Err(e) => return Err(e.into()),
    }
    let mut created = None;
    for _ in 0..100 {
        let path = parent.join(format!(
            ".nanobrush-{}-{}.tmp",
            std::process::id(),
            NEXT_TEMP.fetch_add(1, Ordering::Relaxed)
        ));
        let mut options = OpenOptions::new();
        options.create_new(true).write(true);
        #[cfg(unix)]
        {
            use std::os::unix::fs::OpenOptionsExt;
            options.mode(0o600);
        }
        match options.open(&path) {
            Ok(file) => {
                created = Some((Temp(path), file));
                break;
            }
            Err(e) if e.kind() == io::ErrorKind::AlreadyExists => (),
            Err(e) => return Err(e.into()),
        }
    }
    let (temp, mut file) =
        created.ok_or_else(|| fail("cannot allocate a unique output temporary file"))?;
    file.write_all(bytes)?;
    file.sync_all()?;
    drop(file);
    publish(temp, &output, force)
}
fn publish(temp: Temp, output: &Path, force: bool) -> Result<()> {
    if force {
        fs::rename(&temp.0, output)?;
    } else {
        fs::hard_link(&temp.0, output)?;
    }
    Ok(())
}
/// Execute without exiting the process. Errors distinguish usage (exit 2) from
/// data/I/O (exit 1). Arguments exclude the executable's name.
pub fn run(args: impl IntoIterator<Item = OsString>, stdout: &mut dyn Write) -> Result<()> {
    let Some(o) = parse(args)? else {
        stdout.write_all(HELP.as_bytes())?;
        return Ok(());
    };
    let mut input = load(&o.paths[0], o.from, o.encoding, &o.limits)?;
    if o.compute {
        let limits = nanobrush_geometry::ComputeLimits {
            max_vertices: o.limits.max_items.min(100_000),
            max_owned_bytes: o.limits.max_owned_bytes.min(128 * 1024 * 1024),
            ..Default::default()
        };
        input.world =
            nanobrush_geometry::world::compute(&input.world, Default::default(), limits, o.limits)
                .map_err(|e| fail(e.to_string()))?
                .0;
    }
    match o.command.as_str() {
        "preflight" => {
            let target = match o.to.ok_or_else(|| usage("missing --to"))? {
                To::Txt => preflight::Target::Txt,
                To::Obj => preflight::Target::Obj,
                To::Dat(v) => preflight::Target::Dat(v),
            };
            writeln!(
                stdout,
                "{}",
                preflight::analyze(&input.world, target).json()
            )?;
        }
        "inspect" => {
            let w = &input.world;
            let planes: usize = w.brushes.iter().map(|b| b.planes.len()).sum();
            let polygons: usize = w
                .brushes
                .iter()
                .flat_map(|b| &b.planes)
                .map(|p| p.polygon.as_ref().map_or(0, Vec::len))
                .sum();
            let anchors: usize = w.patches.iter().map(|p| p.anchors.len()).sum();
            let points: usize = w
                .patches
                .iter()
                .map(|p| p.computed.as_ref().map_or(0, |c| c.points.len()))
                .sum();
            let normals: usize = w
                .patches
                .iter()
                .map(|p| p.computed.as_ref().map_or(0, |c| c.normals.len()))
                .sum();
            let version = input
                .version
                .map_or("null".into(), |v| (v as u32).to_string());
            writeln!(
                stdout,
                "{{\"format\":\"{}\",\"dat_version\":{},\"computed\":{},\"brushes\":{},\"planes\":{},\"patches\":{},\"string_properties\":{},\"uv_properties\":{},\"polygon_vertices\":{},\"anchors\":{},\"points\":{},\"normals\":{}}}",
                if input.version.is_some() {
                    "mb3dat"
                } else {
                    "mb3txt"
                },
                version,
                w.computed,
                w.brushes.len(),
                planes,
                w.patches.len(),
                w.string_properties.len(),
                w.uv_properties.len(),
                polygons,
                anchors,
                points,
                normals
            )?;
        }
        "validate" => writeln!(
            stdout,
            "valid: {}",
            if input.version.is_some() {
                "mb3dat"
            } else {
                "mb3txt"
            }
        )?,
        _ => {
            let bytes = match o.to.ok_or_else(|| usage("missing --to"))? {
                To::Obj => {
                    let report = preflight::analyze(&input.world, preflight::Target::Obj);
                    if report.blocked() || (!report.compatible() && !o.allow_lossy) {
                        return Err(fail(format!(
                            "OBJ export requires compatible computed geometry and --allow-lossy: {}",
                            report.json()
                        )));
                    }
                    mb3_obj::encode(&input.world, &o.limits).map_err(|e| fail(e.to_string()))?
                }
                To::Txt => {
                    mb3_txt::encode(&input.world, &o.limits).map_err(|e| fail(e.to_string()))?
                }
                To::Dat(version) => mb3_dat::encode(
                    &Document {
                        version,
                        world: input.world,
                    },
                    &o.limits,
                )
                .map_err(|e| fail(e.to_string()))?,
            };
            save(&o.paths[0], &o.paths[1], &bytes, o.force)?;
        }
    }
    Ok(())
}
#[cfg(test)]
mod tests;