openusd 0.4.0

Rust native USD 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
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
//! Stage-composed handles — value-type wrappers around `(stage, path)` that
//! mirror C++ `UsdPrim`, `UsdAttribute`, and `UsdRelationship`.
//!
//! Each handle is freely [`Clone`], holds no borrow on the composition
//! cache, and re-acquires state from the [`Stage`] per call. They are
//! returned by [`Stage`]'s authoring methods so callers can chain
//! composed-scene edits without dropping to the Sdf tier.
//!
//! # Fluent setters
//!
//! Setters take `self` by value and return `Self`. Chaining writes is a
//! single statement that ends with the final handle bound:
//!
//! ```no_run
//! use openusd::{sdf, usd};
//!
//! let stage = usd::Stage::builder().in_memory("anon.usda").unwrap();
//! let mesh = stage
//!     .define_prim("/World/Mesh").unwrap()
//!     .set_type_name("Mesh").unwrap()
//!     .set_kind("component").unwrap();
//! let radius = mesh
//!     .create_attribute("radius", "double").unwrap()
//!     .set(sdf::Value::Double(1.0)).unwrap();
//! # let _ = radius;
//! ```
//!
//! Each setter does its own short `borrow_mut` on the composition cache and
//! routes invalidation through [`crate::pcp::Changes`], so only the prim
//! indices observably affected by the write are dropped.

use super::{Stage, StageAuthoringError};
use crate::sdf;

/// Stage-composed prim handle. Mirrors C++ `UsdPrim`.
#[derive(Clone)]
pub struct Prim<'s> {
    stage: &'s Stage,
    path: sdf::Path,
}

impl<'s> Prim<'s> {
    pub(crate) fn new(stage: &'s Stage, path: sdf::Path) -> Self {
        Self { stage, path }
    }

    /// Composed namespace path of the prim.
    pub fn path(&self) -> &sdf::Path {
        &self.path
    }

