oxihuman-export 0.1.2

Export pipeline for OxiHuman — glTF, COLLADA, STL, and streaming formats
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
420
421
// Copyright (C) 2026 COOLJAPAN OU (Team KitaSan)
// SPDX-License-Identifier: Apache-2.0

//! glTF 2.0 JSON export — meshes, materials, and scene nodes.
//!
//! Produces a minimal, spec-compliant glTF 2.0 JSON string without external
//! library dependencies.

#![allow(dead_code)]

// ── Structs ───────────────────────────────────────────────────────────────────

/// Configuration for glTF 2.0 export.
#[derive(Debug, Clone)]
pub struct GltfExportConfig {
    /// Generator string placed in the asset section. Default: `"OxiHuman"`.
    pub generator: String,
    /// glTF spec version. Default: `"2.0"`.
    pub version: String,
    /// Whether to pretty-print the JSON output. Default: `false`.
    pub pretty: bool,
}

impl Default for GltfExportConfig {
    fn default() -> Self {
        Self {
            generator: "OxiHuman".to_string(),
            version: "2.0".to_string(),
            pretty: false,
        }
    }
}

/// A glTF scene node with an optional mesh index and transform.
#[derive(Debug, Clone)]
pub struct GltfNode {
    /// Node name.
    pub name: String,
    /// Index into the mesh array, if any.
    pub mesh: Option<usize>,
    /// Translation `[x, y, z]`. Default: `[0, 0, 0]`.
    pub translation: [f32; 3],
    /// Rotation quaternion `[x, y, z, w]`. Default: `[0, 0, 0, 1]`.
    pub rotation: [f32; 4],
    /// Scale `[x, y, z]`. Default: `[1, 1, 1]`.
    pub scale: [f32; 3],
}

/// A glTF mesh with a name and a list of primitive attribute names.
#[derive(Debug, Clone)]
pub struct GltfMesh {
    /// Mesh name.
    pub name: String,
    /// Primitive attribute names (e.g., `"POSITION"`, `"NORMAL"`).
    pub attributes: Vec<String>,
}

/// A glTF PBR metallic-roughness material.
#[derive(Debug, Clone)]
pub struct GltfMaterial {
    /// Material name.
    pub name: String,
    /// Base color factor `[r, g, b, a]` in linear space.
    pub base_color_factor: [f32; 4],
    /// Metallic factor `[0..=1]`.
    pub metallic_factor: f32,
    /// Roughness factor `[0..=1]`.
    pub roughness_factor: f32,
    /// Whether the material is double-sided.
    pub double_sided: bool,
}

// ── Type aliases ──────────────────────────────────────────────────────────────

/// Result type for glTF validation.
pub type GltfValidationResult = Result<(), String>;

// ── Functions ─────────────────────────────────────────────────────────────────

/// Return a default [`GltfExportConfig`].
#[allow(dead_code)]
pub fn default_gltf_config() -> GltfExportConfig {
    GltfExportConfig::default()
}

/// Construct a new [`GltfNode`] with the given name.
#[allow(dead_code)]
pub fn new_gltf_node(name: &str) -> GltfNode {
    GltfNode {
        name: name.to_string(),
        mesh: None,
        translation: [0.0, 0.0, 0.0],
        rotation: [0.0, 0.0, 0.0, 1.0],
        scale: [1.0, 1.0, 1.0],
    }
}

/// Append `node` to `nodes` and return the new node count.
#[allow(dead_code)]
pub fn add_gltf_node(nodes: &mut Vec<GltfNode>, node: GltfNode) -> usize {
    nodes.push(node);
    nodes.len()
}

/// Append `mesh` to `meshes` and return the new mesh count.
#[allow(dead_code)]
pub fn add_gltf_mesh(meshes: &mut Vec<GltfMesh>, mesh: GltfMesh) -> usize {
    meshes.push(mesh);
    meshes.len()
}

/// Append `material` to `materials` and return the new material count.
#[allow(dead_code)]
pub fn add_gltf_material(materials: &mut Vec<GltfMaterial>, material: GltfMaterial) -> usize {
    materials.push(material);
    materials.len()
}

/// Return the number of nodes.
#[allow(dead_code)]
pub fn node_count(nodes: &[GltfNode]) -> usize {
    nodes.len()
}

/// Return the number of meshes.
#[allow(dead_code)]
pub fn mesh_count(meshes: &[GltfMesh]) -> usize {
    meshes.len()
}

/// Return the number of materials.
#[allow(dead_code)]
pub fn material_count_gltf(materials: &[GltfMaterial]) -> usize {
    materials.len()
}

