schematic-mesher 0.1.0

Generate 3D meshes from Minecraft schematics and block data
Documentation
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
//! Schematic Mesher CLI
//!
//! Generate 3D meshes from Minecraft block data.

use clap::{Parser, Subcommand, ValueEnum};
use schematic_mesher::{
    export_glb, load_resource_pack, Mesher, MesherConfig, ObjExport,
};
use std::collections::HashMap;
use std::fs;
use std::path::PathBuf;

#[derive(Parser)]
#[command(name = "schematic-mesher")]
#[command(author, version, about = "Generate 3D meshes from Minecraft block data", long_about = None)]
struct Cli {
    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand)]
enum Commands {
    /// Mesh a single block (useful for testing)
    Block {
        /// Block name (e.g., "minecraft:stone" or "stone")
        #[arg(short, long)]
        block: String,

        /// Block properties as key=value pairs (e.g., "facing=north")
        #[arg(short, long, value_parser = parse_property)]
        property: Vec<(String, String)>,

        /// Path to resource pack (ZIP or directory)
        #[arg(short, long)]
        resource_pack: PathBuf,

        /// Output file path
        #[arg(short, long)]
        output: PathBuf,

        /// Output format
        #[arg(short, long, value_enum, default_value = "glb")]
        format: OutputFormat,
    },

    /// Mesh blocks from a JSON input file
    Mesh {
        /// Input JSON file containing block data
        #[arg(short, long)]
        input: PathBuf,

        /// Path to resource pack (ZIP or directory)
        #[arg(short, long)]
        resource_pack: PathBuf,

        /// Output file path (without extension)
        #[arg(short, long)]
        output: PathBuf,

        /// Output format
        #[arg(short, long, value_enum, default_value = "glb")]
        format: OutputFormat,

        /// Disable face culling
        #[arg(long)]
        no_culling: bool,

        /// Disable ambient occlusion
        #[arg(long)]
        no_ao: bool,

        /// AO intensity (0.0 to 1.0)
        #[arg(long, default_value = "0.4")]
        ao_intensity: f32,

        /// Maximum atlas size
        #[arg(long, default_value = "4096")]
        atlas_size: u32,

        /// Biome for tinting (e.g., "plains", "swamp", "jungle")
        #[arg(long)]
        biome: Option<String>,
    },

    /// Show information about a resource pack
    Info {
        /// Path to resource pack (ZIP or directory)
        #[arg(short, long)]
        resource_pack: PathBuf,
    },
}

#[derive(Copy, Clone, PartialEq, Eq, ValueEnum)]
enum OutputFormat {
    /// Binary glTF format
    Glb,
    /// Wavefront OBJ format
    Obj,
}

fn parse_property(s: &str) -> Result<(String, String), String> {
    let parts: Vec<&str> = s.splitn(2, '=').collect();
    if parts.len() != 2 {
        return Err(format!("Invalid property format: '{}'. Use key=value", s));
    }
    Ok((parts[0].to_string(), parts[1].to_string()))
}

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let cli = Cli::parse();

    match cli.command {
        Commands::Block {
            block,
            property,
            resource_pack,
            output,
            format,
        } => {
            mesh_single_block(&block, property, &resource_pack, &output, format)?;
        }
        Commands::Mesh {
            input,
            resource_pack,
            output,
            format,
            no_culling,
            no_ao,
            ao_intensity,
            atlas_size,
            biome,
        } => {
            mesh_from_json(
                &input,
                &resource_pack,
                &output,
                format,
                !no_culling,
                !no_ao,
                ao_intensity,
                atlas_size,
                biome,
            )?;
        }
        Commands::Info { resource_pack } => {
            show_pack_info(&resource_pack)?;
        }
    }

    Ok(())
}

