mote documentation

Everything you need to build games with mote: the engine, the Lua API and the Blender add-on. The guide comes first; the reference of all 1648 functions follows.

Getting started

What is mote#

mote is a game engine for 2D and 3D games. The engine is a single executable, mote.exe; games are written in Lua 5.4 and talk to the engine through the global table mote. Blender is the level and character editor, through the mote editor add-on.

The last part of this documentation is the API reference: every function the engine exposes, with its arguments. An argument marked ? is optional.

Getting started

Installation#

  1. Put mote.exe in any folder.
  2. Create a folder for your game with a file main.lua.
  3. Run the game: drag the game folder onto mote.exe, or from a terminal:
mote.exe path\to\mygame

Without arguments, mote.exe runs, in this order: a game fused into the executable, a game.lpak next to it, or main.lua in the current folder.

The Blender add-on#

  1. Blender 3.6 or newer: Edit → Preferences → Add-ons → Install…, choose mote_level_exporter.py, enable mote editor.
  2. In the add-on preferences set the path to mote.exe (used by Export and run).
  3. The panels are in the 3D viewport sidebar (N), tab mote.

Installing a newer version over the old one replaces it.

Getting started

Your first game#

-- main.lua
local g3 = mote.graphics3d
local t = 0

function mote.load()
    mote.render.apply{ tonemap = "agx", ssao = 1, taa = true }
end

function mote.update(dt)
    t = t + dt
end

function mote.draw()
    g3.setCamera(0, 2, -5,  0, 0.5, 0,  60)
    g3.setLight(-0.4, -1, 0.3)
    g3.setSunColor(1, 0.95, 0.9, 3)
    g3.setColor(0.4, 0.4, 0.42)
    g3.box(0, -0.05, 0, 10, 0.1, 10)
    g3.setColor(0.9, 0.3, 0.2)
    g3.push()
    g3.translate(0, 0.6, 0)
    g3.rotate(0, t * 45, 0)
    g3.box(0, 0, 0, 1, 1, 1)
    g3.pop()
    mote.graphics.print("Hello, mote", 20, 20)
end

Edit main.lua while the game runs: the change is picked up without a restart.

Getting started

Game structure and the frame#

function mote.load() end              -- once, at start
function mote.update(dt) end          -- game logic; dt = seconds since the last frame
function mote.draw() end              -- describe this frame
function mote.keypressed(key) end
function mote.mousepressed(x, y, button) end
function mote.resize(w, h) end
function mote.quit() end

Frame order: input → mote.update → network → mote.draw → render. Physics steps only when you call mote.physics3d.update(dt) or level:update(dt).

Rendering is immediate: everything in the frame — camera, lights, objects — is described again in every mote.draw. What is not drawn this frame is not on screen; nothing has to be created or destroyed.

Project layout#

