fbxcel 0.9.0

Excellent FBX library
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
620
621
622
623
624
625
626
627
628
//! FBX data tree for v7.4 or later.

use std::fmt;

use indextree::Arena;
use string_interner::{DefaultBackend, StringInterner};

use crate::low::v7400::AttributeValue;

use self::node::{NodeData, NodeNameSym};
pub use self::{
    error::LoadError,
    loader::Loader,
    node::{
        handle::{Children, ChildrenByName, NodeHandle},
        NodeId,
    },
};

mod macros;

mod error;
mod loader;
mod node;

/// FBX data tree.
///
/// # Tree manipulation methods
///
/// You can use the methods below to access and/or modify the tree.
///
/// * Access
///     + [`root`][`Self::root`]
/// * Create nodes / modify tree
///     + [`create_node`][`Self::create_node`]
///     + [`append_new`][`Self::append_new`]
///     + [`prepend_new`][`Self::prepend_new`]
///     + [`insert_new_after`][`Self::insert_new_after`]
///     + [`insert_new_before`][`Self::insert_new_before`]
///     + [`append`][`Self::append`]
///     + [`prepend`][`Self::prepend`]
///     + [`insert_after`][`Self::insert_after`]
///     + [`insert_before`][`Self::insert_before`]
///     + [`detach`][`Self::detach`]
/// * Modify node
///     + [`append_attribute`][`Self::append_attribute`]
///     + [`get_attribute_mut`][`Self::get_attribute_mut`]
///     + [`take_attributes_vec`][`Self::take_attributes_vec`]
///     + [`set_attributes_vec`][`Self::set_attributes_vec`]
#[derive(Debug, Clone, PartialEq)]
pub struct Tree {
    /// Tree data.
    arena: Arena<NodeData>,
    /// Node name interner.
    node_names: StringInterner<DefaultBackend<NodeNameSym>>,
    /// (Implicit) root node ID.
    root_id: NodeId,
}

