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
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
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
// Copyright (C) 2026 COOLJAPAN OU (Team KitaSan)
// SPDX-License-Identifier: Apache-2.0

//! FBX ASCII format writer (FBX 7.4 compatible).
//!
//! Produces human-readable FBX files with geometry, normals, UVs, and
//! optional skeletal (skin/bone) data. The output follows the Autodesk
//! ASCII FBX conventions closely enough to be loaded by most DCC tools
//! that accept FBX 7.4 ASCII.

use std::fmt::Write as FmtWrite;

/// Counter-based unique ID generator for FBX objects.
struct IdGen {
    next: i64,
}

impl IdGen {
    fn new(start: i64) -> Self {
        Self { next: start }
    }

    fn take(&mut self) -> i64 {
        let id = self.next;
        self.next += 1;
        id
    }
}

// ── Writer ───────────────────────────────────────────────────────────────────

/// Writes FBX data in the human-readable ASCII format (version 7.4).
pub struct FbxAsciiWriter {
    output: Vec<u8>,
    indent_level: usize,
}

impl Default for FbxAsciiWriter {
    fn default() -> Self {
        Self::new()
    }
}

impl FbxAsciiWriter {
    /// Creates a new writer with the standard FBX 7.4 ASCII header already
    /// emitted.
    pub fn new() -> Self {
        let mut w = Self {
            output: Vec::with_capacity(64 * 1024),
            indent_level: 0,
        };
        // Write the file-level header comments and FBXHeaderExtension.
        w.push_line("; FBX 7.4.0 project file");
        w.push_line("; Creator: OxiHuman FBX ASCII Exporter");
        w.push_line("; -------------------------------------------");
        w.push_line("");
        w.open_section("FBXHeaderExtension");
        w.push_property_i32("FBXHeaderVersion", 1003);
        w.push_property_i32("FBXVersion", 7400);
        w.push_property_i32("EncryptionType", 0);
        w.open_section("CreationTimeStamp");
        w.push_property_i32("Version", 1000);
        w.push_property_i32("Year", 2026);
        w.push_property_i32("Month", 3);
        w.push_property_i32("Day", 11);
        w.close_section();
        w.push_kv_string("Creator", "OxiHuman FBX ASCII Exporter");
        w.close_section();
        w.push_line("");
        // GlobalSettings
        w.open_section("GlobalSettings");
        w.push_property_i32("Version", 1000);
        w.open_section("Properties70");
        w.push_p70_int("UpAxis", 1);
        w.push_p70_int("UpAxisSign", 1);
        w.push_p70_int("FrontAxis", 2);
        w.push_p70_int("FrontAxisSign", 1);
        w.push_p70_int("CoordAxis", 0);
        w.push_p70_int("CoordAxisSign", 1);
        w.push_p70_double("UnitScaleFactor", 1.0);
        w.close_section();
        w.close_section();
        w.push_line("");
        w
    }

    // ── High-level API ──────────────────────────────────────────────────

    /// Writes a complete mesh object block including geometry, model, and
    /// connections. Optionally includes skin deformer and bone data when
    /// `bone_weights` / `bone_names` are provided.
    pub fn write_mesh(
        &mut self,
        name: &str,
        positions: &[[f64; 3]],
        normals: &[[f64; 3]],
        uvs: &[[f64; 2]],
        triangles: &[[usize; 3]],
        bone_weights: Option<&[Vec<(usize, f64)>]>,
        bone_names: Option<&[String]>,
    ) -> anyhow::Result<()> {
        let mut ids = IdGen::new(100_000_000);

        let geometry_id = ids.take();
        let model_id = ids.take();

        // ── Objects section ─────────────────────────────────────────────
        self.open_section("Objects");

        // Geometry node
        self.write_geometry_block(
            geometry_id,
            name,
            positions,
            normals,
            uvs,
            triangles,
        )?;

        // Model node
        self.write_model_block(model_id, name)?;

        // Skeleton / skin deformer (optional)
        let mut connection_pairs: Vec<(i64, i64)> = Vec::new();
        connection_pairs.push((geometry_id, model_id));
        connection_pairs.push((model_id, 0)); // model -> root

        if let (Some(weights), Some(names)) = (bone_weights, bone_names) {
            self.write_skin_section(
                &mut ids,
                geometry_id,
                positions,
                weights,
                names,
                &mut connection_pairs,
            )?;
        }

        self.close_section(); // Objects
        self.push_line("");

        // ── Connections section ─────────────────────────────────────────
        self.open_section("Connections");
        for (child, parent) in &connection_pairs {
            self.push_connection(*child, *parent);
        }
        self.close_section();
        self.push_line("");

        Ok(())
    }