/// Return a default white PBR [`GltfMaterial`].
#[allow(dead_code)]
pub fn default_gltf_material(name: &str) -> GltfMaterial {
    GltfMaterial {
        name: name.to_string(),
        base_color_factor: [1.0, 1.0, 1.0, 1.0],
        metallic_factor: 0.0,
        roughness_factor: 0.5,
        double_sided: false,
    }
}

/// Validate nodes, meshes, and materials.
///
/// Returns `Err` if any node references a mesh index that is out of range.
#[allow(dead_code)]
pub fn validate_gltf(
    nodes: &[GltfNode],
    meshes: &[GltfMesh],
    _materials: &[GltfMaterial],
) -> GltfValidationResult {
    for node in nodes {
        if let Some(mi) = node.mesh {
            if mi >= meshes.len() {
                return Err(format!(
                    "node '{}' references mesh index {} but only {} meshes exist",
                    node.name,
                    mi,
                    meshes.len()
                ));
            }
        }
    }
    Ok(())
}

/// Estimate the JSON output size in bytes (rough heuristic).
#[allow(dead_code)]
pub fn gltf_file_size_estimate(
    nodes: &[GltfNode],
    meshes: &[GltfMesh],
    materials: &[GltfMaterial],
) -> usize {
    // Base overhead for asset section, scenes, etc.
    let base = 200usize;
    let node_bytes: usize = nodes.iter().map(|n| 80 + n.name.len()).sum();
    let mesh_bytes: usize = meshes.iter().map(|m| 60 + m.name.len() + m.attributes.len() * 15).sum();
    let mat_bytes: usize = materials.iter().map(|m| 100 + m.name.len()).sum();
    base + node_bytes + mesh_bytes + mat_bytes
}