impl Tree {
    /// Returns the root node.
    #[inline]
    #[must_use]
    pub fn root(&self) -> NodeHandle<'_> {
        NodeHandle::new(self, self.root_id)
    }

    /// Creates a new `Tree`.
    #[inline]
    #[must_use]
    fn new(
        arena: Arena<NodeData>,
        node_names: StringInterner<DefaultBackend<NodeNameSym>>,
        root_id: NodeId,
    ) -> Self {
        Self {
            arena,
            node_names,
            root_id,
        }
    }

    /// Returns internally managed node data.
    ///
    /// # Panics
    ///
    /// Panics if a node with the given node ID does not exist in the tree.
    #[must_use]
    pub(crate) fn node(&self, node_id: NodeId) -> &indextree::Node<NodeData> {
        self.arena.get(node_id.raw()).unwrap_or_else(|| {
            panic!(
                "The given node ID is not used in the tree: node_id={:?}",
                node_id
            )
        })
    }

    /// Returns the string corresponding to the node name symbol.
    ///
    /// # Panics
    ///
    /// Panics if the given symbol is not used in the tree.
    #[must_use]
    pub(crate) fn resolve_node_name(&self, sym: NodeNameSym) -> &str {
        self.node_names
            .resolve(sym)
            .unwrap_or_else(|| panic!("Unresolvable node name symbol: {:?}", sym))
    }

    /// Returns node name symbol if available.
    #[must_use]
    pub(crate) fn node_name_sym(&self, name: &str) -> Option<NodeNameSym> {
        self.node_names.get(name)
    }

    /// Checks whether or not the given node ID is used in the tree.
    #[must_use]
    pub(crate) fn contains_node(&self, node_id: NodeId) -> bool {
        self.arena.get(node_id.raw()).is_some()
    }

    /// Creates an orphan node in the arena.
    ///
    /// The created node can be inserted nearby some other nodes (in the same
    /// arena) later.
    pub fn create_node(&mut self, name: &str) -> NodeId {
        let name_sym = self.node_names.get_or_intern(name);
        let new_node = self.arena.new_node(NodeData::new(name_sym, Vec::new()));

        NodeId::new(new_node)
    }

    /// Detaches the node and appends it to the given parent node.
    ///
    /// # Panics
    ///
    /// Panics if:
    ///
    /// * any of the given node IDs are not used in the tree,
    /// * the `new_last_child` is `parent`, or
    /// * the `new_last_child` is an ancestor of `parent`.
    pub fn append(&mut self, new_last_child: NodeId, parent: NodeId) {
        parent.raw().append(new_last_child.raw(), &mut self.arena);
    }

    /// Detaches the node and prepends it to the given parent node.
    ///
    /// # Panics
    ///
    /// Panics if:
    ///
    /// * any of the given node IDs are not used in the tree,
    /// * the `new_first_child` is `parent`, or
    /// * the `new_first_child` is an ancestor of `parent`.
    pub fn prepend(&mut self, new_first_child: NodeId, parent: NodeId) {
        parent.raw().prepend(new_first_child.raw(), &mut self.arena);
    }

    /// Detaches the node and inserts it after the given base node.
    ///
    /// # Panics
    ///
    /// Panics if:
    ///
    /// * any of the given node IDs are not used in the tree,
    /// * the `new_next_sibling` is `prev_sibling`.
    pub fn insert_after(&mut self, new_next_sibling: NodeId, prev_sibling: NodeId) {
        prev_sibling
            .raw()
            .insert_after(new_next_sibling.raw(), &mut self.arena);
    }

    /// Detaches the node and inserts it after the given base node.
    ///
    /// # Panics
    ///
    /// Panics if:
    ///
    /// * any of the given node IDs are not used in the tree,
    /// * the `new_prev_sibling` is `next_sibling`.
    pub fn insert_before(&mut self, new_prev_sibling: NodeId, next_sibling: NodeId) {
        next_sibling
            .raw()
            .insert_after(new_prev_sibling.raw(), &mut self.arena);
    }

    /// Creates a new node and appends to the given parent node.
    ///
    /// # Panics
    ///
    /// Panics if the given node ID is not used in the tree.
    pub fn append_new(&mut self, parent: NodeId, name: &str) -> NodeId {
        let name_sym = self.node_names.get_or_intern(name);
        let new_child = self.arena.new_node(NodeData::new(name_sym, Vec::new()));
        parent.raw().append(new_child, &mut self.arena);

        NodeId::new(new_child)
    }

    /// Creates a new node and prepends to the given parent node.
    ///
    /// # Panics
    ///
    /// Panics if the given node ID is not used in the tree.
    pub fn prepend_new(&mut self, parent: NodeId, name: &str) -> NodeId {
        let name_sym = self.node_names.get_or_intern(name);
        let new_child = self.arena.new_node(NodeData::new(name_sym, Vec::new()));
        parent.raw().prepend(new_child, &mut self.arena);

        NodeId::new(new_child)
    }

    /// Creates a new node and inserts after the given sibling node.
    ///
    /// # Panics
    ///
    /// Panics if the given node ID is invalid (i.e. not used or root node).
    pub fn insert_new_after(&mut self, sibling: NodeId, name: &str) -> NodeId {
        assert_ne!(sibling, self.root_id, "Root node should have no siblings");
        let name_sym = self.node_names.get_or_intern(name);
        let new_child = self.arena.new_node(NodeData::new(name_sym, Vec::new()));
        sibling.raw().insert_after(new_child, &mut self.arena);

        NodeId::new(new_child)
    }

    /// Creates a new node and inserts before the given sibling node.
    ///
    /// # Panics
    ///
    /// Panics if the given node ID is invalid (i.e. not used or root node).
    pub fn insert_new_before(&mut self, sibling: NodeId, name: &str) -> NodeId {
        assert_ne!(sibling, self.root_id, "Root node should have no siblings");
        let name_sym = self.node_names.get_or_intern(name);
        let new_child = self.arena.new_node(NodeData::new(name_sym, Vec::new()));
        sibling.raw().insert_before(new_child, &mut self.arena);

        NodeId::new(new_child)
    }

    /// Detaches the subtree from the tree.
    ///
    /// If the subtree is the root node, does nothing.
    ///
    /// The detached node and its descendants are kept in the arena, so they can
    /// be inserted nearby some other nodes (in the same arena) later.
    pub fn detach(&mut self, subtree_root: NodeId) {
        subtree_root.raw().detach(&mut self.arena);
    }

    /// Creates a new node and inserts before the given sibling node.
    ///
    /// # Panics
    ///
    /// Panics if the given node ID is invalid (i.e. not used or root node).
    pub fn append_attribute(&mut self, node_id: NodeId, v: impl Into<AttributeValue>) {
        self.append_attribute_impl(node_id, v.into())
    }

    /// Internal implementation of `append_attribute`.
    ///
    /// # Panics
    ///
    /// Panics if the given node ID is invalid (i.e. not used or root node).
    fn append_attribute_impl(&mut self, node_id: NodeId, v: AttributeValue) {
        assert_ne!(node_id, self.root_id, "Root node should have no attributes");
        let node = self.arena.get_mut(node_id.raw()).expect("Invalid node ID");
        node.get_mut().append_attribute(v)
    }

    /// Returns a mutable reference to the node attribute at the given index.
    ///
    /// # Panics
    ///
    /// Panics if the given node ID is invalid (i.e. not used or root node).
    #[must_use]
    pub fn get_attribute_mut(&mut self, node_id: NodeId, i: usize) -> Option<&mut AttributeValue> {
        let node = self.arena.get_mut(node_id.raw()).expect("Invalid node ID");
        node.get_mut().get_attribute_mut(i)
    }

    /// Takes all attributes as a `Vec`.
    ///
    /// After calling this, the node will have no attributes (until other values are set).
    ///
    /// # Panics
    ///
    /// Panics if the given node ID is invalid (i.e. not used or root node).
    pub fn take_attributes_vec(&mut self, node_id: NodeId) -> Vec<AttributeValue> {
        let node = self.arena.get_mut(node_id.raw()).expect("Invalid node ID");
        node.get_mut().replace_attributes(Default::default())
    }

    /// Sets the given `Vec` of attribute values as the node attributes.
    ///
    /// After calling this, the node will have only the given attributes.
    ///
    /// # Panics
    ///
    /// Panics if the given node ID is invalid (i.e. not used or root node).
    pub fn set_attributes_vec(&mut self, node_id: NodeId, new: Vec<AttributeValue>) {
        let node = self.arena.get_mut(node_id.raw()).expect("Invalid node ID");
        // Ignore the returned value.
        node.get_mut().replace_attributes(new);
    }

    /// Compares trees strictly.
    ///
    /// Returns `true` if the two trees are same.
    ///
    /// Note that `f32` and `f64` values are compared bitwise.
    ///
    /// Note that this method compares tree data, not internal states of the
    /// objects.
    #[inline]
    #[must_use]
    pub fn strict_eq(&self, other: &Self) -> bool {
        self.root().strict_eq(&other.root())
    }

    /// Pretty-print the tree for debugging purpose.
    ///
    /// Be careful, this output format may change in future.
    #[inline]
    #[must_use]
    pub fn debug_tree(&self) -> impl fmt::Debug + '_ {
        DebugTree { tree: self }
    }
}

