Skip to content

Shaders

Updated

A shader is a small program that runs on the graphics card and decides the position and colour of every point of a surface. The Shader Material draws a mesh with one: either a preset the engine ships (hologram, toon, frozen, lava and more), a preset a script registers, or code you write. MIRA shaders are written much like Behavior scripts: #pragma lines declare the setup, the hooks, the inputs and the editable values, and hook functions hold the GLSL code. This page covers the component, the shader language, the built-in presets, textures, and how scripts drive all of it.

  • Materials. The Shader Material is one of the material kinds and takes the entity’s single material slot. See Materials.
  • Pragmas and hooks. Behavior scripts declare hooks with #pragma lifecycle(...); shaders use the same idea. See Scripting.
  • GLSL is the language graphics cards run. You only need it to write your own shaders; using presets needs none.
  • Vectors and colours. In GLSL, vec3 holds three numbers: a position, a direction or an RGB colour.
  • Preset. A named shader source in the app’s registry. A Shader Material draws one by setting its preset prop. The registry is the ShaderPreset global.
  • Uniform. A value the shader reads that stays the same across the whole draw, such as a tint colour or a speed. Declared with #pragma uniform, it becomes an editor field and a key in the material’s uniforms prop. Changing a uniform value is cheap: no rebuild.
  • Hook. A function MIRA calls at a stage of drawing: vertex to move points, fragment to colour pixels, ramp to shape toon lighting.
  • Input. Live data the engine feeds a shader: time, the pointer, the entity’s bounds.
  • Pass. An extra draw built from the mesh, such as a glowing shell, an ink outline or sparks.
  • Variant. A named set of uniform values a preset offers, such as the hologram’s Blue, Cyan or Amber.

ShaderMaterialComponent · comp-shader-material

Prop Type Default Description
preset string 'custom' A shader from ShaderPreset.list(), or 'custom' to draw shader.
shader string a starter source The material’s own shader source, drawn when preset is 'custom'.
uniforms object {} Values of the shader’s #pragma uniform inputs, by name. A missing one takes the pragma’s default.
color string | number '#ffffff' Where the surface colour starts; color in a raw shader.
opacity number 1 0 to 1. Where the surface alpha starts; opacity in a raw shader.
wireframe boolean false Draw edges only.
side 'front' | 'back' | 'double' 'front' Which faces render.

How the props behave:

  • By reference. A preset is read from the registry each time the material is built, so a fix to a preset reaches every entity that names it. shader is kept while a preset is chosen, so switching back to 'custom' restores it.
  • Values follow the shader. Values for uniforms the active shader does not declare are dropped. Numbers clamp to the pragma’s min and max.
  • Unknown preset. A name not yet registered draws nothing until a script registers it; the material then builds itself.
  • Errors. A source with a bad pragma or a missing hook makes setProps throw, with the line. A GLSL compile error is reported once, and the mesh draws nothing until the shader is fixed.
  • On models a surface shader (unlit, lit or toon) restyles each of the model’s own materials, keeping its texture, transparency and side. A raw shader draws every mesh with one material.
Member What it does
material.source() The source drawn now: the preset’s, or shader. undefined while the preset is unknown.
material.inspect() Reads the source drawn now as the editor does: its shader info, material settings, hooks, inputs, uniforms, variants, passes and error.
ShaderMaterialComponent.inspect(source) The same reading for any source string, before you use it.
material.setTransientModelPreset(preset, uniforms) On a loaded model whose Shader Material is disabled, draw a registered preset for this instance only. Returns true when applied, false when the preset is unknown or the material is enabled. Call with no arguments to clear.
material.setTransientModelUniform(ref, value) On a loaded model, override one numeric uniform for this instance only, updated in place on repeated calls. Call with no arguments to clear.

Transient overrides are local: they are not saved and not sent to other players.