    /// Consumes the writer and returns the finished FBX ASCII bytes.
    pub fn finish(self) -> Vec<u8> {
        self.output
    }

    // ── Geometry block ──────────────────────────────────────────────────

    fn write_geometry_block(
        &mut self,
        geometry_id: i64,
        name: &str,
        positions: &[[f64; 3]],
        normals: &[[f64; 3]],
        uvs: &[[f64; 2]],
        triangles: &[[usize; 3]],
    ) -> anyhow::Result<()> {
        self.push_line(&format!(
            "Geometry: {geometry_id}, \"Geometry::{name}\", \"Mesh\" {{"
        ));
        self.indent_level += 1;

        // Vertices
        let vert_count = positions.len() * 3;
        self.push_line(&format!("Vertices: *{vert_count} {{"));
        self.indent_level += 1;
        self.push_line(&format!("a: {}", format_f64_triples(positions)));
        self.indent_level -= 1;
        self.push_line("}");

        // PolygonVertexIndex  (FBX encodes last index of each polygon as -(idx+1))
        let idx_count = triangles.len() * 3;
        self.push_line(&format!("PolygonVertexIndex: *{idx_count} {{"));
        self.indent_level += 1;
        self.push_line(&format!("a: {}", format_triangle_indices(triangles)));
        self.indent_level -= 1;
        self.push_line("}");

        // LayerElementNormal
        if !normals.is_empty() {
            self.write_layer_element_normal(normals)?;
        }

        // LayerElementUV
        if !uvs.is_empty() {
            self.write_layer_element_uv(uvs)?;
        }

        // Layer block
        self.write_layer_block(!normals.is_empty(), !uvs.is_empty());

        self.indent_level -= 1;
        self.push_line("}");
        Ok(())
    }

    fn write_layer_element_normal(&mut self, normals: &[[f64; 3]]) -> anyhow::Result<()> {
        self.open_section("LayerElementNormal: 0");
        self.push_property_i32("Version", 101);
        self.push_kv_string("Name", "Normals");
        self.push_kv_string("MappingInformationType", "ByVertice");
        self.push_kv_string("ReferenceInformationType", "Direct");
        let count = normals.len() * 3;
        self.push_line(&format!("Normals: *{count} {{"));
        self.indent_level += 1;
        self.push_line(&format!("a: {}", format_f64_triples(normals)));
        self.indent_level -= 1;
        self.push_line("}");
        self.close_section();
        Ok(())
    }

    fn write_layer_element_uv(&mut self, uvs: &[[f64; 2]]) -> anyhow::Result<()> {
        self.open_section("LayerElementUV: 0");
        self.push_property_i32("Version", 101);
        self.push_kv_string("Name", "UVMap");
        self.push_kv_string("MappingInformationType", "ByVertice");
        self.push_kv_string("ReferenceInformationType", "Direct");
        let count = uvs.len() * 2;
        self.push_line(&format!("UV: *{count} {{"));
        self.indent_level += 1;
        self.push_line(&format!("a: {}", format_f64_pairs(uvs)));
        self.indent_level -= 1;
        self.push_line("}");
        self.close_section();
        Ok(())
    }

    fn write_layer_block(&mut self, has_normals: bool, has_uvs: bool) {
        self.open_section("Layer: 0");
        self.push_property_i32("Version", 100);
        if has_normals {
            self.open_section("LayerElement");
            self.push_kv_string("Type", "LayerElementNormal");
            self.push_property_i32("TypedIndex", 0);
            self.close_section();
        }
        if has_uvs {
            self.open_section("LayerElement");
            self.push_kv_string("Type", "LayerElementUV");
            self.push_property_i32("TypedIndex", 0);
            self.close_section();
        }
        self.close_section();
    }

