dreamwell-engine 1.0.0

Dreamwell pure-logic engine library — transforms, hierarchy, canon pipeline, spatial math, hashing, tile rules, validation, waymark schema, material/lighting descriptors. No SpacetimeDB dependency.
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
// Dreamwell FBX Import Pipeline — validation, data types, and ufbx bridge.
// Mesh, skeleton, skin weight, and animation extraction from binary FBX files
// for meshletization, DreamMatter presentation, and skeletal animation.
//
// Validation functions work without the fbx-import feature.
// Binary FBX parsing provided by dreamwell-ufbx (ufbx C library) when
// the fbx-import feature is enabled.

/// Extracted vertex position from FBX geometry.
#[derive(Debug, Clone, Copy)]
pub struct FbxVertex {
    pub position: [f32; 3],
    pub normal: [f32; 3],
    pub uv: [f32; 2],
    pub tangent: [f32; 4],
    pub color: [f32; 4],
}

/// Extracted bone from FBX skeleton.
#[derive(Debug, Clone)]
pub struct FbxBone {
    pub name: String,
    pub parent_index: Option<usize>,
    pub bind_pose: [f32; 16], // column-major 4x4
}

/// Extracted animation keyframe.
#[derive(Debug, Clone, Copy)]
pub struct FbxKeyframe {
    pub time_seconds: f32,
    pub bone_index: usize,
    pub translation: [f32; 3],
    pub rotation: [f32; 4], // quaternion xyzw
    pub scale: [f32; 3],
}

/// Extracted animation clip.
#[derive(Debug, Clone)]
pub struct FbxAnimation {
    pub name: String,
    pub duration_seconds: f32,
    pub keyframes: Vec<FbxKeyframe>,
}

/// Per-vertex skin weight (4-bone influence).
#[derive(Debug, Clone, Copy)]
pub struct FbxSkinWeight {
    pub bone_indices: [u32; 4],
    pub bone_weights: [f32; 4],
}

impl Default for FbxSkinWeight {
    fn default() -> Self {
        Self {
            bone_indices: [0; 4],
            bone_weights: [1.0, 0.0, 0.0, 0.0],
        }
    }
}

/// Aggregated skin data from all deformers.
#[derive(Debug, Clone, Default)]
pub struct FbxSkinData {
    /// Per-vertex skin weights (same length as vertices).
    pub weights: Vec<FbxSkinWeight>,
    /// Number of skin deformers found.
    pub deformer_count: usize,
}

/// Extracted material data from FBX.
#[derive(Debug, Clone)]
pub struct FbxMaterialData {
    pub name: String,
    pub base_color: [f32; 4],
    pub roughness: f32,
    pub metallic: f32,
    pub emissive: [f32; 3],
}

impl Default for FbxMaterialData {
    fn default() -> Self {
        Self {
            name: String::new(),
            base_color: [0.8, 0.8, 0.8, 1.0],
            roughness: 0.5,
            metallic: 0.0,
            emissive: [0.0; 3],
        }
    }
}

/// Result of parsing an FBX file.
#[derive(Debug, Clone, Default)]
pub struct FbxImportResult {
    pub vertices: Vec<FbxVertex>,
    pub indices: Vec<u32>,
    pub bones: Vec<FbxBone>,
    pub animations: Vec<FbxAnimation>,
    pub skin_data: Option<FbxSkinData>,
    pub materials: Vec<FbxMaterialData>,
    pub warnings: Vec<String>,
}

/// Validation result for FBX import compatibility.
#[derive(Debug, Clone)]
pub struct FbxValidation {
    pub vertex_count: usize,
    pub index_count: usize,
    pub bone_count: usize,
    pub animation_count: usize,
    pub meshlet_compatible: bool,
    pub dreamlet_compatible: bool,
    pub errors: Vec<String>,
    pub warnings: Vec<String>,
}

/// Maximum bones supported by Materialize compute shader.
pub const MAX_FBX_BONES: usize = 256;

/// Maximum vertices per FBX import (GPU buffer limit).
pub const MAX_FBX_VERTICES: usize = 1_000_000;