GlobalWhat it is
ShaderPresetThe app's shader presets, by name: ShaderPreset.list(), get(name), register(source); a Shader Material draws one with setProps({ preset: name }).
ShaderMaterialComponentA material drawn by a shader written like a Behavior script, or by a named preset of one.
ShaderTextureComponentAn image its entity's Shader Material reads through one #pragma uniform(…, type=Texture), named by uniform. An entity has one per texture; without one, or while it loads, the uniform reads white. Swapping the image updates the shader in place, without rebuilding it.
Member What it does
ShaderPreset.list() Every preset available to scene materials, each { name, label, description }, in registration order.
ShaderPreset.get(name) The source of name, or undefined when there is none.
ShaderPreset.register(source) Add a source under its #pragma shader name. Throws on a bad source, a missing #pragma shader, the name custom, or a name already taken. Materials waiting for that name build themselves.

Every app’s registry starts with these presets, designed for VR and phones: lit by the scene’s own lights, with every animation running on the graphics card.

Preset Look Variants
hologram See-through hologram with rolling scanlines and a glowing, flickering rim Blue, Cyan, Amber, Mint, Rose
toon Lighting flattened into two soft tones over the model’s own colours, with a thin ink outline Subtle, Anime, Comic, Ghibli, Mono
burn The surface burns away behind a flame front, with char and embers Wood, Gas, Copper, Lithium
spectral A translucent ghost with flowing ectoplasm and glitch slices Wraith, Phantom, Poltergeist, Banshee
electricArc Lightning jumping between points on the surface Storm, Sith, Toxic, Arcane
plasma Plasma flowing over the body, a hot core and a glowing shell Ion, Inferno, Venom, Nova
lava Basalt plates split by glowing magma cracks Magma, Hellfire, Sulfur, Cobalt
energy Twisting energy ribbons and a hazy rim Arcane, Frost, Fel, Solar
frozen Glassy ice creeping over the surface behind a frosty front Glacier, Frostbite, Arctic, Cryo
holoFoil Angle-shifting rainbow foil with sparkling flakes Rainbow, Pearl, Beetle, Sunset
fireAura Flames licking off the silhouette over burning skin Inferno, Soulfire, Hellfire, Witchfire
reboot A sweep rebuilds the surface tile by tile, shedding pixels Reboot, Legend, Glitch, Matrix
stench Soft fumes rising off the body Stink, Toxic, Rot, Miasma
blood Tap the model to splatter it; splashes drip, dry and fade Blood, Zombie, Alien, Ichor

A source is GLSL with pragma lines. The pragma lines are removed before compiling; their options use the same grammar as script slots, so values may be numbers, true, quoted text or [lists].

#pragma shader(name=pulse, label="Pulse", description="A glow that beats.")
#pragma material(shading=unlit, blending=additive, depthWrite=false)
#pragma lifecycle(fragment)
#pragma input(time)
#pragma uniform(ref=tint, type=Color, default=0x00ffaa, group="Look")
#pragma uniform(ref=rate, type=Slider, min=0.5, max=8, step=0.1, default=4)
#pragma variant(name=Mint, swatch="#00ffaa", tint=0x00ffaa)
#pragma variant(name=Rose, swatch="#ff3fa4", tint=0xff3fa4)
void fragment(inout Surface s) {
s.emissive = tint * (0.5 + 0.5 * sin(time * rate));
}
Pragma Options Default
#pragma shader(...) name (one word: the registry key), label, description. Needed to register a preset. none
#pragma material(...) shading: unlit, lit, toon or raw. blending: normal or additive. depthWrite, shadows: true or false. unlit, normal, true, true
#pragma lifecycle(...) The hooks: vertex, fragment, and ramp for toon; startup, update and dispose for the shader’s own script. hook=function names another function. the functions named vertex and fragment
#pragma input(...) time, pointer, bounds, smoothNormals. none
#pragma uniform(...) An editable value. See Uniforms.
#pragma variant(...) name, swatch (a CSS colour for the editor button), then ref=value for any uniform, color and opacity.
#pragma pass(...) An extra draw. See Passes.
Shading Lighting vertex hook fragment hook
unlit None void vertex(inout Vertex v), optional void fragment(inout Surface s), optional; output is s.color + s.emissive
lit Every scene light and light probe: a soft diffuse term and a highlight that s.roughness sharpens, plus s.emissive same same; s.color is the base colour, s.metalness tints the highlight
toon Every scene light in two tones, shaped by an optional vec3 ramp(float light) hook (light is 0 facing away to 1 facing the light) same same
raw Your own void vertex(): the whole vertex stage; it sets gl_Position void fragment(): the whole fragment stage; it sets gl_FragColor

