Skip to content

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.

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 with findEntity('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.

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-mesh-collada ColladaComponent comp-collada
USDZ mesh ent-mesh-usdz USDZComponent comp-usdz
Kit piece ent-kit-piece KitPieceComponent comp-kit-piece

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.

  • 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.
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 src changes, 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 src to '' removes the model.

Every loader sends two events through a Signal Emitter on its entity:

Event EventType constant Data When
GLTF::ready EventType.GLTF.Ready {} The model is in the scene. Sent again after each reload.
GLTF::error EventType.GLTF.Error { 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.

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.
getAnimationClipNames(options?) The names of the animation clips stored in the file. Pass { includeDuplicates: true } to spot clips that share a name.
getModelRestBounds() The model’s box as authored, { min: { x, y, z }, max: { x, y, z } }, or undefined before it loads.
getModelRestNodes() Every named node, each { name, position, isBone }, at its authored position.
getModelExtra(key) A copy of a custom value (an extra) stored in the file under key.
setModelOffset(x, y, z) 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.
setModelView(view), modelView Draw the model 'full' or 'hidden' for this instance only, and read which is requested.

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.

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.

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), heightSegments 16 (2 to 32), thetaLength π
plane width 1, height 1; flat, facing +Z
cylinder radiusTop 0.5, radiusBottom 0.5, height 1, radialSegments 32 (3 to 64)
capsule radius 0.4, length 1, capSegments 8 (1 to 16), radialSegments 16 (3 to 64)
cone radius 0.5, height 1, radialSegments 32 (3 to 64)
torus radius 0.5, tube 0.2, radialSegments 16 (3 to 32), tubularSegments 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_PI gives a half circle, M_HALF_PI a quarter.
  • Domes. A sphere’s thetaLength is how far down from its top it sweeps: M_HALF_PI is 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 params object 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.

ComponentTypeWhat it does
Gltfcomp-gltfLoads a glTF/GLB model.
Fbxcomp-fbxLoads an FBX model.
Objcomp-objLoads a Wavefront OBJ model.
Colladacomp-colladaLoads a Collada .dae model.
Usdzcomp-usdzLoads a USDZ model.
Kit Piececomp-kit-piecePlaces one piece chosen from a modular building kit.
Geometrycomp-geometryA built-in primitive shape: box, sphere, plane, cylinder, ring and more.

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.

GroundModel.jx
#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 returns undefined until the model has loaded, which is why fit checks 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 run fit again safely: it always measures from the authored box.
  • model.isLoaded covers the case where the model finished loading before the script started; the ready listener covers every later load. A replacement model starts with no offset, so refitting on each ready is 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.

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.

PillarRing.jx
#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()}` });
}
}
  • The two #pragma slot lines create editor fields, count and radius, that the script reads as variables.
  • spawn(template, options) copies the entity, with its components, into the scene. enabled: true switches the copy on even though the template is saved disabled.
  • M_TAU is a full turn in radians, so i / count * M_TAU spreads the pillars evenly.
  • GeometryComponent.setProps rebuilds each copy’s mesh once. radialSegments: 16 keeps 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.

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.

DomeOpen.jx
#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');
}
  • startup is async, so it may await. Scripts have no setTimeout; wrapping delay in 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.
  • thetaLength sweeps down from the top of the sphere; M_HALF_PI (a quarter turn) makes a half sphere, closed underneath with a flat disc.

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:

ModelStatus.jx
#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 call startup once when the script starts.
  • on('statue', …) listens to everything the Signal Emitter forwards. Each event has an eventType and data; destructuring them in the parameter list keeps the code short.
  • Comparing with EventType.GLTF.Ready instead of the string 'GLTF::ready' protects you from typos. For an FBX model you would compare with EventType.FBX.Ready, and so on.
  • ready fires again after every reload, so this listener also reports each time the source changes.

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.

ModelVariants.jx
#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 loading flag 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.
  • Listening without a Signal Emitter. A loader’s ready and error events 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, OBJComponent and USDZComponent, all in capitals. When in doubt, use ModelLoaderComponent.
  • Reading the model too early. getModelRestBounds() and the clip list are empty until the model is in place. Check isLoaded, or wait for the ready event.
  • Writing to props directly. loader.props.src = '…' changes nothing on screen. Always call setProps.
  • 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 setProps on a Geometry in update rebuilds 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 widthSegments at 64), and each one adds triangles. Keep them low on shapes you repeat.