fn mesh_single_block(
    block_name: &str,
    properties: Vec<(String, String)>,
    resource_pack_path: &PathBuf,
    output_path: &PathBuf,
    format: OutputFormat,
) -> Result<(), Box<dyn std::error::Error>> {
    println!("Loading resource pack from {:?}...", resource_pack_path);
    let pack = load_resource_pack(resource_pack_path)?;
    println!("  Found {} blockstates", pack.blockstate_count());

    // Normalize block name
    let block_name = if block_name.contains(':') {
        block_name.to_string()
    } else {
        format!("minecraft:{}", block_name)
    };

    // Create the block
    let mut block = schematic_mesher::types::InputBlock::new(&block_name);
    for (key, value) in properties {
        block.properties.insert(key, value);
    }

    println!("Meshing block: {} {:?}", block_name, block.properties);

    // Create a simple block source with just this block
    let blocks = SimpleBlockSource::single(block);

    let mesher = Mesher::new(pack);
    let output = mesher.mesh(&blocks)?;

    println!(
        "  Generated {} vertices, {} triangles",
        output.total_vertices(),
        output.total_triangles()
    );

    export_output(&output, output_path, format, "block")?;

    Ok(())
}

fn mesh_from_json(
    input_path: &PathBuf,
    resource_pack_path: &PathBuf,
    output_path: &PathBuf,
    format: OutputFormat,
    cull_faces: bool,
    ambient_occlusion: bool,
    ao_intensity: f32,
    atlas_size: u32,
    biome: Option<String>,
) -> Result<(), Box<dyn std::error::Error>> {
    println!("Loading resource pack from {:?}...", resource_pack_path);
    let pack = load_resource_pack(resource_pack_path)?;
    println!("  Found {} blockstates", pack.blockstate_count());

    println!("Loading block data from {:?}...", input_path);
    let json_content = fs::read_to_string(input_path)?;
    let block_data: BlockDataInput = serde_json::from_str(&json_content)?;
    println!("  Loaded {} blocks", block_data.blocks.len());

    // Convert to InputBlocks
    let blocks = SimpleBlockSource::from_input(&block_data);

    // Configure mesher
    let mut config = MesherConfig::default();
    config.cull_hidden_faces = cull_faces;
    config.ambient_occlusion = ambient_occlusion;
    config.ao_intensity = ao_intensity;
    config.atlas_max_size = atlas_size;

    if let Some(biome_name) = &biome {
        config = config.with_biome(biome_name);
    }

    println!("Meshing with config:");
    println!("  - Face culling: {}", cull_faces);
    println!("  - Ambient occlusion: {}", ambient_occlusion);
    if ambient_occlusion {
        println!("  - AO intensity: {}", ao_intensity);
    }
    println!("  - Atlas max size: {}", atlas_size);
    if let Some(biome_name) = &biome {
        println!("  - Biome: {}", biome_name);
    }

    let mesher = Mesher::with_config(pack, config);
    let output = mesher.mesh(&blocks)?;

    println!(
        "  Generated {} vertices ({} opaque, {} transparent), {} triangles",
        output.total_vertices(),
        output.opaque_mesh.vertex_count(),
        output.transparent_mesh.vertex_count(),
        output.total_triangles()
    );
    println!(
        "  Atlas: {}x{} with {} regions",
        output.atlas.width,
        output.atlas.height,
        output.atlas.regions.len()
    );

    export_output(&output, output_path, format, "mesh")?;

    Ok(())
}

fn show_pack_info(resource_pack_path: &PathBuf) -> Result<(), Box<dyn std::error::Error>> {
    println!("Loading resource pack from {:?}...", resource_pack_path);
    let pack = load_resource_pack(resource_pack_path)?;

    println!("\nResource Pack Info:");
    println!("  Blockstates: {}", pack.blockstate_count());
    println!("  Models: {}", pack.model_count());
    println!("  Textures: {}", pack.texture_count());

    Ok(())
}