    /// The stage this handle is anchored to.
    pub fn stage(&self) -> &'s Stage {
        self.stage
    }

    /// Set the prim's `typeName` field on the edit target's layer.
    pub fn set_type_name(self, name: impl Into<String>) -> Result<Self, StageAuthoringError> {
        let name = name.into();
        self.edit(&[sdf::FieldKey::TypeName], |spec| spec.set_type_name(name))
    }

    /// Set the prim's `active` flag.
    pub fn set_active(self, active: bool) -> Result<Self, StageAuthoringError> {
        self.edit(&[sdf::FieldKey::Active], |spec| spec.set_active(active))
    }

    /// Set the prim's `kind` metadata.
    pub fn set_kind(self, kind: impl Into<String>) -> Result<Self, StageAuthoringError> {
        let kind = kind.into();
        self.edit(&[sdf::FieldKey::Kind], |spec| spec.set_kind(kind))
    }

    /// Set the prim's `hidden` flag.
    pub fn set_hidden(self, hidden: bool) -> Result<Self, StageAuthoringError> {
        self.edit(&[sdf::FieldKey::Hidden], |spec| spec.set_hidden(hidden))
    }

    /// Set the prim's `instanceable` flag.
    pub fn set_instanceable(self, instanceable: bool) -> Result<Self, StageAuthoringError> {
        self.edit(&[sdf::FieldKey::Instanceable], |spec| {
            spec.set_instanceable(instanceable)
        })
    }

    /// Add an applied API schema name to this prim's `apiSchemas` metadata.
    ///
    /// This is the registry-free authoring operation behind C++
    /// `UsdPrim::AddAppliedSchema`: it edits the current edit target's
    /// `apiSchemas` list op in place rather than replacing existing list-op
    /// opinions. It does not validate that `name` is a registered API schema;
    /// schema-registry-backed `ApplyAPI` behavior is still future work.
    ///
    /// The prim spec must already exist on the active edit target — chain
    /// after [`Stage::define_prim`] or [`Stage::override_prim`]; otherwise
    /// the call returns [`sdf::AuthoringError::InvalidPath`].
    ///
    /// [`Stage::define_prim`]: crate::usd::Stage::define_prim
    /// [`Stage::override_prim`]: crate::usd::Stage::override_prim
    pub fn add_applied_schema(self, name: impl Into<String>) -> Result<Self, StageAuthoringError> {
        let path = self.path.clone();
        let name = name.into();
        self.stage.with_target_layer(|layer| {
            let data = layer.writable_data_mut()?;
            match data.spec_mut(&path).and_then(|s| s.as_prim_mut()) {
                Some(mut spec) => {
                    spec.add_applied_schema(name)?;
                    let mut cl = sdf::ChangeList::new();
                    cl.entry_mut(&path)
                        .info_changed
                        .insert(sdf::FieldKey::ApiSchemas.as_str());
                    Ok(cl)
                }
                None => Err(sdf::AuthoringError::InvalidPath {
                    path: path.clone(),
                    reason: "no prim spec at path on the edit target layer",
                }),
            }
        })?;
        Ok(self)
    }

    /// Author an attribute spec named `name` under this prim. Mirrors C++
    /// `UsdPrim::CreateAttribute`. Defaults `variability = Varying`,
    /// `custom = true` — override via the returned [`Attribute`] handle's
    /// fluent setters.
    pub fn create_attribute(
        &self,
        name: &str,
        type_name: impl Into<String>,
    ) -> Result<Attribute<'s>, StageAuthoringError> {
        let attr_path = self.path.append_property(name).map_err(|_| {
            // Synthesize the would-be path so the error surfaces the
            // offending name rather than just the parent prim.
            StageAuthoringError::Layer(sdf::AuthoringError::InvalidPath {
                path: sdf::Path::from(format!("{}.{}", self.path, name).as_str()),
                reason: "attribute name is not a valid property name",
            })
        })?;
        self.stage.create_attribute(attr_path, type_name)
    }

    /// Author a relationship spec named `name` under this prim. Mirrors C++
    /// `UsdPrim::CreateRelationship`.
    pub fn create_relationship(&self, name: &str) -> Result<Relationship<'s>, StageAuthoringError> {
        let rel_path = self.path.append_property(name).map_err(|_| {
            // Synthesize the would-be path so the error surfaces the
            // offending name rather than just the parent prim.
            StageAuthoringError::Layer(sdf::AuthoringError::InvalidPath {
                path: sdf::Path::from(format!("{}.{}", self.path, name).as_str()),
                reason: "relationship name is not a valid property name",
            })
        })?;
        self.stage.create_relationship(rel_path)
    }

    /// Author a relationship `name` with the given target paths and the
    /// schema-authoring convention `custom = false`. Shortcut for
    /// `create_relationship(name) + set_custom(false) + set_targets`.
    pub fn author_relationship_targets<I, P>(
        &self,
        name: &str,
        targets: I,
    ) -> Result<Relationship<'s>, StageAuthoringError>
    where
        I: IntoIterator<Item = P>,
        P: Into<sdf::Path>,
    {
        self.create_relationship(name)?
            .set_custom(false)?
            .set_targets(targets.into_iter().map(Into::into))
    }

    /// Append `value` to the `uniform token[]` attribute named `name` on this
    /// prim, preserving insertion order. Reads the composed default across
    /// layers (so weaker-layer opinions get materialised into the edit target's
    /// new value), de-duplicates, and writes back via `create_attribute`.
    ///
    /// Returns `true` when `value` was appended, `false` when it was already
    /// present (or the attribute is bound to a non-token-array variant that
    /// can't be flattened).
    ///
    /// Useful for ordered token stacks like `xformOpOrder` or `apiSchemas`.
    pub fn append_to_uniform_token_array(&self, name: &str, value: impl Into<String>) -> anyhow::Result<bool> {
        let value = value.into();
        let attr_path = self.path.append_property(name)?;
        let existing: Vec<String> = match self.stage.field::<sdf::Value>(&attr_path, sdf::FieldKey::Default)? {
            Some(sdf::Value::TokenVec(v) | sdf::Value::StringVec(v)) => v,
            Some(sdf::Value::TokenListOp(op)) => op.flatten(),
            Some(sdf::Value::StringListOp(op)) => op.flatten(),
            _ => Vec::new(),
        };
        if existing.iter().any(|t| t == &value) {
            return Ok(false);
        }
        let mut updated = existing;
        updated.push(value);
        self.stage
            .create_attribute(attr_path, "token[]")?
            .set_variability(sdf::Variability::Uniform)?
            .set_custom(false)?
            .set(sdf::Value::TokenVec(updated))?;
        Ok(true)
    }

    /// Borrow the prim spec at `self.path` on the edit target's layer, apply
    /// `f`, and return `self` for chaining. `fields` names the metadata keys
    /// the closure intends to author so the cache invalidator can classify
    /// them. Surfaces `ReadOnly` if the layer can't be mutated, or
    /// `InvalidPath` if no prim spec exists at the path.
    fn edit<F>(self, fields: &[sdf::FieldKey], f: F) -> Result<Self, StageAuthoringError>
    where
        F: FnOnce(&mut sdf::PrimSpecMut<'_>),
    {
        let path = self.path.clone();
        let info_changed: Vec<&'static str> = fields.iter().map(sdf::FieldKey::as_str).collect();
        self.stage.with_target_layer(|layer| {
            // Detect the read-only case explicitly — otherwise `prim_mut`
            // returns `None` for both "no spec" and "layer not writable"
            // and we'd mask `ReadOnly` as `InvalidPath`.
            let data = layer.writable_data_mut()?;
            match data.spec_mut(&path).and_then(|s| s.as_prim_mut()) {
                Some(mut spec) => {
                    f(&mut spec);
                    let mut cl = sdf::ChangeList::new();
                    let entry = cl.entry_mut(&path);
                    for name in &info_changed {
                        entry.info_changed.insert(name);
                    }
                    Ok(cl)
                }
                None => Err(sdf::AuthoringError::InvalidPath {
                    path: path.clone(),
                    reason: "no prim spec at path on the edit target layer",
                }),
            }
        })?;
        Ok(self)
    }
}