    // ── Model block ─────────────────────────────────────────────────────

    fn write_model_block(&mut self, model_id: i64, name: &str) -> anyhow::Result<()> {
        self.push_line(&format!(
            "Model: {model_id}, \"Model::{name}\", \"Mesh\" {{"
        ));
        self.indent_level += 1;
        self.push_property_i32("Version", 232);
        self.open_section("Properties70");
        self.push_p70_vec3d("Lcl Translation", 0.0, 0.0, 0.0);
        self.push_p70_vec3d("Lcl Rotation", 0.0, 0.0, 0.0);
        self.push_p70_vec3d("Lcl Scaling", 1.0, 1.0, 1.0);
        self.close_section();
        self.indent_level -= 1;
        self.push_line("}");
        Ok(())
    }

    // ── Skin / bones section ────────────────────────────────────────────

    fn write_skin_section(
        &mut self,
        ids: &mut IdGen,
        geometry_id: i64,
        positions: &[[f64; 3]],
        weights: &[Vec<(usize, f64)>],
        bone_names: &[String],
        connections: &mut Vec<(i64, i64)>,
    ) -> anyhow::Result<()> {
        let deformer_id = ids.take();

        // Deformer (Skin)
        self.push_line(&format!(
            "Deformer: {deformer_id}, \"Deformer::Skin\", \"Skin\" {{"
        ));
        self.indent_level += 1;
        self.push_property_i32("Version", 101);
        self.push_property_f64("Link_DeformAcuracy", 50.0);
        self.indent_level -= 1;
        self.push_line("}");
        connections.push((deformer_id, geometry_id));

        // One SubDeformer (Cluster) per bone
        for (bone_idx, bone_name) in bone_names.iter().enumerate() {
            let cluster_id = ids.take();
            let limb_id = ids.take();

            // Collect vertex indices and weight values for this bone
            let mut indices_buf: Vec<i32> = Vec::new();
            let mut weights_buf: Vec<f64> = Vec::new();
            for (vi, vertex_weights) in weights.iter().enumerate() {
                for &(bi, w) in vertex_weights {
                    if bi == bone_idx && w.abs() > 1e-12 {
                        if let Ok(vi32) = i32::try_from(vi) {
                            indices_buf.push(vi32);
                            weights_buf.push(w);
                        }
                    }
                }
            }

            // SubDeformer (Cluster)
            self.push_line(&format!(
                "Deformer: {cluster_id}, \"SubDeformer::{bone_name}\", \"Cluster\" {{"
            ));
            self.indent_level += 1;
            self.push_property_i32("Version", 100);

            if !indices_buf.is_empty() {
                let n = indices_buf.len();
                self.push_line(&format!("Indexes: *{n} {{"));
                self.indent_level += 1;
                self.push_line(&format!("a: {}", format_i32_slice(&indices_buf)));
                self.indent_level -= 1;
                self.push_line("}");

                self.push_line(&format!("Weights: *{n} {{"));
                self.indent_level += 1;
                self.push_line(&format!("a: {}", format_f64_slice(&weights_buf)));
                self.indent_level -= 1;
                self.push_line("}");
            }

            // Transform (identity for bind pose — callers can adjust externally)
            self.write_identity_transform("Transform", positions.len())?;
            self.write_identity_transform("TransformLink", positions.len())?;

            self.indent_level -= 1;
            self.push_line("}");

            // NodeAttribute (LimbNode) for bone
            self.push_line(&format!(
                "NodeAttribute: {limb_id}, \"NodeAttribute::{bone_name}\", \"LimbNode\" {{"
            ));
            self.indent_level += 1;
            self.push_kv_string("TypeFlags", "Skeleton");
            self.indent_level -= 1;
            self.push_line("}");

            connections.push((cluster_id, deformer_id));
            connections.push((limb_id, cluster_id));
        }

        Ok(())
    }

