viewport-lib-io 0.1.0

File format loaders and exporters for viewport-lib
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
use std::collections::HashMap;
use std::path::PathBuf;

/// Sentinel used to pad unused slots in fixed-width volumetric cell connectivity.
pub const CELL_SENTINEL: u32 = u32::MAX;

/// Maximum number of joints permitted in a single skeleton.
///
/// Skinning palettes in real-time renderers are fixed-size; 256 matches the
/// conventional palette limit used across the viewport-lib stack. Loaders
/// reject any source skeleton that exceeds this bound rather than silently
/// truncating, and per-vertex `[u8; 4]` joint indices fit exactly into this
/// range.
pub const MAX_JOINTS: usize = 256;

/// CPU-side RGBA8 image data.
#[derive(Clone, Debug)]
pub struct RasterImageData {
    /// Width in pixels.
    pub width: u32,
    /// Height in pixels.
    pub height: u32,
    /// Row-major RGBA8 pixel data.
    pub rgba: Vec<u8>,
}

/// CPU-side RGBA32F image data.
#[derive(Clone, Debug)]
pub struct HdrImageData {
    /// Width in pixels.
    pub width: u32,
    /// Height in pixels.
    pub height: u32,
    /// Row-major RGBA32F pixel data.
    pub rgba: Vec<f32>,
}

/// Where a scene material's texture content comes from.
#[derive(Clone, Debug)]
pub enum TextureSource {
    /// Resolve texture bytes from a file path at the consumer layer.
    File(PathBuf),
    /// Use already-decoded pixels directly.
    Decoded(RasterImageData),
}

/// Material data extracted from a scene file.
#[derive(Clone, Debug)]
pub struct MaterialData {
    /// Material name from the source scene.
    pub name: String,
    /// Base colour in linear space.
    pub base_color: [f32; 3],
    /// Metallic factor.
    pub metallic: f32,
    /// Roughness factor.
    pub roughness: f32,
    /// Opacity factor from the source file.
    pub opacity: f32,
    /// Base colour texture, if present.
    pub base_color_texture: Option<TextureSource>,
    /// Normal map, if present.
    pub normal_map_texture: Option<TextureSource>,
    /// Ambient-occlusion texture, if present.
    pub ao_texture: Option<TextureSource>,
}

impl Default for MaterialData {
    fn default() -> Self {
        Self {
            name: String::new(),
            base_color: [0.7, 0.7, 0.7],
            metallic: 0.0,
            roughness: 0.5,
            opacity: 1.0,
            base_color_texture: None,
            normal_map_texture: None,
            ao_texture: None,
        }
    }
}

/// Domain on which an attribute is defined.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum AttributeDomain {
    /// One value per point or vertex.
    Point,
    /// One value per cell.
    Cell,
    /// One value per face.
    Face,
    /// One value per directed edge.
    Edge,
    /// One value per halfedge/corner-edge.
    Halfedge,
    /// One value per face corner.
    Corner,
}

/// Attribute payload values.
#[derive(Clone, Debug)]
pub enum AttributeValues {
    /// Scalar values.
    Scalars(Vec<f32>),
    /// RGBA colours.
    Colors(Vec<[f32; 4]>),
    /// 3D vectors.
    Vectors(Vec<[f32; 3]>),
}

/// Named attribute data on a mesh-like topology.
#[derive(Clone, Debug)]
pub struct AttributeData {
    /// Topological domain the values are defined on.
    pub domain: AttributeDomain,
    /// Attribute payload.
    pub values: AttributeValues,
}

impl AttributeData {
    /// Construct scalar attribute data.
    pub fn scalars(domain: AttributeDomain, values: Vec<f32>) -> Self {
        Self {
            domain,
            values: AttributeValues::Scalars(values),
        }
    }

    /// Construct colour attribute data.
    pub fn colors(domain: AttributeDomain, values: Vec<[f32; 4]>) -> Self {
        Self {
            domain,
            values: AttributeValues::Colors(values),
        }
    }