/// Stage-composed attribute handle. Mirrors C++ `UsdAttribute`.
///
/// Returned by [`Stage::create_attribute`] / [`Prim::create_attribute`] with
/// defaults `variability = Varying`, `custom = true`, matching C++ generic
/// property authoring. Override via the fluent setters below.
#[derive(Clone)]
pub struct Attribute<'s> {
    stage: &'s Stage,
    path: sdf::Path,
}

impl<'s> Attribute<'s> {
    pub(super) fn new(stage: &'s Stage, path: sdf::Path) -> Self {
        Self { stage, path }
    }

    /// Composed namespace path of the attribute (e.g. `/World/Mesh.points`).
    pub fn path(&self) -> &sdf::Path {
        &self.path
    }

    /// The stage this handle is anchored to.
    pub fn stage(&self) -> &'s Stage {
        self.stage
    }

    /// Handle to the owning prim.
    pub fn prim(&self) -> Prim<'s> {
        Prim::new(self.stage, self.path.prim_path())
    }

    /// Set the attribute's `variability` field. Always authors an explicit
    /// opinion so weaker layers don't bubble up through composition; use
    /// the Sdf-tier `Spec::remove` directly if you instead want to clear the
    /// local opinion entirely.
    pub fn set_variability(self, v: sdf::Variability) -> Result<Self, StageAuthoringError> {
        self.edit(&[sdf::FieldKey::Variability], |spec| {
            spec.add(sdf::FieldKey::Variability, sdf::Value::Variability(v))
        })
    }

    /// Set the attribute's `custom` flag. Always authors an explicit
    /// opinion (see [`Attribute::set_variability`] for the rationale).
    pub fn set_custom(self, custom: bool) -> Result<Self, StageAuthoringError> {
        self.edit(&[sdf::FieldKey::Custom], |spec| {
            spec.add(sdf::FieldKey::Custom, sdf::Value::Bool(custom))
        })
    }

    /// Set the default value. Mirrors C++ `UsdAttribute::Set(value)`.
    pub fn set(self, value: impl Into<sdf::Value>) -> Result<Self, StageAuthoringError> {
        let value = value.into();
        self.edit(&[sdf::FieldKey::Default], |spec| spec.set_default(value))
    }

    /// Set a value at a specific time. Mirrors C++
    /// `UsdAttribute::Set(value, time)`.
    pub fn set_at(self, time: f64, value: impl Into<sdf::Value>) -> Result<Self, StageAuthoringError> {
        let value = value.into();
        self.edit(&[sdf::FieldKey::TimeSamples], |spec| spec.set_time_sample(time, value))
    }

    /// Block opinions from weaker layers by authoring a value block on the
    /// default and every authored time sample. Mirrors C++
    /// `UsdAttribute::Block()`.
    pub fn block(self) -> Result<Self, StageAuthoringError> {
        self.edit(&[sdf::FieldKey::Default, sdf::FieldKey::TimeSamples], |spec| {
            spec.set_default(sdf::Value::ValueBlock);
            // Block every authored time sample too — otherwise `get_at` would
            // still resolve weaker opinions through the cached samples.
            if let Some(sdf::Value::TimeSamples(samples)) = spec.get_mut(sdf::FieldKey::TimeSamples.as_str()) {
                for (_, value) in samples.iter_mut() {
                    *value = sdf::Value::ValueBlock;
                }
            }
        })
    }

    /// Set the `colorSpace` token.
    pub fn set_color_space(self, color_space: impl Into<String>) -> Result<Self, StageAuthoringError> {
        let color_space = color_space.into();
        self.edit(&[sdf::FieldKey::ColorSpace], |spec| spec.set_color_space(color_space))
    }

    /// Author a generic metadata field on the attribute spec. Mirrors C++
    /// `UsdAttribute::SetMetadata(name, value)`.
    ///
    /// Used for fields the schema layers on top of the core attribute
    /// metadata (e.g. UsdSkel's `weight` on `inbetweens:NAME`, UsdGeom's
    /// `elementSize` / `interpolation` on primvars). The dedicated setters
    /// above (`set_variability`, `set_custom`, `set_color_space`) cover the
    /// common cases — reach for this one when the schema requires a custom
    /// field key not represented by [`sdf::FieldKey`].
    ///
    /// `key` is `&'static str` so the change-tracking layer can record it
    /// without copying; pass a `pub const FOO: &str = "..."` token rather than
    /// a runtime-built string.
    pub fn set_metadata(self, key: &'static str, value: impl Into<sdf::Value>) -> Result<Self, StageAuthoringError> {
        let value = value.into();
        let path = self.path.clone();
        self.stage.with_target_layer(|layer| {
            let data = layer.writable_data_mut()?;
            match data.spec_mut(&path).and_then(|s| s.as_attr_mut()) {
                Some(mut spec) => {
                    spec.add(key, value);
                    let mut cl = sdf::ChangeList::new();
                    cl.entry_mut(&path).info_changed.insert(key);
                    Ok(cl)
                }
                None => Err(sdf::AuthoringError::InvalidPath {
                    path: path.clone(),
                    reason: "no attribute spec at path on the edit target layer",
                }),
            }
        })?;
        Ok(self)
    }

    /// Composed default value, if any layer authored one.
    //
    // TODO: drop `anyhow::Result` once `Stage::field` returns a typed error.
    pub fn get(&self) -> anyhow::Result<Option<sdf::Value>> {
        self.stage.field::<sdf::Value>(&self.path, sdf::FieldKey::Default)
    }

    /// Composed value at `time`, applying the stage's interpolation type.
    /// Mirrors C++ `UsdAttribute::Get(time)`.
    //
    // TODO: drop `anyhow::Result` once `Stage::value_at` returns a typed
    // error.
    pub fn get_at(&self, time: f64) -> anyhow::Result<Option<sdf::Value>> {
        self.stage.value_at(&self.path, time)
    }

    /// Composed `timeSamples` map.
    //
    // TODO: drop `anyhow::Result` once `Stage::time_samples` returns a typed
    // error.
    pub fn time_samples(&self) -> anyhow::Result<Option<sdf::TimeSampleMap>> {
        self.stage.time_samples(&self.path)
    }

    /// Borrow the attribute spec at `self.path` on the edit target's layer,
    /// apply `f`, and return `self` for chaining. `fields` names the metadata
    /// keys the closure intends to author so the cache invalidator can
    /// classify them. See [`Prim::edit`] for the `ReadOnly` vs `InvalidPath`
    /// discrimination.
    fn edit<F>(self, fields: &[sdf::FieldKey], f: F) -> Result<Self, StageAuthoringError>
    where
        F: FnOnce(&mut sdf::AttributeSpecMut<'_>),
    {
        let path = self.path.clone();
        let info_changed: Vec<&'static str> = fields.iter().map(sdf::FieldKey::as_str).collect();
        self.stage.with_target_layer(|layer| {
            let data = layer.writable_data_mut()?;
            match data.spec_mut(&path).and_then(|s| s.as_attr_mut()) {
                Some(mut spec) => {
                    f(&mut spec);
                    let mut cl = sdf::ChangeList::new();
                    let entry = cl.entry_mut(&path);
                    for name in &info_changed {
                        entry.info_changed.insert(name);
                    }
                    Ok(cl)
                }
                None => Err(sdf::AuthoringError::InvalidPath {
                    path: path.clone(),
                    reason: "no attribute spec at path on the edit target layer",
                }),
            }
        })?;
        Ok(self)
    }
}