mygame/
  main.lua            entry point
  *.lua               your modules: require("enemies") loads enemies.lua
  models/*.glb        glTF 2.0 models
  textures/*.png|jpg
  sounds/*.ogg|wav
  levels/*.json       scenes exported from Blender

All paths are relative to the game folder.

Getting started

Conventions#

QuantityConvention
Axesright-handed, Y up. An object faces +Z; its right is −X; its up is +Y. The camera looks along its own +Z.
Distancemetres
Timeseconds
Euler anglesdegrees, applied yaw (Y), then pitch (X), then roll (Z): (rx, ry, rz) or rot = {rx, ry, rz}
Quaternionsx, y, z, w; in tables quat = {x, y, z, w}
Colour0..1 per channel, linear (textures are stored as sRGB)
Scalea number (uniform) or {x, y, z}
Lightlumens (lumens) or candela (intensity)
Physics bodiesinteger ids
2Dpixels, x right, y down; 2D rotations in radians

glTF models and Blender scenes are converted to these axes when loaded or exported.

Getting started

Developer tools#

Available when a game runs from a folder; absent from packaged games.

KeyAction
F3performance overlay: frame time graph, GPU time per pass, draw calls, triangles, lights, shadows, culling, Lua memory and garbage per frame, Lua profiler, 3D brush left changed at the end of the frame (with file and line)
F4physics colliders
F5reload main.lua
F6 / F7pause updates / step one frame
F8slow motion: 1 → 0.25 → 0.05 → 1

The Lua profiler (shown in F3) samples the running function every 1000 VM instructions and lists the six most expensive functions, by own time ("self") and including callees, in milliseconds per second. No code changes are needed.

Garbage. Lua runs its collector in generational mode, which deals with short-lived tables in small steps. F3 shows how many kilobytes of garbage each frame makes; a steady few KB is fine, hundreds of KB per frame are worth fixing. The usual sources are option tables and vectors built inside update and draw: keep them in locals and refill them, or use a transform instead of {pos, rot} tables.

local opts = { color = {1, 1, 1}, rot = {0, 0, 0} }   -- made once
function mote.draw()
    opts.rot[2] = t * 90                              -- refilled each frame
    g3.box(0, 1, 0, 1, 1, 1, opts)
end
CallDescription
mote.devtools.watch(name, fn)a line in the F3 overlay showing fn()
mote.devtools.keys.overlay = "f9"rebind (keys: overlay, colliders, reload, pause, step, slow)
mote.devtools.enable(false)turn the tools off for this game
mote.profile.lua(on) / luaReport(n) / luaReset()the Lua profiler from code
mote.profile.scope(name, fn, ...)time a section of code
mote.profile.gc() → {usedKB, allocKBPerFrame}Lua memory in use and garbage per frame
mote.devtools.trackBrush(on)track the 3D brush without opening F3
mote.devtools.brushLeaks() → {{what, "file:line"}}what the brush was left as at the end of the last frame
3D

Camera and drawing#

local g3 = mote.graphics3d
g3.setCamera(0, 2, -6,  0, 1, 0,  60)      -- eye, target, vertical FOV (degrees)
g3.setCamera(headTransform, 75)            -- or from a transform (looks along its +Z)
CallDescription
g3.setCamera(ex, ey, ez, tx, ty, tz, fov?)camera at e looking at t; fov defaults to 60
g3.setCamera(transform, fov?)camera placed by a transform
g3.camerathe camera as a transform; updated by every setCamera; objects can be parented to it
g3.setClipPlanes(near, far)near and far clip planes
g3.screenRay(sx, sy) → ox, oy, oz, dx, dy, dza ray through a screen pixel
g3.worldToScreen(x, y, z) → sx, sy, depthproject a point; nil behind the camera

The brush#

setColor, setMaterial, setEmissive, setSurface, setTransparency and setModelShading apply to everything drawn after them. Every frame starts with the defaults: white, no emission, metallic 0, roughness 0.5, no surface. Three ways to keep a colour from leaking into the rest of the frame:

g3.push("all")                    -- saves the transform and the brush
g3.setColor(1, 0, 0)
g3.setEmissive(4, 0, 0)
g3.sphere(x, y, z, 0.1)
g3.pop()                          -- everything is restored

model:draw(x, y, z, { color = {1, 0.5, 0.5} })    -- tint for this call only

-- primitives take their look per call too; the brush is not touched
g3.box(0, 1, 0, 1, 1, 1, { color = {0.8, 0.2, 0.1}, rough = 0.3 })
g3.sphere(2, 1, 0, 0.5, { color = {1, 1, 1}, metal = 1, rough = 0.1 })
g3.cylinder(4, 1, 0, 0.3, 2, { emissive = {0, 3, 6}, rot = {90, 0, 0} })
Primitive optionEffect
color = {r, g, b, a}base colour for this call
metal = m, rough = rmetallic and roughness for this call
emissive = {r, g, b}emission for this call
surface = s | falsea surface for this call, or none
rot = {rx, ry, rz} | quat = {x, y, z, w}rotation of the primitive, degrees or quaternion
The options table is the last argument of box, cube, sphere, plane, cylinder, cone, capsule, torus, tube, disc, ring, pyramid, wedge, stairs, roundBox, icosphere, prism, hemisphere and shape. If something is coloured wrong, open F3: when a frame ends with the brush changed, the overlay names the file and line that changed it.
3D

Transforms and hierarchy#

A transform is a scene node: a local position, rotation and scale relative to an optional parent. Its world matrix is the parent's world matrix times its own. Transforms are accepted by model:draw, character:draw, g3.setCamera and g3.applyTransform. Level objects (obj.transform) and the camera (g3.camera) are transforms too.

local T = mote.transform
local tank   = T.new{ pos = {0, 0, 10}, rot = {0, 45, 0} }
local turret = T.new{ parent = tank, pos = {0, 1.2, 0} }
local barrel = T.new{ parent = turret, pos = {0, 0.2, 1.5} }

turret:rotate(0, 30 * dt, 0)          -- around its own Y axis
tank:moveLocal(0, 0, 5 * dt)          -- forward along its own +Z
local x, y, z = barrel:getWorldPosition()
local fx, fy, fz = barrel:forward()

Creating#

CallDescription
mote.transform.new{pos, rot, quat, scale, parent, name}a new transform; every field is optional
mote.transform.is(v)true for a transform
mote.transform.eulerToQuat(rx, ry, rz) → x, y, z, wdegrees to quaternion
mote.transform.quatToEuler(x, y, z, w) → rx, ry, rzquaternion to degrees
mote.transform.lookQuat(dx, dy, dz) → x, y, z, wrotation that points +Z along a direction

Local values (relative to the parent)#

CallDescription
t:getPosition() / t:setPosition(x, y, z)position
t:getRotation() / t:setRotation(rx, ry, rz)rotation, degrees
t:getQuat() / t:setQuat(x, y, z, w)rotation, quaternion
t:getScale() / t:setScale(s | sx, sy, sz)scale
t:set{pos, rot, quat, scale, parent, name}several values at once

World values#

CallDescription
t:getWorldPosition() / t:setWorldPosition(x, y, z)world position
t:getWorldRotation() / t:setWorldRotation(rx, ry, rz)world rotation, degrees
t:getWorldQuat() / t:setWorldQuat(x, y, z, w)world rotation, quaternion
t:forward() / t:right() / t:up()unit vectors of +Z, −X, +Y in world space
t:toWorld(x, y, z) / t:toLocal(x, y, z)convert a point between local and world space
t:matrix() / t:localMatrix()16 numbers, column-major
t:setWorldMatrix(m16)set the world matrix

Motion and hierarchy#

CallDescription
t:move(dx, dy, dz)move in the parent's axes
t:moveLocal(dx, dy, dz)move along its own axes
t:rotate(rx, ry, rz)rotate about its own axes, degrees
t:rotateWorld(rx, ry, rz)rotate about the world axes, degrees
t:lookAt(x, y, z, upx?, upy?, upz?)point +Z at a world point
t:setParent(p, keepWorld?)parent: a transform, level object, character or nil. keepWorld (default true) keeps the world placement; false keeps the local values
t:getParent() / t:getName() / t:setName(s) / t:copy()hierarchy and identity
setParent raises an error when the link would create a cycle.
3D

Transform stack#

The stack holds the current matrix applied to everything drawn in 3D after it: primitives, static and animated models, registered meshes, lights and decals. Every frame starts with the identity matrix; the stack is 64 levels deep.

g3.push()
g3.translate(x, 0, z)
g3.rotate(0, yaw, 0)
g3.box(0, 0.25, 0, 1.2, 0.5, 1.2)            -- local coordinates
    g3.push()
    g3.translate(0, 0.5, 0)
    g3.rotate(-20, 0, 0)
    g3.box(0, 0.2, 0.6, 0.25, 0.25, 1.2)
    g3.addLight{ kind = "point", pos = {0, 0.2, 1.4}, lumens = 800 }
    g3.pop()
g3.pop()
CallDescription
g3.push("all"?) / g3.pop()save / restore the matrix; with "all" also the brush
g3.origin()identity matrix
g3.translate(x, y, z)translate
g3.rotate(rx, ry, rz)rotate about the current axes, degrees
g3.rotateQuat(x, y, z, w)rotate by a quaternion
g3.scale(s | sx, sy, sz)scale
g3.applyTransform(v)multiply by a transform, a level object, or a table of 16 numbers
g3.getTransform() → m16the current matrix
g3.transformPoint(x, y, z) → x, y, za point through the current matrix
Not affected by the stack: instanced meshes, particles, the sun and physics. A registerMesh mesh drawn inside a transform goes through a CPU copy; prefer instancing for thousands of draws.
3D

First-person camera and weapons#

local g3, T = mote.graphics3d, mote.transform
local head = T.new{ pos = {0, 1.7, 0} }
local gun  = T.new{ parent = g3.camera, pos = {-0.25, -0.22, 0.45} }   -- right hand: x < 0
local yaw, pitch = 0, 0

function mote.load()
    mote.mouse.setGrabbed(true)
    mote.mouse.setVisible(false)
end

function mote.update(dt)
    local mx, my = mote.mouse.getDelta()
    yaw   = yaw - mx * 0.15
    pitch = math.max(-89, math.min(89, pitch + my * 0.15))
    head:setRotation(pitch, yaw, 0)
    local kb = mote.keyboard
    local f = (kb.isDown("w") and 1 or 0) - (kb.isDown("s") and 1 or 0)
    local s = (kb.isDown("d") and 1 or 0) - (kb.isDown("a") and 1 or 0)
    local fx, _, fz = head:forward()
    local rx, _, rz = head:right()
    head:move((fx * f + rx * s) * 4 * dt, 0, (fz * f + rz * s) * 4 * dt)
end

function mote.draw()
    g3.setCamera(head, 75)
    weapon:draw(gun, { anim = "idle", time = mote.timer.getTime() })
end

g3.setCamera(head) copies the transform into g3.camera, so everything parented to g3.camera follows the view. Recoil and sway are the local position and rotation of gun. With physics, take the head position from a character capsule (mote.physics3d.moveCharacter).

3D

Primitives#

g3.box(x, y, z, w, h, d)          g3.sphere(x, y, z, r)          g3.plane(x, y, z, w, d)
g3.cylinder(x, y, z, r, h)        g3.cone(x, y, z, r, h)          g3.capsule(x, y, z, r, h)
g3.torus(x, y, z, R, r)           g3.tube(x, y, z, rOut, rIn, h)  g3.disc(x, y, z, r)
g3.ring(x, y, z, rIn, rOut)       g3.hemisphere(x, y, z, r)       g3.pyramid(x, y, z, w, h, d)
g3.wedge(x, y, z, w, h, d)        g3.stairs(x, y, z, w, h, d, n)  g3.roundBox(x, y, z, w, h, d, r)
g3.icosphere(x, y, z, r)          g3.prism(x, y, z, sides, r, h)

Coordinates are the shape's centre. An optional last table takes rot (degrees), quat, segments, sides and top (top radius of a cone).

g3.torus(0, 2, 0, 1.5, 0.3, { rot = {90, 0, 0}, segments = 48 })
g3.shape("capsule", x, y, z, { r = 0.3, h = 1.6, quat = {qx, qy, qz, qw} })

-- a collider of the same shape and parameters
local id = mote.physics3d.addShape("torus", "static", 0, 2, 0, { R = 1.5, tube = 0.3, rot = {90, 0, 0} })

A static collider follows the shape's triangles exactly; a moving one uses its convex hull.

3D

Models#

local car = g3.loadModel("models/car.glb")

car:draw(x, y, z)                                     -- position
car:draw(x, y, z, 2)                                  -- position and uniform scale
car:draw(x, y, z, { rot = {0, 90, 0}, scale = 2 })
car:draw(transform)                                   -- a transform, level object or character
car:draw(transform, { anim = "drive", time = t })     -- animated
car:draw(x, y, z, { anim = "run", time = t, blend = { anim = "walk", time = t, w = 0.3 } })
draw optionMeaning
rot = {rx, ry, rz}rotation, degrees
quat = {x, y, z, w}rotation as a quaternion (instead of rot)
scale = s | {sx, sy, sz}scale
offset = {x, y, z}offset in local axes
relativeTo = transformcoordinates are relative to a transform
color = {r, g, b, a}tint for this call
anim = name | indexanimation clip (index from 1)
time = tclip time, seconds
loop = truewrap the time (true) or clamp it (false)
blend = {anim, time, w}blend with a second clip, w = 0..1

Without anim a model is drawn from the GPU cache with one matrix. With anim the pose is evaluated on the CPU this frame.

CallDescription
g3.loadModel(path) → modelload glTF / GLB
model:animations() → {names}clip names
model:duration(anim) → secondsclip length
model:bones() → {names}node names
model:triangles() → {verts, indices}triangles in model space
model:pose() → posea pose for procedural animation, IK and ragdolls
model:rootMotion(anim, t0, t1, bone?) → dx, dy, dz, dyawroot movement between two clip times

Supported glTF features: multiple meshes and nodes, node hierarchy, skinning, node and bone animation, morph targets, metallic-roughness PBR materials, KHR_texture_transform, a second UV set. Missing tangents are computed at load time.

3D

Loading and streaming assets#

Textures of all models are decoded in parallel on every core; identical images in different files are loaded once; textures larger than the limit (4096 px on the longest side by default) are downscaled while loading. mote.level.load decodes the textures of all its models before creating objects.

CallDescription
g3.setTextureMaxSize(n)texture size limit for models loaded afterwards; 0 = no limit
g3.preloadModels({paths}) → ndecode the textures of several models ahead of time

Background loading#

The synchronous loaders block the frame while they work. mote.loader decodes on worker threads while the game keeps running; meshes are finished on the main thread when ready.

mote.loader.model("models/castle.glb", function(model, err) castle = model end)
mote.loader.image("ui/map.png", function(img) map = img end)
mote.loader.level("levels/act1.json", { navmesh = true }, function(level) lvl = level end)

function mote.draw()
    if not mote.loader.idle() then
        local done, total = mote.loader.progress()
        mote.graphics.print(("Loading %d / %d"):format(done, total), 20, 20)
    end
end
CallDescription
mote.loader.model(path, cb) / image(path, cb) / level(path, opts?, cb)start a background load; cb(result, err)
mote.loader.progress() → done, totalprogress of the current batch
mote.loader.idle()true when nothing is loading
g3.loadModelAsync(path) → handlelow level: handle:ready(), :result(), :error()
mote.graphics.loadImageAsync(path) → handlethe same for images
3D

Materials and procedural textures#

CallDescription
g3.setColor(r, g, b, a?)base colour; a < 1 makes it transparent
g3.setMaterial(metallic, roughness)PBR parameters
g3.setEmissive(r, g, b)emission of the next primitives (values above 1 glow)
g3.setTransparency{transmission, ior, thickness, opacity, ...}refractive glass or plain transparency
g3.setModelShading(name, param?)shading model: standard, skin, cloth, hair
g3.newSurface{...} → surfacea set of maps (albedo, orm, normal, height) from files, a preset or a generator
g3.setSurface(surface | nil)use a surface for the next primitives
g3.decal(image, x, y, z, nx, ny, nz, size, roll?, r?, g?, b?, a?)a decal on the geometry

Procedural materials#

Built-in materials are generated natively on all cores; a 512×512 material takes tens of milliseconds, so they can be built during play.

local wall, tiling = mote.texgen.preset("concrete", { seed = 3, size = 512 })
g3.setSurface(wall)
g3.box(0, 1.5, 4, 8, 3, 0.2)
g3.setSurface(nil)

Presets: wallpaper, carpet, ceiltile, paint, plaster, concrete, lino, damask, hotelcarpet, wood, tile, polished, metal, flesh. Options: seed, size (power of two, 16–2048), tiling, bump, color and any newSurface key.

Noise fields for your own generators tile seamlessly and return a flat 1-based array of n×n values in 0..1, row by row:

CallDescription
mote.texgen.noise(n, cellsX, cellsY?, seed)value noise
mote.texgen.fbm(n, cells, seed, octaves?, gain?)fractal value noise
mote.texgen.perlin(n, cellsX, cellsY?, seed?)gradient noise
mote.texgen.worley(n, cellsX, cellsY?, seed?, kind?, jitter?)cellular noise; kind: "f1", "f2", "edge", "cell"
mote.texgen.white(n, seed)white noise
mote.texgen.surface{size, generate = fn(u, v), ...}a surface from a Lua function returning r, g, b, height, rough?, metal?, ao?
3D

Lights and shadows#

g3.setLight(-0.4, -1, -0.3)                 -- sun direction
g3.setSunColor(1, 0.95, 0.9, 3)             -- colour and strength
g3.setAmbient(0.02, 0.02, 0.03)
g3.setEnvironment{ sky = {0.45, 0.55, 0.75}, horizon = {0.75, 0.72, 0.7}, ground = {0.3, 0.28, 0.26}, drawSky = true }

g3.addLight{ kind = "point", pos = {0, 2.5, 0}, color = {1, 0.8, 0.6}, lumens = 800, range = 10, shadow = true }
g3.addLight{ kind = "spot", pos = {0, 4, 0}, dir = {0, -1, 0}, cone = {20, 30}, lumens = 1500 }
g3.addLight{ kind = "rect", pos = {0, 3.58, 2}, dir = {0, -1, 0}, right = {1, 0, 0}, width = 2.4, height = 0.6, lumens = 5000 }

Lights are added every frame in mote.draw and follow the transform stack.

addLight keyMeaning
kind"point", "spot", "sphere", "tube", "rect"
pos, dir, rightposition, direction, width axis (rect, tube)
lumens | intensityluminous flux or candela
rangereach, metres
cone = {inner, outer}spot cone or barn doors of a panel, degrees
radius, length, width, heightsize of area lights
profile = idphotometric profile from g3.newLightProfile
shadow, shadowPriorityshadow and its priority in the shadow budget

Area lights (rect, tube, sphere) are integrated over their shape: diffuse light uses the polygon form factor clipped at the horizon, specular uses an LTC fit of GGX, so highlights take the shape of the lamp.

CallDescription
g3.newLightProfile(path) → id, peakprofile from an IES LM-63 file
g3.newLightProfile{angles, values} | fn(deg)profile from a table or a function
mote.render.lights{clustered = true}clustered lighting for hundreds of lights
mote.render.shadows{...}sun cascades
mote.render.localShadows{budget, ...}shadow-map budget for local lights
mote.render.gi{...}global illumination with a probe grid
3D

Image settings#

mote.render.apply{
    tonemap = "agx", autoExposure = 0.18, bloom = 0.1,
    ssao = 1, ssr = 0.7, ssgi = 0.5, taa = true,
    motionBlur = 0.5, dof = 0, vignette = 0.3, grain = 0.02,
    renderScale = 0.75,                       -- render at 75 % and upscale with TAA
}

Each key is independent; keys you leave out keep their values. Retro mode: pixelate, vertexSnap, affine, colorDepth, dither, posterize.

CallDescription
g3.setFog(r, g, b, density)exponential fog
g3.addFogVolume{shape, pos, size, density, color}a local fog volume
mote.graphics.setVolumetric(strength, density, phase)volumetric light
mote.render.lut(path | fn | nil, strength?)a .cube 3D LUT (up to 129³) or one built from a function; applied after tonemapping
mote.render.lutStrength(s)LUT strength 0..1
3D

GPU-driven rendering#

Static geometry is drawn by the GPU itself. Static models (their opaque parts), meshes registered with registerMesh and drawn with drawMesh, and primitives (box, sphere, cylinder and the rest) are cut into clusters of up to 64 triangles once. Each frame, compute shaders test every cluster against the camera frustum and against a depth pyramid of what is already drawn, and the G-buffer is drawn with one call per texture set. Shadow maps are culled the same way. Nothing needs to be set up: it is on by default, and the same code draws the same picture either way.

What it changes in practice:

Registering a mesh id again replaces its geometry on the GPU, and removeMesh frees it, so worlds that stream chunks in and out (voxel terrain, tiles) keep a bounded pool. Meshes with an LOD chain (setMeshLOD) keep the classic path, which picks the level.

Occlusion is two-phase: objects visible last frame are drawn first, a depth pyramid is built from them, and everything else is tested against it. Nothing that is visible is ever skipped, even when the camera jumps.

CallDescription
mote.render.gpuScene(on?) → onturn GPU-driven drawing on or off; returns the state (false on hardware without it)
mote.render.gpuSceneStats() → tableentries, clusters, drawn, culled, materials, shadowClusters, poolTriangles of the last frame; reads the GPU back, so use it for debugging only
These go the classic way, automatically: transparent and alpha-tested materials, primitives with a surface, a texture or setVelocity, animated models, and all primitives in a frame that has a mirror, water, probe GI, voxel GI or a reflection-probe bake (those passes re-render the scene from another eye).
-- measure what the GPU culled
mote.render.gpuSceneStats()                -- turns the counters on
function mote.update(dt)
    local s = mote.render.gpuSceneStats()
    print(s.drawn, "of", s.clusters, "clusters drawn")
end
3D

Terrain#

local ter = mote.terrain.new(mote.terrain.preset("hills"))
ter:physics{ radius = 64 }                 -- streamed colliders around the drawn point

function mote.draw()
    ter:draw(player.x, player.z)           -- stream, build and draw chunks around a point
end
CallDescription
mote.terrain.preset(name) → cfgdunes, hills, mountains, islands, mesa, plains
mote.terrain.new(cfg) → terrainterrain from a configuration
ter:draw(x, z)stream and draw around a point
ter:height(x, z) / normal(x, z) / slope(x, z) / color(x, z)surface queries
ter:raycast(ox, oy, oz, dx, dy, dz, max?, step?)ray against the surface
ter:set{...} / ter:rebuild()change settings; rebuild re-creates chunks and colliders
ter:physics{tile, cell, radius, friction, perFrame}heightfield colliders: tiles of tile m (32), sample spacing cell m (1), within radius m (64); at most perFrame new tiles per frame (4), the tile under the point always
ter:physics(false) / updatePhysics(x, z) / physicsTiles()remove, stream without drawing, count
2D

2D graphics#

local g = mote.graphics
local hero = g.loadImage("textures/hero.png")

function mote.draw()
    g.clear(0.1, 0.1, 0.12)
    g.setColor(1, 0.5, 0.2)
    g.rectangle("fill", 20, 20, 100, 60)
    g.circle("line", 200, 60, 30)
    g.setColor(1, 1, 1)
    g.draw(hero, 300, 100, 0, 2, 2)              -- image, x, y, rotation (radians), scale
    g.draw(hero, 400, 100, { scale = 2, color = {1, 0.3, 0.3} })   -- options, tint for this call
end

2D is drawn over the 3D frame. Colour, font, blend mode and line width are state; colour resets to white every frame, the font is kept.

g.push("all")                                 -- saves transform, colour, font, blend, line width
g.setFont("bold", 32)
g.setColor(1, 0.2, 0.2)
g.print("TITLE", 20, 20)
g.pop()

g.print("Score", 20, 60, { font = "bold", size = 24, color = {1, 0.8, 0.2} })
g.print(longText, 20, 100, { width = 300, align = "center" })

Also: transforms (push, pop, translate, rotate, scale, shear), canvases, shaders, 2D lights and shadows (mote.light2d), cameras (mote.camera2d), tilemaps with auto-tiling (mote.tilemap, mote.autotile, Tiled import), particles.

2D

Pixel art#

local g = mote.graphics
g.setVirtualResolution(320, 180)     -- 320×180, whole-number scaling, centred in the window
g.setPixelSnap(true)                 -- sprites and text land on whole virtual pixels

function mote.draw()
    local mx, my = g.toVirtual(mote.mouse.getPosition())
    g.draw(cursor, mx, my)
end
CallDescription
g.setVirtualResolution(w, h, {integer = true})draw 2D in a w×h space; scaled by the largest whole factor (integer = false allows fractions); outside it the clear colour shows; nil turns it off
g.getVirtualResolution() → w, h, scalecurrent values or nil
g.setPixelSnap(on)move sprites onto whole pixels without resizing them
g.toVirtual(x, y)window pixel → virtual pixel
g.getDimensions()size of the 2D area (the virtual size when set)
Magnified sprites are sampled without interpolation. mote.gui and mote.ui work in virtual coordinates.
2D

2D skeletal animation#

local def = mote.skeleton2d.new{
    bones = {
        { name = "root" },
        { name = "hip",   parent = "root", y = -60 },
        { name = "thigh", parent = "hip", rot = 90, len = 30 },
        { name = "shin",  parent = "thigh", x = 30, len = 30 },
    },
    slots = { { name = "leg", bone = "thigh", attachment = "leg" } },     -- draw order
    attachments = {
        leg  = { type = "region", image = legImage, x = 15 },
        cape = { type = "mesh", image = capeImage, verts = {...}, uvs = {...}, tris = {...}, bones = { "hip", "thigh" } },
    },
    ik = { { name = "foot", bones = { "thigh", "shin" }, bend = 1 } },
    animations = {
        walk = { duration = 1, bones = { thigh = { rotate = { {0, -20}, {0.5, 20}, {1, -20} } } } },
    },
}

local hero = def:instance()
hero:play("walk", { loop = true, mix = 0.2 })

function mote.update(dt) hero:update(dt) end
function mote.draw()
    hero:setIK("foot", targetX, targetY)
    hero:draw(400, 300, { scale = 2, flipX = facingLeft })
end

Coordinates are screen-style: x right, y down, rotation in degrees clockwise. A mesh without weights gets automatic weights from the distance to its bones (the two nearest).

CallDescription
mote.skeleton2d.new(spec) → definitiona skeleton definition shared by instances
mote.skeleton2d.loadSpine(path, {images}) → definitionSpine JSON 3.8 / 4.x: bones, slots, region and mesh attachments (weighted or not), rotate/translate/scale and attachment timelines, two-bone IK; curves become linear
def:instance() → instan animated instance
inst:play(name, {loop, mix, speed, track, alpha, onEnd})play a clip; higher tracks layer over lower ones
inst:update(dt) / inst:draw(x, y, {scale, flipX, rot, color, debug})advance and draw
inst:setIK(name, x, y, mix?) / inst:boneWorld(name) → x, y, rotIK target, bone placement
inst:setBone(name, {rot, x, y}) / inst:setAttachment(slot, name)manual overrides
g.drawTriangles(image, {x, y, u, v, ...})textured triangles in 2D
Physics

Bodies and queries#

local P = mote.physics3d
P.setGravity(0, -9.81, 0)
P.newBox("static", 0, -0.5, 0, 50, 1, 50)
local crate = P.newBox("dynamic", 0, 3, 0, 1, 1, 1, 0.1, 0.8)   -- restitution, friction
crate.owner = { name = "crate", hp = 30 }                        -- any value you like

function mote.update(dt)
    P.update(dt)
    local hit = P.raycast(0, 10, 0, 0, -1, 0, 20)
    if hit and hit.body.owner then hit.body.owner.hp = hit.body.owner.hp - 1 end
end
function mote.draw()
    local x, y, z = crate:getPosition()
    g3.push()
    g3.translate(x, y, z)
    g3.rotateQuat(crate:getRotation())
    g3.box(0, 0, 0, 1, 1, 1)
    g3.pop()
end

A body is an object made by one of the new* constructors. They take the same arguments as the add* functions, which return a plain integer id instead. Both work everywhere: every physics function accepts a body or an id, P.bodyOf(id) returns the object for any id, and ray hits and contact events carry the objects (hit.body, contact.bodyA, contact.bodyB). Bodies of a level exported from Blender have their level object as owner.

Body typeBehaviour
"static"never moves
"dynamic"moved by forces and collisions
"kinematic"moved by setPosition / setRotation; pushes dynamic bodies

Shapes: box, ball, capsule, cylinder, convex, trimesh (static only), heightfield, autoConvex (decompose a model into convex parts), addShape (primitive shapes). Body rotations are quaternions.

CallDescription
P.getPosition(id) / P.setPosition(id, x, y, z)position
P.getRotation(id) / P.setRotation(id, x, y, z, w)rotation
P.setVelocity / getVelocity / getAngularVelocityvelocity
P.applyImpulse / applyForce / applyForceAtPoint / applyImpulseAtforces
P.setMass / setDamping / setCcd / wakebody settings
P.raycast(ox, oy, oz, dx, dy, dz, max) → hit{id, x, y, z, nx, ny, nz, distance} or nil
P.sphereCast / P.capsuleCastswept queries
P.moveCharacter(id, dx, dy, dz, dt) → mx, my, mz, groundedmove a capsule with collisions, steps and slopes
P.remove(id)remove a body
Body objectDescription
P.newBox / newBall / newCapsule / newCylinder / newConvex / newTrimesh / newHeightfield / newGround / newSensorBox / newSensorBall → bodycreate a body object; arguments as the matching add*
P.bodyOf(id) → bodythe object for an id
P.isBody(v)true for a body object
body.id / body.ownerthe integer id; your own value
body:getPosition() / setPosition / getRotation / setRotation / getVelocity / setVelocity / getAngularVelocitystate
body:applyImpulse / applyForce / applyForceAtPoint / applyImpulseAtforces
body:setMass / getMass / setDamping / setCcd / wake / setGroups / setContactEventssettings
body:move(dx, dy, dz, dt) → mx, my, mz, groundedcharacter movement (kinematic bodies)
body:draw(opts?)draw the collider shape
body:remove() / body:isValid()remove; false once removed (also after P.remove(id))
A body stays in the world until it is removed: drop your reference to the object and the collider is still there. Remove bodies together with the game object that owns them.
Physics

Joints, ragdolls, vehicles#

local P = mote.physics3d
local hinge = P.addRevoluteJoint(post, door, 0, 1, 0,  0, 0, 0,  0.5, 0, 0)   -- axis, anchor on A, anchor on B
P.setJointMotor(hinge, { velocity = 2.5, maxForce = 4000 })
P.setJointLimits(hinge, -1.2, 1.2)                     -- radians (hinge) or metres (slider)

local lift = P.addPrismaticJoint(base, platform, { axis = {0, 1, 0}, limits = {0, 3} })
P.setJointMotor(lift, { position = 2, stiffness = 6000, damping = 900 })

P.addRopeJoint(hook, weight, 3)
P.addSpringJoint(a, b, rest, stiffness, damping)
P.addFixedJoint(a, b)
P.setJointBreak(hinge, 5000)
for _, id in ipairs(P.pollBreaks()) do print("joint broke", id) end

Ragdolls from a model skeleton: model:pose():ragdoll{ mass = 70 }, or character:die{...}.

local body = P.addBox("dynamic", 0, 1, 0, 1.8, 0.6, 4.0)
P.setMass(body, 1200)
local car = P.newVehicle(body, { engine = { power = 400, topSpeed = 30 }, wheels = {
    { x = -0.85, y = -0.25, z =  1.3, radius = 0.38, steer = true },
    { x =  0.85, y = -0.25, z =  1.3, radius = 0.38, steer = true },
    { x = -0.85, y = -0.25, z = -1.3, radius = 0.38, drive = true },
    { x =  0.85, y = -0.25, z = -1.3, radius = 0.38, drive = true } } })
P.vehicleControl(car, { throttle = 1, steer = 0.3, brake = 0, handbrake = false })

Also: buoyancy (setWater, setBuoyancy), force fields and explosions (addField, explode).

Physics

Contacts, triggers, layers#

local P = mote.physics3d
P.setContactEvents(crate, 150)                       -- report hits stronger than 150 N
for _, c in ipairs(P.pollContacts()) do
    -- c.a, c.b, c.force, c.x, c.y, c.z, c.nx, c.ny, c.nz
end

local zone = P.addSensorBox(0, 1, 5, 2, 2, 2)
for _, e in ipairs(P.pollTriggers()) do
    if e.enter then print("entered", e.a, e.b) end
end

P.setGroups(id, P.layers.debris, P.layers.all - P.layers.player)
P.setGroups(id, P.layers.trigger, P.layers.player, false)    -- events without a collision response
Physics

Destruction#

local wall = mote.ruin.box{ size = {6, 3, 0.4}, pos = {0, 1.5, 6}, material = "concrete", pieces = 70 }
local vase = mote.ruin.model(vaseModel, { material = "ceramic" })

wall:impact(x, y, z, dx, dy, dz, power)
wall:explode(x, y, z, radius, power)
wall:damage(x, y, z, radius, amount)

function mote.update(dt) mote.physics3d.update(dt); wall:update(dt) end
function mote.draw() wall:draw() end

Voronoi fracture, cracks along a connectivity graph, collapse of unsupported pieces, re-fracture on hard impacts, small debris, and merging of settled rubble into one static mesh. Materials: mote.ruin.materials(). Options: pieces, seed, pattern, anchor, color, interior, lifetime, fade, chips, maxLoose, refracture, solid. Queries: raycast, owns, events, info, reset, remove.

Physics

2D physics#

mote.physics mirrors the 3D API in 2D: box, circle, capsule, convex, polyline and heightfield bodies; fixed, revolute, spring and rope joints; sensors; raycasts; collision layers. Soft bodies and ropes: mote.softbody, mote.rope.

Blender

The add-on#

Panels in the 3D viewport sidebar (N), tab mote:

PanelContents
mote: assetsgame folder; export the selection as separate models, as one model or as a collection; Only changed models skips unchanged files
mote: objectrole, script, tags, asset name, physics, navmesh, hidden in game, volume and path settings
mote: characteranimation states and transitions, collider, character export
mote: levellevel name, world, navmesh, markers, Export level, Export and run
In BlenderIn the game
Mesh, curve with geometry, texta level object with a model models/name.glb
Armature with meshes and actionsa character: models/name.glb and name.anim.json
Collection instancea prefab; the collection is exported once
Curve with role Patha path: level:path, level:pathPoint
Emptya marker or a volume (trigger, fog); part of the hierarchy
Light, cameraa light; a camera for level:useCamera
Parentthe parent of the object's transform
Object keyframes (actions, NLA)scene clips (see Scene animation)
Custom propertiesobj.props

Axes are converted from Blender's Z-up to mote's Y-up. Models go to models/, the level to levels/name.json. Re-exporting while the game runs reloads the level and its models in the game.

Blender

Levels in the game#

local lvl
function mote.load()     lvl = mote.level.load("levels/house.json") end
function mote.update(dt) lvl:update(dt) end      -- physics, clips, behaviours, events
function mote.draw()     lvl:draw() end          -- models, lights, world

Every Blender object is a level object with its own transform (obj.transform). The Blender hierarchy is kept: moving a parent moves its children. Colliders of static and kinematic objects follow their objects; dynamic bodies drive theirs.

local door = lvl:find("Door")
door:rotate(0, 90, 0)
local lamp = lvl:find("Lamp")
lamp:setParent(g3.camera)                 -- carry it with the view
for _, crate in ipairs(lvl:withTag("crate")) do crate:hide() end

Object methods#

CallDescription
obj:getPosition() / obj:setPosition(x, y, z)world position
obj:getRotation() / obj:setRotation(rx, ry, rz)world rotation, degrees
obj:getQuat() / obj:setQuat(x, y, z, w)world rotation, quaternion
obj:move(dx, dy, dz) / obj:moveLocal(dx, dy, dz)move in world / own axes
obj:rotate(rx, ry, rz) / obj:rotateWorld(rx, ry, rz)rotate about own / world axes
obj:lookAt(x, y, z)point +Z at a point
obj:forward() / obj:right() / obj:up()world directions
obj:toWorld(x, y, z) / obj:toLocal(x, y, z)convert points
obj:setParent(p, keepWorld?)parent: another object, a transform or nil
obj:getParent() / obj:children()hierarchy
obj:show() / obj:hide() / obj:setVisible(on)visibility of the object and its children
obj:play(clip, opts?) / obj:stop() / obj:isPlaying(clip?)play a clip on this object only

Fields: obj.name, obj.props, obj.tags[tag], obj.model, obj.body, obj.light, obj.char, obj.hidden, obj.size, obj.transform. obj.x/y/z and obj.qx/qy/qz/qw hold the world placement and are refreshed every frame; assigning them moves the object.

Level methods#

CallDescription
lvl:find(name) / lvl:withTag(tag) / lvl:each(fn) / lvl:byBody(id)look objects up
lvl:spawn(template, x, y, z) / lvl:remove(obj)copy / remove an object
lvl:use(obj, who) / lvl:nearestUsable(x, y, z, range, dx, dy, dz)interaction
lvl:path(name) / lvl:pathPoint(name, metres)paths
lvl:useCamera(name)a camera from Blender
lvl:characters() / lvl:spawnPoints(tag?)characters, spawn points
lvl:draw{world, lights, debug, navmesh}draw; keys turn parts on or off

Behaviours#

The Script field in Blender links an object to a behaviour; one instance per object.

mote.level.behavior("door", {
    init   = function(self, obj, lvl) self.open = false end,
    use    = function(self, obj, lvl, who) self.open = not self.open end,
    update = function(self, obj, dt, lvl)
        obj.transform:setRotation(0, self.open and 90 or 0, 0)
    end,
    enter   = function(self, obj, other, lvl) end,          -- triggers
    leave   = function(self, obj, other, lvl) end,
    contact = function(self, obj, other, force, lvl) end,   -- hits above the threshold
})

An object whose model file is missing is drawn as a box of its bounds.

Blender

Scene animation#

Object keyframes in Blender — doors, lifts, machinery, a cut-scene made of many meshes — are exported as tracks, one per object and clip, sampled per frame in the parent's space. Tracks with the same clip name are grouped, so one name plays the whole scene.

lvl:play("Open")
lvl:play("Intro", { loop = false, speed = 1, from = 0, onEnd = function(lvl, name) end })
lvl:stop("Intro")                  lvl:stop()
lvl:isPlaying("Open")              lvl:clipTime("Open")      lvl:setClipTime("Open", 1.5)
lvl.clips.Open.duration            lvl.clips.Open.objects
obj:play("Spin", { loop = true })

A channel that does not change in a clip is not written, so that axis can be driven from code while the clip plays.

Blender

Characters#

In Blender: an armature with meshes and actions. The mote: character panel defines states (a clip, or a blend by a parameter), transitions (by trigger, parameter, flag or end of clip) and events (pose markers), and exports models/name.glb with models/name.anim.json.

local hero = mote.character.load("models/hero.glb")
hero:play("run")
hero:set("speed", 3.5)
hero:trigger("jump")
hero:on("step", function(name, clip) playFootstep() end)

function mote.update(dt) hero:update(dt) end
function mote.draw() hero:draw(heroTransform) end
CallDescription
mote.character.load(path, opts?) → charmodel and states from .anim.json; without the file every clip is a state
char:play(state, fade?)go to a state, fade in seconds (0.2)
char:set(param, value) / char:trigger(name)parameters and triggers for transitions
char:on(event, fn) / char:onState(fn)clip events and state changes
char:update(dt)advance the animation
char:draw(transform, scale?)draw at a transform or level object; stays upright (uses the yaw)
char:state() / clip() / states() / clips() / setSpeed(k)state queries

IK, layers, root motion, ragdoll#

Pose pipeline: animation → layers → foot IK → ragdoll → your pose edits → draw.

hero:footIK{ maxStep = 0.45 }                       -- feet on stairs and slopes
hero:addLayer("upper", { mask = "Spine" })          -- upper body plays its own clip
hero:layerPlay("upper", "aim", { fadeIn = 0.2 })
hero:rootMotion(true)
local dx, dz, dyaw = hero:takeRootMotion(yaw, scale)
hero:die{ impulse = { ix, iy, iz }, bone = "Head" }  -- ragdoll that keeps its momentum
hero:getUp(0.8)
hero:onPose(function(pose) pose:lookAt("Head", tx, ty, tz) end)
CallDescription
char:footIK{maxStep, ignore, legs, align} / footIKWeight(w)foot IK and its weight
char:addLayer(name, {mask, exclude, maskWeights, additive})a body-part layer
char:layerPlay(name, clip, {fadeIn, fadeOut, loop}) / layerWeight / layerStoplayer control
char:rootMotion(on) / takeRootMotion(yaw, scale) → dx, dz, dyawmovement from the clip
char:die{impulse, bone, mass} / flinch(impulse, bone, time) / getUp(time)ragdoll
Legs for IK are found by bone names (foot, its parent the knee, its parent the thigh) or given as legs = {{"thigh_l", "calf_l", "foot_l"}, ...}. Remove the character's capsule from physics before die.
Interface

Menus and HUD#

local gui = mote.gui.new{ reference = { 1280, 720 } }      -- designed for 1280×720, fitted to any window

gui:build{ type = "column", id = "menu", anchor = "center", width = 520, padding = 24, gap = 14,
    { type = "label", rich = true, align = "center", text = "[size=44][b]MY GAME[/b][/size]" },
    { type = "row", gap = 10, justify = "between",
        { type = "button", text = "New game", grow = 2, onClick = startGame },
        { type = "button", text = "Options",  grow = 1, onClick = openOptions },
        { type = "button", text = "Quit", width = "25%", onClick = mote.quit } },
    { type = "slider", id = "volume", min = 0, max = 1, value = 0.8, onChange = setVolume },
}
gui:get("menu"):show{ fade = 0.4, slide = { 0, 40 } }

function mote.update(dt) gui:update(dt) end
function mote.draw() gui:draw() end

Widgets: column, row, panel, grid, scroll, label, button, textField, slider, checkbox, progress, image, spacer. Keyboard and gamepad-style navigation: Tab, arrows, Enter.

Layout keyMeaning
justifymain axis: start, center, end, between, around, evenly
align / alignSelfcross axis: stretch, start, center, end
width / heightpixels, "50%" of the parent, or "fill"
growshare of the free space
minWidth / maxWidth / minHeight / maxHeightsize limits
gap / paddingspacing; padding = n or {l, t, r, b}
anchortop-level position: topleft, top, center, bottomright, ...
CallDescription
gui:build(spec) / gui:get(id)build from a table; find by id
w:animate{alpha, dx, dy, scale, duration, ease, delay, onDone}animate (ease names from mote.ease)
w:show{fade, slide, pop} / w:hide{...}transitions
w:setText(s) / setValue(v) / getValue() / setVisible(on) / setEnabled(on)widget state

Rich text#

mote.text.icons.coin = coinImage
mote.text.richDraw("[b]Gold:[/b] [img=coin] [color=#ffd040]120[/color]", 20, 20, { width = 300, size = 20 })

Tags: [b], [color=name|#rrggbb], [size=N], [img=name]. Text wraps by words when a width is given. In mote.gui, use a label with rich = true. For debug panels drawn every frame there is the immediate-mode mote.ui.

Production

Localization#

mote.locale.load("en", "lang/en.json")       -- {"menu.play": "Play", "enemies": {"one": "{n} enemy", "other": "{n} enemies"}}
mote.locale.load("csv", "lang/strings.csv")  -- key,en,de,ru,...
mote.locale.set("en")

local L = mote.locale.t
L("menu.play")                               -- "Play"
L("hello", { name = "Ada" })                 -- "Hello, {name}!" → "Hello, Ada!"
L("enemies", { n = 5 })                      -- "5 enemies"
mote.locale.number(1234567.5, 1)             -- "1,234,567.5"
mote.locale.money(19.99, "USD")              -- "$19.99"
mote.locale.date(os.time())
mote.locale.onChange(function(lang) rebuildMenus() end)

Plural forms: Russian, Ukrainian, Belarusian, Polish — one/few/many; Japanese, Chinese, Korean — other; others — one/other. A missing key returns the key. The fallback language is mote.locale.fallback (en). Right-to-left scripts are not supported.

Production

Game feel#

mote.juice.hitStop(0.06)                       -- freeze for 60 ms on a hit
mote.juice.impulse(0.6)                        -- camera shake
mote.juice.flash(1, 1, 1, 0.5, 0.15)           -- screen flash
local fov = mote.juice.fov(75, running and 85 or 75)

function mote.draw()
    g3.setCamera(head, fov)
    mote.juice.applyCamera(fov)                -- add the shake to the camera
end
CallDescription
mote.juice.hitStop(seconds)mote.update receives dt = 0 for this long
mote.juice.slowMo(scale, seconds)slow motion easing back to normal
mote.juice.impulse(amount, {decay, freq, angle, offset})add camera trauma 0..1
mote.juice.applyCamera(fov) / shake2d(maxPixels) → dx, dy, rotuse the shake in 3D / 2D
mote.juice.flash(r, g, b, a, seconds)a fading full-screen flash
mote.juice.fov(base, target, speed) → fovsmoothed field of view
mote.juice.timeScale()the current time multiplier

Related modules: mote.camera2d (dead zone, bounds, shake), mote.gamestate (states with enter/exit/pause/resume), mote.save (slots, versions, migration), mote.mixer (buses and crossfades).

Production

Audio#

local A = mote.audio
local step = A.load("sounds/step.ogg")
A.play(step, { volume = 0.8, pitch = 1.1 })
A.playAt(step, x, y, z, { volume = 1 })                    -- 3D sound
local beep = A.synth{ preset = "blip" }                    -- synthesized
A.play(beep)
A.setReverb("room")
local id = A.play(music, { loop = true })
A.set(id, "volume", 0.3)
A.stop(id, 1.0)                                            -- fade out over 1 s

Synth presets: coin, laser, explosion, powerup, hit, jump, blip, shoot, alarm, footstep, zap, teleport (A.synthPresets()), with waveforms, envelope, filters, vibrato and slides. Buses, effects and music: A.bus, A.setEffects, A.playMusic, mote.mixer.

Production

Input#

CallDescription
mote.keyboard.isDown(key) / wasPressed(key)keyboard
mote.mouse.getPosition() / getDelta() / isDown(b) / wasPressed(b) / getWheel()mouse
mote.mouse.setGrabbed(on) / setVisible(on)capture the mouse
mote.gamepad.isDown(i, button) / getAxis(i, axis)gamepads
mote.input, mote.actionactions bound to several keys and gamepad buttons
Production

Multiplayer#

mote.network is the transport; mote.net is a multiplayer layer on top: replicated entities, delta snapshots, client prediction, interpolation, RPCs and lag compensation. The transport is UDP with a "reliable" channel (ordered, large messages split) and an "unreliable" one.

local N = mote.net

-- server
N.startServer(27015, { name = "Room", game = "mygame", maxClients = 8 })
N.onConnect(function(cid)
    N.setOwner(N.spawn("player", { x = 0, z = 0, hp = 100 }), cid)
end)
N.onInput(function(cid, cmd, dt)
    local e = N.ownedEntity(cid)
    e.x = e.x + (cmd.mx or 0) * 5 * dt
end)

-- client
N.connect("192.168.1.5", 27015)
N.setInputSampler(function() return { mx = axisX() } end)
N.setPredict(function(e, cmd, dt) e.x = e.x + (cmd.mx or 0) * 5 * dt end)

-- both
function mote.update(dt) N.update(dt) end
CallDescription
N.rpc(name, fn) / N.call(name, ...)remote calls
N.sync(name, value)a shared variable
N.onSpawn(fn) / N.onDespawn(fn)entity events on clients
N.entities / N.allEntities()entities on a client (interpolated) / on the server
N.enableLagComp(seconds) / N.hitscan(cid, origin, dir)lag-compensated hits
N.setInterest{mode = "radius", radius}send only nearby entities
mote.network.discover(port, game) / servers()find servers on the local network
mote.network.ping() / stats() / simulate{lag, jitter, loss}diagnostics

Transport only#

local net = mote.network
net.host(27015, { name = "srv", maxClients = 16 })
net.onReceive = function(id, msg) local t = mote.deserialize(msg) end
net.sendTo(id, mote.serialize({ hp = 5 }))            -- reliable by default
net.broadcast(data, "unreliable")

Over the internet the server needs a reachable UDP port.

Production

Packaging and release#

mote.exe fuse  mygame  MyGame.exe            # one executable with the game inside (encrypted)
mote.exe lpak  mygame  game.lpak             # a package to place next to mote.exe
mote.exe fuse  mygame  MyGame.exe --plain    # without encryption
mote.exe web   mygame  out --serve           # a browser build (WebAssembly)

From a running game: mote.build.exe(name), mote.build.lpak(), mote.build.verify(name).

Encryption: AES-256-GCM archive with hidden file names and a random key per build, wrapped by the engine key; in an executable the key is bound to the file's bytes. Save files are encrypted with a separate key. This protects against unpackers and casual inspection, not against analysis with a debugger.

Excluded from builds: dot files and folders, build/, dist/, *.blend*, *.psd, *.kra, *.xcf, *.py, *.exe, *.lpak. Add rules in a .moteignore file: name, folder/, *.ext, prefix*, # comments.

Reference

Built-in Lua libraries#

Loaded at start; no require needed.

mote.json, mote.save, mote.dataJSON, save games, data tables
mote.ai, mote.navmesh, mote.crowdAI, navigation, crowds
mote.anim, mote.ease, mote.curvetweens, easing functions, curves
mote.ecs, mote.events, mote.reactive, mote.async, mote.gamestateentities, events, reactive values, coroutines, game states
mote.gui, mote.ui, mote.textinterfaces and text
mote.camera, mote.camera2dcameras
mote.vfx, mote.particleeffects
mote.noise, mote.rng, mote.geom, mote.spatialnoise, random numbers, geometry, spatial queries
mote.loader, mote.locale, mote.juice, mote.skeleton2dbackground loading, localization, game feel, 2D skeletons
Reference

Deprecated functions#

Kept so existing games keep working. Use the replacement in new code.

DeprecatedUse instead
model:drawAt(x, y, z, rx, ry, rz, sx, sy, sz)model:draw(x, y, z, {rot = {rx, ry, rz}, scale = {sx, sy, sz}})
model:drawRot(x, y, z, yawRadians, s)model:draw(x, y, z, {rot = {0, degrees, 0}, scale = s})
model:drawFull(...) (radians)model:draw(x, y, z, {rot = {...}}) or a transform
model:drawAnimated(anim, t, x, y, z, s)model:draw(x, y, z, {anim = anim, time = t, scale = s})
model:drawAnimatedRot, drawAnimatedFullmodel:draw(..., {anim, time, rot})
model:drawBlended, drawBlendedRotmodel:draw(..., {anim, time, blend = {anim, time, w}})
model:drawFps, drawAnimatedFps, drawBlendedFpsa transform parented to g3.camera and model:draw(transform, opts)
char:draw(x, y, z, yawRadians, scale)char:draw(transform)
lvl:setPosition(obj, ...), lvl:setRotation(obj, ...)obj:setPosition, obj:setQuat, obj:setRotation
Reference

API reference#

Every function the engine exposes. ? marks an optional argument. Methods are called with a colon on the object named in the heading.

mote.graphics3d#

3D scene: camera, transform stack, primitives, models, materials, lights

mote.graphics3d.addFogVolume(t)
addFogVolume{ shape="box"|"sphere", pos={x,y,z}, size={w,h,d} | radius=, density=, color={r,g,b}, edge=, noise=, noiseScale=, heightFalloff=, wind=, emissive={r,g,b}, ambient= } — a local volume of fog/smoke/dust for this frame (up to 16).
mote.graphics3d.addLight(args)
addLight — punctual and area lights. Two shapes, because both are worth having. The positional form is what every example already writes and it still means the same thing: addLight("point", x, y, z, r, g, b, intensity, range) addLight("directional", dx, dy, dz, r, g, b, intensity) ...and the table form reaches everything else: addLight{ kind = "spot", pos = {x,y,z}, dir = {0,-1,0}, color = {1,0.9,0.7}, intensity = 60, range = 22, cone = { 18, 30 }, -- inner/outer HALF-angles, degrees shadow = true } addLight{ kind = "tube", pos = {x,y,z}, right = {1,0,0}, radius = 0.05, length = 1.6, lumens = 900 } addLight{ kind = "rect", pos = {x,y,z}, dir = {0,0,-1}, right = {1,0,0}, width = 2.4, height = 1.2, intensity = 400 } `intensity` is CANDELA.
mote.graphics3d.addOccluder(v)
mote.graphics3d.addOccluderBox(x0, y0, z0, x1, y1, z1)
mote.graphics3d.applyTransform(v)
mote.graphics3d.bakeReflectionProbe(x, y, z, size?)
capture the scene into a cubemap at (x,y,z) and use it as the local, parallax-corrected reflection environment. `size` is the box half-extent used for parallax correction.
mote.graphics3d.box(x, y, z, w, h, d, opts?)
a proper box (walls, floors, platforms).
mote.graphics3d.capsule(x, y, z, r, h, opts?)
A capsule is a cylinder and two spheres, so any length shares the same three cached shapes in the GPU scene.
mote.graphics3d.clearMeshCull(id)
back to defaults (and no LOD chain).
mote.graphics3d.clearOccluders()
mote.graphics3d.clearPreloaded()
mote.graphics3d.cube(x, y, z, size, opts?)
mote.graphics3d.decal(ud, x, y, z, nx, ny, nz, size, roll?, tr?, tg?, tb?, ta?)
mote.graphics3d.decalEx(t)
stamp a texture onto the scene surface at (x,y,z) facing (nx,ny,nz): bullet holes, blood, scorch marks, graffiti, puddles. Projected into the G-buffer. decal{ image=, normal=image, pos={x,y,z}, dir={nx,ny,nz}, size= | width=, height=, depth=, roll=, color={r,g,b,a}, normalStrength=, roughness=, metallic=, emissive={r,g,b}, emissiveStrength=, albedo=0..1, normalWeight=0..1, material=0..1 } — a decal into the whole G-buffer.
mote.graphics3d.distanceTo(x, y, z)
mote.graphics3d.drawMesh(id)
draw a previously registered mesh from its cached GPU buffer.
mote.graphics3d.drawMeshInstanced(id, insts, stride?)
draw one cached mesh many times. `instances` is a FLAT array, twelve numbers each, in the same spirit as registerMesh's flat vertex array: x, y, z, scale, upX, upY, upZ, yaw, r, g, b, phase The mesh must be authored around its own origin, not in world space — that is the one semantic difference from drawMesh, and the reason a mesh built for drawMesh will all pile up at the origin if you pass it here.
mote.graphics3d.getClipPlanes()
mote.graphics3d.getOpacity()
mote.graphics3d.getTextureMaxSize()
mote.graphics3d.getTransform()
major); transformPoint(x,y,z) -> world
mote.graphics3d.getTransparency()
> table | nil
mote.graphics3d.getWater(index?)
read a body back as a table (default: the first). Keys match water{} exactly, so it round-trips.
mote.graphics3d.isBoxVisible(x0, y0, z0, x1, y1, z1)
mote.graphics3d.isVisible(x, y, z, r?)
mote.graphics3d.loadModel(path)
mote.graphics3d.loadModelAsync(path)
preloadModels{paths}: decode every texture of these models on all cores now, so the loadModel calls that follow are quick. mote.level calls it for the whole level before creating objects. loadModelAsync(path) -> handle: textures decode on worker threads while the game keeps running.
mote.graphics3d.mesh(verts)
draw an arbitrary immediate triangle mesh: a flat array of 6 numbers per vertex (x, y, z, nx, ny, nz), 3 vertices per triangle, tinted by the current 3D colour + texture. This is the raw primitive the mote.shapes procedural kit is built on — feed it any code-generated geometry.
mote.graphics3d.meshBounds(id)
the bounding sphere computed when the mesh was registered.
mote.graphics3d.mirror(x, y, z, nx, ny, nz, w, h, tr?, tg?, tb?)
a flat planar mirror at (x,y,z) with plane normal (nx,ny,nz) and size w×h. The scene is re-rendered from the reflected camera and projected onto it — a true mirror.
mote.graphics3d.newLightProfile(src)
newLightProfile — a photometric profile for addLight{ profile = id }. local id, peak = g3.newLightProfile("lights/downlight.ies") -- IES LM-63 file local id = g3.newLightProfile{ angles = {0, 30, 60, 90, 180}, -- degrees from the axis values = {1, 0.9, 0.4, 0.05, 0} } local id = g3.newLightProfile(function(deg) return math.cos(math.rad(deg))^8 end) The profile is normalised to its peak, so `intensity` stays the peak candela; an IES file also returns that peak, ready to pass as intensity.
mote.graphics3d.newSurface(t)
mote.graphics3d.origin()
mote.graphics3d.plane(x, y, z, w, d, opts?)
mote.graphics3d.pop()
mote.graphics3d.preloadModels(paths)
mote.graphics3d.push(mode?)
The 3D transform stack g3.push() g3.translate(x, y, z) g3.rotate(rx, ry, rz) g3.scale(s) g3.applyTransform(transform | level object | {16 numbers}) ... draw in local coordinates ... g3.pop() Applies to everything drawn in 3D after it: primitives, models (static and animated), registered meshes, lights and decals.
mote.graphics3d.registerMesh(id, verts)
mote.graphics3d.removeMesh(id)
free a cached mesh's GPU buffer (queues an empty upload).
mote.graphics3d.rotate(rx, ry?, rz?)
mote.graphics3d.rotateQuat(x, y, z, w)
mote.graphics3d.scale(x, y?, z?)
mote.graphics3d.screenRay(sx, sy)
Picking: the two directions between pixels and the world Both go through the inverse of the very matrix the frame is rendered with, rather than rebuilding a camera basis by hand. A hand-rolled basis has to re-derive the handedness, the Y direction of screen space and the depth range, and a sign error there produces a ray that looks plausible and selects the wrong object.
mote.graphics3d.screenSize(x, y, z, r)
mote.graphics3d.setAmbient(r, g, b)
mote.graphics3d.setCamera(ex, ey, ez, tx, ty, tz, fov? | transform, fov?)
mote.graphics3d.setClipPlanes(near, far)
the main camera's depth range. Push `near` out as far as the game allows: depth precision is spent almost entirely near it. `far` is also the hard limit of what can be drawn.
mote.graphics3d.setColor(r, g, b, a?)
mote.graphics3d.setEmissive(r, g, b)
mote.graphics3d.setEnvironment(t)
Procedural environment / IBL: a 3-band sky gradient that lights materials from all directions (fixes flat shading) and provides reflections. setEnvironment{ sky={r,g,b}, horizon={r,g,b}, ground={r,g,b}, diffuse=, specular=, skyIntensity=, drawSky=bool }
mote.graphics3d.setEnvMap(path?)
load an equirectangular panorama as the HDRI environment (drives ambient lighting, reflections and the sky background). Call with no argument to revert to the procedural gradient environment.
mote.graphics3d.setFog(r, g, b, density)
mote.graphics3d.setLight(x, y, z)
mote.graphics3d.setMaterial(args)
setMaterial — metallic and roughness, and optionally which shading model the surface uses. setMaterial(0.0, 0.35) -- as before setMaterial{ metallic = 0, roughness = 0.35, model = "clearcoat", coatRoughness = 0.06 } setMaterial{ model = "subsurface", thickness = 0.7 } setMaterial{ model = "anisotropic", anisotropy = 0.8 } setMaterial{ model = "foliage", thickness = 0.5 } PER-OBJECT: each box/sphere/mesh keeps the value it was drawn with.
mote.graphics3d.setMaterialShader(args)
mote.graphics3d.setMeshCull(id, t)
setMeshCull(id, { cull = true, maxDistance = 0, minPixels = -1, castShadows = true, shadowDistance = 0, bounds = {cx, cy, cz, r} }) Per-mesh visibility. Keys left out keep their current value; 0 / -1 mean "use the global setting".
mote.graphics3d.setMeshLOD(id, levels, bias?)
setMeshLOD(id, { {distance, lodId}, ... } [, shadowBias]) Draw `lodId` instead of `id` once the camera is `distance` metres from the mesh's centre (the last matching entry wins; lists are sorted for you).
mote.graphics3d.setModelShading(name, param?)
shading model ("skin", "cloth", "hair", "subsurface", ...) for models drawn next; "standard" resets.
mote.graphics3d.setOccluders(list)
mote.graphics3d.setOpacity(a)
setOpacity(a) / getOpacity() — the alpha part of setColor on its own.
mote.graphics3d.setShadow(ground?)
mote.graphics3d.setShadowCascades(a, b, c)
far distance of each shadow cascade. Small values sharpen shadows on tight maps (CS-scale); large values cover open worlds (DayZ-scale). Defaults 12/40/120.
mote.graphics3d.setShadowSoftness(r)
PCF kernel scale. 1.0 default; higher = softer edges, lower = sharper/contact.
mote.graphics3d.setSunColor(r, g, b, intensity?)
color of the directional sun, plus an optional brightness multiplier (the "key light" strength). Intensity 1 is neutral; raise it (2-4) for a punchy, high-contrast look.
mote.graphics3d.setSunIntensity(i)
sun brightness independent of color (1 = neutral).
mote.graphics3d.setSurface(s?)
draw subsequent 3D geometry with this surface. Each call starts a fresh batch, so switching back and forth is allowed but grouping by surface is cheaper.
mote.graphics3d.setSurfaceDetail(pom, detail?)
global controls for parallax occlusion mapping depth (height read from the normal map's alpha channel; 0 = off) and detail-normal blend strength on PBR models.
mote.graphics3d.setTexture(id)
select a procedural block texture for subsequent immediate primitives. 0 = flat color (default). See gbuffer_prim.wgsl: 1 grass, 2 dirt, 3 stone, 4 wood, 5 leaves, 6 planks, 7 sand, 8 glass, 9 water (animated).
mote.graphics3d.setTextureMaxSize(n)
model textures larger than n per side are halved while loading (default 4096; 0 keeps every texture as authored).
mote.graphics3d.setTransparency(v)
a transparent material for the following primitives and meshes (glass, liquids, plastic, smoke, holograms). Keys (all optional): opacity, transmission, ior, thickness, dispersion, refraction, absorption, roughness, tint={r,g,b}, emissive={r,g,b}, thin, lens, backFaces, castShadow.
mote.graphics3d.setVelocity(x, y, z)
world-space velocity (m/s) of what is drawn next, for motion vectors: sharp temporal AA and correct motion blur on moving objects. Persistent; setVelocity(0,0,0) for static things. Models get theirs automatically (from the previous frame's transform).
mote.graphics3d.setWind(cfg)
setWind{...} — one wind for every instanced draw. direction = {x, y, z} which way it blows (default +X) strength = metres multiplies each plant's own `sway` gust = 1/metres how big the travelling gusts are (default 0.09) speed = m/s how fast they travel (default 1.4) turbulence= 0..1 per-plant flutter on top (default 0.5) time = seconds OMIT IT.
mote.graphics3d.shape(kind, x, y, z, opts?)
mote.graphics3d.sphere(x, y, z, r, opts?)
mote.graphics3d.surfaceKinds()
the presets newSurface{preset=...} understands.
mote.graphics3d.surfaceParams(kind)
the generator defaults for a preset, as a table shaped exactly like the keys newSurface accepts. Read it, change what you want, pass it back: the alternative is guessing at numbers that live in Rust, which is how a "flexible" system stays theoretical.
mote.graphics3d.trample(x, y, z, r?)
flatten plants around a point, this frame. Per-frame on purpose: a foot is a thing in the world right now, not a setting, so it clears itself and you cannot leave a crushed circle behind by forgetting to turn it off.
mote.graphics3d.transformPoint(x, y, z)
mote.graphics3d.translate(x, y, z)
mote.graphics3d.water(t)
water mote.graphics3d.water{ ... } — add ONE body of water to this frame. Call it again for another: an ocean, a pond and a puddle can all be on screen with completely independent settings. Presets are only a starting point, never a mode: `preset = "ocean"` fills the table in first and every other key in the SAME call overrides it.
mote.graphics3d.waterPreset(name)
the preset as a plain table, NOT applied. Edit whatever you like and hand it to water{}: local w = mote.graphics3d.waterPreset("ocean") w.wind, w.foam = 14, 2.0 mote.graphics3d.water(w) Names: "ocean", "lake", "pool", "puddle", "river", "tropical".
mote.graphics3d.worldToScreen(x, y, z)

mote.transform#

transforms with hierarchy

mote.transform.eulerToQuat(x, y, z)
the conversions on their own
mote.transform.is(v)
> true for a transform
mote.transform.lookQuat(dx, dy, dz)
mote.transform.new(o?)
mote.transform.quatToEuler(x, y, z, w)

mote.render#

image settings

mote.render.affine(on)
PSX affine (non-perspective) texture warping on/off.
mote.render.apply(t)
mote.render.autoExposure(target, lo?, hi?)
mote.render.clearHooks(stage)
Remove all hooks (optionally for one stage).
mote.render.colorDepth(bits)
Colour depth in bits per channel (0 = off; 5 ≈ PSX 15-bit colour).
mote.render.culling(t)
mote.render.culling{ enabled, distance, shadowDistance, minPixels, shadows, lodScale, freeze } enabled master switch for cached-mesh culling (default true) distance draw distance in metres, 0 = unlimited shadowDistance casters further than this from the camera cast no shadow (sun cascades and local lights), 0 = unlimited minPixels skip meshes smaller than this on screen, 0 = off shadows frustum-cull casters per cascade and per light tile lodScale multiplier on every LOD switch distance (quality dial) freeze keep culling from the current camera (debug: fly out and look at what is and is not being drawn)
mote.render.dither(amount)
Ordered (Bayer) dithering amount 0..1, applied when quantizing colour.
mote.render.focus(dist, fstop?, focal?)
Individual setters, for the knobs people reach for every frame rather than once at load: focus pulls and shutter changes are animation, not settings.
mote.render.getCulling()
mote.render.getGi()
mote.render.getLights()
mote.render.getLocalShadows()
shadowed lights fit: tiles / 6).
mote.render.getResolution()
> { scale, current, width, height, outputWidth, outputHeight, dynamic, targetMs, frameMs, min, max, upscale }
mote.render.getShadows()
mote.render.getTransparency()
mote.render.gi(t)
mote.render.gi{ enabled=, spacing=, dims={x,y,z}, follow=, origin={x,y,z}, perFrame=, intensity=, hysteresis=, normalBias=, reflections= } — dynamic probe GI: bounce light and off-screen reflections from a grid of probes that re-capture the lit scene a few at a time.
mote.render.gpuScene(on?)
mote.render.shadows{ cache = {near, mid, far}, cacheMargin =, contact =, contactLocal = } / getShadows() mote.render.lights{ clustered = true, uniformMax = 31, clusterFar = 400 } — beyond `uniformMax` lights (the sun and shadowed lights always count first), the rest are binned into a froxel grid so a pixel only shades the lights that reach it.
mote.render.gpuSceneStats()
what the GPU scene drew. Calling it asks for this frame's counters (a GPU read-back: debug use only); the table holds the last ones read, so call it every frame you want numbers.
mote.render.lights(t)
mote.render.localShadows(t)
mote.render.lut(src, strength?)
FSR-style adaptive sharpen amount (0 = off; ~0.4 pairs well with pixelate). lut(source[, strength]) — colour grading with a 3D LUT: mote.render.lut("grades/teal_orange.cube") -- a .cube from Resolve / Photoshop / Premiere mote.render.lut("grades/film.cube", 0.6) -- 60 % of the look mote.render.lut(function(r, g, b) return r, g * 0.95, b * 1.1 end, 33) -- build one in Lua mote.render.lut(nil) -- off Applied after tonemapping and the grade sliders, in display space — the space .cube files are authored in.
mote.render.lutStrength(v)
mote.render.motionBlur(amount)
mote.render.off(stage, fn)
Remove a previously registered hook.
mote.render.on(stage, fn)
Register a hook on a stage; returns the fn as a handle for off().
mote.render.onBackground(fn)
Named convenience.
mote.render.onOverlay(fn)
mote.render.onPost(fn)
mote.render.onWorld(fn)
mote.render.pixelate(n)
Resolution scaling / pixelation: virtual vertical pixel count (0 = native).
mote.render.posterize(levels)
Colour posterization: levels per channel (0 = off; e.g. 16 for a retro feel).
mote.render.resolution(t)
mote.render.resolution{ scale=, dynamic=, targetFps= | targetMs=, min=, max=, upscale="bicubic"|"bilinear"|"nearest", sharpen= } — the internal resolution of the 3D scene. The UI and 2D overlay stay at window size.
mote.render.retroOff()
Turn every retro knob back off (return to the modern look).
mote.render.shadows(t)
mote.render.sharpen(amount)
mote.render.skip(name, on?)
switch a built-in stage off (false turns it back on). Pair with your own pass at the same point to REPLACE it: skip("lighting") + addScenePass(myLighting, "lit") = your lighting model. Stages: lighting, ssao, ssr, ssgi, volumetric, vmo, taa, bloom, overlay.
mote.render.skipped()
mote.render.taa(on)
Temporal anti-aliasing (reproject + neighbourhood clamp over the HDR scene).
mote.render.tonemap(name)
mote.render.transparency(t)
Bulk configure any subset of knobs at once: mote.render.apply{ ... }. mote.render.localShadows{ budget = 12, tile = 256, softness = 1.5, ... } Fine control of local-light shadow maps; see apply_local_shadow_keys for every key.
mote.render.vertexSnap(grid)
PSX vertex jitter: NDC grid steps (0 = off; ~120 chunky, ~400 subtle).
mote.render.vmo(on)
VMO voxel GI: cone-trace the voxelized scene and ADD indirect bounce light.
mote.render.vmoBake(x?, y?, z?)
Re-bake the world-anchored voxel volume around a point (default origin). The volume is frozen between bakes — that's what keeps the GI stable. Static geometry emits GI; dynamic objects receive it but need a re-bake to emit.
mote.render.vmoConfig(t)
Tune the VMO look: mote.render.vmoConfig{ intensity=, range=, spread=, sky={r,g,b} }.
mote.render.vmoDebug(on)
Show the raw voxel volume (debug ray-march) instead of GI.
mote.render.vmoDynamic(on)
Real-time GI: re-voxelize the world-anchored volume every frame so moving objects contribute bounce light live (no manual re-bake). Costs more per frame than the frozen bake; still call vmoBake(x,y,z) once to place the volume.
mote.render.vmoFog(v)
Volumetric in-scatter density: makes VMO light visible in the air.
mote.render.vmoIntensity(v)
Indirect-light strength (default 1.0).

mote.graphics#

2D drawing, text, images, canvases, shaders, screen effects

mote.graphics.addScenePass(ud, stage?, opts?)
addScenePass(shader, [stage], [{output = target, inputs = {...}, buffers = {...}}]) stage: "begin" | "gbuffer" | "lit" | "hdr" (default "hdr") output: a target from newTarget (default: the HDR scene itself) inputs: up to 4 targets, read in WGSL as in0(uv)..in3(uv) / in0_px(p) buffers: up to 4 buffers from newBuffer, read/written as buf0..buf3
mote.graphics.addScreenShader(ud)
Append a shader to the chain (applied in order — stack effects).
mote.graphics.arc(mode, cx, cy, r, a1, a2)
mote.graphics.bezier(v)
cubic Bézier curve(s), stroked with the current line width. Chains share end points: 8 numbers for one curve, then 6 more per further segment.
mote.graphics.capsule(mode, x1, y1, x2, y2, r)
a stadium between two points.
mote.graphics.circle(mode, x, y, r)
mote.graphics.clear(r, g, b, a?)
mote.graphics.clearScreenShader()
mote.graphics.clearTarget(ud, r?, gg?, b?, a?, stage?)
targets otherwise keep their contents between frames.
mote.graphics.dispatch(ud, opts?)
dispatch(shader, {stage=, outputs={...}, inputs={...}, buffers={...}, groups={x,y,z}}) groups default: the first output's size / 8 (for @workgroup_size(8,8,1)).
mote.graphics.draw(image, x, y, r?, sx?, sy?, ox?, oy? | image, x, y, opts)
mote.graphics.drawTriangles(ud, verts)
textured triangles (three vertices each) in 2D coordinates, tinted by the current colour.
mote.graphics.ellipse(mode, cx, cy, rx, ry)
mote.graphics.fontHeight(scale?)
Baseline-to-baseline distance, which is what a UI needs to stack rows.
mote.graphics.getClip()
> x, y, w, h (screen pixels) or nil when nothing is clipped.
mote.graphics.getDimensions()
mote.graphics.getFont()
> id | nil, size
mote.graphics.getLineCap()
mote.graphics.getLineStyle()
mote.graphics.getLineWidth()
mote.graphics.getTransform()
> a, b, c, d, e, f (x' = a x + c y + e, y' = b x + d y + f)
mote.graphics.getVirtualResolution()
mote.graphics.inverseTransformPoint(x, y)
mote.graphics.loadImage(path)
Sprites
mote.graphics.loadImageAsync(path)
newImageData(w, h) or newImageData(image) -> a CPU canvas you can draw into with code (setPixel, rect, circle, line, polygon, gradient, noise, outline, paste, mapPixel) and turn into an Image with :toImage().
mote.graphics.newBuffer(v)
> buffer of `count` vec4<f32> (or sized and filled from the table). buf:set({floats...}, [offsetFloats]).
mote.graphics.newCanvas(w, h)
build a texture procedurally. fn(x, y) returns r, g, b, [a] in 0..1 for each pixel. Great for decals, ramps, masks. newCanvas(w, h) -> a GPU render target. Draw into it with setCanvas(c), back to the screen with setCanvas(); draw it like any image.
mote.graphics.newCompute(source, names?)
> shader. The source defines @compute @workgroup_size(8, 8, 1) fn cs_main(@builtin(global_invocation_id) id: vec3<u32>) and writes its outputs with textureStore(out0, ...) .. out3. Everything a scene pass sees (frame textures, inputs, buffers, U) is available too.
mote.graphics.newImage(w, h, f)
mote.graphics.newImageData(a, b?)
mote.graphics.newMaterial(source, names?)
> material shader. The author writes `fn surface(world_pos, normal, color, time) -> Surface`; the engine wraps it with the G-buffer vertex stage + MRT outputs, so the scene's deferred lighting lights the custom surface normally.
mote.graphics.newScenePass(source, names?)
> shader. Queue it each frame with addScenePass(shader, "lit" | "hdr").
mote.graphics.newShader(source, names?)
User post-process (screen) shaders mote.graphics.newShader(fragmentWGSL, {"p0","p1",...}) -> shader. The engine prepends a prelude (vs_main, bindings, `tex(uv)`); the author writes only `@fragment fn fs_main(@location(0) uv: vec2<f32>) -> ...`.
mote.graphics.newTarget(t?)
newTarget{ width=, height= } or { scale = 1.0 } (follows the window), format = "rgba16f" | "rgba32f" | "rgba8" | "r32f". Persistent between frames: accumulate, simulate, feed back.
mote.graphics.ngon(mode, x, y, r, n, rot?)
regular polygon, first vertex up.
mote.graphics.origin()
mote.graphics.overrideShader(name, source)
runtime shader overrides Replace a built-in shader with your OWN WGSL. Your source must keep the same bind groups + vs_main/fs_main as the built-in — grab it with shaderSource(name), edit, and pass it here.
mote.graphics.parametric(func, t0, t1, steps, mode?)
Custom shapes from a parametric formula: func(t) -> x, y over [t0, t1].
mote.graphics.pie(mode, x, y, r, a1, a2)
a filled wedge (arc's "pie" shape).
mote.graphics.point(x, y, size?)
mote.graphics.polygon(args)
mote.graphics.polyline(coords)
mote.graphics.pop()
mote.graphics.popClip()
mote.graphics.printWidth(text, scale?)
mote.graphics.printWrapped(text, x, y, width, align?, scale?)
the same, broken to fit `width`. align: "left" (default), "center", "right".
mote.graphics.push(mode?)
2D v2: transform stack Applies to every 2D draw — shapes, sprites, clips — before the 2D camera. Reset to identity at the start of every frame. push() saves the transform; push("all") also the colour, font, blend mode and line width, which pop() then restores.
mote.graphics.pushClip(x, y, w, h)
Clipping A clip rect confines every following 2D draw to a rectangle. It is what makes a scroll view, a list, a dropdown or a text field that is narrower than its content possible at all: without it the only way to hide overflow is to not draw it, which cannot cut a glyph or a sprite in half.
mote.graphics.pushClipScreen(x, y, w, h)
pushClipScreen — the same, in screen pixels, ignoring the 2D camera. A HUD panel should not scroll away when the world camera pans; a clip on world geometry should. Two calls rather than a flag, because getting this wrong produces a rectangle that drifts, which reads as a renderer bug.
mote.graphics.rectangle(mode, x, y, w, h, rx?, ry?)
mode "fill" | "line" | "both".
mote.graphics.resetShader(name)
mote.graphics.ring(mode, x, y, r, ri, a1?, a2?)
an annulus, or a sector of one.
mote.graphics.rotate(a)
mote.graphics.roundRect(mode, x, y, w, h, r0, r1?, r2?, r3?)
2D v2: shapes roundRect(mode, x, y, w, h, r) or roundRect(mode, x, y, w, h, tl, tr, br, bl)
mote.graphics.scale(sx, sy?)
mote.graphics.setAntialias(on)
mote.graphics.setBlendMode(mode)
affects 2D fills (rectangle/circle/polygon). Resets to "alpha" each frame.
mote.graphics.setBlur(px?)
soft edges on every following shape (glows, shadows).
mote.graphics.setCanvas(c?)
setCanvas(canvas) / setCanvas() — where 2D drawing goes.
mote.graphics.setClip(x?, y?, w?, h?)
setClip(x, y, w, h) replaces the whole stack; setClip() clears it. The blunt version, for code that is not nesting anything.
mote.graphics.setColor(r, g, b, a?)
mote.graphics.setDash(len?, gap?)
setDash(length, gap) for lines and polylines; setDash() for solid.
mote.graphics.setExposure(e)
mote.graphics.setFont(font, size?)
`font` is an id from mote.font.load, or one of the built-in names "sans" / "bold", or nil to go back to the bitmap font. setFont(nil) and setFont() both mean the bitmap font; setFont("sans", 18) is the one-liner a UI wants.
mote.graphics.setFontSize(px)
mote.graphics.setFXAA(on)
anti-aliasing on the final image (default on).
mote.graphics.setGrade(t)
Cinematic colour grade. setGrade{ contrast=, saturation=, temperature=, tint=, grain=, chromatic= } — any subset; unspecified keys keep their value.
mote.graphics.setGradient(args)
setGradient("linear", x0, y0, x1, y1, c0, c1) setGradient("radial", cx, cy, r, c0, c1) setGradient("conic", cx, cy, angle, c0, c1) setGradient(nil) -- back to the flat colour Colours are {r, g, b, a} tables; coordinates are the same user space the shapes are drawn in.
mote.graphics.setLineCap(cap)
setLineCap("butt" | "round" | "square")
mote.graphics.setLineStyle(st)
"rough" keeps the original pixel-exact triangle path for every shape (pixel-art games).
mote.graphics.setLineWidth(w)
2D v2: style
mote.graphics.setPixelSnap(on)
mote.graphics.setScreenShader(shader?)
Replace the active screen-shader chain with a single shader (or clear it).
mote.graphics.setSSAO(strength, radius?, power?)
strength 0 disables occlusion.
mote.graphics.setSSGI(strength, radius?)
screen-space global illumination (bounce light).
mote.graphics.setSSR(strength, max_dist?, thickness?)
strength 0 disables reflections.
mote.graphics.setStrokeColor(r, gg, b, a?)
the outline colour in "both" mode.
mote.graphics.setTransform(a, b, c, d, e, ff)
mote.graphics.setVignette(strength, softness?)
strength 0 disables the vignette.
mote.graphics.setVirtualResolution(w?, h?, o?)
Pixel art setVirtualResolution(w, h, {integer = true}) — draw 2D in a w x h pixel space, scaled to the window by whole multiples (integer) and centred; the rest of the window stays the clear colour. nil turns it off.
mote.graphics.setVolumetric(strength, density?, phase?)
sun light shafts. 0 disables.
mote.graphics.shaderSource(name)
Return the built-in WGSL of a named shader (to copy, edit, and override).
mote.graphics.shear(kx, ky?)
mote.graphics.spline(mode, pts, closed?)
a smooth Catmull-Rom curve through every point. points = {x1, y1, x2, y2, ...}. "fill" closes and fills it.
mote.graphics.star(mode, x, y, r, inner, n, rot?)
star(mode, x, y, r, inner, points, [rotation])
mote.graphics.textSize(text, scale?)
> width, height. Height counts the lines, so a single line still returns the font's line height rather than the ink.
mote.graphics.toVirtual(x, y)
mote.graphics.transformPoint(x, y)
> the point after the transform (before the camera); inverseTransformPoint does the reverse (e.g. a mouse in local space).
mote.graphics.translate(x, y)
mote.graphics.triangle(mode, x1, y1, x2, y2, x3, y3)

mote.physics3d#

3D physics

mote.physics3d.addBall(kind, x, y, z, r, rest?, fric?)
mote.physics3d.addBallJoint(a, b, ax, ay, az, bx, by, bz)
mote.physics3d.addBox(kind, x, y, z, w0, h0, d0, rest?, fric?)
mote.physics3d.addCapsule(kind, x, y, z, hh, r, rest?, fric?)
Advanced 3D colliders + triggers.
mote.physics3d.addConeJoint(a, b, ax, ay, az, bx, by, bz, swing, twist?)
joints & breaking
mote.physics3d.addConvex(kind, x, y, z, vflat, rest?, fric?)
mote.physics3d.addCylinder(kind, x, y, z, hh, r, rest?, fric?)
mote.physics3d.addField(cfg)
fields & explosions
mote.physics3d.addFixedJoint(a, b)
Constraints / joints.
mote.physics3d.addGround(y)
mote.physics3d.addHeightfield(x, y, z, nrows, ncols, heights, sx, sz, fric?)
addHeightfield(x, y, z, nrows, ncols, heights[], sizeX, sizeZ, fric)
mote.physics3d.addPrismaticJoint(a, b, o?)
addPrismaticJoint(a, b, {axis={x,y,z}, anchorA={..}, anchorB={..}, limits={min,max}})
mote.physics3d.addRevoluteJoint(a, b, axx, axy, axz, ax, ay, az, bx, by, bz)
mote.physics3d.addRopeJoint(a, b, len, o?)
addRopeJoint(a, b, maxLength, {anchorA=..., anchorB=...}?)
mote.physics3d.addSensorBall(x, y, z, r)
mote.physics3d.addSensorBox(x, y, z, w0, h0, d0)
mote.physics3d.addShape(kind, body, x, y, z, opts?)
> { {id, shape="box"|"ball"|"capsule"|"cylinder"|"other", x,y,z, qx,qy,qz,qw, sx,sy,sz, sleeping}, ... } addShape(kind, body, x, y, z, opts) — a collider of the same shape the graphics primitive draws (same option names, same rotation): local id = P.addShape("torus", "static", 0, 1, 0, { R = 2, tube = 0.4, rot = {90, 0, 0} }) Static: the exact triangles.
mote.physics3d.addSpringJoint(a, b, rest, stiff, damp)
mote.physics3d.addTrimesh(x, y, z, vflat, iflat, fric?)
addTrimesh(x, y, z, verts[flat x,y,z], indices[flat i0,i1,i2], fric)
mote.physics3d.applyForce(id, fx, fy, fz)
mote.physics3d.applyForceAtPoint(id, fx, fy, fz, px, py, pz)
mote.physics3d.applyImpulse(id, ix, iy, iz)
mote.physics3d.applyImpulseAt(id, ix, iy, iz, px, py, pz)
mote.physics3d.autoConvex(verts, indices, opts?)
the same automatic decomposition as model:autoConvex, for geometry that never came from a file: procedural shapes, a terrain chunk, the result of a boolean or a shatter. `verts` is a list of {x,y,z}, `indices` a flat 1-based triangle list — exactly what model:triangles() hands back, so the two compose.
mote.physics3d.bodyOf(id)
mote.physics3d.capsuleCast(ox, oy, oz, half, r, dx, dy, dz, max)
mote.physics3d.clearBuoyancy(id)
mote.physics3d.clearFields()
mote.physics3d.debugDraw(opts)
debug draw -- Draw every collider as its shape: boxes, balls (as boxes), capsules, cylinders; sleeping bodies blue, awake ones green.
mote.physics3d.debugMesh(with_static?)
push every collider's real triangles into the scene with the current transparency: green moving, blue asleep, grey static, yellow triggers, orange kinematic. P.debugDraw uses it.
mote.physics3d.debugShapes()
mote.physics3d.drawBox(id, hx, hy, hz)
Draw one body as an oriented box of the given half sizes.
mote.physics3d.explode(x, y, z, cfg?)
mote.physics3d.fracture(cfg)
fracture == Break a mesh into convex pieces and drop them into the world as debris. Returns the body ids, so the caller can throw them, colour them or count them down.
mote.physics3d.getAngularVelocity(id)
mote.physics3d.getMass(id)
mote.physics3d.getPosition(id)
mote.physics3d.getRotation(id)
mote.physics3d.getVelocity(id)
mote.physics3d.isBody(v)
mote.physics3d.jointForce(jid)
mote.physics3d.moveCharacter(id, dx, dy, dz, dt)
Character controller: move(id, dx,dy,dz, dt) -> movedX, movedY, movedZ, grounded.
mote.physics3d.newVehicle(chassis, cfg?)
vehicles
mote.physics3d.pollBreaks()
The joints that let go since the last call.
mote.physics3d.pollContacts()
> { {a, b, force, x, y, z, nx, ny, nz}, ... }
mote.physics3d.pollTriggers()
mote.physics3d.quatAxes(x, y, z, w)
math The three unit axes of a rotation quaternion: right (x), up (y), forward (z).
mote.physics3d.ragdoll(o)
mote.physics3d.raycast(ox, oy, oz, dx, dy, dz, max)
mote.physics3d.remove(id)
mote.physics3d.removeField(id)
mote.physics3d.removeJoint(jid)
mote.physics3d.removeVehicle(vid)
mote.physics3d.setBuoyancy(id, cfg?)
mote.physics3d.setCcd(id, on)
Continuous collision detection.
mote.physics3d.setContactEvents(id, th?)
contacts, layers, sliders, ropes, motors, debug setContactEvents(id, threshold) — report hits on this body harder than `threshold` newtons via pollContacts(); -1 turns it off.
mote.physics3d.setDamping(id, lin, ang?)
mote.physics3d.setGravity(x, y, z)
mote.physics3d.setGroups(id, m, f, solver?)
collision layers.
mote.physics3d.setJointBreak(jid, force, torque?)
mote.physics3d.setJointLimits(jid, mn, mx, axis?)
radians for hinges, metres for sliders
mote.physics3d.setJointMotor(jid, o)
spin / slide setJointMotor(joint, {position=, stiffness=, damping=, maxForce=, axis=}) — servo
mote.physics3d.setMass(id, kg)
mote.physics3d.setPosition(id, x, y, z)
mote.physics3d.setRotation(id, x, y, z, w4)
body state
mote.physics3d.setVelocity(id, vx, vy, vz)
mote.physics3d.setWater(arg)
water & buoyancy The physics world needs its own copy of the wave parameters, because the renderer's water bodies are emitted during `draw` and buoyancy has to be applied during `update`. Handing it the same table you hand the renderer is what keeps the two surfaces one surface.
mote.physics3d.sphereCast(ox, oy, oz, r, dx, dy, dz, max)
mote.physics3d.submersion(id)
How much of the hull is under, 0..1. A propeller in the air should not push, and a swimmer's controller needs to know it is swimming.
mote.physics3d.update(dt)
mote.physics3d.vehicleControl(vid, cfg)
mote.physics3d.vehicleState(vid)
Signed speed in m/s, wheels touching the ground, wheels in total.
mote.physics3d.vehicleWheel(vid, i)
Where to draw wheel `i`, as a table: `x, y, z` (also `[1..3]`), `steer` and `spin` in radians, and `grounded`. A table rather than six return values because six of them is exactly the number at which a caller starts getting the order wrong, and `w.steer` cannot be mistaken for `w.spin` the way the fourth and fifth positions can.
mote.physics3d.wake(id)
mote.physics3d.waterHeight(x, z)
Surface height under a point, wave and all — for spawning things on the water, aiming at it, or deciding whether a shot splashed.

mote.physics#

2D physics

mote.physics.addBox(kind, x, y, w0, h0, rest?, fric?)
mote.physics.addCapsule(kind, x, y, hh, r, rest?, fric?)
Advanced 2D colliders + triggers.
mote.physics.addCircle(kind, x, y, r, rest?, fric?)
mote.physics.addConvex(kind, x, y, vflat, rest?, fric?)
Convex polygon (hull of a flat x,y point list) — sloped platforms, triangles.
mote.physics.addFixedJoint(a, b)
Joints / constraints.
mote.physics.addGround(y)
mote.physics.addHeightfield(x, y, heights, width, fric?)
mote.physics.addPolyline(kind, x, y, vflat, fric?)
Thin polyline outline (open/closed) — one-way floors, static level edges.
mote.physics.addRevoluteJoint(a, b, ax, ay, bx, by)
mote.physics.addRopeJoint(a, b, max_len)
mote.physics.addSensorBox(x, y, w0, h0)
mote.physics.addSensorCircle(x, y, r)
mote.physics.addSpringJoint(a, b, rest, stiff, damp)
mote.physics.addTrimesh(x, y, vflat, iflat, fric?)
mote.physics.applyForce(id, fx, fy)
mote.physics.applyForceAtPoint(id, fx, fy, px, py)
mote.physics.applyImpulse(id, ix, iy)
mote.physics.getPosition(id)
mote.physics.getTransform(id)
mote.physics.getVelocity(id)
mote.physics.pollTriggers()
mote.physics.raycast(ox, oy, dx, dy, max)
Raycast against every body in the world (nearest hit). Sensors excluded.
mote.physics.remove(id)
mote.physics.setGravity(x, y)
mote.physics.setGroups(id, membership, filter)
Collision layers/masks: membership + filter bitmasks (32 groups). E.g. put bullets in group 1 with a filter excluding group 1 so they don't hit bullets.
mote.physics.setPosition(id, x, y)
mote.physics.setVelocity(id, vx, vy)
mote.physics.update(dt)

mote.level#

levels exported from Blender

mote.level.behavior(name, def)
Register Lua logic for a "script" name used in Blender.
mote.level.load(path, opts)
Load a level exported from Blender. Returns the level object. opts: physics (true), fixedStep (1/60), navmesh (false | true | {...}), live (true): when the level or its models are exported again from Blender, the running game reloads them (folder runs only; free in a packaged game).

mote.character#

mote.character.clearCache()
Forget cached models and state files (a re-export from Blender).
mote.character.data(modelPath, model)
The state description for a model: from its .anim.json, or one looping state per clip.
mote.character.load(modelPath, opts)
Load (or reuse) a character model and give back a new character.
mote.character.new(model, data, opts)
A character from a model and a state table (the .anim.json format, or the mote.anim.build format — they are the same).

mote.loader#

background loading

mote.loader.idle()
mote.loader.image(path, cb)
mote.loader.level(path, opts, cb)
Load a Blender level with every model's textures decoded in the background first; cb(level) runs when the level exists.
mote.loader.model(path, cb)
mote.loader.progress()
mote.loader.update()

mote.terrain#

terrain

mote.terrain.new(cfg?)
mote.terrain.preset(name)
> a config table you can edit before handing it to new(). These are starting points, not modes: every one of them is just numbers.
mote.terrain.presets()

mote.scatter#

vegetation and object scattering

mote.scatter.new(cfg?)

mote.sky#

sky and clouds

mote.sky.cloud(x, y, z, radius, opts?)
add ONE volumetric cloud puff this frame. Call it in a loop (random or by formula) for many clouds; up to 32 render. Emit each frame (immediate). The clouds{} params above set the shared look; `opts` varies it per puff so a bank of them does not read as one shape copied thirty times: squash height / radius (0.62 default; > 1 = a tower) density multiplier on this puff only type offset on the stratus..cumulus knob, -1..1 softness offset on the edge softness, -1..1 mote.sky.cloud(x, y, z, r, { squash = 0.9, density = 1.3 })
mote.sky.cloudCarve(x, y, z, radius)
an object punches a soft hole in the clouds this frame (fog parts around a plane, ship, character…). Emit each frame at the object's position. Up to 16 carvers.
mote.sky.cloudPreset(name, coverage?)
a complete, tuned cloudscape in one call. Presets set every look parameter, so call this FIRST and then override whatever you want with mote.sky.clouds{...}. "clear" a few high wisps "fair" scattered fair-weather cumulus (the default sunny day) "cumulus" classic cauliflower cumulus, well separated "stratus" low flat sheet, soft and featureless "overcast" full grey lid "storm" towering cumulonimbus with anvils, dark and dense "cirrus" thin, high, fibrous "alien" stylized: hard edges, saturated rim light "sunset" low warm sun, cold ambient, deep haze, a cirrus deck "tropical" tall bright cumulus over a bright ground, hard shadows "toon" cel-shaded bands — a cartoon sky, not a photographic one "gasgiant" banded, curl-swirled cyclones: a sky for somewhere else
mote.sky.clouds(t)
clouds mote.sky.clouds{ ... } — configure the volumetric cloudscape. Every key is optional; omit one and its current value stays. coverage = 0 (and no puff instances) turns clouds off entirely. SHAPE coverage, density, base, top, type, typeBias, anvil, scale, detail, detailScale, softness, weatherScale, seed, planet MOTION wind = {x, z}, shear, curl, boil, weatherDrift, curlScale, baseCurl LIGHT phaseG, phaseBack, phaseBlend, silver, powder, scatter, extinction, ambient, ground = {r,g,b}, skyOcclusion, skyOcclusionDist, msOctaves, haze, hazeSun, hazeColor = {r,g,b}, ambientColor = {r,g,b}, sunTint = {r,g,b}, shadow SHADOW shadow, shadowRes, shadowRange, shadowSteps, shadowDensity, shadowSoftness CIRRUS cirrus = { coverage, altitude, scale, speed, density, detail, stretch } — the high ice sheet; `cirrus = 0.4` also works STYLE stylize (0 physical ..
mote.sky.cloudsOff()
disable the infinite layer (instances still render if added).
mote.sky.cloudWeather(img?)
replace the procedural weather map with your own, so you decide where the sky is clear and where it storms: R = coverage (0 clear .. 1 solid) G = cloud type (0 flat sheet .. 1 towering) B = anvil / storminess A = unused The image tiles across the world; `weatherScale` sets how big one tile is (tile edge = 1 / weatherScale world units).
mote.sky.enable(on)
mote.sky.getClouds()
read back the ENTIRE cloud configuration as a table. The keys match mote.sky.clouds{...} exactly, so a round trip works: local c = mote.sky.getClouds() c.coverage = c.coverage + 0.1 mote.sky.clouds(c) Plus three read-only extras: `effectiveScale` / `effectiveDetailScale` (what the renderer will actually use — these differ from `scale` while scaleAuto is on) and `hasWeatherImage`.
mote.sky.setParams(t)
setParams{ rayleigh=, mie=, sunDisk=, exposure=, stars=, aerial=, mieG=, ozone=, multiScatter=, rayleighHeight=, mieHeight=, sunSize= } — tune the atmosphere. Any subset; unspecified keys keep their value.
mote.sky.setSun(az, elev)
place the sun directly (radians).
mote.sky.setTime(t)
t in [0,1] — 0/1 midnight, 0.25 sunrise, 0.5 noon, 0.75 sunset. Moves the sun along its arc and drives the entire scene lighting from it.

mote.water#

water

mote.water.disturb(x, z, radius, strength, body?)
mote.water.foam(x, z, radius, amount, body?)
foam with no ripple, for effects that should stain the surface without disturbing it.
mote.water.impact(x, z, radius, speed, body?)
something HIT the water. Unlike `disturb`/`splash` this also lays down foam, which lives on its own decay, so a wake trails behind a moving hull instead of vanishing with the ripple that made it. This is the manual half of collider interaction; the automatic half is `autoSplash` on the body itself.
mote.water.splash(x, z, radius, strength, body?)

mote.ruin#

destruction

mote.ruin.box(opts)
mote.ruin.convex(opts)
mote.ruin.materials()
the preset names
mote.ruin.mesh(opts)
mote.ruin.model(model, opts?)

mote.gui#

retained-mode interface

mote.gui.new(cfg)

mote.ui#

immediate-mode interface

mote.ui.bar(x, y, w, h, value, c)
A progress/health bar (non-interactive).
mote.ui.begin()
Call once before drawing widgets. Computes the auto-fit transform and reads the pointer into reference-space coordinates.
mote.ui.beginScroll(id, x, y, w, h, contentH, contentW)
Returns (offsetX, offsetY): subtract them from content coordinates.
mote.ui.button(id, str, x, y, w, h)
Returns true on the frame the button is clicked (press + release inside it).
mote.ui.captured()
True while the UI owns the pointer: hovering a widget, or mid-drag on one even if the pointer has since left it. A slider dragged off its track still belongs to the slider, and the world underneath should stay untouched until release.
mote.ui.checkbox(id, str, x, y, checked)
Returns the (possibly toggled) checked state.
mote.ui.defer(fn)
Queue a function to run at the end of the UI block, on top of everything.
mote.ui.dropdown(id, x, y, w, items, index)
Dropdown. `items` is an array of strings, `index` the current 1-based choice. Returns the (possibly new) index.
mote.ui.endScroll()
mote.ui.finish()
Call at the very end of the UI block: draws anything deferred (dropdown lists and other popups) on top, then drops keyboard focus if the click landed on empty space.
mote.ui.focused()
mote.ui.input(id, x, y, w, value, placeholder)
Pass the current string, use the return value as the new one.
mote.ui.isHot()
mote.ui.label(str, x, y, scale, c)
mote.ui.panel(x, y, w, h, c)
mote.ui.scale()
current auto-fit scale (e.g. to size your own draws consistently)
mote.ui.scrollTo(id, y)
Read or set a scroll position without drawing (e.g. "scroll to selection").
mote.ui.separator(x, y, w)
A thin horizontal rule, for grouping.
mote.ui.setReference(w, h)
mote.ui.slider(id, x, y, w, value, min, max)
Horizontal slider; returns the current value.
mote.ui.tabs(id, x, y, w, names, index)
A row of tabs. Returns the selected index.
mote.ui.window(id, title, x, y, w, h)
Draggable, titled window. Returns the content origin (x, y) and content width, so you place widgets relative to it. Remembers its position across frames.

mote.text#

text layout

mote.text.printAligned(str, x, y, boxW, scale, align)
Draw a single line aligned within a box of width boxW ("left"/"center"/"right").
mote.text.printWrapped(str, x, y, maxWidth, scale, lineHeight)
Draw wrapped text; returns the total height used.
mote.text.rich(str, x, y, scale, default)
Rich text with <color=...>...</color> (or <c=...></c>). Color can be a name, "r,g,b" floats, or "#rrggbb". Returns the height used.
mote.text.richDraw(str, x, y, opts)
Lay out and draw in one call. opts: width, size, color, scale, align ("left" | "center" | "right" within width). Returns width, height.
mote.text.richDrawLayout(lay, x, y, k, alpha, color)
Draw a layout from richLayout at screen (x, y). `k` multiplies sizes and positions (a UI scale), alpha multiplies every colour, color is the default.
mote.text.richLayout(str, maxW, opts)
Lay out rich text. opts: scale (1), color, size (current font size), width (wrap; nil = no wrap). Returns { lines, width, height }.
mote.text.width(str, scale)
mote.text.wrap(str, maxWidth, scale)
Break a string into lines that each fit within maxWidth (honours existing \n).

mote.audio#

audio

mote.audio.addEffect(name, e)
> index
mote.audio.addReverbZone(t)
addReverbZone{shape="sphere", x,y,z, radius, fade, preset|params, lowpass, priority} addReverbZone{shape="box", min={...}, max={...}} or {x,y,z, w,h,d}
mote.audio.bus(name, parent?)
buses -- bus(name, [parent]) -> name. Built in: master, music, sfx, ui, voice, ambient.
mote.audio.buses()
mote.audio.clearReverbZones()
mote.audio.duck(target, trigger, amount?, t?)
ducking -- duck(target, trigger, amount, {threshold, attack, release})
mote.audio.fade(id, to, time)
mote.audio.getBus(name)
mote.audio.getEnvironment()
> the blended reverb the listener hears now
mote.audio.getListener()
mote.audio.isPlaying(id)
mote.audio.level()
analysis -- level() -> peakL, peakR, rms (output meters)
mote.audio.load(src)
> ok, duration (decode now, avoid a hitch on first play)
mote.audio.micActive()
mote.audio.micLevel()
mote.audio.micSamples(n?)
mote.audio.micSpectrum(bands?)
mote.audio.musicId()
mote.audio.pause(id)
mote.audio.pauseAll()
mote.audio.pauseMusic()
mote.audio.play(src, a2, pitch?, looped?)
play -- play(src, [volume | opts], [pitch], [loop]) -> id
mote.audio.playAt(src, x, y, z, a5, looped?)
> id
mote.audio.playMusic(path, vol?, looped?, xf?, bus?)
music -- playMusic(path, [volume], [loop=true], [crossfade seconds], [bus])
mote.audio.removeReverbZone(id)
mote.audio.resume(id)
mote.audio.resumeAll()
mote.audio.resumeMusic()
mote.audio.reverbPresets()
mote.audio.set(id, k, v?)
set(id, key, value) or set(id, {key = value, ...}) — any voice knob.
mote.audio.setAutoListener(on)
follow the 3D camera again (default).
mote.audio.setBus(name, t)
setBus(name, {volume, muted, pitch, paused, send, parent})
mote.audio.setBusVolume(name, v)
mote.audio.setCone(id, dx, dy, dz, inner?, outer?, g?)
mote.audio.setDefaults(t)
setDefaults{minDist, maxDist, rolloff, model, doppler, air, spread}
mote.audio.setDopplerScale(v)
mote.audio.setEffect(name, which, key, v)
turn one knob live.
mote.audio.setEffects(name, list?)
setEffects(bus, { {"lowpass", freq = 800}, {"delay", time = 0.3, feedback = 0.5} })
mote.audio.setLimiter(on)
mote.audio.setListener(x, y, z, fx?, fy?, fz?, ux?, uy?, uz?)
listener
mote.audio.setListenerVelocity(x, y, z)
mote.audio.setMasterVolume(v)
global knobs
mote.audio.setMaxVoices(n)
mote.audio.setMusicVolume(v)
mote.audio.setPosition(id, x, y, z)
mote.audio.setReverb(v, lowpass?)
environment -- setReverb("cave") / setReverb{preset="hall", wet=0.5} / setReverb("none")
mote.audio.setSpeedOfSound(v)
mote.audio.setTimeScale(v)
everything slows and drops in pitch (bullet time).
mote.audio.setVelocity(id, x, y, z)
mote.audio.spectrum(bands?, n?)
> table 0..1 of what is playing now
mote.audio.startMic()
microphone
mote.audio.stats()
mote.audio.stop(id, fade?)
voice control
mote.audio.stopAll(fade?)
mote.audio.stopBus(name, fade?)
silence everything routed through a bus.
mote.audio.stopMic()
mote.audio.stopMusic(fade?)
mote.audio.synth(what, seed?)
synth -- synth("coin" [, seed]) / synth{preset="laser", slide=-12, ...} -> sound name
mote.audio.synthParams(name, seed?)
> table you can tweak and pass back to synth{}
mote.audio.synthPresets()
mote.audio.tell(id)
> time, duration, audibleGain
mote.audio.unduck(target, trigger)
mote.audio.unload(src)
mote.audio.waveform(n?)

mote.keyboard#

keyboard

mote.keyboard.getText()
mote.keyboard.isDown(name)
mote.keyboard.wasPressed(name)
mote.keyboard.wasReleased(name)

mote.mouse#

mouse

mote.mouse.getDelta()
mote.mouse.getPosition()
mote.mouse.getWheel()
mote.mouse.getX()
mote.mouse.getY()
mote.mouse.isDown(button)
mote.mouse.setGrabbed(v)
Grab / release the cursor (confine + lock to the window for mouse-look).
mote.mouse.setVisible(v)
Hide / show the OS cursor (e.g. for first-person mouse-look).
mote.mouse.wasPressed(button)
mote.mouse.wasReleased(button)

mote.gamepad#

gamepads

mote.gamepad.count()
mote.gamepad.getAxis(idx, axis)
mote.gamepad.isConnected(idx)
mote.gamepad.isDown(idx, btn)
mote.gamepad.wasPressed(idx, btn)
mote.gamepad.wasReleased(idx, btn)

mote.touch#

touch

mote.touch.count()
mote.touch.getTouches()

mote.window#

window

mote.window.getHeight()
mote.window.getSize()
mote.window.getWidth()
mote.window.setFullscreen(on)
mote.window.setMode(width, height, opts?)
mote.window.setResizable(on)
mote.window.setSize(width, height)
mote.window.setTitle(title)
mote.window.setVsync(on)

mote.net#

multiplayer

mote.net.allEntities()
mote.net.call(name, ...)
Invoke an RPC: client → server (on a client), or server → ALL clients (on a server).
mote.net.callAll(name, ...)
Server → all clients (explicit alias of call() on the server).
mote.net.callTo(clientId, name, ...)
Server → one specific client.
mote.net.connect(host, port, opts)
client
mote.net.despawn(netId)
mote.net.enableLagComp(seconds, fields)
Enable server-side lag compensation: keep `seconds` of position history so hits can be tested against where targets *were* on the shooter's screen. `fields` overrides which numeric fields are rewound (default = interpFields).
mote.net.entity(netId)
mote.net.getSync(key)
Read a synced global (server or client).
mote.net.hitscan(clientId, origin, dir, opts)
Built-in lag-compensated ray/sphere hitscan. origin/dir are {x,y[,z]} tables. opts: range, radius (fallback hitbox), ignoreOwner (default true). Returns netId, distance, entity of the nearest hit (or nil).
mote.net.isClient()
mote.net.isServer()
mote.net.onConnect(fn)
callback setters
mote.net.onDespawn(fn)
mote.net.onDisconnect(fn)
mote.net.onEvent(fn)
mote.net.onInput(fn)
mote.net.onReady(fn)
mote.net.onServerTick(fn)
mote.net.onSpawn(fn)
mote.net.ownedEntity(clientId)
The (first) entity owned by a client — handy in onInput.
mote.net.rewindTo(clientId, fn)
Run `fn` with every entity temporarily moved to where the shooter saw it, then restore. Use this to wrap ANY custom hit test for perfect lag compensation.
mote.net.role()
mote.net.rpc(name, fn)
Register an RPC handler: fn(fromId, ...). fromId = client id (server) or 0 (client).
mote.net.sendEvent(name, data)
events / RPC (reliable)
mote.net.sendEventTo(clientId, name, data)
mote.net.setInputSampler(fn)
mote.net.setInterest(opts)
Area of interest. mode="all" replicates everything (small games / CS servers). mode="radius" replicates only entities within `radius` of each client's owned entity (MMO scale) — the owned entity and anything flagged _alwaysRelevant are always sent.
mote.net.setOwner(netId, clientId)
mote.net.setPredict(fn)
mote.net.shutdown()
mote.net.spawn(etype, fields)
Spawn a networked entity (server). `fields` become replicated state.
mote.net.startServer(port, opts)
server
mote.net.sync(key, value)
Server: set a replicated global value.
mote.net.update(dt)
per frame

mote.network#

network transport

mote.network.address(id?)
mote.network.broadcast(msg, ch?)
Server → all clients.
mote.network.clientCount()
mote.network.clients()
> { id, id, ... } (server)
mote.network.connect(host, port, opts?)
mote.network.disconnect(id?)
mote.network.discover(port, game?)
start probing the LAN; servers() lists who answered.
mote.network.host(port, opts?)
mote.network.isClient()
mote.network.isConnected()
mote.network.isServer()
mote.network.ping(id?)
> round trip in ms (UDP). Client: id omitted.
mote.network.send(msg, ch?)
Client → server.
mote.network.sendTo(id, msg, ch?)
Server → one client.
mote.network.servers()
mote.network.setTimeout(secs)
mote.network.simulate(t?)
simulate{ lag = ms, jitter = ms, loss = 0..1 } — test a bad connection at home.
mote.network.stats(id?)
> { rtt, loss, sent, received, resent, bytesOut, bytesIn }
mote.network.stopDiscovery()
mote.network.transport()
> "udp" | "tcp" | nil

mote.locale#

localization

mote.locale.add(lang, t)
mote.locale.date(t, pattern)
mote.locale.get()
mote.locale.languages()
mote.locale.load(lang, path)
Load translations. `lang` "csv" reads a table with one column per language.
mote.locale.money(v, currency)
mote.locale.number(n, decimals)
A number with this language's decimal and grouping separators.
mote.locale.onChange(fn)
mote.locale.set(lang)
mote.locale.t(key, args)
Translate `key`, substituting {name} from `args`.

mote.juice#

game feel

mote.juice.applyCamera(fov)
Apply the shake to the 3D camera after g3.setCamera(...).
mote.juice.flash(r, g, b, a, seconds)
mote.juice.fov(base, target, speed)
Smoothed field of view: call every frame with the base and the wanted value.
mote.juice.hitStop(seconds)
mote.juice.impulse(amount, cfg)
mote.juice.shake()
Current shake: offset x, y, z (metres in camera axes) and roll (degrees).
mote.juice.shake2d(maxPixels)
2D shake in pixels (max) and radians.
mote.juice.slowMo(scale, seconds)
mote.juice.timeScale()
mote.juice.trauma()
mote.juice.update(dt)

mote.skeleton2d#

2D skeletal animation

mote.skeleton2d.loadSpine(path, opts)
Spine --- Load a Spine JSON export (3.8 / 4.x). opts.images: {name = image} for attachments (looked up by path, then name).
mote.skeleton2d.new(spec)
Build a skeleton definition (shared by any number of instances).

mote.action#

mote.action.add(name, keys)
Add extra keys to an existing action.
mote.action.axis(negName, posName)
Axis from two actions (e.g. -1/0/+1). Handy for movement.
mote.action.bind(name, keys)
Bind (replace) an action's keys. Keys are keyboard names or "mouse1/2/3".
mote.action.down(name)
Is any key of the action currently held?
mote.action.keys(name)
The keys currently bound to an action (for a controls UI).
mote.action.pressed(name)
Was any key of the action pressed this frame (edge)?

mote.ai#

mote.ai.agent(o)
mote.ai.astar(sx, sy, gx, gy, walkable)
mote.ai.blackboard()
mote.ai.canSee(fromPos, forward, target, opts, blocked)
Full sight check: FOV cone + range + line of sight.
mote.ai.fsm(initial)
Finite state machine — for AI, animation, dialogue, menus… anything with modes. Minimal use (unchanged from before): states with enter/update/exit + manual :to(). local m = mote.ai.fsm("idle") :state("idle", { enter=fn, update=fn, exit=fn }) :state("chase", { update=fn }) m:to("chase") ; m:update(dt) Declarative use (no hand-written switch statements): give each state its transitions, and the machine drives itself.
mote.ai.goap(opts)
Create a planner over a fixed action set.
mote.ai.goapAgent(cfg)
A runner that plans, then executes the plan one action at a time, replanning when an action fails or the plan runs out. cfg: actions = { … } (or planner = a mote.ai.goap instance) worldState = function() -> facts current facts (re-read on each replan) goal = facts | function(facts) -> facts Each action's perform(...) should return "running" | "done" | "failed".
mote.ai.gridGraph(o)
Convenience: build a grid graph usable with mote.ai.astar. Nodes are {x,y}. walkable(x,y) -> bool ; diagonal (default true) ; Manhattan/octile heuristic.
mote.ai.gridPath(graph, sx, sy, gx, gy)
Find a grid path in one call: returns list of {x,y} or nil.
mote.ai.inFov(fromPos, forward, target, halfAngle, range)
True if `target` lies inside a view cone (half-angle radians) + range.
mote.ai.lineOfSight(fromPos, target, blocked, step)
March from -> to, sampling `blocked(x,y[,z])`; false if anything blocks.
mote.ai.rvo(agent, neighbors, vpref, opts)
Pick a collision-free velocity for `agent` given nearby `neighbors`. agent = { pos, vel, radius, maxSpeed } neighbors= list of { pos, vel, radius } (agent itself is skipped) vpref = desired velocity this frame (e.g.
mote.ai.utility(actions)

mote.ai.bt#

mote.ai.bt.action(fn)
mote.ai.bt.condition(fn)
mote.ai.bt.invert(child)
mote.ai.bt.repeatN(child, n)
mote.ai.bt.selector(children)
mote.ai.bt.sequence(children)

mote.anim#

mote.anim.animator(model)
animation state machine == local anim = mote.anim.animator(model) :param("speed", 0):param("grounded", true) :state("move", mote.anim.blendTree1d(model, "speed"):add("idle",0):add("run",6)) :state("jump", { clip = "jump", loop = false }) anim:transition("move", "jump"):trigger("jump") anim:transition("jump", "move"):done() anim:transition("*", "fall"):bool("grounded", false) anim:start("move") -- each frame: anim:set("speed", spd):set("grounded", onGround) if pressedJump then anim:trigger("jump") end anim:update(dt) anim:drawRot(x, y, z, yaw, scale)
mote.anim.blendTree1d(model, param)
1D blend tree Blends between clips placed at threshold values along one parameter. At any value only the two neighbouring clips are active, blended via model:drawBlended and phase-matched on a shared normalized phase (keeps foot-steps in sync).
mote.anim.build(model, data)
Build an animator from a plain data table (editor-friendly format). mote.anim.build(model, { params = { speed = 0, grounded = true }, states = { move = { blendTree = { param = "speed", clips = { {clip="idle",value=0}, {clip="run",value=6} } } }, jump = { clip = "jump", loop = false }, }, transitions = { { from = "move", to = "jump", when = { { trigger = "jump" } } }, { from = "jump", to = "move", when = { { done = true } } }, { from = "*", to = "fall", when = { { param = "grounded", bool = false } } }, { from = "move", to = "run", when = { { param = "speed", op = ">", value = 5 } } }, }, start = "move", })
mote.anim.controller(model)
mote.anim.frames(images, frameTime, loop)
images: array of mote.graphics.loadImage handles.
mote.anim.grid(image, frameW, frameH)
Cut an image into a grid of frameW x frameH cells (row-major, 1-based index).
mote.anim.new(grid, frames, frameTime, loop)
Animate a set of grid frame indices.
mote.anim.path(points, duration, loop)
Animate motion along a spline path over `duration` seconds.
mote.anim.skeleton()
A 2D bone skeleton. Bones form a tree; each has a local angle and length. Forward kinematics computes world transforms; sprites can be attached.
mote.anim.spline(points, t)
Sample a Catmull-Rom spline through points (vec2 or {x=,y=}) at t in 0..1.
mote.anim.sprite2d(grid)
mote.anim.timeline()

mote.assets#

mote.assets.clearImages()
mote.assets.imageCount()
mote.assets.read(path)
any file of the game (folder, fused exe or package), the same lookup models and images use.
mote.assets.unloadImage(path)

mote.async#

mote.async.all(list)
Every one of them, results in the order given. Fails as soon as any one fails, cancelling the rest — a loading screen that waits for a file which is never coming is worse than one that says so.
mote.async.any(list)
The first that SUCCEEDS. Failures are tolerated until there are no runners left, and then the whole thing fails.
mote.async.await(x)
Inside a task: wait for something and return what it produced. An error in what you awaited is re-raised here; a cancellation cancels the waiter too.
mote.async.clear()
mote.async.count()
mote.async.delay(sec)
A task that finishes after `sec`. Useful on its own as a racer.
mote.async.mapLimit(items, limit, fn)
Run `fn` on each item concurrently, at most `limit` at a time. The shape a loading screen actually needs: everything at once saturates the disk, one at a time takes forever.
mote.async.now()
mote.async.race(list)
The first that FINISHES, win or lose; the others are cancelled. This is the one you want for "whichever comes first", including a timeout expressed as a plain number in the list.
mote.async.retry(n, fn, delay)
Run `fn` as a task, and if it fails try again, up to `n` attempts, waiting `delay` seconds between them (0 by default). The last failure is the one that comes back out, because that is the one worth reading.
mote.async.run(fn, ...)
Start a task. `fn` is called with `await` as its first argument, then whatever else you pass — so the common case needs no upvalues and no `mote.async.` prefix inside the body.
mote.async.step()
Inside a task: give up the rest of this frame.
mote.async.stop(t)
Stop a task. Accepts the task, or the bare coroutine older code held onto.
mote.async.timeout(sec, x)
Give up on something after `sec`. The thing being timed out is cancelled, not merely abandoned, so it stops consuming frames.
mote.async.toTask(x)
Turn anything awaitable into a task: a task stays itself, a number becomes a delay, a function becomes a sub-task, a list becomes `all`.
mote.async.try(x)
`await` that reports instead of raising: returns `ok, value...`.
mote.async.update(dt)
Advance every task. Safe to call from your own `mote.update`: the automatic tick has already stood down for this frame, so tasks still advance exactly once whichever way you do it.
mote.async.wait(sec)
Inside a task: pause for `sec` seconds.
mote.async.waitUntil(pred)
Inside a task: pause until `pred()` returns true, checked once per frame.

mote.autotile#

mote.autotile.draw(cfg)
Draw a tile grid with autotiling. cfg: image, tw, th, cols (tileset) solid(x,y) -> bool (which cells are filled) x0,y0,x1,y1 (cell range) lut(mask) -> tileIndex (map a 4-bit mask to a tileset index) originX,originY (world pixel origin, default 0)
mote.autotile.mask4(solid, x, y)
4-bit edge mask: N=1, E=2, S=4, W=8 (0..15). `solid(x,y)` = is a neighbour set.
mote.autotile.mask8(solid, x, y)
8-bit mask including diagonals (0..255): N,NE,E,SE,S,SW,W,NW as bits 1..128. Diagonals only count when both their edges are set (blob-tiling friendly).

mote.build#

packaging

mote.build.exe(out?)
> path | nil, err
mote.build.lpak(out?)
the same game as a data file next to an existing runtime, for iterating without re-fusing.
mote.build.verify(name?)
open a built package the way a player's machine will (decrypt, read main.lua) and report what is in it.

mote.cam2d#

mote.cam2d.new(opts)

mote.cam3d#

mote.cam3d.new(opts)
mote.cam3d.set(ex, ey, ez, tx, ty, tz, fov)
Low-level: set the engine camera directly (bypasses the rig).

mote.camera#

mote.camera.getShake()
mote.camera.shake(intensity, duration)

mote.camera2d#

mote.camera2d.controller(o)
mote.camera2d.follower(opts)
opts: { x, y, zoom=1, rot=0, lerp=8, deadzone=0, bounds={x,y,w,h}, shake=true }
mote.camera2d.getMouseWorld()
mote.camera2d.reset()
mote.camera2d.set(x, y, zoom?, rot?)
mote.camera2d.toScreen(wx, wy)
mote.camera2d.toWorld(sx, sy)

mote.camera3d#

mote.camera3d.fps(x, y, z, yaw, pitch)
First-person: eye at (x,y,z) looking along yaw/pitch.
mote.camera3d.lookAt(ex, ey, ez, tx, ty, tz)
mote.camera3d.orbit(tx, ty, tz, dist, yaw, pitch)
Orbit a target: distance + yaw (around Y) + pitch (up/down), in radians.
mote.camera3d.setFov(f)

mote.cloth#

mote.cloth.new(cfg)
Cloth

mote.collide#

mote.collide.aabb(a, b)
Do two AABBs overlap?
mote.collide.move(box, vx, vy, solids)
Move `box` by (vx,vy) resolving against `solids`, sliding along surfaces. Mutates and returns box.x, box.y and a list of hit normals {nx,ny}.
mote.collide.resolve(box, other)
Static penetration resolve: push `box` out of `other` along the least axis. Returns dx, dy applied (0,0 if not overlapping).
mote.collide.sweep(box, vx, vy, other)
Swept AABB: time in [0,1] of first contact moving `box` by (vx,vy), + normal. Returns (time, nx, ny). time==1 & (0,0) means no hit.

mote.crowd#

mote.crowd.new(opts)
Create a crowd. opts: navmesh = a mote.navmesh (smooth paths), OR gridGraph = a mote.ai.gridGraph (grid paths) cell = spatial-hash cell size for neighbour queries (default 2) arrive = waypoint arrival radius (default from agent radius) slow = arrival slowdown distance at the final waypoint (default 3) plus any mote.ai.rvo opts (timeHorizon, avoidWeight, samples)

mote.curve#

mote.curve.bezier(p0, p1, p2, p3, segments)
Sample a cubic Bézier into a flat-ish list of {x,y} points.
mote.curve.catmullRom(points, perSeg)
Smooth Catmull-Rom spline through control points {{x,y},...}. Returns a dense list of {x,y}. The curve passes through every control point.
mote.curve.cubic(p0, p1, p2, p3, t)
Cubic Bézier point at t.
mote.curve.length(pts)
Total length of a polyline {{x,y},...}.
mote.curve.pointAt(pts, u)
Constant-speed point at parameter u in [0,1] along a polyline (arc-length). Returns x, y, and the unit tangent tx, ty.
mote.curve.quad(p0, p1, p2, t)
Quadratic Bézier point at t.

mote.data#

mote.data.base64Decode(s)
Base64-decode back to a string.
mote.data.base64Encode(s)
Base64-encode a string.
mote.data.djb2(s)
djb2 hash of a string.
mote.data.fnv1a(s)
FNV-1a 32-bit hash of a string (fast, good distribution; NOT cryptographic).
mote.data.hashId(s)
Short stable id string from any string (hex of fnv1a).
mote.data.rleDecode(s)
mote.data.rleEncode(s)
Run-length encode/decode of a byte string (cheap compression for tilemaps etc.).

mote.debug#

mote.debug.circle(x, y, r)
mote.debug.collider(cam, shape)
Draw a collider / trigger shape. `shape` mirrors the raycast2d shapes: { kind = "box"|"aabb", x, y, w, h } (x,y = top-left) { kind = "circle", x, y, r } { kind = "segment", x1, y1, x2, y2 }
mote.debug.cross(x, y, s)
mote.debug.line(x1, y1, x2, y2)
mote.debug.off()
mote.debug.on()
mote.debug.path(cam, pts)
Draw an AI path / polyline through a list of {x=,y=} (or {x,y}) points.
mote.debug.point(x, y, s)
screen-space primitives (for HUD / gizmos)
mote.debug.ray(cam, ox, oy, dx, dy, len)
Draw a ray from an origin along a direction for `len` world units.
mote.debug.rect(x, y, w, h)
mote.debug.setColor(r, g, b, a)
mote.debug.text(str, x, y, sc)
mote.debug.toggle()
mote.debug.waabb(cam, x, y, w, h)
mote.debug.wcircle(cam, x, y, r)
mote.debug.wline(cam, x1, y1, x2, y2)
mote.debug.wpoint(cam, x, y, s)
world-space primitives (pass the camera as the first argument)

mote.devtools#

mote.devtools.brushLeaks()
What the 3D brush was left as at the end of the last frame: a list of { what, "file:line" } (empty when everything is back to the defaults).
mote.devtools.enable(on)
mote.devtools.trackBrush(on)
Track the 3D brush without opening F3 (true/false).
mote.devtools.watch(name, fn)

mote.ease#

mote.ease.get(name)
Look up an easing by name (default linear).
mote.ease.inBack(t)
mote.ease.inBounce(t)
mote.ease.inCirc(t)
mote.ease.inCubic(t)
mote.ease.inElastic(t)
mote.ease.inExpo(t)
mote.ease.inOutBack(t)
mote.ease.inOutBounce(t)
mote.ease.inOutCubic(t)
mote.ease.inOutExpo(t)
mote.ease.inOutQuad(t)
mote.ease.inOutQuart(t)
mote.ease.inOutSine(t)
mote.ease.inQuad(t)
mote.ease.inQuart(t)
mote.ease.inSine(t)
mote.ease.linear(t)
mote.ease.outBack(t)
mote.ease.outBounce(t)
mote.ease.outCirc(t)
mote.ease.outCubic(t)
mote.ease.outElastic(t)
mote.ease.outExpo(t)
mote.ease.outQuad(t)
mote.ease.outQuart(t)
mote.ease.outSine(t)

mote.ecs#

mote.ecs.world()
Create an empty world.

mote.editor#

mote.editor.add(kind)
mote.editor.build()
Build the project into a single self-contained executable, using the same code path as `mote fuse` on the command line: the running runtime is copied and the packaged game appended. Nothing has to be installed to run the result.
mote.editor.drawGizmos()
3D overlay: gizmo and selection outline. Call inside draw(), after the scene.
mote.editor.drawOverlay()
2D overlay: the panels. Call last in draw().
mote.editor.drawScene()
Draw every placed entity. A game that wants its own look can ignore this and walk `mote.editor.entities` itself — the table is the contract, not this call.
mote.editor.duplicate(i)
mote.editor.editable()
Where levels live. The project folder when there is one — a level belongs next to the game that loads it, under version control, not in an OS data directory the player will never look in. The save folder is the fallback for a packaged build, where the project no longer exists and the editor is read-mostly anyway.
mote.editor.enable(opts)
mote.editor.levels()
Every level in the project, by name, sorted.
mote.editor.load(name)
mote.editor.path()
mote.editor.push()
mote.editor.remove(i)
mote.editor.render()
Everything the editor draws, in the right order. Convenience for the common case where the game is happy to let the editor own the frame.
mote.editor.save(name)
mote.editor.say(m)
mote.editor.serialize()
mote.editor.toggle()
mote.editor.undo()
mote.editor.update(dt)
Call from mote.update. Returns true while the editor owns input, so a game can skip its own controls: `if not mote.editor.update(dt) then game(dt) end`.

mote.events#

mote.events.clear(name)
Remove every listener for an event (or all events if name is nil).
mote.events.emit(name, ...)
Emit an event; extra args are passed to each listener. Returns how many fired.
mote.events.off(h)
Unsubscribe using the handle returned by on()/once().
mote.events.on(name, fn)
Subscribe to an event. Returns a handle you can pass to off().
mote.events.once(name, fn)
Subscribe for a single fire.

mote.flipbook#

mote.flipbook.new(cfg)
Create a player over a sheet. cfg: image, frameW, frameH, [cols] (auto from image width).

mote.fn#

mote.fn.after(n, fn)
mote.fn.bind(obj, name)
A method with its receiver already attached, so it can be passed anywhere a plain function is wanted without `function(...) return o:m(...) end`.
mote.fn.compose(...)
Right to left, for when the maths reads better: `compose(c, b, a)` is the same machine as `pipe(a, b, c)`.
mote.fn.constant(v)
A function that always returns the same value, whatever it is called with.
mote.fn.curry(fn, arity)
Curry: call with fewer arguments than the function takes and get back a function waiting for the rest. The arity is read off the function itself when it is a Lua function, so `curry(f)` usually just works.
mote.fn.debounce(sec, fn)
Fire once, `sec` after the LAST call — the shape you want for "the player stopped typing", "the window stopped resizing", "the slider stopped moving". Every call inside the window pushes the deadline out again.
mote.fn.gather(fn)
mote.fn.identity(v)
Returns its argument. The identity function is the one you reach for when an API wants a key function and the element already is the key.
mote.fn.limit(n, fn)
Let the first `n` calls through and ignore the rest. `after(n, fn)` is the mirror: ignore the first `n`, then let everything through.
mote.fn.memoize(fn, keyFn)
Cache results by argument. The key is the first argument by default, or whatever `keyFn` returns — which is how you memoise on a pair: pass `function(x, y) return x .. ":" .. y end`. A function that legitimately returns nil is cached too, through a sentinel; storing nil in the table would mean recomputing it forever, which is exactly the case where memoising was supposed to help.
mote.fn.method(name, ...)
`method("hurt", 10)` is `function(o) return o:hurt(10) end`. The colon call is the point: `prop` cannot express it because `o.hurt` loses the receiver.
mote.fn.negate(pred)
The logical inverse of a predicate.
mote.fn.noop()
A function that does nothing. Cheaper and clearer than `function() end` written out at every call site that wants an optional callback.
mote.fn.now()
mote.fn.once(fn)
Run at most once; every later call returns the first result. The idiom for "initialise on first use" without a boolean flag in an upvalue.
mote.fn.partial(fn, ...)
Fix the leading arguments of a function.
mote.fn.partialRight(fn, ...)
Fix the TRAILING arguments instead. Needed more often than it looks: most engine calls put the subject first and the options last, so `partialRight` is what fixes the options and leaves the subject open.
mote.fn.pipe(...)
Left to right: `pipe(a, b, c)(x)` is `c(b(a(x)))`. This direction, not the mathematical one, because it reads in the order the data actually moves — which is the whole reason to write it as a pipe instead of nesting calls.
mote.fn.prop(path)
`prop "hp"` is `function(e) return e.hp end`, and `prop "stats.hp"` walks the path, stopping at the first nil rather than erroring — a missing branch in a data file should read as "no value", not as a crash in a sort comparator.
mote.fn.safe(fn, fallback)
Call `fn`, and if it errors return `fallback` instead of unwinding. For the places where one bad entity should not take the frame down with it; the error is still printed, because silently swallowing it is how a bug lives for a month.
mote.fn.spread(fn)
Turn `f(a, b, c)` into `f{ a, b, c }` and back. Useful at the seam between a query pipeline (which carries one value per element) and a function that wants several.
mote.fn.tap(fn)
Call `fn` for its side effect, then return the value untouched. The one combinator that makes a pipe debuggable: drop `mote.tap(print)` into the middle of one and the values walk past on the console without the pipe changing shape.
mote.fn.throttle(sec, fn, opts)
At most one call per `sec`. Fires immediately on the first call (`leading`), and once more at the end of the window with the most recent arguments if any were dropped (`trailing`) — that trailing call is the difference between a throttled autosave that saves the latest state and one that saves whatever happened to land on a window boundary.

mote.font#

mote.font.count()
mote.font.load(path)
> id. TrueType or OpenType, read through the same virtual filesystem as every other asset, so it works the same from a folder, a .lpak and a fused exe.
mote.font.metrics(id, px)
> { ascent, descent, lineGap, lineHeight }. What a layout needs to align a label against something that is not text.
mote.font.name(id)

mote.game#

mote.game.ability(opts)
abilities === Cooldown + resource cost + optional cast time (WoW / MOBA style).
mote.game.actor(opts)
actors === A game entity with health, team, tags and a position. Drives combat.
mote.game.interactable(x, y, z, radius, onUse)
mote.game.interactAt(px, py, pz)
Nearest interactable within range of (px,py,pz), or nil.
mote.game.inventory(opts)
inventory === Stackable items with an optional weight limit (survival).
mote.game.moveInteractable(id, x, y, z)
mote.game.removeInteractable(id)
mote.game.spawner(points)
spawns === Spawn points + timed respawn helper.
mote.game.use(id, ...)
mote.game.weapon(opts)
weapons === Hitscan weapon with ammo, reload, fire rate and spread. Uses physics raycast.

mote.gamestate#

mote.gamestate.current()
mote.gamestate.draw()
Draw the stack bottom→top from the last state that requests it opaque. By default draws every state so overlays (pause menu over frozen game) work; a state can set `opaque = true` to stop lower states drawing beneath it.
mote.gamestate.emit(name, ...)
Forward an arbitrary event (e.g. input) to the top state.
mote.gamestate.pop(...)
Pop the top state; resumes the one below.
mote.gamestate.push(state, ...)
Push a state on top (pauses the one below). Good for pause/dialog overlays.
mote.gamestate.switch(state, ...)
Replace the entire stack with one state.
mote.gamestate.update(dt)
Update only the top state.

mote.geom#

mote.geom.area(poly)
Signed area (positive = counter-clockwise) and its magnitude.
mote.geom.centroid(poly)
Polygon centroid (x, y).
mote.geom.convexHull(poly)
Convex hull (Andrew's monotone chain). In: {x1,y1,...} → out: hull {x,y,...}.
mote.geom.fill(poly)
Convenience: fill a concave polygon (triangulates, then draws).
mote.geom.pointInPoly(px, py, poly)
Is point (px,py) inside a polygon? (ray casting)
mote.geom.segIntersect(x1, y1, x2, y2, x3, y3, x4, y4)
Segment/segment intersection point, or nil.
mote.geom.triangulate(poly)
Ear-clipping triangulation of a simple polygon. Returns a list of triangles, each {x1,y1,x2,y2,x3,y3} — feed to mote.graphics.polygon("fill", ...) to fill CONCAVE shapes (which a fan can't do).

mote.gfx#

mote.gfx.apply(x, y)
Transform a local point to screen space.
mote.gfx.arc(mode, cx, cy, r, a0, a1, seg)
Arc / pie slice.
mote.gfx.circle(mode, cx, cy, r, segments)
mote.gfx.gradientRect(x, y, w, h, c1, c2, horizontal, bands)
Vertical/horizontal gradient rectangle (c1/c2 = {r,g,b,a}). Stacks colour bands.
mote.gfx.image(img, x, y, r, sx, sy, ox, oy)
Draw an image through the transform (position + accumulated rotation/scale).
mote.gfx.ngon(mode, cx, cy, r, n, rot)
Regular n-gon (also the basis for circles).
mote.gfx.origin()
mote.gfx.polygon(mode, pts)
Polygon from a flat point list {x1,y1,x2,y2,...}.
mote.gfx.polyline(width, pts)
Thick polyline: a flat point list drawn as quads of pixel `width`.
mote.gfx.pop()
mote.gfx.print(text, x, y, scale)
Print text through the transform (position + scale).
mote.gfx.push()
mote.gfx.rect(mode, x, y, w, h)
Rectangle (becomes a transformed quad, so rotation/shear work).
mote.gfx.reset()
mote.gfx.rotate(t)
mote.gfx.roundrect(mode, x, y, w, h, r, seg)
Rounded rectangle.
mote.gfx.scale(sx, sy)
mote.gfx.shear(kx, ky)
mote.gfx.star(mode, cx, cy, outer, inner, points, rot)
Star with `points` spikes.
mote.gfx.translate(x, y)

mote.gpu#

mote.gpu.burst(n)
Emit a one-off burst of n particles on the next step().
mote.gpu.set(def)
Update one or more fields at runtime (e.g. move the emitter each frame): mote.gpu.set{ emitter = { mx, my, 0, 4 } }
mote.gpu.setRate(r)
mote.gpu.step(dt)
Advance the simulation: accumulate the continuous spawn rate + any bursts and hand dt / time / spawn count to the GPU. Call once per frame.
mote.gpu.stop()
mote.gpu.system(def)
Configure (or reconfigure) the system. See the header for the fields.

mote.hotreload#

mote.hotreload.disable()
mote.hotreload.enable(opts)
Enable hot reload. opts: { reloadMain=true, pollFrames=20 }.
mote.hotreload.tick()
Poll watched files (called automatically each frame when enabled).
mote.hotreload.unwatch(path)
mote.hotreload.watch(path, onChange)
Watch a source/asset path; onChange(path) fires when its mtime advances.

mote.input#

mote.input.axis(opts)
mote.input.button(sources)
action constructors (tagged tables)
mote.input.new(opts)
mote.input.vector(opts)

mote.json#

mote.json.decode(s)
Decode a JSON string. Returns the value (or nil, err on failure).
mote.json.encode(v)

mote.light#

mote.light.clear()
mote.light.emit()
Push every live light for this frame. Call once per frame before drawing 3D.
mote.light.move(id, x, y, z)
mote.light.point(opts)
Add a point light (glows through volumetric haze). Returns an id.
mote.light.remove(id)
mote.light.setColor(id, r, g, b)
mote.light.setHaze(opts)
Configure the volumetric haze that lights become visible in. strength (0 = off), density (thickness), phase (-0.95..0.95 forward scatter).
mote.light.setIntensity(id, i)
mote.light.setRange(id, r)
mote.light.sun(dir, color, intensity)
Add/replace the directional sun (also drives volumetric god-rays + shadows).

mote.light2d#

mote.light2d.new(o)

mote.mixer#

mote.mixer.bus(name, volume, parent)
Declare / configure a bus. Returns the bus name for chaining.
mote.mixer.effects(name, list)
mote.mixer.getVolume(name)
mote.mixer.music(name, path, volume, loop, crossfade)
Background music routed through a bus (crossfades from the previous track).
mote.mixer.mute(name, on)
mote.mixer.play(name, path, volume, pitch, loop)
Play a sound through a bus. Extra args mirror mote.audio.play.
mote.mixer.playAt(name, path, x, y, z, volume, loop)
Positional (3D) sound through a bus.
mote.mixer.setMaster(v)
mote.mixer.setVolume(name, v)
mote.mixer.stopBus(name, fade)
Stop every live sound on a bus (optionally fading).
mote.mixer.stopMusic(_, fade)
mote.mixer.update()
Kept for compatibility; the engine does this itself now.

mote.navmesh#

mote.navmesh.fromGrid(opts)
Build a navmesh at runtime from a walkable grid (e.g. a tilemap or a rasterized set of obstacles). Each walkable cell becomes one quad; because all cells are the same size and aligned, neighbouring cells share exact full edges, so adjacency is robust (no T-junctions) and the funnel smooths the per-cell corridor into straight lines.
mote.navmesh.fromHeightmap(opts)
Build a 3D navmesh over a heightmap (terrain / ramps). Each grid cell becomes a quad whose four corners carry real heights sampled from `sample(gx, gy)` at the corner grid coords (gx in 0..cols, gy in 0..rows).
mote.navmesh.fromTriangles(vflat, iflat, dim)
Build from a triangle soup: flat vertex list (x,y[,z]) + flat index triples.
mote.navmesh.new(polys, dim)
Build from a list of polygons (each a list of points, convex, consistent order).

mote.nineslice#

mote.nineslice.new(cfg)
Create a 9-patch from an image + border insets (pixels). Optional src region {sx,sy,sw,sh} if the patch is inside an atlas (defaults to the whole image).

mote.noise#

mote.noise.fbm(x, y, opts)
Fractal Brownian motion (layered perlin). opts: octaves, lacunarity, gain.
mote.noise.fbm3(x, y, z, opts)
Layered 3D perlin. Same options as `fbm`: octaves, lacunarity, gain.
mote.noise.perlin(x, y)
Perlin noise in [-1,1] (2D).
mote.noise.perlin01(x, y)
Perlin remapped to [0,1].
mote.noise.perlin3(x, y, z)
Perlin noise in [-1,1] (3D).
mote.noise.perlin301(x, y, z)
3D Perlin remapped to [0,1].
mote.noise.ridged(x, y, opts)
Ridged multifractal (sharp mountain ridges), [0,1].
mote.noise.seed(s)
mote.noise.worley(x, y)
Worley / cellular noise: distance to the nearest feature point (F1), [0,~1]. Great for stone, scales, cracks (use 1-F1), and Voronoi looks.

mote.parallax#

mote.parallax.new()

mote.particle#

mote.particle.new(cfg)

mote.particle2d#

mote.particle2d.new(cfg)

mote.particles#

mote.particles.explosion(x, y, power)
mote.particles.fire(x, y)
mote.particles.fire3d(x, y, z)
mote.particles.magicTrail(x, y, z)
mote.particles.new()
mote.particles.new3d()
mote.particles.smoke(x, y)
mote.particles.smoke3d(x, y, z)
mote.particles.sparks(x, y)
mote.particles.sparks3d(x, y, z, power)
mote.particles.trail3d()
mote.particles.water(x, y)
mote.particles.water3d(x, y, z)

mote.plugins#

mote.plugins.draw()
Draw every plugin that defines a draw() hook.
mote.plugins.each(fn)
Iterate loaded plugins: fn(name, module).
mote.plugins.get(name)
Get a registered plugin module by name.
mote.plugins.has(name)
Is a plugin loaded?
mote.plugins.list()
List loaded plugin names (in load order).
mote.plugins.register(nameOrTable, tbl)
Register a plugin module. Call with (table) to use the folder name, or (name, table) to name it explicitly.
mote.plugins.update(dt)
Tick every plugin that defines an update(dt) hook.

mote.pool#

mote.pool.new(factory, reset)
factory() makes a fresh object; reset(obj) preps a reused one (both optional; default factory returns {}).

mote.profile#

profiling

mote.profile.callsite(level?)
line": where the code `level` frames up the stack is (1 = the function calling callsite). Works without the debug library, which games do not get.
mote.profile.enable(on?)
mote.profile.gc()
Lua memory: used KB and garbage made per frame (KB, averaged over 0.5 s).
mote.profile.lua(on?)
the sampling Lua profiler (see LuaProf)
mote.profile.luaFrame()
"Lua was not running until now" — the time since the last sample (rendering, vsync) is not charged to anyone. devtools calls it before update and before each render hook.
mote.profile.luaReport(n?)
> { {name=, self=ms, total=ms, selfShare=0..1, totalShare=}, ... }, the n hottest functions by self time since the last luaReset()
mote.profile.luaReset()
mote.profile.scope(name, f, args)
time a piece of the game's own frame. The function's return values are passed straight through, so wrapping a call in a scope never changes what it does.
mote.profile.stats()

mote.project#

mote.project.dir()
> absolute path | nil. nil means "not editable": running from a package, so every tool should hide its save controls.
mote.project.exists(rel)
> bool
mote.project.list(sub?, ext?)
> { "a.lua", "b.lua" }. Names only, sorted, so a level browser is three lines of Lua.
mote.project.read(rel)
> string | nil
mote.project.write(rel, data)
> ok, err

mote.reactive#

mote.reactive.batch(fn)
Coalesce a burst of writes into one notification. Nested calls are fine; only the outermost one flushes.
mote.reactive.bind(src, obj, key)
Keep `obj[key]` equal to a reactive value. The bridge between reactive state and the plain tables the rest of the engine reads every frame — set it up once and the entity, the light, the material stays in step by itself.
mote.reactive.computed(fn)
A value derived from other reactive values. Recomputed lazily — on the first read after something it depends on changed — so a computed nothing looks at costs nothing.
mote.reactive.effect(fn)
Run `fn` now, and again whenever anything it read has changed. Returns a handle with `:stop()`; an effect that outlives the thing it updates is a leak that shows up as a crash three scenes later, so stop it when the owner dies.
mote.reactive.isRef(v)
True for a ref or a computed, so an API can accept either a plain value or a reactive one and tell them apart.
mote.reactive.ref(v)
A value other things can depend on. Call it to read, call it with an argument to write; `.value` does the same for code that prefers a field.
mote.reactive.watch(src, cb, opts)
Watch a source and call `cb(new, old)` when its value changes. The source may be a ref, a computed, a plain function of reactive values, or a list of any of those (then `new`/`old` are lists). With `opts.immediate` the callback also fires once straight away; with `opts.once` it fires at most once and then stops itself.

mote.rng#

mote.rng.new(seed)
Create a stream seeded by `seed` (default: time-ish). Deterministic per seed.

mote.rope#

mote.rope.new(cfg)
Rope

mote.save#

mote.save.autosave(slot, interval, dataFn)
Autosave: every `interval` seconds, call dataFn() and write the result to `slot` (skipped if it returns nil). Returns a timer handle (mote.cancel it).
mote.save.delete(slot)
Delete a slot (does not remove its backups).
mote.save.dir()
Absolute path of the save folder (for display/debugging).
mote.save.exists(slot)
Does a slot exist?
mote.save.list()
List existing slot names (without extension).
mote.save.read(slot, opts)
Read a named slot. Returns (data, info) or (nil, err). `data` is migrated to the current version. On corruption, pass opts.fallbackBackup=true to try the newest backup instead.
mote.save.setIdentity(name)
Set the per-game save folder name (call once, e.g. in mote.load).
mote.save.slot(name)
A small handle bound to one slot: obj:write(data), obj:read(), obj:exists(), obj:delete().
mote.save.write(slot, data, opts)
Write `data` to a named slot. Returns (true) or (false, err). opts = { encrypt = bool, backups = int } overrides config per call.

mote.scene#

mote.scene.count()
mote.scene.current()
mote.scene.find(name)
mote.scene.findWithTag(tag)
mote.scene.load(name)
mote.scene.newObject(name?)
mote.scene.switch(name)
mote.scene.unload(name)

mote.screen#

mote.screen.draw()
Draw flash + fade overlays. Call last in mote.draw().
mote.screen.fade(duration, dir, cb)
Fade "out" (to black) or "in" (from black) over `duration`; cb on complete.
mote.screen.flash(r, g, b, duration, a)
Flash a full-screen colour that fades out over `duration`.
mote.screen.offset()
Current shake offset — add it to your camera position.
mote.screen.shake(intensity, duration)
Trigger a shake of `intensity` pixels for `duration` seconds.
mote.screen.update(dt)

mote.shapes#

mote.shapes.capsule(x, y, z, r, h, seg)
capsule (pill): a cylinder capped by two hemispheres.
mote.shapes.cone(x, y, z, r, h, seg)
mote.shapes.cylinder(x, y, z, r, h, seg)
solids
mote.shapes.disc(x, y, z, r, seg)
flat disc facing +Y.
mote.shapes.grid(nx, nz, spacing, y, fn)
mote.shapes.prism(x, y, z, r, h, sides)
n-sided flat-faced prism (hexagonal columns, crystals, etc.).
mote.shapes.pyramid(x, y, z, base, h, sides)
n-sided pyramid (default 4 = a proper pyramid; higher = spire).
mote.shapes.ring(count, radius, y, fn)
modifiers: place many shapes with one call
mote.shapes.scatter(count, area, seed, fn)
mote.shapes.spiral(count, radius, rise, turns, fn)
mote.shapes.torus(x, y, z, ringR, tubeR, seg, sides)
torus (donuts, rings, halos).
mote.shapes.tube(x, y, z, r, h, thick, seg)
hollow cylinder (pipes, rings, arches).
mote.shapes.wedge(x, y, z, w, h, d)
wedge / ramp (right-triangle prism): rises from +Z front to -Z back.

mote.softbody#

mote.softbody.box(cx, cy, cz, size)
A springy soft cube: 8 corners fully cross-linked (holds its shape but jiggles).
mote.softbody.new(cfg)
Soft body Give explicit points {{x,y,z},...} + links {{a,b},...}, or a box helper below.

mote.spatial#

mote.spatial.new(cell)

mote.textfx#

mote.textfx.rainbow(text, x, y, scale, t, speed)
Rainbow-cycled text. Sets colour per character (restore your colour after).
mote.textfx.shake(text, x, y, scale, intensity)
Per-character jitter (impact / scared text). `intensity` in pixels.
mote.textfx.typewriter(text, x, y, scale, count)
Reveal the first `count` characters (typewriter). Returns the x cursor end.
mote.textfx.wave(text, x, y, scale, t, amp, freq, speed)
Vertical sine wave per character. `t` = time; amp/freq/speed optional.

mote.tiled#

mote.tiled.load(path, opts)
Load a map from a Tiled JSON file in the virtual filesystem.

mote.tilemap#

mote.tilemap.new(o)

mote.timer#

mote.timer.getTime()

mote.trigger#

mote.trigger.clear(id)
mote.trigger.on(id, onEnter, onExit)
mote.trigger.update(world)

mote.vehicle#

mote.vehicle.new(cfg)
cfg: body (chassis rigidbody id), world (mote.physics3d), wheels = { {offset={x,y,z}, radius=, rest=, stiffness=, damping=, drive=bool, steer=bool}, ... }.

mote.vfx#

mote.vfx.alphaOverLife(ramp)
mote.vfx.attract(cx, cy, strength)
mote.vfx.collision(opt)
mote.vfx.colorOverLife(grad)
mote.vfx.curl2(x, y)
divergence-free 2D flow (curl of a noise potential)
mote.vfx.curlNoise(scale, strength)
mote.vfx.drag(coef)
mote.vfx.fbm2(x, y, oct)
mote.vfx.force(field)
mote.vfx.gradient(points)
gradient: interpolate a colour over 0..1 through { {t, {r,g,b,a?}}, ... }
mote.vfx.gravity(gx, gy, gz)
modules Modules are function(p, dt, sys) that mutate a particle. Chain them in order.
mote.vfx.noise2(x, y)
mote.vfx.radial(cx, cy, strength)
mote.vfx.ramp(points)
curves ramp: interpolate a scalar over 0..1 through control points { {t, value}, ... }
mote.vfx.rand(seed)
mote.vfx.repel(cx, cy, strength)
mote.vfx.sizeOverLife(ramp)
mote.vfx.system(def)
system
mote.vfx.turbulence(scale, strength)
mote.vfx.vortex(cx, cy, strength)
mote.vfx.wind(dx, dy, dz)
fields A field is function(x,y,z,time) -> fx,fy,fz. Apply one as a force via V.force.

mote.vfx.emit#

mote.vfx.emit.circle(cx, cy, r, filled)
mote.vfx.emit.fromParticles(other)
spawn from another system's live particles (e.g. secondary sparks off a trail)
mote.vfx.emit.line(x1, y1, x2, y2)
mote.vfx.emit.point(x, y, z)
mote.vfx.emit.polygon(pts)
mote.vfx.emit.rect(x, y, w, h)

mote.vfx.render#

mote.vfx.render.circle(r)
mote.vfx.render.cube(sz)
mote.vfx.render.custom(fn)
mote.vfx.render.point(size)
mote.vfx.render.sphere(r)
mote.vfx.render.sprite(image, imgW, imgH, size)
sprite: pass the image's pixel size so it can be centred + scaled by p.scale
mote.vfx.render.streak(len)
mote.vfx.render.text(str, scale)

mote.vr#

mote.vr.getController(idx)
> table of pose + inputs (or nil if absent).
mote.vr.getHeadPose()
> x, y, z, qx, qy, qz, qw
mote.vr.isActive()
mote.vr.isAvailable()
mote.vr.recenter()
mote.vr.setActive(on)
mote.vr.vibrate(idx, amp, dur?)
vibrate(index, amplitude 0..1, duration seconds)

Agent methods#

agent:addForce(f, w)
Add a raw steering force (already a vector), weighted.
agent:align(neighbors, radius, w)
agent:arrive(target, slow, w)
agent:arrived()
agent:avoid(obstacles, w, lookAhead)
Steer around circular obstacles {pos=, radius=}.
agent:canSee(x, y, z, fov, range, ignoreBody)
Can this agent see a point? Inside `fov` degrees of its facing (default 120), within `range` (30), and nothing solid in between.
agent:cohere(neighbors, radius, w)
agent:evade(target, targetVel, w)
agent:flee(target, w)
agent:flock(neighbors, opts)
Combined boids: separation + alignment + cohesion.
agent:follow(target, stopAt)
Keep walking toward another object (or a function returning x, y, z); `stopAt` metres short of it.
agent:followPath(path, w, arrive)
Follow a polyline path (list of points); returns to the last point on arrival.
agent:heading()
agent:moveTo(x, y, z)
Walk to a point. Returns false when there is no way at all.
agent:patrol(pathName, wait)
Walk a path from Blender (by name) back and forth, or round if closed. Also takes a list of points {{x,y,z}, ...} or of objects (waypoints), walked round in order.
agent:position()
agent:pursue(target, targetVel, w)
Predictive: aim where the target will be.
agent:seek(target, w)
agent:separate(neighbors, radius, w)
Flocking primitives. `neighbors` is a list of agents (or {pos=,vel=}).
agent:speed()
agent:stop()
agent:update(dt)
agent:wander(w, jitter)
Smooth random roaming (any dimension).

Async methods#

handle:error()
handle:ready()
> true when finished (loaded or failed)
handle:result()
> the model / image, or nil while loading or on failure

Body methods#

body:draw(opts)
Draw the body as its collider shape (P.drawBody options).
body:isValid()
body:move(dx, dy, dz, dt)
Character move for a kinematic body: moved x, y, z and grounded.
body:remove()

Buffer methods#

buffer:id()
buffer:set(t, off?)
uploaded before the buffer's next use.
buffer:size()

C methods#

c:apply()
c:forward()
Ground-plane basis for movement code (character walks relative to camera).
c:getPosition()
c:pan(right, forward)
Pan the internal focus along the ground (right, forward), relative to yaw. Used for strategy/RTS style movement (no target).
c:right()
c:rotate(dx, dy)
driving the camera
c:setAngles(yaw, pitch)
c:setDistance(d)
c:setFocus(x, y, z)
c:setFov(f)
c:setOffset(x, y, z)
c:setSmoothing(pos, look, fov)
c:setTarget(t)
configuration (all chainable)
c:shake(intensity, duration)
c:update(dt)
c:zoom(dz)

C2 methods#

c2:apply()
c2:follow(t)
c2:setBounds(b)
c2:setRotation(r)
c2:setZoom(z)
c2:shake(i, d)
c2:update(dt)

Cam methods#

cam:apply()
Push this camera to the renderer (call in draw, before drawing the world).
cam:clearBounds()
cam:getPosition()
cam:setBounds(x, y, w, h)
cam:setRoom(x, y, w, h, snap)
Room-based framing: bound the camera to a room rect; optionally jump to it.
cam:setTarget(x, y)
cam:setZoom(z)
cam:shake(amp, dur)
cam:snap()
cam:toScreen(wx, wy)
World<->screen through this controller (works for sprites/tilemaps that draw in screen space, independent of the native camera state).
cam:toWorld(sx, sy)
cam:update(dt)

Char methods#

char:addLayer(name, opts)
layers A layer over the base animation. opts: mask (bone or list: that bone and everything below it), exclude, maskWeights = { Bone = w }, additive, ref/refTime (additive reference), weight (0).
char:clip()
char:clips()
char:die(opts)
ragdoll Go limp. opts: impulse = {x,y,z} (+ bone), velocity = {vx,vy,vz} (the character's own motion), fade (0.08 s), plus pose:ragdoll options (mass, thickness, swing, twist, friction, damping).
char:draw(x, y, z, yaw, scale)
Draw at a position, turned by yaw (radians, 0 = facing +z), uniform scale.
char:duration(clip)
char:flinch(impulse, bone, amount)
Hit while alive: a partial ragdoll flinch that recovers by itself.
char:footIK(opts)
foot IK Feet on the ground: stairs, slopes, rubble. true, false, or options (maxStep, smooth, align, maxAngle, legs, pelvis, ignore = {bodyIds}, weight).
char:footIKWeight(w)
Fade foot IK (0 while airborne, 1 on the ground).
char:get(name)
char:getUp(secs)
Back to animation over secs (stands up from where it lies).
char:isDead()
char:isRagdoll()
char:layer(name)
char:layerPlay(name, clip, opts)
Play a clip on a layer. opts: loop (true), speed (1), fadeIn (0.15), fadeOut (0.2, used when a one-shot ends), weight (1), restart (true).
char:layerStop(name, secs)
char:layerWeight(name, w, secs)
Fade a layer's weight to w over secs.
char:on(name, fn)
Call fn(eventName, clip) when an event marker is passed. name "*" = all.
char:onPose(fn)
fn(pose) after everything else, before drawing: aim, look-at, recoil.
char:onState(fn)
char:play(name, fade)
char:ragdollBody(bone)
char:ragdollPosition()
char:rootMotion(on, bone)
root motion Let the clips move the character: the root stays in place in the pose, and takeRootMotion gives the travel. bone = which bone (auto).
char:set(name, value)
char:setSpeed(s)
char:state()
char:states()
char:takeRootMotion(yaw, scale)
World-space travel since the last call: dx, dz, dyaw (and dy).
char:trigger(name)
char:update(dt)

Convex methods#

convex:add(kind, x, y, z, rest?, fric?)
one body carrying every piece. kind is "static", "dynamic" or "kinematic".
convex:addAnimated(fric?)
one kinematic body per piece, ready to be driven by the skeleton. Returns a rig; call rig:sync(...) every frame.
convex:bone(i)
name of the bone carrying piece `i`, or nil if it is free.
convex:count()
convex:hullMesh(i)
piece `i` as a flat triangle array for graphics3d.mesh.
convex:info()
what the bake actually produced, as opposed to what was asked for. V-HACD stops early when the model is simpler than the budget, so the piece count is a result, not a setting, and the vertex numbers are how you find out whether maxVerts is doing anything.

ConvexRig methods#

convexrig:count()
convexrig:hullMesh(i)
piece `i` where the last sync put it, for debug drawing.
convexrig:ids()
the raw body ids, so the rest of mote.physics3d still applies: collision groups, sensors, raycasts, removal.
convexrig:remove()
convexrig:sync(anim, time, x, y, z, scale?)
move every piece onto the pose the model would draw with the same arguments. Call it once per frame, next to the draw. `anim` may be nil for the rest pose.

Crowd methods#

crowd:add(m)
Add an agent. m = { pos={x,y[,z]}, radius=, maxSpeed= } (all optional but pos).
crowd:arrived(m, eps)
Has an agent reached (near) its goal?
crowd:setGoal(m, gx, gy, gz)
Give an agent a goal; computes a path via the navmesh/grid (or a straight line if neither was provided). Returns true if a path was found.
crowd:update(dt)
Step the whole crowd: preferred velocities, reciprocal avoidance, integrate. On a 3D navmesh, agents are re-projected onto the walkable surface each frame (so they follow ramps / terrain) unless opts.snapToFloor == false.

Def methods#

def:addAnimation(name, a)
def:instance()

FB methods#

fb:clip(name, def)
Define a clip: { from, to (0-based frame indices), fps, loop=true, pingpong=false }.
fb:draw(x, y, r, sx, sy, ox, oy)
Draw the current frame. Signature mirrors image:draw (x,y,[r],[sx],[sy],[ox],[oy]).
fb:isPlaying(name)
fb:onEnd(fn)
fb:pause()
fb:play(name, force)
Play a clip (restarts if different, or if force=true).
fb:resume()
fb:update(dt)

Follower methods#

follower:setBounds(b)
follower:setZoom(z)
follower:snap(tx, ty)
Jump instantly (no lerp) — e.g. on level load / teleport.
follower:update(dt, tx, ty)
Advance toward (tx,ty) and apply to the native camera. Returns cam x,y.

G methods#

g:clear()
g:insert(id, x, y, r)
Insert item `id` at (x,y) with optional radius (default 0). Any id (number/table/string).
g:overlaps(x, y, r)
Precise circle-overlap query (filters the broadphase by actual distance).
g:query(x, y, r)
Ids whose cells overlap a circle at (x,y,r). Broadphase (may include near-misses).
g:queryRect(x, y, w, h)
Ids whose cells overlap an axis-aligned rectangle.

IM methods#

im:add(name, act)
im:bindings(name)
im:disable()
im:down(name)
im:enable()
Enable/disable this context (menu vs gameplay maps).
im:pressed(name)
im:rebind(name, index, source)
Rebuild a button action's probe at index (for rebinding UIs).
im:released(name)
im:setActive(b)
im:setGamepad(idx)
im:update()
Call once per frame: refresh button edge (pressed/released) state.
im:value(name)
Scalar axis value (analog trigger/stick axis and/or key pair), -1..1 or 0..1.
im:vector(name)
2D vector (keys / stick / dpad / mouse). Returns x, y with +y up. Sticks and keyboard are normalized; mouse returns raw delta * mouseScale (for look).

Image methods#

image:draw(x, y, r?, sx?, sy?, ox?, oy?)
image:drawRegion(qx, qy, qw, qh, x, y, r?, sx?, sy?, ox?, oy?)
image:getDimensions()
image:getHeight()
image:getWidth()

ImageData methods#

imagedata:circle(mode, x, y, r, c, lw?, c2)
circle(mode, x, y, r, color, [lineWidth], [strokeColor])
imagedata:clear(r?, g?, b?, a?)
imagedata:clone()
> a copy of this canvas.
imagedata:ellipse(mode, x, y, rx, ry, c, lw?, c2)
ellipse(mode, x, y, rx, ry, color, [lineWidth], [strokeColor])
imagedata:flip(dir?)
flip("h" | "v")
imagedata:getDimensions()
imagedata:getHeight()
imagedata:getPixel(x, y)
> r, g, b, a ; setPixel(x, y, r, g, b, [a])
imagedata:getWidth()
imagedata:gradient(args)
gradient("linear", x0, y0, x1, y1, c0, c1) / ("radial", cx, cy, r, c0, c1): paint the whole canvas (alpha-blended over what is there).
imagedata:line(x1, y1, x2, y2, c, w?)
round caps
imagedata:mapPixel(f, x0?, y0?, w?, h?)
> r, g, b, a, [x, y, w, h])
imagedata:noise(scale, seed?, oct?, c0, c1)
fill with value noise.
imagedata:outline(c, t?)
ring around opaque pixels.
imagedata:paste(src, x, y, a?)
src is an ImageData or an Image.
imagedata:polygon(mode, pts, c, lw?, c2)
polygon(mode, {x1, y1, ...}, color, [lineWidth], [strokeColor])
imagedata:rect(mode, x, y, w, h, c, r?, lw?, c2)
rect(mode, x, y, w, h, color, [radius], [lineWidth], [strokeColor])
imagedata:setPixel(x, y, r, g, b, a?)
imagedata:toImage()
> a drawable Image (cached until the canvas changes).

Inst methods#

inst:boneWorld(name)
World placement of a bone in skeleton space: x, y, rotation (degrees).
inst:current(track)
inst:draw(x, y, opts)
draw --- Draw at (x, y). opts: scale (1), flipX, rot (degrees), color = {r,g,b,a}, debug.
inst:play(name, opts)
Play an animation. opts: loop (true), mix (cross-fade seconds, 0.15), speed (1), track (1; higher tracks are layered over lower ones).
inst:setAttachment(slotName, attName)
inst:setBone(name, o)
Override a bone's local rotation / position after update (procedural aim).
inst:setIK(name, x, y, mix)
Two-bone IK target in skeleton space (the coordinates draw() is given relative to its origin before scale), or nil to release.
inst:stop(track)
inst:update(dt)

Level methods#

level:agent(obj, opts)
Make an object walk on the navmesh. opts: speed (m/s, 3.5), accel (12), turn (rad/s, 8), radius (0.35), repath (s, 0.5), arrive (0.3), eye (1.6, height for canSee), animate (true: sets "speed" on a character).
level:applyWorld()
World settings from Blender (background colour, ambient, fog).
level:attach(obj, name)
Give an object a behaviour (by name) at runtime.
level:byBody(id)
level:characters()
Characters (animated objects) in the level.
level:clipTime(name)
level:draw(opts)
level:drawLights()
draw --- Lights from Blender. Called by draw(); exposed for custom draw loops.
level:each(fn)
level:find(name)
queries
level:isPlaying(name)
level:navBlock(obj, on)
Block / unblock an object's footprint (a door that closed, a crate pushed in).
level:navmesh(opts)
navigation --- The level's navmesh, generated from its static colliders the first time it is asked for. opts override the Blender level settings: cell, cellHeight, height, radius, climb, slope, bounds, extra, rebuild.
level:nearestUsable(x, y, z, range, dx, dy, dz)
The usable object nearest to a point within `range`, optionally in front of a direction (dx, dz).
level:path(name)
A path (a curve in Blender): its points { {x,y,z}, ... } and whether it closes.
level:pathPoint(name, dist)
A point `dist` metres along a path (wraps on closed paths, clamps on open ones), and the direction there: x, y, z, dx, dy, dz.
level:play(name, opts)
Play a Blender clip on every object that has it (one name = the whole animated scene). opts: loop (false), speed (1), from (0 s), onEnd(lvl, name).
level:reload()
Throw the level away and load it again from disk: the same table, so the game's reference stays valid. Bodies, agents and the navmesh are rebuilt; behaviours run init() again. Called by itself on a re-export (live).
level:remove(obj)
level:setClipTime(name, t)
level:setPosition(obj, x, y, z)
level:setRotation(obj, qx, qy, qz, qw)
level:spawn(template, x, y, z)
Copy an object (by name) to a new place — enemies, pickups, debris.
level:spawnPoints(tag)
Empties tagged as spawn points (or with `tag`), as a list of objects.
level:stop(name)
level:update(dt)
update --- Step physics (fixed rate), sync moving bodies, run behaviours, deliver contacts and trigger events.
level:use(obj, who)
Tell an object's behaviour it is being used (E key, a click, a bullet).
level:useCamera(name)
A camera placed in Blender: sets the view from it. Returns the object.
level:withTag(tag)

Map methods#

map:autotile(li, filled, tiles)
4-bit edge auto-tiling: for every filled cell, choose a tile from the bitmask of its N,E,S,W filled neighbours. `filled(tx,ty) -> bool`; `tiles` maps a mask 0..15 -> tileId (N=1, E=2, S=4, W=8). Handy for walls/ground borders.
map:draw(cam, camY, zoom)
Draw only the tiles visible for a camera. `cam` may be a camera controller (mote.camera2d.controller) or explicit numbers: map:draw(camX, camY, zoom).
map:drawLayer(name)
Draw one tile layer by name.
map:get(li, tx, ty)
map:isSolid(tx, ty)
map:load(li, data)
Fill a layer from a 2D array (rows top->bottom, 1-based). 0/nil = empty.
map:loadCSV(li, csv)
Parse a CSV string (rows on separate lines) into a layer.
map:objects(layerName)
Objects of an object layer (spawns, triggers, regions). Each has x,y,width, height,name,type,gid,properties (properties flattened to a table).
map:pixelSize()
Pixel size of the map.
map:rectSolid(x, y, w, h)
AABB (world coords) vs solid tiles — true if any solid tile overlaps the box.
map:set(li, tx, ty, id)
map:setSize(w, h)
map:setSolid(id, on)
map:tileAt(layerName, tx, ty)
Raw gid at tile coords in a layer (0 = empty). Good for collision maps.
map:tileToWorld(tx, ty)
map:worldToTile(wx, wy)

Model methods#

model:animations()
model:autoConvex(opts?)
autoConvex{...} — turn this model into convex collision automatically. hulls how many convex pieces the model may become (default 16) maxVerts vertex ceiling for any one piece (default 32) precision how hard the split searches, 0..1 (default 0.5) concavity how deep a dent is tolerated before splitting again solid fill the inside (true) or wrap the surface (false) This is the slow call — seconds at high precision on a dense mesh.
model:bones()
List every bone/node name (for discovering a rig's skeleton).
model:draw(x, y, z, scale? | x, y, z, opts | transform, opts?)
draw(x, y, z [, scale]) | draw(x, y, z, opts) | draw(transform [, opts]) opts: rot = {deg x, y, z}, quat = {x,y,z,w}, scale = n | {x,y,z}, offset = {x,y,z}, relativeTo = transform, anim = "clip" | index, time = seconds, loop = true, blend = { anim =, time =, w = 0..1 } Without `anim` the model is drawn from its GPU cache (no per-frame CPU work); with it the pose is evaluated this frame.
model:drawAnimated(anim, time, x, y, z, scale?)
deprecated
model:drawAnimatedFps(anim, time, off_x, off_y, off_z, pitch, yaw, roll, scale?)
deprecated
model:drawAnimatedFull(anim, time, x, y, z, pitch, yaw, roll, scale?)
deprecated Full orientation (pitch, yaw, roll) in world space — aircraft, ships, etc.
model:drawAnimatedRot(anim, time, x, y, z, rot_y, scale?)
deprecated Animated draw with a Y rotation (radians).
model:drawAt(x, y, z, rx?, ry?, rz?, sx?, sy?, sz?)
deprecated the same static draw with a full transform. `draw` takes a position and one uniform scale, which is all a game placing props by hand tends to need; a scene editor cannot live with it, because a prop that cannot be turned is a prop that has to be authored facing the right way.
model:drawBlended(a, ta, b, tb, w, x, y, z, scale?)
deprecated Cross-fade blend between two animations: w = 0 (a) .. 1 (b).
model:drawBlendedFps(a, ta, b, tb, w, off_x, off_y, off_z, pitch, yaw, roll, scale?)
deprecated
model:drawBlendedRot(a, ta, b, tb, w, x, y, z, rot_y, scale?)
deprecated Cross-fade blend between two animations, with a Y rotation (radians).
model:drawFps(off_x, off_y, off_z, pitch, yaw, roll, scale?)
deprecated
model:drawFull(x, y, z, pitch, yaw, roll, scale?)
deprecated
model:drawRot(x, y, z, rot_y, scale?)
deprecated Static draw with a Y rotation (radians) — e.g. face a movement direction.
model:duration(anim)
model:pose()
model:rootBone()
model:rootMotion(anim, t0, t1, bone?)
Create a manipulable skeletal pose bound to this model. The pose is where advanced animation happens: sample/blend animations, then edit bones directly, run IK / look-at, and draw the composed result. rootMotion(clip, t0, t1[, bone]) -> dx, dy, dz, dyaw: how far the clip carries its root between two times, in model space (loops wrap).
model:triangles()
the full mesh as { verts = {{x,y,z}..}, indices = {..} } (1-based) for surface-accurate fracture of complex/concave shapes.
model:vertices()
the model's rest-pose vertex positions as a list of {x,y,z} (model space).

NM methods#

nm:blockAt(x, z)
Block the single polygon containing a world point (nil if none). Returns bool.
nm:blockCircle(x, z, radius)
Block every polygon whose centroid is within `radius` of (x,z). Returns count.
nm:contains(x, y, z)
Is a world point on the mesh (walkable)?
nm:findPath(sx, sy, sz, gx, gy, gz)
Find a smooth path between two world points. Returns a list of {x,y[,z]} arrays (ready for mote.ai.agent:followPath), or nil if unreachable.
nm:sampleHeight(x, z)
Walkable surface height at world (x,z), or nil if off the mesh. 3D only. Use it to keep agents planted on terrain/ramps (see mote.crowd's floor snap).
nm:unblockAll()
Clear all dynamic blocks.

NS methods#

ns:draw(x, y, w, h)
Draw the panel at (x,y) with size (w,h). Uses the current colour as a tint.

Nav methods#

nav:block(x, y, z, r, h?)
nav:blockBox(ax, ay, az, bx, by, bz)
nav:connected(ax, ay, az, bx, by, bz)
nav:draw(k?)
the walkable surface as tinted tiles, one colour per island, blocked cells red. Debug only: it is one quad per cell.
nav:findPath(sx, sy, sz, gx, gy, gz, max?)
> { {x,y,z}, ... }, complete
nav:info()
nav:moveAlong(x, y, z, tx, tz)
nav:nearest(x, y, z, r?)
nav:randomPoint()
nav:randomPointNear(x, y, z, r)
nav:raycast(sx, sy, sz, tx, ty, tz)
nav:sampleHeight(x, z, y?)
nav:unblock(id)
nav:unblockAll()

Obj methods#

obj:children()
obj:forward()
obj:getParent()
obj:getPosition()
obj:getQuat()
obj:getRotation()
obj:hide()
obj:isPlaying(name)
obj:lookAt(x, y, z)
obj:move(dx, dy, dz)
obj:moveLocal(dx, dy, dz)
obj:play(name, opts)
Play one of this object's Blender clips (see lvl:play for the options).
obj:right()
obj:rotate(rx, ry, rz)
obj:rotateWorld(rx, ry, rz)
obj:setParent(p, keepWorld)
Attach to another object, a transform (g3.camera, a character's hand...) or nil. keepWorld (default true): stay where it is now.
obj:setPosition(x, y, z)
obj:setQuat(x, y, z, w)
obj:setRotation(rx, ry, rz)
obj:setVisible(on)
Hide / show the object and everything parented to it.
obj:show()
obj:stop()
obj:toLocal(x, y, z)
obj:toWorld(x, y, z)
obj:up()

Object methods#

object:addTag(tag)
object:childCount()
object:destroy()
object:exists()
object:getChild(index)
object:getName()
object:getPosition()
object:getWorldPosition()
object:hasTag(tag)
object:id()
object:isActive()
object:setActive(active)
object:setName(name)
object:setParent(v)
object:setPosition(x, y, z?)
object:setRotation(rx, ry?, rz?)
object:setScale(sx, sy?, sz?)

P methods#

p:draw(camX, camY)
Draw all layers, tiled horizontally, offset by the camera.
p:layer(image, factor, opts)
Add a layer. opts: { y=0, scale=1 }. `factor` 0..1 = scroll speed vs camera.

Particles methods#

particles:burst(count)
particles:count()
particles:emit(x, y, count?)
particles:setAdditive(on)
particles:setColors(r1, g1, b1, a1, r2, g2, b2, a2)
particles:setDamping(d)
particles:setDirection(dir, spread?)
particles:setGravity(x, y)
particles:setLife(min, max?)
particles:setMax(n)
particles:setPosition(x, y)
particles:setRadial(a)
particles:setRate(r)
particles:setShape(kind, a?, b?)
particles:setSize(start, finish?)
particles:setSpeed(min, max?)
particles:setSpin(min, max?)
particles:setTangential(a)
particles:setTexture(ud)
particles:setTurbulence(t)
particles:start()
particles:stop()

Pool methods#

pool:countLive()
pool:each(fn)
Iterate live objects: fn(obj) — return true to free it during iteration.
pool:free(obj)
Return an object to the pool for reuse.
pool:freeAll()
Free every live object.
pool:get()
Acquire an object (reused if available, else newly made). It's tracked as live.

Pose methods#

pose:bind()
Reset to the bind (rest) pose.
pose:blend(a, ta, b, tb, w)
Cross-fade two animations into the pose (w: 0 = a .. 1 = b).
pose:blendToward(anim, time, w)
Blend the CURRENT pose toward animation `anim` by `w` (layering: call after sample/blend to mix in another clip, e.g. an additive aim).
pose:boneAxis(name, ax?, ay?, az?)
World-space direction of a bone's local axis (default +Z).
pose:bones()
pose:boneWorld(name)
queries World position of a bone (uses the pose's current world transform).
pose:clone()
pose:draw(x, y, z, scale?)
Draw the composed pose at (x,y,z[,scale]).
pose:drawRot(x, y, z, rot_y, scale?)
Draw with a Y rotation (radians).
pose:footIK(opts?)
foot IK footIK{ dt=, weight=1, maxStep=0.45, smooth=14, align=true, maxAngle=35, legs = {{hip,knee,foot},...} (auto by name), pelvis = name (auto), ignore = {bodyIds} } — call after setWorld. Each foot is put on the ground under it (stairs, slopes, rubble), the pelvis drops so the lower foot can reach, the knees bend forward, and the soles turn to the ground's slope.
pose:hasBone(name)
pose:ikTwoBone(root, mid, end, tx, ty, tz, px?, py?, pz?)
Two-bone IK (leg/arm): root, mid, end bones reach for a world target.
pose:layer(anim, time, w, opts?)
layers layer(clip, time, weight, { mask = "Spine" | {...}, exclude =, maskWeights = { Bone = w }, additive = false, ref = clip, refTime = 0 }) Override: the masked bones move toward the clip by weight (run below, shoot above).
pose:legs()
The legs foot IK found (or was given), as {{hip, knee, foot}, ...}.
pose:lookAt(name, tx, ty, tz, ax?, ay?, az?)
procedural: look-at + IK Aim a bone's local axis (default +Z) at a world target.
pose:ragdoll(cfg?)
ragdoll Build a physics skeleton shaped like this pose. Everything is optional; `mass` is the whole character and the rest are the knobs that turn a bag of sticks into a body.
pose:resetBone(name)
Reset one bone to its bind transform.
pose:rotateBone(name, x, y, z)
Post-multiply a bone's local rotation by an Euler delta (procedural, on top of whatever animation put there — recoil, head turn, sway, …).
pose:sample(anim, time)
compose from animations Replace the pose with animation `anim` sampled at `time`.
pose:setBonePosition(name, x, y, z)
Set a bone's local translation.
pose:setBoneQuat(name, x, y, z, w)
Set a bone's local rotation from a quaternion.
pose:setBoneRotation(name, x, y, z)
direct bone manipulation Set a bone's local rotation from Euler angles (radians, X→Y→Z).
pose:setBoneScale(name, sx, sy?, sz?)
Set a bone's local scale (uniform, or per-axis if sy/sz given).
pose:setRootMotion(v)
root motion setRootMotion(true | boneName | false): clips sampled into this pose keep their root bone in place horizontally; read the travel with model:rootMotion and move the character by it.
pose:setWorld(x, y, z, rot_y?, scale?)
world transform + draw Set the world placement used for drawing AND for boneWorld/IK queries.

Q methods#

q:all(pred)
q:any(pred)
q:average(fn)
Mean, or nil for an empty query. Returning 0 there would quietly poison whatever the average feeds.
q:chunk(n)
Fixed-size groups: `:chunk(3)` over 1..7 gives {1,2,3}, {4,5,6}, {7}.
q:concat(other)
q:contains(target)
q:count(pred)
q:distinct(keyFn)
First occurrence of each key wins; later duplicates are dropped. Without a key function the element itself is the key, so this only works on values a table can key on — which is why `distinct(mote.prop "id")` is the form you actually want for entities.
q:each(fn)
q:first(pred)
First element, or the first that matches. Stops as soon as it has one.
q:flatMap(fn)
q:flatten(depth)
Splice list elements into the stream. `depth` defaults to 1, which is what you want after a map that returns lists; pass more to go deeper.
q:groupBy(keyFn)
Group into `key -> list`, in encounter order inside each group.
q:having(name)
Only the elements whose `prop` is truthy: `:having "alive"`. The common case of `:where(mote.prop "alive")` written the short way.
q:iter()
Iterate a query in a `for` loop: `for e in q:iter() do`. Ends at the first nil, so it is the one place the nil-safety does not hold; use `:each` when the stream may contain nils.
q:join(sep, fn)
q:last()
q:map(fn)
q:max(fn)
q:maxBy(keyFn)
q:min(fn)
q:minBy(keyFn)
The element with the smallest/largest key, not the key itself — which is almost always what a game wants: the nearest enemy, not its distance.
q:none(pred)
q:nth(i)
q:partition(pred)
Two lists: the ones that match, and the ones that do not.
q:pluck(name)
`:pluck "name"` is `:map(mote.prop "name")`.
q:reduce(fn, init)
Fold. Without `init` the first element seeds the accumulator, and an empty query folds to nil — which is the honest answer, not zero.
q:reject(pred)
q:reverse()
q:shuffle()
Fisher-Yates, through `mote.random` so a seeded run stays reproducible.
q:skip(n)
q:skipWhile(pred)
q:sort(cmp)
Sort with your own comparator. Not stabilised: a comparator is free to express the tiebreak itself, and forcing one on it would override it.
q:sortBy(keyFn, desc)
Sort by a key, ascending unless `desc`. STABLE, which `table.sort` is not: equal keys keep their original order. That matters more than it sounds — an unstable sort on a scoreboard makes tied entries swap places every frame.
q:sum(fn)
q:take(n)
q:takeWhile(pred)
q:tap(fn)
q:toMap(keyFn, valFn)
Build a map. `keyFn` picks the key; `valFn` picks the value, defaulting to the element. Later keys overwrite earlier ones.
q:toTable()
q:where(pred)
Keep the elements the predicate likes. `filter` is the same function under the name mote_std already uses.
q:window(n)
Windows of `n` consecutive elements, sliding one at a time. Pairs of neighbours (`:window(2)`) is how you turn a path into its segments.
q:withIndex()
`{ index = i, value = v }` records, for when a later stage needs the position.
q:zip(other, fn)
Pair up with another list or query. With `fn`, the pairs are combined by it; without, each element becomes `{ a, b }`. Stops at the shorter side.

RNG methods#

rng:bool(p)
rng:dice(n, sides)
Roll `n` dice of `sides` (e.g. r:dice(3, 6) = 3d6). Returns total, {rolls}.
rng:float(a, b)
Float in [a,b) (or [0,1) with no args).
rng:gaussian(mu, sigma)
Gaussian (Box–Muller), mean `mu`, standard deviation `sigma`.
rng:inCircle(r)
A point uniformly inside a circle of radius `r`.
rng:int(a, b)
Integer in [a,b] inclusive.
rng:next()
Park–Miller minimal standard LCG -> [0,1).
rng:pick(t)
Uniform pick from an array.
rng:reseed(seed)
rng:shuffle(t)
In-place Fisher–Yates shuffle.
rng:sign()
rng:weighted(map)
Weighted pick from { key = weight, ... }; returns the key.

Ragdoll methods#

ragdoll:amount()
ragdoll:apply(pose, dt?)
Write the physics back into a pose, blended. Rotations are written as WORLD rotations through the same path the IK uses, so a limb the ragdoll does not simulate — fingers, a jaw, a cape — keeps animating on top of a body that is falling over.
ragdoll:blend(v)
Hold a partial blend — a hit reaction. 0.3 is a flinch that keeps walking; 1.0 is a body on the floor.
ragdoll:bodies()
ragdoll:bodyFor(name)
ragdoll:capture(pose)
Move the bodies back onto the animated bones. Called once when the ragdoll starts, and again by `recover` — otherwise the second fall starts from wherever the first one ended.
ragdoll:destroy()
Take the bodies and joints out of the world.
ragdoll:draw()
Draw every part as an oriented box. Call setColor / setSurface first.
ragdoll:go(secs?)
Go limp over `secs` (0 = at once). The bodies are already where the bones are, so this is only the blend.
ragdoll:impulse(part, ix, iy, iz)
Shove one part (name) with an impulse.
ragdoll:isActive()
ragdoll:isSettled()
Has it stopped moving? The cue to start a get-up animation.
ragdoll:position()
Where the ragdoll ended up: the world position of its root limb.
ragdoll:push(x, y, z, bone?)
Shove one limb. With a bone name the impulse lands on that limb at its own position, which is what makes a shot to the head spin the head and a shot to the leg take the legs out.
ragdoll:recover(secs?)
Return to the animation over `secs`. The pose is interpolated back, so a character gets up from where it fell rather than snapping to wherever the animation happens to be.
ragdoll:remove()
ragdoll:setStiff(on, stiffness)
Make it limp (true) or let the joints hold a pose with motors (false): a stand-in for "active ragdoll" — knees and elbows servo to straight.
ragdoll:setVelocity(x, y, z)
Give every limb the same velocity — the character's own motion at the moment it went limp. Without this a sprinter drops straight down, which reads as a bug even to people who could not say why.
ragdoll:update(dt)
Advance the blend. Called for you by `apply`, so games that just want a ragdoll never see it.

Root methods#

root:blur()
root:draw()
draw the whole tree
root:get(id)
root:hasFocus()
root:isHovered()
Helpers for the game to avoid double-handling input.
root:setReference(w, h)
root:update(dt)

Ruin methods#

ruin:damage(x, y, z, radius, amount)
wear that builds up.
ruin:draw()
ruin:events()
where things broke since the last call: { {x,y,z,size}, .. }.
ruin:explode(x, y, z, radius, power)
a blast, strongest at the centre.
ruin:impact(x, y, z, dx, dy, dz, power)
a localised hit. The crack starts where it lands and spreads while it still carries energy.
ruin:info()
ruin:loose()
every loose piece: { {x,y,z, qx,qy,qz,qw, id, size}, ... }
ruin:owns(id)
is this physics body part of this object (a standing piece or loose debris)? For "the cannonball hit the wall".
ruin:raycast(ox, oy, oz, dx, dy, dz, max?)
where a bullet or a click lands.
ruin:remove()
ruin:reset()
ruin:update(dt)

Scatter methods#

scatter:add(cfg)
scatter:clear()
scatter:config(cfg)
scatter:draw()
cull against this frame's real camera and submit instances.
scatter:mesh(id, verts)
hand scatter the geometry for one LOD. Give it the vertices here rather than calling registerMesh yourself, and the upload is guaranteed to reach the GPU: scatter queues it from its own draw, which is the only phase where a queued upload survives.
scatter:remove(i)
scatter:set(i, cfg)
scatter:stats()
scatter:update(ground, x, z)
update(terrain, x, z) or update(y, x, z) for flat ground.

Scene methods#

scene:addPolygon(pts)
Closed polygon from a flat {x1,y1,x2,y2,...} list.
scene:addRect(x, y, w, h)
scene:addSegment(x1, y1, x2, y2)
scene:begin()
Optional: darken the whole screen before casting (ambient occlusion feel).
scene:cast(lx, ly, cam)
Cast the shadow of every occluder away from a light at (lx, ly). Pass a camera controller as `cam` if your coordinates are world-space.
scene:clear()

Shader methods#

shader:id()
shader:send(key, a?, b?, c?, d?)
key is a param name (from newShader's name list) or a 0-based slot index. Sets params[slot] = vec4(a,b,c,d).

Soft methods#

soft:links()
soft:pin(i, pinned)
soft:point(i)
soft:points()
soft:update(dt)

Surface methods#

surface:getParallax()
surface:getQuality()
> specularAA, antiTile, antiTileScale, antiTileBlend
surface:getShading()
surface:getTiling()
surface:hasLayer()
surface:setAntiTile(a, scale?, blend?)
surface:setColor(r, g, b)
surface:setDetail(mult, strength, fade?)
setDetail(tilingMultiple, strength, fadeDistance)
surface:setLayerEnabled(on)
surface:setLayerRange(lo, hi)
slide the second layer's mask at runtime, so moss can spread or snow can melt without touching any texture.
surface:setMaterial(m, r?)
surface:setNormalStrength(s)
surface:setParallax(depth, shadow?)
surface:setProjection(x, y, z, yaw?)
move and turn the world projection.
surface:setShading(name, param?)
break up visible repetition: each map is sampled from two of eight offset "versions" of itself, chosen by a smooth noise over the surface (Quilez's technique #3). amount 0 off .. 1 full (partial = how far the versions may drift) scale how often the version changes, per texture repeat (0.33) blend width of the cross-fade between versions, 0.05..1 (0.5) setShading(model, [param]) — shading model of this surface: "cloth" (param = sheen), "skin" (scatter), "hair" (highlight shift), "subsurface"/"foliage" (thickness), "clearcoat", "anisotropic".
surface:setSharpness(s)
surface:setSpecularAA(k)
0 off, 1 default, up to 4: how much sub-pixel normal variation widens the highlight instead of sparkling.
surface:setTiling(t)
Everything a game might want to drive from gameplay — wetness after rain, moss spreading, a wall seen from closer up — without rebuilding the maps, which is the expensive half.

System3D methods#

system3d:burst(count)
system3d:count()
system3d:emit(x, y, z, count?)
system3d:onDeath(child, count)
system3d:setAdditive(on)
system3d:setColorRamp(r1, g1, b1, a1, r2, g2, b2, a2, r3, g3, b3, a3)
3-stop color gradient over life (start -> mid -> end).
system3d:setColors(r1, g1, b1, a1, r2, g2, b2, a2)
system3d:setDamping(d)
system3d:setDirection(x, y, z, cone?)
system3d:setGravity(x, y, z)
system3d:setLife(min, max?)
system3d:setMax(n)
system3d:setMeshShape(kind)
system3d:setMode(mode)
system3d:setPosition(x, y, z)
system3d:setRate(r)
system3d:setShape(kind, a?, b?, c?)
system3d:setSize(a, b?)
system3d:setSpeed(min, max?)
system3d:setSpin(min, max?)
system3d:setStretch(s)
system3d:setTexture(ud)
system3d:setTurbulence(t)
system3d:start()
system3d:stop()

Target methods#

target:id()
target:setSize(a, b?)
setSize(w, h) or setSize(scale) — resizes on the next frame (contents reset).

Task methods#

task:cancel()
Stop the task, and everything it started. The cascade is the point: a cutscene that spawns three helpers and is then skipped should not leave the three helpers running behind the next scene.
task:isDone()
task:isRunning()
task:onDone(cb)
Call `cb(ok, value...)` when the task finishes — now, if it already has.
task:result()
`ok, value...` once finished; nil while still running.

Terrain methods#

terrain:color(x, z)
terrain:draw(x, z)
stream, mesh, upload and draw around a point. One method rather than update()+draw() on purpose: mesh uploads are queued onto the frame and the frame is reset at the top of every render, so anything queued from update() is thrown away before it is used.
terrain:height(x, z)
terrain:normal(x, z)
terrain:physics(opts?)
physics{ tile = 32, cell = 1, radius = 64, friction = 0.9, perFrame = 4 } makes the terrain solid in mote.physics3d: heightfield tiles are streamed around the point given to draw() (or updatePhysics()).
terrain:physicsTiles()
terrain:raycast(ox, oy, oz, dx, dy, dz, maxd?, step?)
> x, y, z, dist | nil
terrain:rebuild()
terrain:set(cfg)
set{...} — any subset of the constructor's keys, at runtime. Changing anything that alters the SHAPE needs a rebuild() to be visible in chunks that already exist.
terrain:slope(x, z)
> steepness 0..1, and the downhill direction.
terrain:stats()
terrain:updatePhysics(x, z)
stream colliders from update() (draw() already does it), e.g. to have them before the first frame.

Trail3D methods#

trail3d:setAdditive(on)
trail3d:setColors(r1, g1, b1, a1, r2, g2, b2, a2)
trail3d:setLifetime(l)
trail3d:setMaxPoints(n)
trail3d:setPosition(x, y, z)
trail3d:setTexture(ud)
trail3d:setWidth(w)

Transform methods#

transform:copy()
> a new transform with the same local values and parent
transform:forward()
world directions (unit vectors)
transform:getName()
transform:getParent()
transform:getPosition()
local placement (relative to the parent)
transform:getQuat()
transform:getRotation()
transform:getScale()
transform:getWorldPosition()
world placement
transform:getWorldQuat()
transform:getWorldRotation()
transform:localMatrix()
transform:lookAt(x, y, z, ux?, uy?, uz?)
face a world point (+Z toward it).
transform:matrix()
major (world); localMatrix() likewise
transform:move(x, y, z)
motion --- move(dx,dy,dz): in the parent's axes. moveLocal: along its own axes (moveLocal(0, 0, 1) = one metre forward, wherever it faces).
transform:moveLocal(x, y, z)
transform:right()
transform:rotate(rx, ry, rz)
degrees about its own axes; rotateWorld about the world axes (rotateWorld(0, 90, 0) turns it left about world up).
transform:rotateWorld(rx, ry, rz)
transform:set(o)
transform:setName(n)
transform:setParent(p, keep?)
hierarchy --- setParent(p [, keepWorld = true]): attach to another transform (or a level object / character), nil to detach. With keepWorld the object stays where it is on screen; with false its local values are kept (it jumps to the same offset from the new parent).
transform:setPosition(x, y, z)
transform:setQuat(x, y, z, w)
transform:setRotation(rx, ry, rz)
transform:setScale(x, y?, z?)
transform:setWorldMatrix(a)
transform:setWorldPosition(x, y, z)
transform:setWorldQuat(x, y, z, w)
transform:setWorldRotation(rx, ry, rz)
transform:toLocal(x, y, z)
transform:toWorld(x, y, z)
point conversions
transform:up()

W methods#

w:animate(o)
w:build(spec)
Declarative construction from a table (see the header). Array items are the children; `type` picks the widget: column, row, panel, grid, scroll, label, button, textField, slider, checkbox, progress, image, spacer.
w:button(p)
w:checkbox(p)
w:column(p)
w:getValue()
w:grid(p)
Inventory-style grid of fixed cells (cols, cellW, cellH, gap).
w:hide(o)
w:image(p)
w:label(p)
w:panel(p)
Container / widget builders (chainable off any container or the root).
w:progress(p)
w:row(p)
w:scroll(p)
Scroll viewport: children lay out in a column taller than the panel; wheel or drag scrolls. Give it a fixed height. Content is clipped to the viewport, so a row at the edge is cut, not dropped.
w:setEnabled(b)
w:setText(s)
Convenience accessors (fields are public too).
w:setValue(v)
w:setVisible(b)
w:show(o)
w:slider(p)
w:spacer(p)
w:textField(p)

World methods#

world:add(e, name, data)
Attach (or replace) a component. `data` defaults to an empty table (tags).
world:alive(e)
world:count(name)
Count entities that have a component (or all live entities if name is nil).
world:destroy(e)
Destroy an entity and all its components.
world:each(name, fn)
Run `fn(component, id)` for every entity with `name`.
world:entity()
Create a new entity id.
world:get(e, name)
Get a component table, or nil.
world:has(e, name)
Does an entity have a component?
world:remove(e, name)
Remove one component from an entity.
world:removeSystem(fn)
world:system(fn)
Register a system: fn(world, dt). Returns the fn (a handle for removeSystem).
world:update(dt)
Run every system in registration order.
world:view(...)
Iterate every entity that has ALL of the named components. Yields (id, compA, compB, ...). Put the most selective component first.

a methods#

a:drawFps(offX, offY, offZ, pitch, yaw, roll, scale)

computedMethods methods#

computedmethods:peek()
computedmethods:stop()

effectMethods methods#

effectmethods:run()
effectmethods:stop()

refMethods methods#

refmethods:freeze()
Stop tracking: subscribers are dropped and the value becomes inert.
refmethods:peek()
Read without registering a dependency. The escape hatch for an effect that both reads and writes the same value — with a tracked read that is a loop.
refmethods:touch()
Notify as if the value had changed. Refs compare with `~=`, so a table mutated in place looks identical to the one that was there before; this is how you say it is not. Watchers see it because they compare the revision counter as well as the value.

vec2mt methods#

vec2mt:angle()
vec2mt:clone()
vec2mt:distance(o)
vec2mt:dot(o)
vec2mt:length()
vec2mt:length2()
vec2mt:lerp(o, t)
vec2mt:normalize()
vec2mt:rotate(a)
vec2mt:unpack()

vec3mt methods#

vec3mt:cross(o)
vec3mt:distance(o)
vec3mt:dot(o)
vec3mt:length()
vec3mt:lerp(o, t)
vec3mt:normalize()
vec3mt:unpack()
Nothing found.