    /// Construct vector attribute data.
    pub fn vectors(domain: AttributeDomain, values: Vec<[f32; 3]>) -> Self {
        Self {
            domain,
            values: AttributeValues::Vectors(values),
        }
    }
}

/// Per-vertex joint influence data for CPU skinning workflows.
#[derive(Clone, Debug)]
pub struct SkinWeights {
    /// Joint indices for each vertex: 4 per vertex, parallel to positions.
    pub joint_indices: Vec<[u8; 4]>,
    /// Blend weights for each vertex: 4 per vertex.
    pub joint_weights: Vec<[f32; 4]>,
}

/// One joint in a skeleton hierarchy.
#[derive(Clone, Debug)]
pub struct Joint {
    /// Display name for the joint, copied from the source file when present.
    pub name: String,
    /// Index of the parent joint within the same skeleton, or `None` for the
    /// root. Always less than the joint's own index (topological order).
    pub parent: Option<u8>,
    /// Inverse of the joint's world-space transform in the bind pose.
    pub inverse_bind: glam::Mat4,
}

/// A joint hierarchy with bind-pose inverse matrices, source-agnostic.
#[derive(Clone, Debug, Default)]
pub struct Skeleton {
    /// Skeleton name, when the source format provides one.
    pub name: String,
    /// Joints in topological order: each parent index is less than its own.
    pub joints: Vec<Joint>,
}

/// Which component of a joint's local transform an animation track drives.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum AnimationChannel {
    /// Translation channel (Vec3 sampler values).
    Translation,
    /// Rotation channel (Quat sampler values).
    Rotation,
    /// Scale channel (Vec3 sampler values).
    Scale,
}

/// How an animation sampler blends between adjacent keyframes.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum AnimationInterpolation {
    /// Hold the value of the lower keyframe until the next one starts.
    Step,
    /// Vec3 channels lerp; Quat channels slerp.
    Linear,
    /// Cubic-spline interpolation as defined by glTF. Not yet consumed by
    /// downstream players; preserved on import for round-trip fidelity.
    CubicSpline,
}

/// Per-keyframe values for an animation sampler. The variant must match the
/// channel of the parent track.
#[derive(Clone, Debug)]
pub enum AnimationTrackValues {
    /// Translation or scale keyframes.
    Vec3(Vec<glam::Vec3>),
    /// Rotation keyframes.
    Quat(Vec<glam::Quat>),
}

/// Keyframe times paired with values plus an interpolation mode.
#[derive(Clone, Debug)]
pub struct AnimationSampler {
    /// Interpolation mode between keyframes.
    pub interpolation: AnimationInterpolation,
    /// Keyframe times in seconds, non-empty and strictly increasing.
    pub times: Vec<f32>,
    /// Keyframe values, same length as `times`. For `CubicSpline`, each
    /// keyframe carries three values (in-tangent, value, out-tangent) so the
    /// inner length is `3 * times.len()`.
    pub values: AnimationTrackValues,
}

/// One animation track: a sampler bound to one channel on one joint.
#[derive(Clone, Debug)]
pub struct AnimationTrack {
    /// Index into the target [`Skeleton::joints`].
    pub joint: usize,
    /// Which component of the joint's local transform this track drives.
    pub channel: AnimationChannel,
    /// Keyframe sampler producing values for this channel.
    pub sampler: AnimationSampler,
}

/// A collection of tracks that together animate one or more joints.
#[derive(Clone, Debug)]
pub struct AnimationClip {
    /// Clip name, when the source format provides one.
    pub name: String,
    /// Length of the clip in seconds, derived from the maximum sampler time.
    pub duration: f32,
    /// Index of the [`Skeleton`] this clip targets within the parent
    /// [`SceneData::skeletons`].
    pub skeleton_index: usize,
    /// Per-channel tracks.
    pub tracks: Vec<AnimationTrack>,
}