/// Stage-composed relationship handle. Mirrors C++ `UsdRelationship`.
///
/// Returned by [`Stage::create_relationship`] / [`Prim::create_relationship`]
/// with defaults `variability = Varying`, `custom = true`, matching C++
/// generic property authoring. Override via the fluent setters below.
#[derive(Clone)]
pub struct Relationship<'s> {
    stage: &'s Stage,
    path: sdf::Path,
}

impl<'s> Relationship<'s> {
    pub(super) fn new(stage: &'s Stage, path: sdf::Path) -> Self {
        Self { stage, path }
    }

    /// Composed namespace path of the relationship.
    pub fn path(&self) -> &sdf::Path {
        &self.path
    }

    /// The stage this handle is anchored to.
    pub fn stage(&self) -> &'s Stage {
        self.stage
    }

    /// Handle to the owning prim.
    pub fn prim(&self) -> Prim<'s> {
        Prim::new(self.stage, self.path.prim_path())
    }

    /// Set the relationship's `variability` field. Always authors an
    /// explicit opinion (see [`Attribute::set_variability`] for rationale).
    pub fn set_variability(self, v: sdf::Variability) -> Result<Self, StageAuthoringError> {
        self.edit(&[sdf::FieldKey::Variability], false, |spec| {
            spec.add(sdf::FieldKey::Variability, sdf::Value::Variability(v))
        })
    }

    /// Set the relationship's `custom` flag. Always authors an explicit
    /// opinion (see [`Attribute::set_variability`] for rationale).
    pub fn set_custom(self, custom: bool) -> Result<Self, StageAuthoringError> {
        self.edit(&[sdf::FieldKey::Custom], false, |spec| {
            spec.add(sdf::FieldKey::Custom, sdf::Value::Bool(custom))
        })
    }

    /// Append a target path. No-op if already present.
    pub fn add_target(self, target: sdf::Path) -> Result<Self, StageAuthoringError> {
        self.edit(&[sdf::FieldKey::TargetPaths], true, |spec| spec.add_target(target))
    }

    /// Replace the entire target list.
    pub fn set_targets<I: IntoIterator<Item = sdf::Path>>(self, targets: I) -> Result<Self, StageAuthoringError> {
        let targets: Vec<sdf::Path> = targets.into_iter().collect();
        self.edit(&[sdf::FieldKey::TargetPaths], true, |spec| {
            spec.set_target_paths(targets)
        })
    }

    /// Remove a target path. Returns `Ok(true)` if it was present. Takes
    /// `&self` rather than consuming — `remove_target` returns a `bool` (not
    /// `Self`), so it doesn't fit the chain pattern. Skips cache invalidation
    /// when the target wasn't authored (no mutation occurred).
    pub fn remove_target(&self, target: &sdf::Path) -> Result<bool, StageAuthoringError> {
        let path = self.path.clone();
        let target = target.clone();
        let mut removed = false;
        self.stage.with_target_layer(|layer| {
            let data = layer.writable_data_mut()?;
            match data.spec_mut(&path).and_then(|s| s.as_relationship_mut()) {
                Some(mut spec) => {
                    removed = spec.remove_target(&target);
                    let mut cl = sdf::ChangeList::new();
                    if removed {
                        let entry = cl.entry_mut(&path);
                        entry.flags |= sdf::ChangeFlags::CHANGE_RELATIONSHIP_TARGETS;
                        entry.info_changed.insert(sdf::FieldKey::TargetPaths.as_str());
                    }
                    Ok(cl)
                }
                None => Err(sdf::AuthoringError::InvalidPath {
                    path: path.clone(),
                    reason: "no relationship spec at path on the edit target layer",
                }),
            }
        })?;
        Ok(removed)
    }

    /// Borrow the relationship spec at `self.path` on the edit target's
    /// layer, apply `f`, and return `self` for chaining. `fields` names the
    /// authored metadata keys; `targets_changed` sets the target-list flag
    /// in the change list. See [`Prim::edit`] for the `ReadOnly` vs
    /// `InvalidPath` discrimination.
    //
    // The change-list entry is recorded at the relationship's property
    // path, which `pcp::Changes::did_change` currently skips (no consumer
    // for relationship-target invalidation). Flag and `info_changed`
    // opinions are still emitted here so the producer side is in place
    // when a consumer lands.
    //
    // TODO: wire the consumer. When `Cache` starts memoizing per-attribute
    // composed values or per-relationship resolved-target lists:
    //   1. Add a `classify_property_entry` branch in `pcp/change.rs`
    //      mirroring `classify_prim_entry`, gated on
    //      `path.is_property_path()`. Inspect
    //      `entry.flags & CHANGE_RELATIONSHIP_TARGETS` and the
    //      `TargetPaths` / `ConnectionPaths` keys in `info_changed`.
    //   2. Decide tier: relationship/connection target list changes
    //      are conceptually tier-3 (spec-stack refresh) — they don't
    //      reshape the prim graph but they do invalidate composed
    //      target resolution. Insert the owning prim path into
    //      `did_change_specs` (or a new `did_change_targets` set keyed
    //      by property path).
    //   3. Extend `Changes::apply` to consume the new set by either
    //      dropping the owner's resolved-target cache or refreshing it
    //      in place. The current `did_change_specs` field is already
    //      reserved for this; right now the entry is dropped on the
    //      floor (see CacheChanges docs).
    //   4. Remove the `targets_changed` parameter from `edit` and the
    //      flag emission here if the classifier ends up not needing
    //      either signal (e.g. it can infer everything from
    //      `info_changed[TargetPaths]`). Until then both stay for
    //      forward-compat.
    fn edit<F>(self, fields: &[sdf::FieldKey], targets_changed: bool, f: F) -> Result<Self, StageAuthoringError>
    where
        F: FnOnce(&mut sdf::RelationshipSpecMut<'_>),
    {
        let path = self.path.clone();
        let info_changed: Vec<&'static str> = fields.iter().map(sdf::FieldKey::as_str).collect();
        self.stage.with_target_layer(|layer| {
            let data = layer.writable_data_mut()?;
            match data.spec_mut(&path).and_then(|s| s.as_relationship_mut()) {
                Some(mut spec) => {
                    f(&mut spec);
                    let mut cl = sdf::ChangeList::new();
                    let entry = cl.entry_mut(&path);
                    if targets_changed {
                        entry.flags |= sdf::ChangeFlags::CHANGE_RELATIONSHIP_TARGETS;
                    }
                    for name in &info_changed {
                        entry.info_changed.insert(name);
                    }
                    Ok(cl)
                }
                None => Err(sdf::AuthoringError::InvalidPath {
                    path: path.clone(),
                    reason: "no relationship spec at path on the edit target layer",
                }),
            }
        })?;
        Ok(self)
    }
}