impl Default for Tree {
    fn default() -> Self {
        let mut arena = Arena::new();
        let mut node_names = StringInterner::new();
        let root_id =
            NodeId::new(arena.new_node(NodeData::new(node_names.get_or_intern(""), Vec::new())));

        Self {
            arena,
            node_names,
            root_id,
        }
    }
}

/// A simple wrapper for pretty-printing tree.
struct DebugTree<'a> {
    /// Tree.
    tree: &'a Tree,
}

impl fmt::Debug for DebugTree<'_> {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let v = DebugNodeHandle {
            node: self.tree.root(),
        };
        v.fmt(f)
    }
}

/// A simple wrapper for pretty-printing node.
struct DebugNodeHandle<'a> {
    /// Node.
    node: NodeHandle<'a>,
}

impl fmt::Debug for DebugNodeHandle<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Node")
            .field("name", &self.node.name())
            .field("attributes", &self.node.attributes())
            .field("children", &DebugNodeHandleChildren { node: self.node })
            .finish()
    }
}

/// A simple wrapper for pretty-printing children.
struct DebugNodeHandleChildren<'a> {
    /// Parent node.
    node: NodeHandle<'a>,
}

impl fmt::Debug for DebugNodeHandleChildren<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_list()
            .entries(
                self.node
                    .children()
                    .map(|child| DebugNodeHandle { node: child }),
            )
            .finish()
    }
}