/// Source-agnostic surface mesh data.
#[derive(Clone, Debug, Default)]
pub struct SurfaceMesh {
    /// Vertex positions in local space.
    pub positions: Vec<[f32; 3]>,
    /// Per-vertex normals.
    pub normals: Vec<[f32; 3]>,
    /// Triangle index list.
    pub indices: Vec<u32>,
    /// Optional per-vertex UV coordinates.
    pub uvs: Option<Vec<[f32; 2]>>,
    /// Optional per-vertex tangents.
    pub tangents: Option<Vec<[f32; 4]>>,
    /// Named attributes on this mesh.
    pub attributes: HashMap<String, AttributeData>,
    /// Optional skinning weights.
    pub skin_weights: Option<SkinWeights>,
}

/// A mesh entry inside a loaded scene.
#[derive(Clone, Debug)]
pub struct SceneMesh {
    /// Mesh name.
    pub name: String,
    /// Mesh geometry and attributes.
    pub mesh: SurfaceMesh,
    /// Index into `SceneData::materials`.
    pub material_index: Option<usize>,
    /// Local transform carried through from the source format.
    pub transform: glam::Mat4,
    /// Whether the source format explicitly marked the mesh double-sided.
    pub two_sided: bool,
    /// Parent mesh index for scene hierarchy reconstruction.
    pub parent_index: Option<usize>,
    /// Human-readable names for imported vertex attributes.
    pub vertex_attribute_names: Vec<String>,
    /// Optional importer-specific tags.
    pub metadata: HashMap<String, String>,
    /// Index into `SceneData::skeletons`, if this mesh is skinned.
    pub skeleton_index: Option<usize>,
}

impl Default for SceneMesh {
    fn default() -> Self {
        Self {
            name: String::new(),
            mesh: SurfaceMesh::default(),
            material_index: None,
            transform: glam::Mat4::IDENTITY,
            two_sided: false,
            parent_index: None,
            vertex_attribute_names: Vec::new(),
            metadata: HashMap::new(),
            skeleton_index: None,
        }
    }
}

/// A generic point set with optional colours and scalar attributes.
#[derive(Clone, Debug, Default)]
pub struct PointSet {
    /// Point-set name.
    pub name: String,
    /// Point positions.
    pub positions: Vec<[f32; 3]>,
    /// Optional per-point colours.
    pub colors: Vec<[f32; 4]>,
    /// Optional primary scalar values.
    pub scalars: Vec<f32>,
    /// Named scalar attributes carried with the points.
    pub scalar_attributes: HashMap<String, Vec<f32>>,
}

/// Spherical-harmonic degree for gaussian splat colour data.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ShDegree {
    /// Degree-0 SH; three coefficients `[r, g, b]` per splat.
    Zero,
    /// Degree-1 SH.
    One,
    /// Degree-3 SH.
    Three,
}

impl ShDegree {
    /// Number of RGB coefficients per splat.
    pub fn coeff_count(self) -> usize {
        match self {
            Self::Zero => 3,
            Self::One => 12,
            Self::Three => 48,
        }
    }
}

/// Source-agnostic gaussian splat input data.
#[derive(Clone, Debug)]
pub struct GaussianSplatSet {
    /// Object-space center positions, one per splat.
    pub positions: Vec<[f32; 3]>,
    /// Scale per splat.
    pub scales: Vec<[f32; 3]>,
    /// Rotation per splat as `[x, y, z, w]`.
    pub rotations: Vec<[f32; 4]>,
    /// Opacity per splat.
    pub opacities: Vec<f32>,
    /// Packed SH coefficients.
    pub sh_coefficients: Vec<f32>,
    /// SH degree for this set.
    pub sh_degree: ShDegree,
}

impl Default for GaussianSplatSet {
    fn default() -> Self {
        Self {
            positions: Vec::new(),
            scales: Vec::new(),
            rotations: Vec::new(),
            opacities: Vec::new(),
            sh_coefficients: Vec::new(),
            sh_degree: ShDegree::Zero,
        }
    }
}