#[cfg(test)]
mod tests {
    use crate::sdf;
    use crate::usd::Stage;

    fn stage() -> anyhow::Result<Stage> {
        Stage::builder().in_memory("anon.usda")
    }

    #[test]
    fn prim_chain() -> anyhow::Result<()> {
        let stage = stage()?;
        stage
            .define_prim("/World")?
            .set_type_name("Xform")?
            .set_kind("group")?
            .set_active(true)?;
        assert_eq!(
            stage.field::<sdf::Value>("/World", sdf::FieldKey::TypeName)?,
            Some(sdf::Value::Token("Xform".into())),
        );
        assert_eq!(stage.kind("/World")?.as_deref(), Some("group"));
        Ok(())
    }

    #[test]
    fn attribute_chain() -> anyhow::Result<()> {
        let stage = stage()?;
        let radius = stage
            .define_prim("/Sphere")?
            .set_type_name("Sphere")?
            .create_attribute("radius", "double")?
            .set_variability(sdf::Variability::Uniform)?
            .set(sdf::Value::Double(1.5))?;
        assert_eq!(radius.get()?, Some(sdf::Value::Double(1.5)));
        assert_eq!(
            stage.field::<sdf::Value>(radius.path(), sdf::FieldKey::Custom)?,
            Some(sdf::Value::Bool(true)),
        );
        assert_eq!(radius.path().as_str(), "/Sphere.radius");
        assert_eq!(radius.prim().path().as_str(), "/Sphere");
        Ok(())
    }