unlit, lit and toon build one lean shader around your hooks, so instancing, skinning, morphs, vertex colours, a model’s textures, fog and clipping keep working, and the shader compiles fast. They have no physically based shading, no environment light and receive no shadows. A source with no fragment hook keeps the surface’s own colours.

The data your hooks receive:

  • struct Vertex { vec3 position; vec3 normal; }: in the object’s own space, after skinning and morphs. Change position to move the surface.
  • struct Surface { vec3 color; float alpha; vec3 emissive; float roughness; float metalness; vec3 normal; }: color starts as the material’s color times its texture, alpha as opacity.
  • Varyings, available when a source uses them: vLocalPosition and vLocalNormal (object space), vWorldPosition, vWorldNormal, vEntityPosition (needs the bounds input) and vUv. cameraPosition is each eye’s in a headset.

Everything outside a hook (constants, helper functions) is shared by every stage. SHADER_VERTEX or SHADER_FRAGMENT is defined in each stage, SHADER_RAW in raw stages and SHADER_SHADOW in the shadow pass, so stage-specific code can sit inside #ifdef.

#pragma uniform declares the GLSL uniform for you (do not declare it again) and gives it an editor field. It takes ref, type, label, tooltip, group, default, min, max, step, items, enabled and visible, plus define and size.

type GLSL Value in uniforms
Number, Slider float a number
Integer int a whole number
Color vec3, linear a colour: 0xff8800 or '#ff8800'
Vector2, Vector3, Quaternion, Vector4 vec2, vec3, vec4, vec4 [x, y, …]
Boolean bool true or false
Dropdown int: the item’s number, else its index an item
Texture sampler2D none: a Shader Texture feeds it
  • if or #if. A Boolean or Dropdown is a uniform, so if (glow) { … } works and toggling it never recompiles. With define=true it becomes a compile-time switch (#if glow … #endif): no runtime branch, but each combination is its own program. Use it for features that are usually off and cost something when on.
  • Arrays. size=N declares an array that only the shader’s own script writes; it is never saved in uniforms. visible=false hides a uniform’s editor field.
  • Names are camelCase, such as rimColor. Names the engine already uses (time, color, opacity, normal, roughness, …) are rejected.
Input GLSL Cost
time float time, in seconds One value shared by every Shader Material
pointer vec3 pointerPosition (the last hit, in the hit mesh’s space), float pointerOver, float pointerDown (0 or 1), float pointerPressTime Nothing per frame: written only on pointer events, in play
bounds vec3 boundsMin, vec3 boundsMax: the entity’s box in its own space; vEntityPosition; toEntity(local) in vertex stages One matrix inverse per frame
smoothNormals vec3 smoothNormal, one normal per position, so a hull pushed along it stays closed at hard edges Memory for one more attribute

pointer makes the entity a pointer target, so pointers stop at it. A shader with pointer, bounds, smoothNormals or passes is not drawn in a Cache Mesh batch.

#pragma pass(...) adds a draw built once from each mesh, attached to it. Passes are never picked, cast no shadow and are not outlined. The main options are name, geometry (mesh to draw the mesh again, points for up to 4096 small quads sampled on the surface, arcs for up to 64 ribbons between surface points), the pass’s own vertex and fragment functions, and blending, depthWrite and side. A mesh pass with colorWrite=false draws depth only, first, which keeps an additive shader’s inside hidden. Each pass adds one draw per mesh; nothing runs on the CPU per frame.