impl PointSet {
    /// Create a degree-0 gaussian splat set from points.
    pub fn to_gaussian_splats(
        &self,
        default_scale: [f32; 3],
        default_opacity: f32,
    ) -> GaussianSplatSet {
        let count = self.positions.len();
        let mut sh_coefficients = Vec::with_capacity(count * 3);
        for index in 0..count {
            let rgb = self
                .colors
                .get(index)
                .copied()
                .map(|color| [color[0], color[1], color[2]])
                .unwrap_or([1.0, 1.0, 1.0]);
            sh_coefficients.extend_from_slice(&rgb);
        }

        GaussianSplatSet {
            positions: self.positions.clone(),
            scales: vec![default_scale; count],
            rotations: vec![[0.0, 0.0, 0.0, 1.0]; count],
            opacities: vec![default_opacity; count],
            sh_coefficients,
            sh_degree: ShDegree::Zero,
        }
    }
}

/// Geometry model for a structured volume.
#[derive(Clone, Debug)]
pub enum VolumeGridGeometry {
    /// Uniform voxel spacing.
    Uniform {
        /// World-space origin of the first sample.
        origin: [f32; 3],
        /// Uniform spacing between samples on each axis.
        spacing: [f32; 3],
    },
    /// Axis-aligned grid with variable spacing along each axis.
    Rectilinear {
        /// Sample coordinates along X.
        xs: Vec<f32>,
        /// Sample coordinates along Y.
        ys: Vec<f32>,
        /// Sample coordinates along Z.
        zs: Vec<f32>,
    },
}

impl Default for VolumeGridGeometry {
    fn default() -> Self {
        Self::Uniform {
            origin: [0.0, 0.0, 0.0],
            spacing: [1.0, 1.0, 1.0],
        }
    }
}

/// Dense structured volume data and named fields.
#[derive(Clone, Debug, Default)]
pub struct StructuredVolume {
    /// Volume name or field-set label.
    pub name: String,
    /// Point dimensions `[nx, ny, nz]`.
    pub dims: [u32; 3],
    /// Geometry description for the grid.
    pub geometry: VolumeGridGeometry,
    /// Named point-centred scalar fields.
    pub point_fields: HashMap<String, Vec<f32>>,
    /// Named cell-centred scalar fields.
    pub cell_fields: HashMap<String, Vec<f32>>,
}

impl StructuredVolume {
    /// World-space axis-aligned bounds of the volume.
    pub fn bounds(&self) -> ([f32; 3], [f32; 3]) {
        match &self.geometry {
            VolumeGridGeometry::Uniform { origin, spacing } => {
                let max = [
                    origin[0] + spacing[0] * self.dims[0].saturating_sub(1) as f32,
                    origin[1] + spacing[1] * self.dims[1].saturating_sub(1) as f32,
                    origin[2] + spacing[2] * self.dims[2].saturating_sub(1) as f32,
                ];
                (*origin, max)
            }
            VolumeGridGeometry::Rectilinear { xs, ys, zs } => {
                let min = [
                    *xs.first().unwrap_or(&0.0),
                    *ys.first().unwrap_or(&0.0),
                    *zs.first().unwrap_or(&0.0),
                ];
                let max = [
                    *xs.last().unwrap_or(&0.0),
                    *ys.last().unwrap_or(&0.0),
                    *zs.last().unwrap_or(&0.0),
                ];
                (min, max)
            }
        }
    }

    /// Return scalar values for a named field, checking point fields then cell fields.
    pub fn scalar_values(&self, name: &str) -> Option<&[f32]> {
        if let Some(values) = self.point_fields.get(name) {
            return Some(values);
        }
        self.cell_fields.get(name).map(Vec::as_slice)
    }
}