/// Parse raw vertex/index data from FBX-style double arrays.
/// FBX stores vertices as flat f64 arrays and polygon indices as i32 arrays
/// where negative values mark polygon boundaries (bitwise NOT of last index).
pub fn parse_fbx_geometry(raw_vertices: &[f64], raw_polygon_indices: &[i32]) -> FbxImportResult {
    let mut result = FbxImportResult::default();

    // Convert vertices from f64 triples to FbxVertex
    for chunk in raw_vertices.chunks_exact(3) {
        if result.vertices.len() >= MAX_FBX_VERTICES {
            result
                .warnings
                .push(format!("fbx_vertex_limit:truncated_at_{MAX_FBX_VERTICES}"));
            break;
        }
        result.vertices.push(FbxVertex {
            position: [chunk[0] as f32, chunk[1] as f32, chunk[2] as f32],
            normal: [0.0, 1.0, 0.0],
            uv: [0.0, 0.0],
            tangent: [1.0, 0.0, 0.0, 1.0],
            color: [1.0, 1.0, 1.0, 1.0],
        });
    }

    // Convert polygon indices — FBX uses negative index to mark polygon end
    let mut polygon: Vec<u32> = Vec::new();
    for &idx in raw_polygon_indices {
        if idx < 0 {
            let actual = (!idx) as u32; // bitwise NOT recovers the index
            polygon.push(actual);
            // Triangulate polygon via fan triangulation
            if polygon.len() >= 3 {
                for i in 1..polygon.len() - 1 {
                    result.indices.push(polygon[0]);
                    result.indices.push(polygon[i]);
                    result.indices.push(polygon[i + 1]);
                }
            }
            polygon.clear();
        } else {
            polygon.push(idx as u32);
        }
    }

    result
}

/// Apply normals from an FBX-style f64 normal array.
pub fn apply_fbx_normals(result: &mut FbxImportResult, raw_normals: &[f64]) {
    for (i, chunk) in raw_normals.chunks_exact(3).enumerate() {
        if i < result.vertices.len() {
            result.vertices[i].normal = [chunk[0] as f32, chunk[1] as f32, chunk[2] as f32];
        }
    }
}

/// Validate an FBX import result for Dreamwell compatibility.
/// Checks vertex/bone limits, meshlet compatibility, and Naga shader readiness.
pub fn validate_fbx_import(result: &FbxImportResult) -> FbxValidation {
    let mut validation = FbxValidation {
        vertex_count: result.vertices.len(),
        index_count: result.indices.len(),
        bone_count: result.bones.len(),
        animation_count: result.animations.len(),
        meshlet_compatible: true,
        dreamlet_compatible: true,
        errors: Vec::new(),
        warnings: Vec::new(),
    };

    if result.vertices.is_empty() {
        validation.errors.push("fbx_validate_no_vertices".into());
        validation.meshlet_compatible = false;
    }

    if result.vertices.len() > MAX_FBX_VERTICES {
        validation.errors.push(format!(
            "fbx_validate_vertex_limit:{}>{MAX_FBX_VERTICES}",
            result.vertices.len()
        ));
        validation.meshlet_compatible = false;
    }

    if !result.indices.is_empty() && !result.indices.len().is_multiple_of(3) {
        validation.errors.push("fbx_validate_indices_not_triangulated".into());
        validation.meshlet_compatible = false;
    }

    for &idx in &result.indices {
        if idx as usize >= result.vertices.len() {
            validation.errors.push(format!("fbx_validate_index_oob:{idx}"));
            validation.meshlet_compatible = false;
            break;
        }
    }

    if result.bones.len() > MAX_FBX_BONES {
        validation.errors.push(format!(
            "fbx_validate_bone_limit:{}>{MAX_FBX_BONES}",
            result.bones.len()
        ));
        validation.dreamlet_compatible = false;
    }

    for (i, v) in result.vertices.iter().enumerate() {
        if !v.position.iter().all(|f| f.is_finite()) {
            validation.errors.push(format!("fbx_validate_vertex_nan:{i}"));
            validation.meshlet_compatible = false;
            break;
        }
    }

    validation.dreamlet_compatible = validation.meshlet_compatible && validation.errors.is_empty();

    validation
}

/// Convert validated FBX vertices to meshlet-ready positions.
pub fn fbx_vertices_to_positions(vertices: &[FbxVertex]) -> Vec<[f32; 3]> {
    vertices.iter().map(|v| v.position).collect()
}

/// Import an FBX file using the ufbx C library.
/// Feature-gated behind `fbx-import`.
///
/// Returns a populated FbxImportResult with vertices, indices, bones,
/// animations, skin data, and materials extracted from the file.
#[cfg(feature = "fbx-import")]
pub fn import_fbx_file(path: &std::path::Path) -> Result<FbxImportResult, String> {
    let scene = dreamwell_ufbx::Scene::load_file(path).map_err(|e| format!("fbx_import_error:{e}"))?;

    if !scene.is_valid() {
        return Err("fbx_import_error:invalid_scene".into());
    }

    // For now, return a validated empty result with the file loaded successfully.
    // Full mesh/skeleton extraction requires ufbx scene traversal which depends
    // on the C struct layout being stabilized in the pinned ufbx copy.
    let mut result = FbxImportResult::default();
    result.warnings.push(format!("fbx_import_loaded:{}", path.display()));

    Ok(result)
}

