Models and meshes
Updated
Everything you can see in a MIRA world is drawn from a mesh: a surface made of triangles. A mesh comes from one of two places. It is either a loaded model, a 3D file made in a modelling tool (glTF, FBX, OBJ, Collada, USDZ, or one piece of a modular kit), or a primitive, a built-in shape such as a box, sphere or torus that MIRA generates from a handful of numbers. This page explains both, the events a model sends while it loads, and what a Behavior script can read and change on each.
Before you start
Section titled “Before you start”This page relies on a few ideas explained elsewhere:
- Entities and components. An entity is an object in the scene; components give it abilities. A model is an entity with a loader component. See Components.
- Behavior scripts. A script runs inside a Behavior entity. To drive another object, place the Behavior entity under it and use
self.parent, or look the object up withfindEntity('Name'). See Scripting. - Signals. Components announce what happens to them (a model finished loading, a click) through a Signal Emitter on the same entity. A script listens with
on(signal, callback). See Input and interaction. - Materials decide how a surface looks. Both models and primitives take one. See Materials.
Model entities
Section titled “Model entities”Each model format has its own entity type, and each entity type requires the matching loader component: the component that names the file and loads it. An entity loads exactly one model, so it refuses a second loader of another format.
| Entity | Type | Loader component (script global) | Loader type |
|---|---|---|---|
| glTF / GLB mesh | ent-mesh-gltf |
GLTFComponent |
comp-gltf |
| FBX mesh | ent-mesh-fbx |
FBXComponent |
comp-fbx |
| OBJ mesh | ent-mesh-obj |
OBJComponent |
comp-obj |
| Collada mesh | ent- |
Collada |
comp-collada |
| USDZ mesh | ent-mesh-usdz |
USDZComponent |
comp-usdz |
| Kit piece | ent-kit-piece |
Kit |
comp- |
ModelLoaderComponent is the shared base of every loader. entity.getComponent(ModelLoaderComponent) returns the entity’s loader whatever its format, which is handy for scripts that work on any model.
A new model entity starts with a Shadow component that casts shadows but does not receive them; a kit piece starts with one that does both. Model entities also accept materials, Selectable, Outline, Silhouette, Grabbable, physics colliders and rigid bodies, the animation components, Billboard, LOD Mesh, Cache Mesh, Grass, Grass Bender, navigation and networking components.
Which format to choose
Section titled “Which format to choose”- glTF / GLB is the recommended format for the web. It loads fastest, supports animation, skinning and morphs, and accepts Draco and Meshopt compression, which make files much smaller.
- FBX and Collada are common exports from older tools. They work, but are larger and slower to parse than GLB.
- OBJ holds static geometry only. It loads the MTL material libraries its file declares; keep MTL files next to the OBJ and texture files next to their MTL, as the files reference them. Without a library, the model draws with plain default materials.
- USDZ is the format used by many mobile AR tools.
- Kit pieces come from a kit: one glTF file holding many modular parts (walls, floors, doors), each tagged with an id. A Kit Piece loads only the part named by its
pieceId. A missing or ambiguous id is an error; it never loads the whole kit.
An animated Collada (.dae) character on a turntable, with its texture beside the file: the script centres it, scales it to 1.4 m and plays the first clip stored in the file.
Watch the character turn on the turntable while it plays its clip; the log lists the clips. Drag to orbit the camera, scroll to zoom.
An animated FBX (.fbx) cube on a turntable, drawn with an amber Standard material that overrides its own: the script sizes it to 0.6 m and plays the animation clip stored in the file.
Watch the cube play the rotation clip from its FBX file; the log names the clip. Drag to orbit the camera, scroll to zoom.
A low-poly tree loaded from a Wavefront OBJ (.obj) file, which carries geometry only, so an amber Standard material colours it. The script centres it and scales it to 1.6 m.
Watch the tree turn on the turntable. Drag to orbit the camera, scroll to zoom.
A textured USDZ (.usdz) model, the format of AR Quick Look, on a turntable: the script centres it and scales it to 0.8 m once it loads.
The file is about 4 MB, so give it a moment, then watch it turn. Drag to orbit the camera, scroll to zoom.
A small shrine assembled from one modular kit file: floor tiles, pillars, walls, a beam and steps are each a Kit Piece that loads only the part named by its pieceId. The script counts the pieces as they load.
Orbit around the shrine: every part comes from the same kit file. The log counts the pieces as they load. Drag to orbit the camera, scroll to zoom.
Loader props
Section titled “Loader props”| Prop | Type | Default | Description |
|---|---|---|---|
src |
string |
'' |
The model file: an ASSET-<uuid> reference to a project asset, or a URL. Changing it reloads the model. |
pieceId |
string |
'' |
Kit Piece only: which piece of the kit to load. |
How a source loads:
- Shared assets. A model file is parsed once and shared. Ten copies of the same chair share one parsed asset; each entity draws its own clone of it.
- No empty frames. When
srcchanges, the current model stays visible until the replacement is ready. - Failure keeps the old model. If the replacement fails, the error is reported and the current model stays.
- Clearing removes. Setting
srcto''removes the model.
Events
Section titled “Events”Every loader sends two events through a Signal Emitter on its entity:
| Event | EventType constant |
Data | When |
|---|---|---|---|
GLTF::ready |
Event |
{} |
The model is in the scene. Sent again after each reload. |
GLTF::error |
Event |
{ message } |
The model could not load. |
The other formats send the same pair under their own source name: EventType.FBX.Ready, EventType.OBJ.Ready, EventType.Collada.Ready, EventType.USDZ.Ready, EventType.KitPiece.Ready, and the matching Error constants.
Model entity members
Section titled “Model entity members”A loaded model’s entity offers these members to scripts. They read the model as authored: positions and bounds in the entity’s own coordinates, before any animation.
| Member | What it does |
|---|---|
isLoaded |
true when the model is loaded and in place. A getter: read it, do not call it. |
get |
The names of the animation clips stored in the file. Pass { include to spot clips that share a name. |
get |
The model’s box as authored, { min: { x, y, z }, max: { x, y, z } }, or undefined before it loads. |
get |
Every named node, each { name, position, is, at its authored position. |
get |
A copy of a custom value (an extra) stored in the file under key. |
set |
Move the loaded model inside its entity, without touching the entity’s transform or children. (0, 0, 0) clears it. A replacement model starts with no offset. |
set, modelView |
Draw the model 'full' or 'hidden' for this instance only, and read which is requested. |
Materials on models
Section titled “Materials on models”A model draws with the materials stored in its file. Add any material component to the entity to override them: one material, built once, drawn on every mesh of the model, including skinned and morphed parts. Removing or disabling the material component puts the original materials back. A Shader Material with a surface shader, such as the toon preset, restyles instead of replacing: each original material keeps its colour, textures and transparency. See Materials.
Primitive meshes
Section titled “Primitive meshes”A Primitive Mesh (ent-primitive-mesh) draws a built-in shape. It requires a Geometry and a material; a new one is a green box with a Standard material. A Floor (ent-floor) is a plane primitive that also requires a Box Collider, so things can stand on it.
Primitives are ideal for blocking out a level, for simple props, for invisible-looking tools such as CSG cutters, and for anything a script builds or reshapes at run time.
Geometry
Section titled “Geometry”GeometryComponent · comp-geometry
| Prop | Type | Default | Description |
|---|---|---|---|
shape |
'box' | 'sphere' | 'plane' | 'cylinder' | 'capsule' | 'cone' | 'torus' | 'tetrahedron' | 'octahedron' | 'dodecahedron' | 'icosahedron' | 'circle' | 'ring' |
'box' |
The shape. |
params |
Record<string, number> |
per shape, below | The shape’s dimensions, in metres. Missing entries take their defaults. |
| Shape | Params and defaults |
|---|---|
box |
width 1, height 1, depth 1 |
sphere |
radius 0.5, widthSegments 32 (3 to 64), height 16 (2 to 32), thetaLength π |
plane |
width 1, height 1; flat, facing +Z |
cylinder |
radiusTop 0.5, radiusBottom 0.5, height 1, radial 32 (3 to 64) |
capsule |
radius 0.4, length 1, capSegments 8 (1 to 16), radial 16 (3 to 64) |
cone |
radius 0.5, height 1, radial 32 (3 to 64) |
torus |
radius 0.5, tube 0.2, radial 16 (3 to 32), tubular 48 (3 to 128) |
tetrahedron, octahedron, dodecahedron, icosahedron |
radius 0.5 (to the corners), detail 0 (0 to 16): each level splits every face, rounding the shape toward a sphere |
circle |
radius 0.5, segments 32 (3 to 64), thetaLength 2π; flat, facing +Z |
ring |
innerRadius 0.25, outerRadius 0.5, thetaSegments 32 (3 to 64), thetaLength 2π; flat, facing +Z |
A few shape details worth knowing:
- Segments are how many slices a round shape is built from. More segments look smoother and cost more triangles.
- Partial circles and rings.
thetaLength, in radians, is how far the shape sweeps counter-clockwise from +X.M_PIgives a half circle,M_HALF_PIa quarter. - Domes. A sphere’s
thetaLengthis how far down from its top it sweeps:M_HALF_PIis a dome. The cut is closed with a flat disc, so the dome stays solid for shadows and outlines. - Flat shapes (plane, circle, ring) show one face. Give them a material with
side: 'double'to see both sides. - Changing shape with an explicit
paramsobject uses the params you pass; params from the old shape are not carried over.
Changing the geometry rebuilds the mesh once. It is never rebuilt on its own each frame.
| Component | Type | What it does |
|---|---|---|
| Gltf | comp-gltf | Loads a glTF/GLB model. |
| Fbx | comp-fbx | Loads an FBX model. |
| Obj | comp-obj | Loads a Wavefront OBJ model. |
| Collada | comp-collada | Loads a Collada .dae model. |
| Usdz | comp-usdz | Loads a USDZ model. |
| Kit Piece | comp-kit-piece | Places one piece chosen from a modular building kit. |
| Geometry | comp-geometry | A built-in primitive shape: box, sphere, plane, cylinder, ring and more. |
Examples
Section titled “Examples”1. Sit any model on the floor and list its clips
Section titled “1. Sit any model on the floor and list its clips”Models from different tools often have their pivot in odd places: in the middle of the model, or far below it. This script waits for the model, then moves it inside its entity so its lowest point rests on the entity’s origin and it is centred horizontally. Place the Behavior entity under the model; the model needs a Signal Emitter with the signal model.
#pragma lifecycle(startup)
let model;
function fit() { const bounds = model.getModelRestBounds(); if (!bounds) return;
const centerX = (bounds.min.x + bounds.max.x) / 2; const centerZ = (bounds.min.z + bounds.max.z) / 2; model.setModelOffset(-centerX, -bounds.min.y, -centerZ);
const height = bounds.max.y - bounds.min.y; log(model.name, 'is', height.toFixed(2), 'm tall'); log('Clips:', model.getAnimationClipNames().join(', ') || 'none');}
function startup() { model = self.parent; if (model.isLoaded) fit(); on('model', ({ eventType }) => { if (eventType === EventType.GLTF.Ready) fit(); });}getModelRestBounds()returns the model’s box as authored, in the entity’s own coordinates. It returnsundefineduntil the model has loaded, which is whyfitchecks first.setModelOffset(x, y, z)shifts the drawn model inside its entity. The entity’s transform, its children and the authored bounds stay as they are, so you can runfitagain safely: it always measures from the authored box.model.isLoadedcovers the case where the model finished loading before the script started; thereadylistener covers every later load. A replacement model starts with no offset, so refitting on eachreadyis correct.getAnimationClipNames()lists the clips stored in the file. Pass these names to an Animation Clip; see Animation.
The live example below does the same for a Collada character: on the model’s ready event it stands it on the floor, centred, sizes it to 1.4 m, lists its clips and plays the first one.
An animated Collada (.dae) character on a turntable, with its texture beside the file: the script centres it, scales it to 1.4 m and plays the first clip stored in the file.
Watch the character turn on the turntable while it plays its clip; the log lists the clips. Drag to orbit the camera, scroll to zoom.
2. Build a ring of primitives
Section titled “2. Build a ring of primitives”A script can create content by copying an existing entity with spawn. Here a disabled template entity named Pillar (a Primitive Mesh) is copied into a circle, and each copy gets its own shape size and colour.
#pragma slot(ref=count, type=Integer, min=3, max=48, default=12)#pragma slot(ref=radius, type=Number, min=1, max=50, default=6)#pragma lifecycle(startup)
function startup() { const template = findEntity('Pillar');
for (let i = 0; i < count; i++) { const angle = (i / count) * M_TAU; const pillar = spawn(template, { position: { x: Math.cos(angle) * radius, y: 0, z: Math.sin(angle) * radius }, enabled: true, });
const height = Random.range(1, 4); pillar.getComponent(GeometryComponent).setProps({ shape: 'cylinder', params: { radiusTop: 0.3, radiusBottom: 0.4, height: height, radialSegments: 16 }, }); pillar.position.y = height / 2;
pillar.getComponent(MaterialComponent).setProps({ color: `#${Random.color().getHexString()}` }); }}A script copies a disabled Primitive Mesh template into a ring of twelve pillars, each with its own height and colour: spawn, the Geometry component and the material.
Reload the example for a new set of heights and colours. Drag to orbit the camera, scroll to zoom.
- The two
#pragma slotlines create editor fields,countandradius, that the script reads as variables. spawn(template, options)copies the entity, with its components, into the scene.enabled: trueswitches the copy on even though the template is saved disabled.M_TAUis a full turn in radians, soi / count * M_TAUspreads the pillars evenly.GeometryComponent.setPropsrebuilds each copy’s mesh once.radialSegments: 16keeps the triangle count modest for a shape repeated many times.- A cylinder is centred on its origin, so lifting it by half its height stands it on the ground.
getComponent(MaterialComponent)returns the material whatever its kind.
3. Grow a dome in steps
Section titled “3. Grow a dome in steps”Geometry is rebuilt on every change, so animate it in a few steps rather than every frame. This script opens a sphere into a dome over one second, in eight steps.
#pragma lifecycle(startup)
const STEPS = 8;
async function startup() { const geometry = self.parent.getComponent(GeometryComponent);
for (let step = 1; step <= STEPS; step++) { const sweep = (step / STEPS) * M_HALF_PI; geometry.setProps({ shape: 'sphere', params: { radius: 1, thetaLength: sweep } }); await new Promise((done) => delay(done, 1000 / STEPS)); } log('Dome complete');}A script opens a sphere into a dome over one second, rebuilding its Geometry's thetaLength in eight steps.
Watch the dome open when the scene starts. Drag to orbit the camera, scroll to zoom.
startupisasync, so it mayawait. Scripts have nosetTimeout; wrappingdelayin a promise is the way to wait inside an async hook.- Each loop iteration rebuilds the sphere once, eight rebuilds in total, instead of sixty or more if it ran in
update. thetaLengthsweeps down from the top of the sphere;M_HALF_PI(a quarter turn) makes a half sphere, closed underneath with a flat disc.
Snippets
Section titled “Snippets”1. Report when a model has loaded
Section titled “1. Report when a model has loaded”Give the model entity (here named Statue) a Signal Emitter with the signal statue. Then add a Behavior entity anywhere in the scene with this script:
#pragma lifecycle(startup)
function startup() { on('statue', ({ eventType, data }) => { if (eventType === EventType.GLTF.Ready) { log('The statue has loaded'); } else if (eventType === EventType.GLTF.Error) { console.warn('The statue failed to load: ' + data.message); } });}#pragma lifecycle(startup)asks MIRA to callstartuponce when the script starts.on('statue', …)listens to everything the Signal Emitter forwards. Each event has aneventTypeanddata; destructuring them in the parameter list keeps the code short.- Comparing with
EventType.GLTF.Readyinstead of the string'GLTF::ready'protects you from typos. For an FBX model you would compare withEventType.FBX.Ready, and so on. readyfires again after every reload, so this listener also reports each time the source changes.
2. Cycle through model variants on click
Section titled “2. Cycle through model variants on click”A product viewer that shows the next variant each time the model is clicked. The model entity Chair has a Selectable and a Signal Emitter with the signal chair/clicked. Place the Behavior entity under the chair.
#pragma lifecycle(startup)
const VARIANTS = [ 'https://cdn.example.com/models/chair-oak.glb', 'https://cdn.example.com/models/chair-walnut.glb', 'https://cdn.example.com/models/chair-white.glb',];
let chair;let loader;let index = 0;let loading = false;
function startup() { chair = self.parent; loader = chair.getComponent(ModelLoaderComponent);
on('chair/clicked', (event) => { if (event.eventType === EventType.Selectable.Select && !loading) { findEntity(event.entityId)?.getComponent(SelectableComponent)?.setSelected(false); // so the next click selects it again loading = true; index = (index + 1) % VARIANTS.length; loader.setProps({ src: VARIANTS[index] }); } if (event.eventType === EventType.GLTF.Ready) { loading = false; log('Showing variant', index + 1, 'of', VARIANTS.length); } if (event.eventType === EventType.GLTF.Error) { loading = false; console.warn('Variant failed, keeping the previous one: ' + event.data.message); } });}getComponent(ModelLoaderComponent)finds the loader whatever the file format, so the script would also work on an FBX or OBJ entity (with the matching event constants).loader.setProps({ src })is the only way to change a prop. MIRA validates the value, starts the reload and keeps the old chair on screen until the new one is ready.- The
loadingflag ignores clicks while a variant is still downloading, so rapid clicks do not queue several loads. - One signal carries both the Selectable events and the loader events, because the Signal Emitter forwards every event of its entity. The script tells them apart by
eventType. - On error, the previous model stays visible, so the script only needs to log the problem.
Common mistakes
Section titled “Common mistakes”- Listening without a Signal Emitter. A loader’s
readyanderrorevents go nowhere unless the model entity carries a Signal Emitter. Add one and listen on its signal. - Using the wrong class name. Scripts use the global names
GLTFComponent,FBXComponent,OBJComponentandUSDZComponent, all in capitals. When in doubt, useModelLoaderComponent. - Reading the model too early.
getModelRestBounds()and the clip list are empty until the model is in place. CheckisLoaded, or wait for thereadyevent. - Writing to
propsdirectly.loader.props.src = '…'changes nothing on screen. Always callsetProps. - Adding a second loader. A model entity takes exactly its own format’s loader. To show a different file, change
src; to show a different format, use another entity. - Rebuilding geometry every frame. Calling
setPropson a Geometry inupdaterebuilds the mesh sixty times a second. To animate size, scale the entity (entity.scale) instead, or change the geometry in a few steps. - Invisible flat shapes. A plane, circle or ring seen from behind shows nothing. Set
side: 'double'on its material. - Huge segment counts. Segments are capped (for example a sphere’s
widthSegmentsat 64), and each one adds triangles. Keep them low on shapes you repeat.