What the graphics card cannot remember from frame to frame lives in a small JavaScript block inside the source, between #script_begin and #script_end, with startup(shader), update(dt, time) and dispose() hooks named in #pragma lifecycle. It runs once per entity, and update runs each frame while the entity is drawn. shader.uniforms holds the uniform objects (write .value), shader.value(ref) reads a uniform’s current prop value, and shader.entity is the entity. The blood preset keeps its splats this way.

A Texture uniform reads a Shader Texture on the same entity: ShaderTextureComponent, type comp-shader-texture. An entity has one per texture.

Prop Type Default Description
uniform string '' The ref of the Texture uniform it feeds.
src string '' The image: a PNG, JPEG or WebP, or a .ktx2 (GPU-compressed).

The image repeats and is read as sRGB. Until it loads, the uniform reads white. Changing or removing a Shader Texture updates the shader in place, without rebuilding it.

ComponentTypeWhat it does
Shader Materialcomp-shader-materialDraws its mesh with a shader: a preset, or code written with pragmas and hooks.
Shader Texturecomp-shader-textureOne image a shader material reads through a texture uniform.

The simplest use: turn an object into a hologram when the scene starts, and log every preset the app offers. Place the Behavior entity under the object.

MakeHologram.jx
#pragma lifecycle(startup)
function startup() {
for (const preset of ShaderPreset.list()) {
log(preset.name, '-', preset.label);
}
const target = self.parent;
let material = target.getComponent(ShaderMaterialComponent);
if (!material) {
material = new ShaderMaterialComponent({ preset: 'hologram' });
target.addComponent(material);
} else {
material.setProps({ preset: 'hologram' });
}
}
  • ShaderPreset.list() returns { name, label, description } for each preset. Use name in props; label is the friendly title.
  • If the object has no Shader Material yet, the script creates one already set to 'hologram' and adds it. Because all materials share one slot, it replaces the existing material.
  • On a loaded model the hologram is drawn on every mesh of the model. A surface preset such as toon would instead restyle each mesh’s own material.

Presets come with named looks, their variants. A variant is applied by writing its values: color and opacity as props, everything else into uniforms. The object has a Shader Material, a Selectable and a Signal Emitter with the signal orb/clicked.

VariantCycle.jx
#pragma lifecycle(startup)
let material;
let variants = [];
let current = 0;
function applyVariant(variant) {
const props = {};
const uniforms = Object.assign({}, material.props.uniforms);
for (const key of Object.keys(variant.values)) {
if (key === 'color' || key === 'opacity') props[key] = variant.values[key];
else uniforms[key] = variant.values[key];
}
props.uniforms = uniforms;
material.setProps(props);
log('Variant:', variant.name);
}
function startup() {
material = self.parent.getComponent(ShaderMaterialComponent);
const info = material.inspect();
variants = info ? info.variants : [];
if (variants.length === 0) return;
on('orb/clicked', (event) => {
if (event.eventType !== EventType.Selectable.Select) return;
findEntity(event.entityId)?.getComponent(SelectableComponent)?.setSelected(false); // so the next click selects it again
current = (current + 1) % variants.length;
applyVariant(variants[current]);
});
}
  • material.inspect() reads the shader drawn now and returns its variants, each { name, swatch, values }. It returns undefined while the preset is unknown, hence the check.
  • applyVariant sorts each value into a prop (color, opacity) or a uniform. It copies the existing uniforms first with Object.assign, so values the variant does not mention are kept.
  • Everything goes into one setProps call. Uniform values update without a rebuild; color and opacity do rebuild, once.

A custom dissolve shader: pixels whose noise value falls below progress are cut away, with a glowing edge. The script registers it, applies it, and tweens progress from 0 to 1 when the signal crate/destroy arrives.