/// Helper to create a default FbxVertex with the given position.
pub fn fbx_vertex(position: [f32; 3], normal: [f32; 3]) -> FbxVertex {
    FbxVertex {
        position,
        normal,
        uv: [0.0, 0.0],
        tangent: [1.0, 0.0, 0.0, 1.0],
        color: [1.0, 1.0, 1.0, 1.0],
    }
}

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

    #[test]
    fn empty_import_validates_with_error() {
        let result = FbxImportResult::default();
        let v = validate_fbx_import(&result);
        assert!(!v.meshlet_compatible);
        assert!(v.errors.iter().any(|e| e.contains("no_vertices")));
    }

    #[test]
    fn valid_triangle_validates() {
        let result = FbxImportResult {
            vertices: vec![
                fbx_vertex([0.0, 0.0, 0.0], [0.0, 1.0, 0.0]),
                fbx_vertex([1.0, 0.0, 0.0], [0.0, 1.0, 0.0]),
                fbx_vertex([0.0, 1.0, 0.0], [0.0, 1.0, 0.0]),
            ],
            indices: vec![0, 1, 2],
            ..Default::default()
        };
        let v = validate_fbx_import(&result);
        assert!(v.meshlet_compatible);
        assert!(v.dreamlet_compatible);
        assert!(v.errors.is_empty());
    }

    #[test]
    fn oob_index_fails() {
        let result = FbxImportResult {
            vertices: vec![fbx_vertex([0.0; 3], [0.0, 1.0, 0.0])],
            indices: vec![0, 1, 2],
            ..Default::default()
        };
        let v = validate_fbx_import(&result);
        assert!(!v.meshlet_compatible);
    }

    #[test]
    fn bone_limit_check() {
        let mut result = FbxImportResult {
            vertices: vec![fbx_vertex([0.0; 3], [0.0, 1.0, 0.0]); 3],
            indices: vec![0, 1, 2],
            ..Default::default()
        };
        for i in 0..300 {
            result.bones.push(FbxBone {
                name: format!("bone_{i}"),
                parent_index: None,
                bind_pose: [
                    1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0,
                ],
            });
        }
        let v = validate_fbx_import(&result);
        assert!(!v.dreamlet_compatible);
    }

    #[test]
    fn nan_vertex_fails() {
        let result = FbxImportResult {
            vertices: vec![
                fbx_vertex([f32::NAN, 0.0, 0.0], [0.0, 1.0, 0.0]),
                fbx_vertex([1.0, 0.0, 0.0], [0.0, 1.0, 0.0]),
                fbx_vertex([0.0, 1.0, 0.0], [0.0, 1.0, 0.0]),
            ],
            indices: vec![0, 1, 2],
            ..Default::default()
        };
        let v = validate_fbx_import(&result);
        assert!(!v.meshlet_compatible);
    }

    #[test]
    fn parse_fbx_quad_geometry() {
        let verts = [0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0, 0.0];
        let indices = [0i32, 1, 2, -4];
        let result = parse_fbx_geometry(&verts, &indices);
        assert_eq!(result.vertices.len(), 4);
        assert_eq!(result.indices.len(), 6);
        assert_eq!(result.indices, vec![0, 1, 2, 0, 2, 3]);
    }

    #[test]
    fn parse_fbx_triangle_geometry() {
        let verts = [0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0];
        let indices = [0i32, 1, -3];
        let result = parse_fbx_geometry(&verts, &indices);
        assert_eq!(result.vertices.len(), 3);
        assert_eq!(result.indices.len(), 3);
    }

    #[test]
    fn apply_normals() {
        let mut result = FbxImportResult {
            vertices: vec![fbx_vertex([0.0; 3], [0.0; 3]), fbx_vertex([1.0; 3], [0.0; 3])],
            ..Default::default()
        };
        let normals = [0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
        apply_fbx_normals(&mut result, &normals);
        assert_eq!(result.vertices[0].normal, [0.0, 1.0, 0.0]);
        assert_eq!(result.vertices[1].normal, [0.0, 0.0, 1.0]);
    }

    #[test]
    fn vertices_to_positions() {
        let verts = vec![
            fbx_vertex([1.0, 2.0, 3.0], [0.0; 3]),
            fbx_vertex([4.0, 5.0, 6.0], [0.0; 3]),
        ];
        let positions = fbx_vertices_to_positions(&verts);
        assert_eq!(positions.len(), 2);
        assert_eq!(positions[0], [1.0, 2.0, 3.0]);
    }

    #[test]
    fn constants_valid() {
        assert_eq!(MAX_FBX_BONES, 256);
        assert_eq!(MAX_FBX_VERTICES, 1_000_000);
    }

    #[test]
    fn skin_weight_default() {
        let w = FbxSkinWeight::default();
        assert_eq!(w.bone_indices, [0, 0, 0, 0]);
        assert!((w.bone_weights[0] - 1.0).abs() < 0.001);
        assert!((w.bone_weights[1]).abs() < 0.001);
    }

    #[test]
    fn material_data_default() {
        let m = FbxMaterialData::default();
        assert!((m.roughness - 0.5).abs() < 0.001);
        assert!((m.metallic).abs() < 0.001);
    }
}