fn export_output(
    output: &schematic_mesher::MesherOutput,
    path: &PathBuf,
    format: OutputFormat,
    name: &str,
) -> Result<(), Box<dyn std::error::Error>> {
    match format {
        OutputFormat::Glb => {
            let glb_path = if path.extension().is_some() {
                path.clone()
            } else {
                path.with_extension("glb")
            };
            let glb_data = export_glb(output)?;
            fs::write(&glb_path, &glb_data)?;
            println!("Exported GLB ({} bytes) to {:?}", glb_data.len(), glb_path);
        }
        OutputFormat::Obj => {
            let obj_export = ObjExport::from_output(output, name)?;

            let obj_path = if path.extension().is_some() {
                path.clone()
            } else {
                path.with_extension("obj")
            };
            let mtl_path = obj_path.with_extension("mtl");
            let png_path = obj_path.with_file_name(format!("{}_atlas.png", name));

            fs::write(&obj_path, &obj_export.obj)?;
            fs::write(&mtl_path, &obj_export.mtl)?;
            fs::write(&png_path, &obj_export.texture_png)?;

            println!("Exported OBJ to {:?}", obj_path);
            println!("  Material: {:?}", mtl_path);
            println!("  Texture: {:?}", png_path);
        }
    }

    Ok(())
}

// JSON input format
#[derive(serde::Deserialize)]
struct BlockDataInput {
    blocks: Vec<BlockEntry>,
}

#[derive(serde::Deserialize)]
struct BlockEntry {
    x: i32,
    y: i32,
    z: i32,
    #[serde(default = "default_block_name")]
    name: String,
    #[serde(default)]
    properties: HashMap<String, String>,
}

fn default_block_name() -> String {
    "minecraft:stone".to_string()
}

// Simple block source implementation
struct SimpleBlockSource {
    blocks: HashMap<schematic_mesher::types::BlockPosition, schematic_mesher::types::InputBlock>,
    bounds: schematic_mesher::types::BoundingBox,
}

impl SimpleBlockSource {
    fn single(block: schematic_mesher::types::InputBlock) -> Self {
        use schematic_mesher::types::{BlockPosition, BoundingBox};
        let mut blocks = HashMap::new();
        blocks.insert(BlockPosition::new(0, 0, 0), block);
        Self {
            blocks,
            bounds: BoundingBox::new([0.0, 0.0, 0.0], [1.0, 1.0, 1.0]),
        }
    }

    fn from_input(input: &BlockDataInput) -> Self {
        use schematic_mesher::types::{BlockPosition, BoundingBox, InputBlock};

        let mut blocks = HashMap::new();
        let mut min = [i32::MAX; 3];
        let mut max = [i32::MIN; 3];

        for entry in &input.blocks {
            let pos = BlockPosition::new(entry.x, entry.y, entry.z);

            // Normalize block name
            let name = if entry.name.contains(':') {
                entry.name.clone()
            } else {
                format!("minecraft:{}", entry.name)
            };

            let mut block = InputBlock::new(name);
            for (key, value) in &entry.properties {
                block.properties.insert(key.clone(), value.clone());
            }

            blocks.insert(pos, block);

            min[0] = min[0].min(entry.x);
            min[1] = min[1].min(entry.y);
            min[2] = min[2].min(entry.z);
            max[0] = max[0].max(entry.x);
            max[1] = max[1].max(entry.y);
            max[2] = max[2].max(entry.z);
        }

        let bounds = if blocks.is_empty() {
            BoundingBox::new([0.0, 0.0, 0.0], [0.0, 0.0, 0.0])
        } else {
            BoundingBox::new(
                [min[0] as f32, min[1] as f32, min[2] as f32],
                [(max[0] + 1) as f32, (max[1] + 1) as f32, (max[2] + 1) as f32],
            )
        };

        Self { blocks, bounds }
    }
}

impl schematic_mesher::types::BlockSource for SimpleBlockSource {
    fn get_block(
        &self,
        pos: schematic_mesher::types::BlockPosition,
    ) -> Option<&schematic_mesher::types::InputBlock> {
        self.blocks.get(&pos)
    }

    fn iter_blocks(
        &self,
    ) -> Box<
        dyn Iterator<Item = (schematic_mesher::types::BlockPosition, &schematic_mesher::types::InputBlock)>
            + '_,
    > {
        Box::new(self.blocks.iter().map(|(k, v)| (*k, v)))
    }

    fn bounds(&self) -> schematic_mesher::types::BoundingBox {
        self.bounds
    }
}