/// Sparse regular grid data.
#[derive(Clone, Debug, Default)]
pub struct SparseGrid {
    /// World-space position of the `[0, 0, 0]` corner of cell `[0, 0, 0]`.
    pub origin: [f32; 3],
    /// Side length of one cubic cell in world units.
    pub cell_size: f32,
    /// Grid indices `[i, j, k]` of occupied cells.
    pub active_cells: Vec<[u32; 3]>,
    /// Named per-cell scalar fields.
    pub cell_fields: HashMap<String, Vec<f32>>,
    /// Named per-node scalar fields.
    pub node_fields: HashMap<String, Vec<f32>>,
    /// Named per-cell RGBA colours.
    pub cell_colors: HashMap<String, Vec<[f32; 4]>>,
}

/// Unstructured volumetric mesh data.
#[derive(Clone, Debug, Default)]
pub struct VolumeMesh {
    /// Vertex positions in local space.
    pub positions: Vec<[f32; 3]>,
    /// Cell connectivity; unused slots are padded with [`CELL_SENTINEL`].
    pub cells: Vec<[u32; 8]>,
    /// Named per-cell scalar fields.
    pub cell_fields: HashMap<String, Vec<f32>>,
    /// Named per-cell RGBA colours.
    pub cell_colors: HashMap<String, Vec<[f32; 4]>>,
}

/// A decoded scientific/container dataset that may expose several representations.
#[derive(Clone, Debug, Default)]
pub struct DecodedDataSet {
    /// Dataset name.
    pub name: String,
    /// Optional extracted surface mesh.
    pub surface_mesh: Option<SurfaceMesh>,
    /// Optional point-set representation.
    pub point_set: Option<PointSet>,
    /// Optional dense structured volume.
    pub volume: Option<StructuredVolume>,
    /// Optional sparse regular grid.
    pub sparse_grid: Option<Box<SparseGrid>>,
    /// Optional unstructured volume mesh.
    pub volume_mesh: Option<Box<VolumeMesh>>,
}

impl DecodedDataSet {
    /// Return the dataset as a surface mesh when available.
    pub fn as_surface_mesh(&self) -> Option<&SurfaceMesh> {
        self.surface_mesh.as_ref()
    }

    /// Return the dataset as a point set when available.
    pub fn as_point_set(&self) -> Option<&PointSet> {
        self.point_set.as_ref()
    }

    /// Return the dataset as a structured volume when available.
    pub fn as_structured_volume(&self) -> Option<&StructuredVolume> {
        self.volume.as_ref()
    }

    /// Return the dataset as a sparse grid when available.
    pub fn as_sparse_grid(&self) -> Option<&SparseGrid> {
        self.sparse_grid.as_deref()
    }

    /// Return the dataset as a volume mesh when available.
    pub fn as_volume_mesh(&self) -> Option<&VolumeMesh> {
        self.volume_mesh.as_deref()
    }
}

/// A decoded multi-object scene.
#[derive(Clone, Debug, Default)]
pub struct SceneData {
    /// Meshes in the scene.
    pub meshes: Vec<SceneMesh>,
    /// Materials referenced by meshes.
    pub materials: Vec<MaterialData>,
    /// Point sets carried by the scene.
    pub point_sets: Vec<PointSet>,
    /// Skeletons referenced by skinned meshes via `SceneMesh::skeleton_index`.
    pub skeletons: Vec<Skeleton>,
    /// Animation clips targeting the scene's skeletons.
    pub animations: Vec<AnimationClip>,
}

pub(crate) type TextureData = RasterImageData;
pub(crate) type HdrTextureData = HdrImageData;
pub(crate) type IoMaterial = MaterialData;
pub(crate) type IoMesh = SceneMesh;
pub(crate) type IoPointCloud = PointSet;
pub(crate) type IoVolumeGeometry = VolumeGridGeometry;
pub(crate) type IoVolume = StructuredVolume;
pub(crate) type IoSparseVolume = SparseGrid;
pub(crate) type IoVolumeMesh = VolumeMesh;
pub(crate) type IoDataSet = DecodedDataSet;
pub(crate) type IoScene = SceneData;