Dissolve.jx
#pragma lifecycle(startup)
const DISSOLVE = `
#pragma shader(name=dissolve, label="Dissolve", description="Burns away along a blocky noise pattern.")
#pragma material(shading=lit)
#pragma uniform(ref=progress, type=Slider, min=0, max=1, step=0.01, default=0)
#pragma uniform(ref=edgeColor, type=Color, default=0xff6a00)
#pragma uniform(ref=cells, type=Number, min=1, max=64, default=8)
float hash(vec3 p) {
return fract(sin(dot(p, vec3(12.9898, 78.233, 37.719))) * 43758.5453);
}
void fragment(inout Surface s) {
float n = hash(floor(vLocalPosition * cells));
if (n < progress) discard;
float edge = 1.0 - smoothstep(0.0, 0.08, n - progress);
s.emissive = edgeColor * edge * 4.0;
}
`;
let material;
function setProgress(value) {
material.setProps({ uniforms: Object.assign({}, material.props.uniforms, { progress: value }) });
}
function startup() {
if (!ShaderPreset.get('dissolve')) ShaderPreset.register(DISSOLVE);
const crate = self.parent;
material = new ShaderMaterialComponent({ preset: 'dissolve', color: '#a16207' });
crate.addComponent(material);
on('crate/destroy', async () => {
const finished = await Tween.value(0, 1, setProgress, { duration: 1.5, ease: Ease.InQuad });
if (finished) destroy(crate);
});
}
  • The source is a JavaScript template string. #pragma shader names it dissolve; shading=lit lets the scene’s lights shade it.
  • Each #pragma uniform declares a GLSL uniform and an editor field. progress is a Slider from 0 to 1.
  • vLocalPosition is the pixel’s position in the object’s own space; floor(… * cells) turns it into blocks, and hash gives each block a random value. discard drops the pixel.
  • ShaderPreset.get('dissolve') checks whether it is already registered. register throws on a name already taken, which happens when the script restarts.
  • Tween.value calls setProgress every frame for 1.5 seconds. Changing a uniform value writes it straight into the drawn material, with no rebuild, so this is cheap, unlike animating a Standard material’s props.
  • await on the tween resolves true when it finished, and the crate is then removed with destroy.
  • Because the shader discards pixels, its shadow follows the dissolving shape too.

A shader can react to the pointer by itself, with no script work per frame. This custom shader is set as the material’s own shader, with preset: 'custom'.

HoverGlow.jx
#pragma lifecycle(startup)
const HOVER = `
#pragma material(shading=lit)
#pragma input(pointer, time)
#pragma uniform(ref=glowColor, type=Color, default=0x38bdf8)
void fragment(inout Surface s) {
float pulse = 0.6 + 0.4 * sin(time * 6.0);
float pressFlash = exp(-(time - pointerPressTime) * 4.0);
s.emissive = glowColor * (pointerOver * pulse + pressFlash * 2.0);
}
`;
function startup() {
const button = self.parent;
const check = ShaderMaterialComponent.inspect(HOVER);
if (check.error) {
console.error('Shader error: ' + check.error);
return;
}
button.addComponent(new ShaderMaterialComponent({ preset: 'custom', shader: HOVER, color: '#1e293b' }));
}
  • #pragma input(pointer, time) asks for the pointer values and the clock. pointerOver is 1 while a mouse, finger or XR ray is over the entity; pointerPressTime is the time of the last press.
  • exp(-(time - pointerPressTime) * 4.0) is 1 at the moment of a press and fades quickly toward 0: a flash with no script involved.
  • ShaderMaterialComponent.inspect(source) checks the pragmas before the material is built, so the script can report a clear error instead of drawing nothing. (GLSL compile errors are only found when the shader is first drawn.)
  • The pointer input makes the entity a pointer target and keeps it out of Cache Mesh batches.

On a loaded model, setTransientModelPreset draws a preset on this one instance without changing the saved material. The model has a disabled Shader Material and a Signal Emitter with the signal knight/freeze.