/// Event of depth-first traversal.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum DepthFirstTraversed {
    /// Opening of a node.
    Open(NodeId),
    /// Closing of a node.
    Close(NodeId),
}

impl DepthFirstTraversed {
    /// Returns the node ID.
    #[inline]
    #[must_use]
    pub fn node_id(self) -> NodeId {
        match self {
            Self::Open(id) => id,
            Self::Close(id) => id,
        }
    }

    /// Returns true if the event is node open.
    #[inline]
    #[must_use]
    pub fn is_open(self) -> bool {
        matches!(self, Self::Open(_))
    }

    /// Returns true if the event is node close.
    #[inline]
    #[must_use]
    pub fn is_close(self) -> bool {
        matches!(self, Self::Close(_))
    }

    /// Returns the opened node ID.
    #[inline]
    #[must_use]
    pub fn node_id_open(self) -> Option<NodeId> {
        match self {
            Self::Open(id) => Some(id),
            Self::Close(_) => None,
        }
    }

    /// Returns the closed node ID.
    #[inline]
    #[must_use]
    pub fn node_id_close(self) -> Option<NodeId> {
        match self {
            Self::Open(_) => None,
            Self::Close(id) => Some(id),
        }
    }

    /// Returns next (forward) event.
    ///
    /// Returns `None` for `Close(root_id)`.
    #[must_use]
    pub fn next(self, tree: &Tree) -> Option<Self> {
        let next = match self {
            Self::Open(current) => {
                // Dive into the first child if available, or otherwise leave the node.
                match current.to_handle(tree).first_child() {
                    Some(child) => Self::Open(child.node_id()),
                    None => Self::Close(current),
                }
            }
            Self::Close(current) => {
                // Dive into the next sibling if available, or leave the parent.
                let node = current.to_handle(tree);
                match node.next_sibling() {
                    Some(next_sib) => Self::Open(next_sib.node_id()),
                    None => Self::Close(node.parent()?.node_id()),
                }
            }
        };
        Some(next)
    }

    /// Returns previous (backward next) event.
    ///
    /// Note that this backward traversal returns `Clone` first, and `Open`
    /// later for every node.
    ///
    /// Returns `None` for `Open(root_id)`.
    #[must_use]
    pub fn prev(self, tree: &Tree) -> Option<Self> {
        let prev = match self {
            Self::Close(current) => {
                // Dive into the last child if available, or otherwise leave the node.
                match current.to_handle(tree).last_child() {
                    Some(child) => Self::Close(child.node_id()),
                    None => Self::Open(current),
                }
            }
            Self::Open(current) => {
                // Dive into the previous sibling if available, or leave the parent.
                let node = current.to_handle(tree);
                match node.previous_sibling() {
                    Some(prev_sib) => Self::Close(prev_sib.node_id()),
                    None => Self::Open(node.parent()?.node_id()),
                }
            }
        };
        Some(prev)
    }
}