    fn write_identity_transform(&mut self, label: &str, _n: usize) -> anyhow::Result<()> {
        self.push_line(&format!("{label}: *16 {{"));
        self.indent_level += 1;
        self.push_line("a: 1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1");
        self.indent_level -= 1;
        self.push_line("}");
        Ok(())
    }

    // ── Low-level helpers ───────────────────────────────────────────────

    fn indent(&self) -> String {
        "\t".repeat(self.indent_level)
    }

    fn push_line(&mut self, text: &str) {
        let ind = self.indent();
        let _ = write!(
            StringAdapter(&mut self.output),
            "{ind}{text}\n"
        );
    }

    fn open_section(&mut self, name: &str) {
        self.push_line(&format!("{name}: {{"));
        self.indent_level += 1;
    }

    fn close_section(&mut self) {
        self.indent_level = self.indent_level.saturating_sub(1);
        self.push_line("}");
    }

    fn push_property_i32(&mut self, key: &str, val: i32) {
        self.push_line(&format!("{key}: {val}"));
    }

    fn push_property_f64(&mut self, key: &str, val: f64) {
        self.push_line(&format!("{key}: {val}"));
    }

    fn push_kv_string(&mut self, key: &str, val: &str) {
        self.push_line(&format!("{key}: \"{val}\""));
    }

    fn push_p70_int(&mut self, name: &str, val: i32) {
        self.push_line(&format!(
            "P: \"{name}\", \"int\", \"Integer\", \"\", {val}"
        ));
    }

    fn push_p70_double(&mut self, name: &str, val: f64) {
        self.push_line(&format!(
            "P: \"{name}\", \"double\", \"Number\", \"\", {val}"
        ));
    }

    fn push_p70_vec3d(&mut self, name: &str, x: f64, y: f64, z: f64) {
        self.push_line(&format!(
            "P: \"{name}\", \"Vector3D\", \"Vector\", \"\", {x},{y},{z}"
        ));
    }

    fn push_connection(&mut self, child: i64, parent: i64) {
        self.push_line(&format!("C: \"OO\", {child}, {parent}"));
    }
}

// ── Adapter for `write!` into Vec<u8> ───────────────────────────────────────

struct StringAdapter<'a>(&'a mut Vec<u8>);

impl<'a> std::fmt::Write for StringAdapter<'a> {
    fn write_str(&mut self, s: &str) -> std::fmt::Result {
        self.0.extend_from_slice(s.as_bytes());
        Ok(())
    }
}

// ── Formatting helpers ──────────────────────────────────────────────────────

fn format_f64_triples(data: &[[f64; 3]]) -> String {
    let mut buf = String::with_capacity(data.len() * 30);
    for (i, v) in data.iter().enumerate() {
        if i > 0 {
            buf.push(',');
        }
        let _ = write!(buf, "{},{},{}", v[0], v[1], v[2]);
    }
    buf
}

fn format_f64_pairs(data: &[[f64; 2]]) -> String {
    let mut buf = String::with_capacity(data.len() * 20);
    for (i, v) in data.iter().enumerate() {
        if i > 0 {
            buf.push(',');
        }
        let _ = write!(buf, "{},{}", v[0], v[1]);
    }
    buf
}

fn format_triangle_indices(triangles: &[[usize; 3]]) -> String {
    let mut buf = String::with_capacity(triangles.len() * 15);
    for (i, tri) in triangles.iter().enumerate() {
        if i > 0 {
            buf.push(',');
        }
        // FBX convention: last index of each polygon is bitwise-negated (-(idx+1))
        let last = -(tri[2] as i64) - 1;
        let _ = write!(buf, "{},{},{last}", tri[0], tri[1]);
    }
    buf
}

fn format_i32_slice(data: &[i32]) -> String {
    let mut buf = String::with_capacity(data.len() * 6);
    for (i, v) in data.iter().enumerate() {
        if i > 0 {
            buf.push(',');
        }
        let _ = write!(buf, "{v}");
    }
    buf
}