FreezeEffect.jx
#pragma lifecycle(startup)
const FROZEN_MS = 3000;
function startup() {
const material = self.parent.getComponent(ShaderMaterialComponent);
on('knight/freeze', () => {
const applied = material.setTransientModelPreset('frozen');
if (!applied) {
console.warn('Could not freeze: is the Shader Material disabled and the preset registered?');
return;
}
delay(() => material.setTransientModelPreset(), FROZEN_MS);
});
}
  • The Shader Material must be disabled: the transient preset is a temporary look on top of the model’s own materials, not a change to the material component.
  • setTransientModelPreset('frozen') returns true when applied. Calling it with no arguments clears it and the model looks as authored.
  • Nothing is saved or replicated, so each player can see a different effect on their own copy.

The toon shading accepts a ramp hook that maps how much light a point receives (0 facing away, 1 facing the light) to a brightness. That is how you design cel shading. This script registers a three-band ramp and applies it to several characters.

ThreeBandToon.jx
#pragma lifecycle(startup)
const THREE_BAND = `
#pragma shader(name=threeBand, label="Three band", description="Cel shading in three hard bands.")
#pragma material(shading=toon)
#pragma lifecycle(ramp)
#pragma uniform(ref=shadowTone, type=Slider, min=0, max=1, default=0.35)
vec3 ramp(float light) {
if (light < 0.3) return vec3(shadowTone);
if (light < 0.75) return vec3(0.75);
return vec3(1.0);
}
`;
function startup() {
if (!ShaderPreset.get('threeBand')) ShaderPreset.register(THREE_BAND);
for (const name of ['Hero', 'Sidekick', 'Villain']) {
const character = findEntity(name);
if (!character) {
console.warn('No entity named ' + name);
continue;
}
character.addComponent(new ShaderMaterialComponent({ preset: 'threeBand' }));
}
}
  • Inside the shader source, #pragma lifecycle(ramp) declares the toon hook. It is the shader’s own pragma and has nothing to do with the script’s #pragma lifecycle(startup) above it.
  • With no fragment hook, each model keeps its own colours and textures: only the lighting is banded.
  • Because toon is a surface shading, applying it to a model restyles each of the model’s own materials rather than replacing them.
  • shadowTone is a uniform, so each character’s material can darken or lighten its shadow band without a rebuild.
  • A material naming a preset that is not registered yet waits and builds itself as soon as the name is registered, so the order of scripts does not matter.
  • Built on change. The material is rebuilt only when its props change. Materials with the same source and compile switches share one GPU program.
  • Uniform values are cheap. Changing a uniform value writes into the drawn material without a rebuild. A define=true switch, color, opacity, the preset or the shader does rebuild, and so does any change on an entity drawn in a Cache Mesh batch.
  • First draw compiles. The first time a source is drawn, its program compiles, which can hold a frame. Later draws reuse it. Lean lit and toon programs compile much faster than physically based ones.
  • Passes add one draw per mesh each. Particles and cards cost fill rate where they overlap, most on phones and headsets.
  • Shadows. A Shader Material never receives shadows. It casts unless it is additive or says shadows=false.
  • Headsets. Use object, world or view space in your code, never gl_FragCoord, which differs per eye.
  • Registering twice. ShaderPreset.register throws when the name is taken, for example when the script restarts. Check with ShaderPreset.get(name) first.
  • Replacing all uniforms. setProps({ uniforms: { tint: 0xff0000 } }) replaces the whole uniforms object, resetting the others to their defaults. Copy the existing ones with Object.assign({}, material.props.uniforms, { … }).
  • Declaring a uniform twice. #pragma uniform already declares it in GLSL. Writing uniform vec3 tint; again is a compile error.
  • Reserved names. A uniform called time, color or opacity is rejected. Use names such as tint or fade.
  • Animating color or opacity every frame. These rebuild the material. Animate a uniform instead.
  • Expecting received shadows. Shader Materials never show shadows cast on them. Use a Standard material where shadows matter.
  • Using gl_FragCoord for patterns: they swim between the eyes of a headset. Use vLocalPosition or vWorldPosition.
  • Endless loops. A runaway loop in a shader can stall the graphics card until the browser resets it. Keep loops bounded by constants.