    #[test]
    fn attribute_time_samples() -> anyhow::Result<()> {
        let stage = stage()?;
        let attr = stage
            .define_prim("/A")?
            .set_type_name("Xform")?
            .create_attribute("x", "double")?
            .set_at(0.0, sdf::Value::Double(1.0))?
            .set_at(10.0, sdf::Value::Double(3.0))?;
        // Linear interpolation default → halfway = 2.0.
        assert_eq!(attr.get_at(5.0)?, Some(sdf::Value::Double(2.0)));
        let samples = attr.time_samples()?.expect("samples");
        assert_eq!(samples.len(), 2);
        Ok(())
    }

    #[test]
    fn attribute_block() -> anyhow::Result<()> {
        let stage = stage()?;
        let attr = stage
            .define_prim("/A")?
            .set_type_name("Xform")?
            .create_attribute("x", "double")?
            .set(sdf::Value::Double(1.0))?
            .block()?;
        // ValueBlock resolves to None through Stage::field / value_at.
        assert_eq!(attr.get()?, None);
        assert_eq!(attr.get_at(0.0)?, None);
        Ok(())
    }

    /// `block()` must also replace every authored time-sample value with
    /// `ValueBlock` — otherwise the default block is silently bypassed for
    /// `get_at` queries that fall onto an authored sample.
    #[test]
    fn attribute_block_clears_time_samples() -> anyhow::Result<()> {
        let stage = stage()?;
        let attr = stage
            .define_prim("/A")?
            .set_type_name("Xform")?
            .create_attribute("x", "double")?
            .set_at(0.0, sdf::Value::Double(1.0))?
            .set_at(10.0, sdf::Value::Double(3.0))?
            .block()?;
        assert_eq!(attr.get_at(0.0)?, None);
        assert_eq!(attr.get_at(5.0)?, None);
        assert_eq!(attr.get_at(10.0)?, None);
        Ok(())
    }

