Application-owned OpenUSD file I/O above Layerstack's composition kernel and
USDA, USDC and USDZ format implementations. StageDocument loads dependencies
into one shared store, exposes its retained stage, saves dirty layers separately
from session edits, and reloads only the sources that changed, with an explicit
dirty policy.
[dependencies]
layerstack = "0.1"
layerstack_io = "0.1"Requires Rust 1.89 or later.
use layerstack::StageOptions;
use layerstack_io::{Filesystem, StageDocument};
let storage = Filesystem::new(".", [])?;
let document = StageDocument::open(storage, "scene.usda", StageOptions::default())?;
println!("Loaded {} layers", document.load_report().layers.len());
# Ok::<(), layerstack_io::IoError>(())For schema fallbacks and typed views, open into a store of your own: construct
layerstack_schemas::openusd using that store's tokens, then pass the same
store (OpenOptions::store) and its registry (StageOptions::schemas) to
StageDocument::open. Without a store, open creates a fresh one, so it
rejects a registry (IoErrorKind::ForeignSchemaRegistry): no registry
built beforehand belongs to that store's tokens.
The default std feature provides Filesystem. Use MemoryStorage to open
and save documents from bytes with or without std. With default features
disabled, no_std + alloc applications can also implement Storage for their
own identifier policy, transport and write atomicity. Recoverable format
errors require explicit ImportPolicy::AllowRecovery.
A load reports where its work went: each layer it read (LoadReport::reads,
with the bytes decoded and the prim specs made) and each composition after a
batch of reads (LoadReport::compositions). This crate has no clock; the host
supplies one (LoadOptions::clock, a Clock) to time them, and without one
every time is None.
USDA and USDC source layers can be saved in place. USDZ members are read-only;
use prepare_package to inventory and localize a dependency closure, inspect its
report, then export_package to write the candidate. Layer export writes
a copy and preserves the original source binding and dirty state. Every mutating
Layer method records its edit, so synchronization and saving see each one.
Author with StageDocument::apply(&transaction): it applies the edit and loads
the assets the edit asks for (Applied::asset_requests), such as a deferred
payload it adds.
The Rust methods save, save_layers, and save_session_layers now return
Result<SaveReport, SaveError>. Replace a manual report.failures check with
let report = document.save()?;. To recover from a partial save, inspect
error.report.saved for the writes that succeeded and error.failures for
the layer and cause of each failure. Anonymous layers are listed separately
in the report and remain dirty.
Start with cargo run -p layerstack_examples --example tutorial_stage_io for a
complete create/edit/undo/export/reload workflow, or tutorial_references for
a filesystem dependency example. Backends implement three operations:
identify, read and write. Format dispatch, store-local identity allocation,
package-relative resolution, expression-asset discovery and source tracking
stay in this crate.
Opening reads only the layers the stage's variant selections reach, as OpenUSD
does: an arc inside a variant branch its own layer does not select is deferred,
and composition asks for those its selections reach (Stage::asset_requests),
which opening loads. After an edit selects another variant,
StageDocument::apply loads what it needs; after a reload or an edit through
parts_mut, StageDocument::load_requested_assets does;
VariantArcLoading::All resolves every branch's arcs up front instead.
A host that supplies sources as they arrive, such as a browser, loops:
StageDocument::unavailable_assets lists what to fetch, the host supplies
it to its storage, and load_requested_assets reads and composes it. Each
round reaches one arc deeper, so a host that wants only the finished stage
calls read_requested_assets instead, which reads without composing (the
layers read then list what they need themselves), and loads once nothing is
unavailable: the stage composes once, as an open whose storage held every
source does.
For large USDC scenes, OpenOptions::loading takes LoadOptions with UsdcArrayLoading::Retained and an optional per-file decoder
budget. The policy also applies to dependencies, package members and reloads.
retained_values(layer_id).stats() exposes decode attempts, failures and work
remaining. Checked attribute reads preserve deferred failures; save/export
reports them as IoErrorKind::Decode with the original array_read_error().
Encoded files are still read completely. Package members, including nested
archives, share checked ranges into one immutable encoded owner. Decoder units are not memory bytes or a scene-wide memory limit.
Run cargo run -p layerstack_examples --bin lazy_io for a complete example.
For a time-specific clip read, call Stage::plan_clip_query(property, Time::at(time), max_demands)
to inspect manifest, active-interval and interpolation bound demands without I/O. StageDocument::prepare_clip_query explicitly loads
and replans under a request budget. Inspect plan.is_complete(), failures and
budget exhaustion before a checked value read; a complete plan can describe a
confirmed gap. A zero-load budget only inspects residency. Dormant clips outside
the required interval remain unread when an explicit manifest permits it. Automatic
manifests, templates and missing-value searches can require more files.
clip_asset_requests and load_asset remain available for custom scheduling. Other retained clients over
the document's store synchronize independently after publication.
A reload reads only what changed. The document records each source's
version as it reads it (Storage::version: modification time and length for
Filesystem; a digest of the bytes for storage that reports none), and
reload skips a clean layer whose source is unchanged, as
UsdStage::Reload does. A changed layer publishes only its differences,
through Transaction::transfer_content in one transaction, so the stage's
notices name what the file changed (a value info-only on its property, a
prim added or removed resynced, the pseudo-root info-only for a root layer
stack layer read again) rather than resyncing the stage. A missing asset
that now exists resolves, a search path that now finds another file reads
it, and force_reload_layers reads unchanged layers too
(SdfLayer::Reload(force)). With nothing changed a reload reads no layer
and sends no notice. A layer that cannot be read or parsed again keeps its
content and is reported in the result's asset_failures, while the others
reload, as in OpenUSD.
Use prepare_reload or prepare_reload_layers when an engine must inspect
a reload before publication. PreparedReload lists the layers it read
again, their new content, the import report, source identities and retained
decode statistics, and candidate() composes the scene it would publish,
on request. Dropping it rejects the reload; commit() publishes it without
reading a source again, preserving existing change observers. Rejection
leaves layers, dirty generations and dependency freshness unchanged,
including failed or leaked candidates; the names the layers read intern
stay in the document's interners. The document stays exclusively borrowed
until acceptance or rejection. Synchronize direct edits before preparation
if they change which source layers the stage uses.
read_asset_bytes(path, authoring_layer) reads arbitrary images, environment maps
and other bytes using the same package/member policy as layer imports. Capture
the winning source with layerstack_schemas::assets::AssetReference::read rather
than assuming the composed root authored the asset. The result contains immutable
bytes, canonical identity and package provenance; no image decoder, renderer or
new layer identity is introduced. Candidate reads use the candidate USDZ snapshot,
so keep those validated bytes for renderer/GPU publication after commit. Loose
external assets are read at call time. Explicit package[member] identifiers
support nested archives, for example scene.usdz[props.usdz[textures/base.png]].
Relative identifiers stay inside their innermost containing package. Returned
EncodedBytes views expose backing_bytes() and shares_backing(); detached()
copies a small resource when retaining its whole archive would be undesirable.
package_stats reports directory/CRC work and package_cache_stats reports
package opens, index hits, copied encoded bytes and resident archive ownership.
Run cargo run -p layerstack_examples --bin prepared_reload for a complete
reject/accept workflow with checked geometry, host budgets and packaged textures.
The Layerstack CLI compares layers and composed stages
and traces property opinions. Install the executable from the layerstack_cli crate.
Rust callers can compare authored layer bytes with layerstack_io::diff::diff_layers.
resolve_udim_tiles(pattern, authoring_layer, &mut discovery) lists the
existing tiles of a layerstack::asset::UdimPattern such as
./textures/color.<UDIM>.png, as OpenUSD's dependency discovery finds them:
tile spellings resolve relative to the authoring layer (inside its package
first) from 1001 upwards until one exists, and the other tiles of 1001 through
1100 are looked for beside it. Each UdimTileAsset carries its tile number,
authored spelling and resolved identifier, which read_asset_bytes(identifier, None) reads. Storage needs Storage::exists for tile probes;
Storage::list_siblings, which Filesystem implements, lets one directory
listing replace up to 99 of them. Package members come from the resident index
without storage work. A host-owned UdimDiscovery keeps found sets, directory
listings and packages for later calls, so a directory is listed once for all
its sets; it never refreshes, so clear it when files change. A listing reads a
whole directory, about 1 ms for 2000 files on local APFS against 0.1 ms to probe
one set's tiles, so UdimDiscovery::probing() never lists. UdimDiscoveryWork
reports every identify, probe, listing and package lookup, per call and in
total.
read_asset_bytes_bounded(asset, authoring_layer, AssetReadLimits { bytes, package_bytes }) rejects oversized resident members before returning shared views and
uses Storage::read_bounded for loose resources and nonresident archives.
The storage extension defaults to an unsupported error without invoking read;
custom transports opt into bounded reads explicitly. Filesystem bounds reads
and checks file size before allocation. Existing unbounded resource APIs retain
their behavior; use the bounded API when admitting renderer inputs.
prepare_reload_root(policy) reads the authored root and its freshly reachable
file dependencies once, preserving source IDs and session opinions. Old unused
sources and package members are not mandatory reload roots. Session-only file
dependencies are outside this explicit root-file scope; selected prepare_reload
and prepare_reload_layers remain available for other policies. Only sources
actually replaced by this candidate participate in dirty protection. Expression
asset bindings from replaced layers are rediscovered, so retained expression
dependencies refresh and participate in the same dirty protection. Drop rejects
all source/catalog/freshness changes; commit publishes the composed candidate.
These additions keep transport, composition and renderer ownership unchanged; no new dependency or architectural boundary is introduced.
prepare_package(root, "scene.usda", PackagePreparationLimits::default(), |_| PackageInclusion::Include) inventories authored dependencies across variants
and inactive list items in an isolated store. Resident layers include their unsaved
edits. The candidate rewrites copied layers and shares opaque resource bytes;
preparation and export preserve live source bindings and dirty generations.
Inspect report() for exact unresolved authoring uses and plan() for destinations.
Missing resources, unsupported resource types and unexpanded patterns prevent a
plan. A UDIM texture expands to every existing tile, each set discovered once
(udim_work() reports the storage work): the copied value keeps <UDIM> and its
file name, assets/000002/color.<UDIM>.png, beside one member per tile. A pattern
without tiles is unresolved, as in OpenUSD. Choose KeepExternal for intentional
external dependencies; concrete paths are anchored to their original sources, a
UDIM pattern to its tiles' directory, while expressions remain host controlled.
Use the lower-level localization callback for custom pattern expansion.
Set layer/asset inventory counts, cumulative opaque bytes and per-resource
transport limits explicitly. These bound inventory and resource reads; layer
format imports can follow arcs and the counts are not a scene allocation cap.
LoadOptions::package separately bounds nesting, total directory entries and
checksum work, including unused nested archives. Limits apply before admitting a
snapshot. Each resident package directory is reused for later layer/resource reads.
Filesystem writes a sibling candidate, synchronizes its contents, then replaces
the destination. Failed writes preserve the old file and clean up the candidate.
Symlink destinations retain the link and replace its resolved target. Replacement
changes inode identity; hard links retain the old inode. This is a single-file
replacement guarantee, not a multi-file transaction or directory durability promise.
Standard permissions are preserved on native platforms; macOS also preserves
extended metadata. WASI relies on host-granted filesystem rights, without file
permission bits.
Other platforms' extended access controls require a host-specific Storage.
Direct asset-valued prim assetInfo.identifier entries are identity uses rather
than required package resources. prepare_package reports them as ignored and
preserves their spelling without loading them or calling the resource inclusion
callback. Other nested assets remain dependencies, including nested dictionaries
whose keys happen to be identifier. Generic authored inventory and rewriting
retain identity uses as AssetDependencyKind::Identity; see
the identity contract and caller update.
Storage backends can override read_encoded and read_encoded_bounded to return
an existing immutable EncodedBytes owner. Their defaults transfer vectors from
read/read_bounded without copying payload bytes, so existing backends benefit
without changes. Bounds remain explicit and never fall back to an unbounded read.
Package members and retained numeric inputs keep independent shared views.
encoded_bytes_copied counts document-layer copies after transport; copies made
inside a backend remain outside that counter. Vector owners retain spare capacity,
which EncodedBytes::backing_bytes accounts; detached explicitly copies a small
view when releasing a large owner is preferable.
Storage::open_ranges(identifier) optionally returns a fixed logical byte source
for layerstack_usdz::range::RangePackage and read_usdz_ranges. The default
reports Unsupported without reading. Filesystem implements exact bounded
range reads through a retained open file handle; there is no full-read fallback.
Filesystem sources survive atomic replacement. Hosts must exclude external
in-place writes during a source's lifetime: length/mtime checks detect ordinary
changes but do not make the file a snapshot.
This lower-level import path verifies selected member headers and CRCs, including
reachable layer dependencies. Unselected members and enclosing nested-package
CRCs remain unverified. Inspect RangeStats for actual read and verification
work and use RangeLimits to bound it. StageDocument continues to open completely
verified package snapshots, including unused members. Range transport is an
explicit choice for hosts assembling their own import/store workflow.