/// Serialize everything into a minimal glTF 2.0 JSON string.
#[allow(dead_code)]
pub fn gltf_to_json(
    nodes: &[GltfNode],
    meshes: &[GltfMesh],
    materials: &[GltfMaterial],
    cfg: &GltfExportConfig,
) -> String {
    let sep = if cfg.pretty { "\n  " } else { "" };
    let nl = if cfg.pretty { "\n" } else { "" };

    // asset
    let asset = format!(
        r#"{{"generator":"{}","version":"{}"}}"#,
        cfg.generator, cfg.version
    );

    // nodes
    let nodes_json: Vec<String> = nodes
        .iter()
        .map(|n| {
            let mesh_part = match n.mesh {
                Some(i) => format!(r#","mesh":{}"#, i),
                None => String::new(),
            };
            format!(
                r#"{{"name":"{}","translation":[{},{},{}],"rotation":[{},{},{},{}],"scale":[{},{},{}]{}}}"#,
                n.name,
                n.translation[0], n.translation[1], n.translation[2],
                n.rotation[0], n.rotation[1], n.rotation[2], n.rotation[3],
                n.scale[0], n.scale[1], n.scale[2],
                mesh_part
            )
        })
        .collect();

    // meshes
    let meshes_json: Vec<String> = meshes
        .iter()
        .map(|m| {
            let attrs: Vec<String> = m
                .attributes
                .iter()
                .enumerate()
                .map(|(i, a)| format!(r#""{}":{}"#, a, i))
                .collect();
            format!(
                r#"{{"name":"{}","primitives":[{{"attributes":{{{}}}}}]}}"#,
                m.name,
                attrs.join(",")
            )
        })
        .collect();

    // materials
    let mats_json: Vec<String> = materials
        .iter()
        .map(|mat| {
            let cf = mat.base_color_factor;
            format!(
                r#"{{"name":"{}","pbrMetallicRoughness":{{"baseColorFactor":[{},{},{},{}],"metallicFactor":{},"roughnessFactor":{}}},"doubleSided":{}}}"#,
                mat.name,
                cf[0], cf[1], cf[2], cf[3],
                mat.metallic_factor,
                mat.roughness_factor,
                mat.double_sided
            )
        })
        .collect();

    // scene node indices
    let node_indices: Vec<String> = (0..nodes.len()).map(|i| i.to_string()).collect();

    format!(
        r#"{{{sep}"asset":{asset},{sep}"scene":0,{sep}"scenes":[{{"nodes":[{nodes_idx}]}}],{sep}"nodes":[{nodes_arr}],{sep}"meshes":[{meshes_arr}],{sep}"materials":[{mats_arr}]{nl}}}"#,
        sep = sep,
        nl = nl,
        asset = asset,
        nodes_idx = node_indices.join(","),
        nodes_arr = nodes_json.join(","),
        meshes_arr = meshes_json.join(","),
        mats_arr = mats_json.join(","),
    )
}

// ── Tests ─────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;

    fn sample_node() -> GltfNode {
        let mut n = new_gltf_node("RootNode");
        n.mesh = Some(0);
        n
    }

    fn sample_mesh() -> GltfMesh {
        GltfMesh {
            name: "Body".to_string(),
            attributes: vec!["POSITION".to_string(), "NORMAL".to_string()],
        }
    }

    fn sample_material() -> GltfMaterial {
        default_gltf_material("Skin")
    }

    #[test]
    fn test_default_gltf_config() {
        let cfg = default_gltf_config();
        assert_eq!(cfg.version, "2.0");
        assert_eq!(cfg.generator, "OxiHuman");
        assert!(!cfg.pretty);
    }

    #[test]
    fn test_new_gltf_node_defaults() {
        let n = new_gltf_node("Pelvis");
        assert_eq!(n.name, "Pelvis");
        assert_eq!(n.mesh, None);
        assert_eq!(n.scale, [1.0, 1.0, 1.0]);
        assert_eq!(n.rotation[3], 1.0);
    }

    #[test]
    fn test_add_gltf_node_count() {
        let mut nodes: Vec<GltfNode> = Vec::new();
        assert_eq!(add_gltf_node(&mut nodes, sample_node()), 1);
        assert_eq!(add_gltf_node(&mut nodes, new_gltf_node("Head")), 2);
    }

    #[test]
    fn test_add_gltf_mesh_count() {
        let mut meshes: Vec<GltfMesh> = Vec::new();
        assert_eq!(add_gltf_mesh(&mut meshes, sample_mesh()), 1);
    }

    #[test]
    fn test_add_gltf_material_count() {
        let mut mats: Vec<GltfMaterial> = Vec::new();
        assert_eq!(add_gltf_material(&mut mats, sample_material()), 1);
    }

    #[test]
    fn test_node_count() {
        let nodes = vec![sample_node(), new_gltf_node("B")];
        assert_eq!(node_count(&nodes), 2);
    }

    #[test]
    fn test_mesh_count() {
        let meshes = vec![sample_mesh()];
        assert_eq!(mesh_count(&meshes), 1);
    }

    #[test]
    fn test_material_count_gltf() {
        let mats = vec![sample_material(), default_gltf_material("Hair")];
        assert_eq!(material_count_gltf(&mats), 2);
    }

    #[test]
    fn test_default_gltf_material_fields() {
        let mat = default_gltf_material("Eyes");
        assert_eq!(mat.name, "Eyes");
        assert_eq!(mat.base_color_factor, [1.0, 1.0, 1.0, 1.0]);
        assert_eq!(mat.metallic_factor, 0.0);
        assert!(!mat.double_sided);
    }

    #[test]
    fn test_validate_gltf_ok() {
        let nodes = vec![sample_node()];
        let meshes = vec![sample_mesh()];
        let mats = vec![sample_material()];
        assert!(validate_gltf(&nodes, &meshes, &mats).is_ok());
    }

    #[test]
    fn test_validate_gltf_bad_mesh_ref() {
        let mut node = new_gltf_node("Bad");
        node.mesh = Some(99);
        let meshes: Vec<GltfMesh> = Vec::new();
        let mats: Vec<GltfMaterial> = Vec::new();
        assert!(validate_gltf(&[node], &meshes, &mats).is_err());
    }

    #[test]
    fn test_gltf_file_size_estimate_positive() {
        let nodes = vec![sample_node()];
        let meshes = vec![sample_mesh()];
        let mats = vec![sample_material()];
        assert!(gltf_file_size_estimate(&nodes, &meshes, &mats) > 0);
    }

    #[test]
    fn test_gltf_to_json_contains_asset() {
        let cfg = default_gltf_config();
        let json = gltf_to_json(&[sample_node()], &[sample_mesh()], &[sample_material()], &cfg);
        assert!(json.contains("\"asset\""));
        assert!(json.contains("\"2.0\""));
        assert!(json.contains("OxiHuman"));
    }

    #[test]
    fn test_gltf_to_json_contains_node_name() {
        let cfg = default_gltf_config();
        let json = gltf_to_json(&[sample_node()], &[sample_mesh()], &[sample_material()], &cfg);
        assert!(json.contains("RootNode"));
    }

    #[test]
    fn test_gltf_to_json_contains_mesh_name() {
        let cfg = default_gltf_config();
        let json = gltf_to_json(&[sample_node()], &[sample_mesh()], &[sample_material()], &cfg);
        assert!(json.contains("Body"));
    }

    #[test]
    fn test_gltf_to_json_contains_material_name() {
        let cfg = default_gltf_config();
        let json = gltf_to_json(&[sample_node()], &[sample_mesh()], &[sample_material()], &cfg);
        assert!(json.contains("Skin"));
    }

    #[test]
    fn test_gltf_to_json_empty() {
        let cfg = default_gltf_config();
        let json = gltf_to_json(&[], &[], &[], &cfg);
        assert!(json.contains("\"asset\""));
        assert!(json.contains("\"scenes\""));
    }
}