    #[test]
    fn relationship_chain() -> anyhow::Result<()> {
        let stage = stage()?;
        let mesh = stage.define_prim("/World/Mesh")?.set_type_name("Mesh")?;
        stage.define_prim("/World/Material")?.set_type_name("Material")?;
        stage.define_prim("/World/Material2")?.set_type_name("Material")?;
        let binding = mesh
            .create_relationship("material:binding")?
            .set_variability(sdf::Variability::Uniform)?
            .add_target(sdf::Path::new("/World/Material")?)?
            .add_target(sdf::Path::new("/World/Material2")?)?;
        assert!(binding.remove_target(&sdf::Path::new("/World/Material2")?)?);
        assert_eq!(stage.spec_type(binding.path())?, Some(sdf::SpecType::Relationship));
        assert_eq!(
            stage.field::<sdf::Value>(binding.path(), sdf::FieldKey::Custom)?,
            Some(sdf::Value::Bool(true)),
        );
        Ok(())
    }

    #[test]
    fn add_api_schema() -> anyhow::Result<()> {
        let stage = stage()?;
        let prim = stage.define_prim("/World")?.add_applied_schema("MaterialBindingAPI")?;
        assert_eq!(stage.api_schemas(prim.path())?, vec!["MaterialBindingAPI".to_string()]);
        assert!(stage.has_api_schema(prim.path(), "MaterialBindingAPI")?);
        Ok(())
    }

    #[test]
    fn add_api_schema_merges() -> anyhow::Result<()> {
        let stage = stage()?;
        stage.define_prim("/World")?;
        stage.with_target_layer(|layer| {
            let data = layer.writable_data_mut()?;
            let spec = data
                .spec_mut(&sdf::Path::new("/World").expect("valid path"))
                .expect("prim spec");
            spec.add(
                sdf::FieldKey::ApiSchemas,
                sdf::Value::TokenListOp(sdf::TokenListOp {
                    appended_items: vec!["ExistingAPI".to_string()],
                    ..Default::default()
                }),
            );
            let mut cl = sdf::ChangeList::new();
            cl.entry_mut(&sdf::Path::new("/World").expect("valid path"))
                .info_changed
                .insert(sdf::FieldKey::ApiSchemas.as_str());
            Ok(cl)
        })?;

        stage
            .override_prim("/World")?
            .add_applied_schema("ExistingAPI")?
            .add_applied_schema("NewAPI")?;

        let local = stage.field::<sdf::Value>("/World", sdf::FieldKey::ApiSchemas)?;
        let Some(sdf::Value::TokenListOp(op)) = local else {
            panic!("expected apiSchemas TokenListOp");
        };
        assert_eq!(op.appended_items, vec!["ExistingAPI".to_string()]);
        assert_eq!(op.prepended_items, vec!["NewAPI".to_string()]);
        Ok(())
    }
}