/// A type to traverse a node and its descendants in depth-first order.
///
/// This type has two cursors, forward cursor and backward cursor.
/// In the initial state, forward cursor points to the opening of the root node,
/// and the backward cursor points to the ending of the root node.
///
/// Forward cursor advances forward, and backward cursor advances backward.
/// `next_forward` and `next_backward` methods returns the node ID the
/// corresponding cursor points to, and advances the cursor.
///
/// When the forward cursor goes after the backward cursor, then all events are
/// considered emitted.
#[derive(Debug, Clone, Copy)]
pub struct DepthFirstTraverseSubtree {
    /// Next (forward and backward) events to return.
    cursors: Option<(DepthFirstTraversed, DepthFirstTraversed)>,
}

impl DepthFirstTraverseSubtree {
    /// Creates a new object.
    #[inline]
    #[must_use]
    fn with_root_id(root: NodeId) -> Self {
        Self {
            cursors: Some((
                DepthFirstTraversed::Open(root),
                DepthFirstTraversed::Close(root),
            )),
        }
    }

    /// Returns the forward next traversal event and advances the forward cursor.
    #[inline]
    pub fn next_forward(&mut self, tree: &Tree) -> Option<DepthFirstTraversed> {
        let (forward, backward) = self.cursors?;
        if forward == backward {
            self.cursors = None;
        } else {
            let next_of_next = forward
                .next(tree)
                .expect("`forward` should point before `backward`");
            self.cursors = Some((next_of_next, backward));
        }
        Some(forward)
    }

    /// Returns the backward next traversal event and advances the backward cursor.
    #[inline]
    pub fn next_backward(&mut self, tree: &Tree) -> Option<DepthFirstTraversed> {
        let (forward, backward) = self.cursors?;
        if forward == backward {
            self.cursors = None;
        } else {
            let next_of_next = backward
                .prev(tree)
                .expect("`forward` should point before `backward`");
            self.cursors = Some((forward, next_of_next));
        }
        Some(backward)
    }

    /// Returns the forward next traversal event without advancing the cursor.
    #[inline]
    #[must_use]
    pub fn peek_forward(&self) -> Option<DepthFirstTraversed> {
        self.cursors.map(|(forward, _backward)| forward)
    }

    /// Returns the backward next traversal event without advancing the cursor.
    #[inline]
    #[must_use]
    pub fn peek_backward(&self) -> Option<DepthFirstTraversed> {
        self.cursors.map(|(_forward, backward)| backward)
    }

    /// Returns the forward next `Open` traversal event and advances the forward cursor.
    ///
    /// This makes it easy to forward-traverse the subtree in preorder.
    pub fn next_open_forward(&mut self, tree: &Tree) -> Option<NodeId> {
        loop {
            let next = self.next_forward(tree)?;
            if let DepthFirstTraversed::Open(id) = next {
                return Some(id);
            }
        }
    }

    /// Returns the forward next `Close` traversal event and advances the forward cursor.
    ///
    /// This makes it easy to forward-traverse the subtree in postorder.
    pub fn next_close_forward(&mut self, tree: &Tree) -> Option<NodeId> {
        loop {
            let next = self.next_forward(tree)?;
            if let DepthFirstTraversed::Close(id) = next {
                return Some(id);
            }
        }
    }

    /// Returns the backward next `Open` traversal event and advances the backward cursor.
    ///
    /// This makes it easy to backward-traverse the subtree in postorder.
    #[must_use]
    pub fn next_open_backward(&mut self, tree: &Tree) -> Option<NodeId> {
        loop {
            let next = self.next_backward(tree)?;
            if let DepthFirstTraversed::Open(id) = next {
                return Some(id);
            }
        }
    }

    /// Returns the backward next `Close` traversal event and advances the backward cursor.
    ///
    /// This makes it easy to backward-traverse the subtree in preorder.
    #[must_use]
    pub fn next_close_backward(&mut self, tree: &Tree) -> Option<NodeId> {
        loop {
            let next = self.next_backward(tree)?;
            if let DepthFirstTraversed::Close(id) = next {
                return Some(id);
            }
        }
    }
}