---
url: /pawn/docs/guide/assets.md
description: Loading glTF models with Assets and the Model trait.
---

# Models (glTF)

The `Assets` plugin loads glTF files (`.gltf` and `.glb`) and draws them for
entities with a `Model` trait. Each URL is fetched once. Every entity gets
its own copy of the scene, and the copies share the file's geometries,
materials and textures. An engine installs `Assets` when an entity first
gets a `Model`; install it yourself for decoders or to preload.

```ts
import { Model, Position } from "@pawnjs/core";

engine.world.spawn(Position({ x: 2 }), Model({ url: "/models/lantern.glb" }));
```

Until the file is loaded, the entity has the `Loading` tag. Once loaded, it
gets a `Visual` with its copy of the model, and the tag goes away. Finished
loads are applied early in the `input` phase, so a frame never shows half
of a change. A model already loaded is shown on the next frame, without `Loading`. A `Visual` set by hand wins: the model does not replace it. A `Shape` or `Light` look is replaced, so a `Shape` can stand in until the model arrives.

```ts
import { Loading, Model } from "@pawnjs/core";

entity.set(Model, { url: "/models/lamp-on.glb" }); // swap; the old model stays until the new one is ready
entity.remove(Model);                              // removes the Visual the model added

for (const entity of world.query(Model, Loading)) {
  // still loading
}
```

Skinned models are copied with their skeletons, so each copy can play its
own animation.

## Animations

`Animation` plays one of the model's clips, by its name in the file. It
needs a `Model`; the `Animations` plugin, installed with the first
`Animation`, gives each entity its own three.js `AnimationMixer` and steps
it on the engine clock, so a paused or slowed clock (`clock.timeScale`)
pauses or slows the clips, on a headless engine too.

```ts
import { Animation, Model } from "@pawnjs/core";

const skater = engine.spawn(
  Model({ url: "/models/skater.glb" }),
  Animation({ clip: "Idle" }),
);

skater.set(Animation, { clip: "Jump", enableLoop: false, speed: 1.5 });
engine.events.on(skater, "animationend", ({ clip }) => {
  if (clip === "Jump") skater.set(Animation, { clip: "Idle" });
});
```

Setting another `clip` cross-fades to it: the old clip fades out as the new
one fades in, halfway after `halfLife` seconds (`0` cuts at once). A clip
with `enableLoop: false` plays once, holds its last pose and the entity gets
an `animationend` entity event. `engine.plugin(Animations).restart(entity)`
plays the current clip again from its start, such as the same trick twice,
and `time(entity)` tells how far into it the clip is. A clip the file does
not have is reported once through `onMissingClip` (by default
`console.warn`).

The loaded file lists its clips:

```ts
const names = engine.plugin(Assets).get("/models/skater.glb")?.animations.map((clip) => clip.name);
```

## Loading ahead and progress

```ts
const assets = new Assets();
engine.use(assets);

await assets.preload(["/models/pawn.glb", "/models/board.glb"], (loaded, total) => {
  bar.style.width = `${(loaded / total) * 100}%`;
});

const gltf = await assets.load("/models/pawn.glb"); // the same load, from the cache
assets.get("/models/pawn.glb"); // the loaded file, or undefined while loading
```

`assets.progress` counts the files that are loading now, as
`{ loaded, total }`. A count starts again when a file starts loading while
nothing else is. While the plugin is installed, the engine's world holds
the same count as the `AssetProgress` trait, so systems read it with
`world.get(AssetProgress)` and React with `useAssetProgress()` (or koota's
`useTrait(world, AssetProgress)`):

```tsx
import { useAssetProgress } from "@pawnjs/react";

function LoadingBar() {
  const { loaded, total } = useAssetProgress();
  if (loaded === total) return null;
  return <progress value={loaded} max={total} />;
}
```

## Compressed files

Files compressed with Draco or meshopt need their decoder:

```ts
engine.use(
  new Assets({
    draco: "https://www.gstatic.com/draco/versioned/decoders/1.5.7/",
    enableMeshopt: true,
  }),
);
```

`draco` is the folder with the Draco decoder files (from three's
`examples/jsm/libs/draco/`, or a CDN). With `enableMeshopt: true`, three's meshopt
decoder is fetched when the first file starts loading.
[`gltf-transform optimize`](https://gltf-transform.dev/cli) makes files much
smaller. The lanterns in the showcase's Energy demo went from 9.6 MB to
70 KB with `--compress meshopt --texture-compress webp --texture-size 256`.

## Errors and cleanup

A file that fails to load is reported once through `onError` (by default
`console.warn`). Its entities lose `Loading` and keep what they showed
before, if anything. A failed URL is not cached: the next `load()`, or
setting the same `Model` URL again, tries again.

Loaded files stay in memory until `assets.unload(url)`, which frees their
geometries, materials and textures, or until the engine is disposed. Call
`unload()` only when no entity draws the model anymore.
