# @openusd-wasm/three-loader

Three.js loader for OpenUSD `.usd`, `.usda`, `.usdc`, and `.usdz` assets.
Parsing runs through `@openusd-wasm/pxr`; this package converts the opened USD
stage into a Three.js object tree, returns extracted USD scene data, and keeps
runtime lookup state separate from Three.js `userData`.

```ts
import { USDLoader } from '@openusd-wasm/three-loader'

const loader = new USDLoader()
const model = await loader.loadAsync('/models/robot.usda')
const { scene, data, index } = model
threeScene.add(scene)

console.log(data.physics)
console.log(data.joints)
console.log(data.lights)
console.log(index.objectsByPath.get('/World/Robot'))
```

## Returned Data

`USDLoader` returns:

- `scene`: a `THREE.Group` containing mesh/group objects that mirror the USD prim hierarchy.
- `data`: extracted stage info, view prims, mesh geometry summaries,
  material/shader inputs, lights, animation data, variants, and USD physics
  info.
- `index`: runtime lookup maps such as `objectsByPath`, `meshesByPath`,
  `materialsByPath`, `lightsByPath`, `rigidBodiesByPath`, `jointsByBodyPath`,
  and `bonesBySkeletonPath`.
- `resources`: object URL maps for images discovered in USDZ packages or auto-resolved next to the root layer.
- `sourcePath` and `rootLayerIdentifier`: useful for diagnostics and texture resolution.

Generated prim objects only store a lightweight USD bridge in `userData`:

```ts
object.userData.usd
// { kind: 'prim', path: '/World/Mesh', typeName: 'Mesh' }
```

Use `model.index` to look up heavy USD data or Three.js runtime objects. The
loader does not mirror scene data, physics summaries, texture URL maps, or
object indexes into `Object3D.userData`.

Skeleton bones and animation clips use the same lightweight bridge:

```ts
bone.userData.usd
// { kind: 'skelJoint', skeletonPath: '/World/Skeleton', jointPath: 'root', jointIndex: 0 }

clip.userData.usd
// { kind: 'animation', id: 'skel:/World/Skeleton/Animation', source: 'skel', variant: null }
```

Animation variants retain their skeletal samples in
`data.animations[].skelAnimations[].animation`. Each clip uses the samples
captured for its own variant, including when multiple variants share the same
USD animation path or the initial selection has no skeletal animation.
This data also survives serialization for worker-based scene building.

Material animation is included in the same `scene.animations` clips. The
loader currently maps animated surface-shader emissive color and emissive
intensity inputs to `THREE.MeshStandardMaterial` or
`THREE.MeshPhysicalMaterial`, preserving OpenUSD linear or held interpolation.
An animated USD material updates every generated Three.js material instance
bound to that material.

```ts
const mixer = new THREE.AnimationMixer(model.scene)
mixer.clipAction(model.scene.animations[0]).play()
```

Other animated shader inputs remain available in
`data.animations[].materialTracks`, but are not yet converted into Three.js
material properties. Animated texture assets and shader-network topology are
not evaluated as keyframe tracks.

Call `model.dispose()` or `disposeUSDLoadedModel(model)` when a loaded model is
removed. This releases generated Three.js resources, preserved USD stages, and
object URLs created for auto-resolved or USDZ textures stored in
`model.resources`.

## Geometry Support

Mesh topology and OpenUSD analytic Gprims are triangulated by the native Wasm
bindings before Three.js objects are created. Supported analytic schemas are
`Cube`, `Sphere`, `Cylinder`, `Cylinder_1`, `Cone`, `Capsule`, `Capsule_1`, and
`Plane`. Authored size/radius/height/axis values, display color, display
opacity, double-sided state, orientation, and local transforms are preserved.

Mesh face material assignments in `UsdGeomSubset` (`familyName = "materialBind"`)
are preserved as `element.materialGroups` and Three.js geometry groups with a
material array. Unassigned faces retain the mesh's resolved material; each
subset resolves its own material through OpenUSD, including binding strength
and inheritance. Subset materials keep their UV primvar/transform, opacity,
and supported material animation. Subsets in other families do not override
face materials. Group `start` and `count` refer to triangulated vertices.

## Lighting

The loader reads light values through the native `UsdLux` Wasm bindings and
supports the six core OpenUSD light schemas:

- `DistantLight` becomes `THREE.DirectionalLight`.
- `RectLight` becomes `THREE.RectAreaLight`.
- `DiskLight` becomes an equal-area `THREE.RectAreaLight`.
- `SphereLight` and `CylinderLight` use energy-preserving point-light
  approximations.