fn format_f64_slice(data: &[f64]) -> String {
    let mut buf = String::with_capacity(data.len() * 12);
    for (i, v) in data.iter().enumerate() {
        if i > 0 {
            buf.push(',');
        }
        let _ = write!(buf, "{v}");
    }
    buf
}

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

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

    #[test]
    fn test_new_writer_has_header() {
        let w = FbxAsciiWriter::new();
        let bytes = w.finish();
        let text = String::from_utf8_lossy(&bytes);
        assert!(text.contains("FBX 7.4.0"));
        assert!(text.contains("FBXHeaderVersion: 1003"));
        assert!(text.contains("FBXVersion: 7400"));
    }

    #[test]
    fn test_write_mesh_basic() {
        let mut w = FbxAsciiWriter::new();
        let positions = vec![
            [0.0, 0.0, 0.0],
            [1.0, 0.0, 0.0],
            [0.0, 1.0, 0.0],
        ];
        let normals = vec![
            [0.0, 0.0, 1.0],
            [0.0, 0.0, 1.0],
            [0.0, 0.0, 1.0],
        ];
        let uvs = vec![
            [0.0, 0.0],
            [1.0, 0.0],
            [0.0, 1.0],
        ];
        let triangles = vec![[0, 1, 2]];

        let result = w.write_mesh("TestMesh", &positions, &normals, &uvs, &triangles, None, None);
        assert!(result.is_ok());

        let text = String::from_utf8_lossy(&w.finish());
        assert!(text.contains("Geometry::TestMesh"));
        assert!(text.contains("Vertices: *9"));
        assert!(text.contains("PolygonVertexIndex: *3"));
        assert!(text.contains("LayerElementNormal"));
        assert!(text.contains("LayerElementUV"));
        assert!(text.contains("Objects:"));
        assert!(text.contains("Connections:"));
    }

    #[test]
    fn test_write_mesh_no_normals_no_uvs() {
        let mut w = FbxAsciiWriter::new();
        let positions = vec![[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]];
        let triangles = vec![[0, 1, 2]];

        let result = w.write_mesh("Simple", &positions, &[], &[], &triangles, None, None);
        assert!(result.is_ok());

        let text = String::from_utf8_lossy(&w.finish());
        assert!(!text.contains("LayerElementNormal"));
        assert!(!text.contains("LayerElementUV"));
    }

    #[test]
    fn test_write_mesh_with_bones() {
        let mut w = FbxAsciiWriter::new();
        let positions = vec![
            [0.0, 0.0, 0.0],
            [1.0, 0.0, 0.0],
            [0.0, 1.0, 0.0],
            [1.0, 1.0, 0.0],
        ];
        let normals = vec![[0.0, 0.0, 1.0]; 4];
        let uvs: Vec<[f64; 2]> = vec![];
        let triangles = vec![[0, 1, 2], [1, 3, 2]];

        let bone_weights = vec![
            vec![(0, 1.0)],
            vec![(0, 0.5), (1, 0.5)],
            vec![(1, 1.0)],
            vec![(1, 1.0)],
        ];
        let bone_names = vec!["Hips".to_string(), "Spine".to_string()];

        let result = w.write_mesh(
            "Skinned",
            &positions,
            &normals,
            &uvs,
            &triangles,
            Some(&bone_weights),
            Some(&bone_names),
        );
        assert!(result.is_ok());

        let text = String::from_utf8_lossy(&w.finish());
        assert!(text.contains("Deformer::Skin"));
        assert!(text.contains("SubDeformer::Hips"));
        assert!(text.contains("SubDeformer::Spine"));
        assert!(text.contains("LimbNode"));
    }

    #[test]
    fn test_format_triangle_indices_negative() {
        let tris = vec![[0, 1, 2], [3, 4, 5]];
        let s = format_triangle_indices(&tris);
        // Last index per triangle: -(2+1) = -3, -(5+1) = -6
        assert!(s.contains("-3"));
        assert!(s.contains("-6"));
    }

    #[test]
    fn test_default_trait() {
        let w = FbxAsciiWriter::default();
        let bytes = w.finish();
        assert!(!bytes.is_empty());
    }
}