- Lights with `ShapingAPI` cone controls up to 90 degrees become
  `THREE.SpotLight` when the target Three.js light has no equivalent shaping
  support. Wider cones retain the source point/area-light approximation
  because a single Three.js spot light cannot represent them.
- `DomeLight` becomes a uniform `THREE.AmbientLight` approximation.

Intensity includes authored exposure and OpenUSD normalization. Color
temperature is evaluated by OpenUSD's native
`UsdLuxBlackbodyTemperatureAsRgb()` implementation. Local transforms and the
USD `-Z` emission direction are preserved.

Set `loadLights: false` to extract `data.lights` without creating Three.js
lights. Set `castShadows: true` to opt into shadows for supported Three.js
lights; an authored `ShadowAPI` disable still takes precedence.

```ts
const loader = new USDLoader({
  loadLights: true,
  castShadows: true,
})
```

Three.js has no exact representation for cylindrical/spherical area lights,
separate USD diffuse/specular multipliers, shaping focus/IES profiles,
shadow color/distance/falloff, textured area lights, or a group-scoped
textured dome environment. These authored values and texture paths remain
available in `data.lights` and `index.lightsByPath`; only cone angle/softness
and shadow enable have direct Three.js mappings. `RectAreaLight` also follows
Three.js's limitation of not casting shadows.

## Lower-Level APIs

Use `parseDataAsync()` when an application needs the OpenUSD scene facts before
creating Three.js objects:

```ts
const parsed = await loader.parseDataAsync(file, { sourcePath: 'robot.usda' })
console.log(parsed.data.stage)
console.log(parsed.data.materials)
```

Use `extractUSDSceneData()` when you already opened a `Usd.Stage` through
`@openusd-wasm/pxr`, and `buildUSDScene()` when you want to convert extracted
data into Three.js manually:

```ts
import { buildUSDScene, extractUSDSceneData } from '@openusd-wasm/three-loader'

const data = extractUSDSceneData(pxr, stage, { sourcePath: 'robot.usda' })
const { scene, index } = buildUSDScene(data, { loadTextures: false })
```

## USDZ

For USDZ packages, OpenUSD can often open the package path directly. If the
package requires an explicit root layer, pass it when constructing or parsing:

```ts
const loader = new USDLoader({
  pxr,
  usdzLayer: 'robot.usda',
})
```

The loader will open `file.usdz[robot.usda]` before falling back to `file.usdz`.

## References

For URL-based loads, the loader resolves same-origin relative USD references
automatically before opening the stage. It scans the entry asset for referenced
USD, image, and material paths, fetches those files recursively, and mirrors
them into the same virtual filesystem directory that OpenUSD opens from.

This handles common exported asset layouts where files reference extensionless
assets like `./resource/material` while the server stores `material.usd`.
When the entry layer references a known asset root, such as `resource/` or
`textures/`, sibling references are also searched under that root. Use
`assetSearchRoots` to configure additional pipeline-specific root folders,
pass `files` to `parseAsync` for explicit virtual filesystem entries, or set
`autoResolveAssets: false` to disable this behavior.

When generating USDA files that reference assets written next to the layer, use
`toLayerRelativeAssetPath` before authoring the reference. OpenUSD treats
`@assets/model.usdz@` as a search-path asset, while `@./assets/model.usdz@`
is anchored to the current layer directory and packages without transient
`0/model.usdz` remap warnings.

```ts
import { toLayerRelativeAssetPath } from '@openusd-wasm/utils'

refs.AddReference(toLayerRelativeAssetPath('assets/gearbox.usdz'), '')
```

## Textures

USD asset paths do not always map directly to browser URLs. The loader creates
object URLs for image files it auto-resolves and for image entries inside stored
USDZ packages. Pass `textureResolver` to override or extend that mapping for
custom asset systems.

`UsdPreviewSurface` transparency follows the authored opacity semantics:

- Scalar opacity below `1` in the default `transparent` mode maps to physical
  transmission while keeping the Three.js material opacity at `1`.
- `opacityMode = "presence"` uses alpha blending and disables depth writes.
- A positive `opacityThreshold` uses alpha testing and keeps surviving pixels
  in the opaque render queue.

Texture-driven opacity without a positive threshold continues to use alpha
blending because Three.js transmission maps do not provide the channel
inversion required by USD opacity textures.

```ts
const loader = new USDLoader({
  pxr,
  textureResolver(asset, context) {
    if (asset.path) return new URL(asset.path, context.sourcePath).href
    return null
  },
})
```
