API reference
Everything the library exports, module by module. Points are plain { x, y, z } objects (or { x, y } on screen). No function changes its inputs unless it says so.
Modules
Math
Pipeline
From trid/math/transform.js.
localToWorld(v, inst) // → point
worldToCamera(p, camera) // → point
cameraToScreen(p, camera, w, h) // → { x, y }
worldToScreen(p, camera, w, h) // → { x, y }
clipNear(a, b, near) // → [a, b] or nulllocalToWorldmoves a mesh vertex into world space using an object's transform: scale, then rotate (X → Y → Z), then translate bypos.instneedspos,rotandscale.worldToCameramoves a world point into camera space: subtracts the camera position, then undoes its yaw and pitch. In camera space the camera sits at the origin looking down +Z, sozis the distance in front of it.cameraToScreenprojects a camera-space point to canvas pixels, usingcamera.fovand the aspect ratiow / h.p.zmust be > 0 — clip segments withclipNearfirst if they can cross behind the camera.worldToScreenisworldToCamerafollowed bycameraToScreen. Handy for placing labels on top of 3D points.clipNearclips a camera-space segment against the planez = near. Returns the segment unchanged if both ends are in front,nullif both are behind, or a shortened segment with the hidden end moved onto the plane.
Camera directions
cameraForward(camera) // → point
cameraRight(camera) // → point
cameraUp(camera) // → pointUnit vectors in world space for where the camera looks, the screen's right side and the screen's top side. Use them to move things relative to the view.
Basic transforms
scale(p, sx, sy, sz) // → point
translate(p, dx, dy, dz) // → point
rotateX(p, angle) // → point (pitch, YZ plane)
rotateY(p, angle) // → point (yaw, XZ plane)
rotateZ(p, angle) // → point (roll, XY plane)
rotateXYZ(p, { x, y, z }) // → point (X, then Y, then Z)Each returns a new point. Angles are in radians. Rotation order matters: rotateXYZ always applies X first, then Y, then Z.
Constants
| Name | Value |
|---|---|
DEFAULT_FOV | 50° vertical field of view, in radians (50 * Math.PI / 180) |
DEFAULT_NEAR | 0.01 — near plane distance |
Projection
From trid/math/projection.js.
project(p, fov = DEFAULT_FOV, aspect = 1) // → { x, y }
screen(p, w, h) // → { x, y }projectis the perspective projection of a camera-space point to normalized coordinates (−1 to +1). X is divided byaspectso shapes don't stretch on wide canvases.p.zmust be > 0.screenconverts normalized coordinates to canvas pixels. Y is flipped: +1 is the top of the canvas.
Rendering
Drawing
From trid/render/draw.js.
clear(ctx, w, h, color)
point(ctx, p, color, size = 20)
line(ctx, p1, p2, color, width = 4)
drawWireframe(ctx, points2, edges, color, width = 4)
drawInstance(ctx, inst, camera, w, h, color, lineWidth = 3)
edgeSegments(edges)
wireEdges(mesh)clearclears the whole canvas, then fills it withcolor. With"transparent"ornull, it stays see-through.pointdraws a filled square centered on screen pointp. Useful for debugging vertices.linedraws one line between two screen points.drawWireframeconnects already-projected screen points using index edges (2 indices = segment, 3+ = closed loop). Everything is stroked as one path. No clipping is done.drawInstanceis the main drawing call: it transforms an object's mesh, clips every edge against the camera's near plane, projects it and strokes it as one path. The canvas renderer uses it for scenes with only wireframe objects.edgeSegmentsturns edge definitions into[a, b]index pairs (a generator), expanding closed loops. Missingedgesgive no pairs.wireEdgesis what a wireframe draws for a mesh: itsedges, or the outline of each face when it has none.
CanvasRenderer
From trid/render/canvasRenderer.js. The default scene.renderer: it draws wireframes and filled faces with the canvas 2D context.
new CanvasRenderer({ maxFaceSize = null } = {})
renderer.render(scene)maxFaceSizesplits faces bigger than that fraction of their mesh's size into triangles, so they sort better (see Splitting big faces). Off by default.render(scene)clears the canvas and draws every object of the scene.Scene.rendercalls it, then lets tools draw.DEFAULT_LIGHTis{ x: -0.5, y: 1, z: -0.8 }andDEFAULT_AMBIENTis0.25.
WebGLRenderer
From trid/render/webglRenderer.js. Draws with the graphics card and a depth buffer. See Renderers.
WebGLRenderer.isSupported()
new WebGLRenderer({ antialias = true } = {})
renderer.render(scene)
renderer.dispose()
renderer.canvasisSupported()says whether the browser can create a WebGL context.- The constructor throws an
Errorif WebGL isn't available. render(scene)draws on the hiddenrenderer.canvas, then copies the picture ontoscene.canvas.dispose()frees the graphics card memory;scene.destroy()calls it. Safe to call twice.- Meshes are uploaded once. Set
mesh.dirty = trueafter changing a mesh's arrays in place. DEFAULT_FARis1000, the farthest distance drawn unless the camera setsfar.
Normals
From trid/render/normals.js.
cornerNormals(mesh, crease = 60)
creaseOf(smooth)
newell(points)cornerNormalsreturns, for each face, one unit normal per corner: the average of the faces around that vertex that meet it at less thancreasedegrees. Faces with normals from an OBJ file use those. Cached per mesh until its arrays change ormesh.dirtyis set.creaseOfturns a material'ssmoothvalue into a crease angle (true→ 60), ornullfor flat shading.newellreturns the (not normalized) normal of a polygon. For points clockwise as seen from a side, it points to that side. Also exported fromcanvasRenderer.js.DEFAULT_CREASEis60.
Effects
From trid/render/effects.js. The built-in effects and how to write your own are on the Effects page. The helpers below are what the renderers use:
buildEffects(effects)joins a list of effects into GLSL code, with names made unique per effect. Returns{ code, calls, uniforms }.effectsKey(effects)returns a string that's equal for lists that compile to the same shader (same code, same uniform types).uniformType(value)returns the GLSL type a uniform value becomes, ornull.SURFACE_GLSLis the GLSL declaration of theSurfacestruct.
Lights
From trid/render/lights.js. Using lights is explained on the Lights page. The helpers below are what the renderers use:
sceneLights(scene, rgba)returns a scene's lights ready for shading:{ ambient, ambientLevel, lights, mainDir, shadow }, colors parsed byrgba(css)and multiplied by their intensity.shadowslists the lights casting shadows, directional ones first (indexinlights,point,dirorpos,range, and their settings);shadowis the first directional one, ornull. A scene-like object with onlylight/ambientgets the default pair.lightAt(lights, normal, position)returns the light reaching a point as[r, g, b]: the same math as the WebGL shader.lightLevels(color, ambientLevel)returns{ light, diffuse }, the numbers effects get.rangeFade(dist, range)is how much of a point light reachesdistaway.
Shadows
From trid/render/shadows.js. Using shadows is explained on the Lights page. Used by the renderers:
shadowOptions(value, point?)returns a light's shadow settings with the defaults (DEFAULT_SHADOWS; for a point light,sizeisPOINT_SHADOW_SIZE) filled in.shadowFlag(obj, "castShadow" | "receiveShadow")isfalsewhen the object or a group above it sets that field tofalse.shadowFrame(casters, dir)returns{ matrix, radius }: a directional light's shadow map box around the casting objects, facing along the light.pointShadowFar(casters, position, range)is how far a point light's shadow map reaches: itsrange, or the far side of the farthest casting object.findGround(receivers)returns the floor height for ground shadows, ornull.flattenOnGround(points, dir, ground)flattens a world polygon onto the floor along a directional light, cutting off what's below it.flattenFromPoint(points, position, ground)does the same for a point light: along the rays from it, keeping only what's between the floor and the light's height.
Post effects
From trid/render/post.js. The built-in effects and how to write your own are on the Post effects page. Used by the renderers:
postPasses(effect)returns an effect's passes as{ glsl, scale }(empty for a canvas-only effect).activePost(list)returns the effects that are on.runCanvasPost(scene, list, start)runs the effects'canvasfunctions on the scene's canvas.FRAME_GLSLis the GLSL declaration ofFrameand theframe/sourcehelpers.GEOMETRY_GLSLdeclaresdepthAt,normalAtandmaskAt, added for effects withgeometry: true(see Reading depth and normals).wantsGeometry(effect)istruefor an effect withgeometry: trueand GLSL.maskedObjects(effect)returns the objects an effect'sobjectslist covers, children included, as aSet(nullwithout a list).DEFAULT_OUTLINE_CREASEis the crease angleoutline()uses by default: 40°.
Textures
From trid/loaders/texture.js. Using textures is explained on the Textures page.
loadTexture(url)returns a promise for a loaded<img>(with CORS enabled).textureReady(src)says whether an image, canvas or video has pixels to draw yet.textureSize(src)returns{ w, h }in pixels.textureIsLive(src, material?)istruefor textures read again every frame: videos, or any source whose material hasliveTexture: true(liveTexture: falsefreezes a video).updateTexture(src)tells the renderers a canvas (or image) changed: it's read again once, on the next frame. See Changing a canvas.textureVersion(src)is how many timesupdateTexturewas called for a source (0 when never); renderers compare it with the version they read last.
Texture mapping
From trid/render/uvMapping.js. Using mappings is explained on the Textures page.
computeUVs(mesh, mapping)returns{ uvs, faceUVs }made from the mesh's shape. The mesh isn't changed.mapUVs(mesh, mapping)writes them into the mesh and returns it.uvsFor(mesh, mapping)returns the coordinates a renderer uses: the mesh's own, or computed for the mapping and cached until the mesh changes.uvTransform(material)turnstextureRepeat,textureOffsetandtextureRotationinto a 2D matrix[a, b, c, d, e, f](u' = a·u + c·v + e,v' = b·u + d·v + f), ornullwhen they change nothing.applyUVTransform(m, uv)applies it to one coordinate.mappingOf(mapping)returns the mapping as{ type, axis }and throws for an unknown one.mappingKey(mapping)is a short string for caches.MAPPINGSlists the mapping types.materialsOf(obj)(fromcanvasRenderer.js) returns an object's materials as a list, ornullfor a wireframe.meshEdges(mesh)(fromcanvasRenderer.js) returns each edge of a mesh's faces once, as{ a, b, f1, f2 }: its two vertices and the faces on its sides (f2is -1 on an open border). Vertices at the same spot count as one, so texture seams aren't borders. Cached per mesh. The canvas renderer uses it for outlines.
parseColor
From trid/render/color.js.
parseColor(ctx, color)Turns any CSS color into [r, g, b, a] (0..255, alpha 0..1), using a 2D context to read it. Unknown colors come out black.
Frame loop
From trid/render/loop.js.
const stop = loop(update, { maxDt = 0.1 } = {})Calls update(dt, time) every animation frame with requestAnimationFrame. dt is the seconds since the last frame (0 on the first, capped at maxDt) and time is the seconds since the loop started. Call the returned stop() to end it.
Using the pipeline without Scene
Scene is a thin layer over these functions. You can drive them yourself:
import { clear, drawInstance, point, loop, makeShape, worldToScreen } from "./trid/index.js";
export default function (canvas) {
canvas.width = 800;
canvas.height = 300;
const ctx = canvas.getContext("2d");
const { width: w, height: h } = canvas;
const camera = { z: -1.5, fov: Math.PI / 3 };
const box = {
mesh: makeShape("box", { w: 0.8, h: 0.4, d: 0.4 }),
pos: { x: 0, y: 0, z: 0 },
rot: { x: 0.4, y: 0, z: 0 },
scale: { x: 1, y: 1, z: 1 },
};
const stop = loop((dt, time) => {
box.rot.y = time * 0.8;
clear(ctx, w, h, "#141414");
drawInstance(ctx, box, camera, w, h, "#e5c07b", 2);
// A dot circling the box, projected by hand
const p = { x: Math.cos(time) * 0.7, y: 0, z: Math.sin(time) * 0.7 };
point(ctx, worldToScreen(p, camera, w, h), "#E9806E", 8);
});
return stop;
}Helpers
From trid/tools/helpers.js (also exported by trid/tools/index.js).
pick
pick(scene, x, y, { filter, padding = 4, exact = false } = {}) // → object or nullReturns the object under canvas pixel (x, y). An object is hit when the point is inside its screen-space bounding box, grown by padding pixels. If several are hit, the one whose center is closest to the camera wins. filter(obj) can exclude objects.
INFO
Bounding boxes are approximate: clicking the empty corner around a sphere still picks it, and of two objects overlapping on screen, the one with the nearer center wins even where the other is in front. Pass exact: true to test triangles instead (same as pickHit).
pickHit
pickHit(scene, x, y, { filter, padding = 4, objects = scene.objects } = {}) // → hit or nullExact picking: the nearest object whose drawn surface is under the pixel. Every face is projected with the renderers' own math and tested triangle by triangle, so a click always matches what's drawn: through a ring's hole, a sword guard in front of its blade. Objects without faces (wireframes) are hit within padding pixels of one of their lines.
| Field | Meaning |
|---|---|
object | The object with the mesh that was hit |
face | Index in mesh.faces, or -1 for a line of a wireframe |
depth | Distance in front of the camera |
path | The object, then its groups up to the top: [part, group, ..., root] |
point | Where the hit is, in the world |
local | Where the hit is, in the mesh's own space (mesh.vertices space) |
triangle | The 3 vertex indices of the triangle hit (faces with more corners are cut into a fan from their first corner); null for a line |
barycentric | The weights of those 3 vertices at the hit, adding up to 1 (local is their weighted sum); null for a line |
normal | Unit normal of the face, in the world, on its front side; null for a line |
uv | Texture coordinates at the hit, from the face's material mapping (before repeat, offset and rotation); null without any |
textureUV | Where the texture is read at the hit: uv with the material's textureRepeat, textureOffset and textureRotation. Can be outside 0..1 when the texture repeats |
The hit point is exact on tilted faces too (weighted for perspective). To paint on a model's texture, the image pixel under the mouse is:
const hit = pickHit(scene, x, y);
if (hit?.textureUV) {
const u = hit.textureUV.u - Math.floor(hit.textureUV.u), v = hit.textureUV.v - Math.floor(hit.textureUV.v);
paint(u * image.width, (1 - v) * image.height); // v goes up, image rows go down
updateTexture(image);
}Objects with pickable: false, or inside a group with it (like a grid), are skipped by pick and pickHit. isPickable(obj) tells whether an object can be found.
Faces with a corner behind the camera's near plane are skipped. It's one pass over the objects' vertices per call: fine for clicks and hover on models of a few thousand faces.
To cast a ray from any point in the world instead of from a pixel, see raycastScene.
screenBounds
screenBounds(scene, obj) // → { minX, minY, maxX, maxY } or nullAn object's bounding box on screen, in canvas pixels. Only vertices in front of the near plane count; returns null if the whole object is behind the camera.
worldPerPixel
worldPerPixel(scene, depth) // → numberHow many world units one canvas pixel covers at depth units in front of the camera. Multiply pointer dx / dy by it to make something follow the cursor exactly.
screenRay
screenRay(scene, x, y) // → { origin, direction }The ray from the camera through a canvas pixel, in world space: what's under the cursor is the first thing it meets. origin is the camera's position and direction is unit length. It's the exact inverse of how points are drawn, so it pairs with raycastScene:
const { origin, direction } = screenRay(scene, e.x, e.y);
const hit = raycastScene(scene, origin, direction); // the surface under the cursorRotations
From trid/math/rotation.js. 3×3 rotation matrices (row-major, m[row][col], applied as M · v), built from rotateXYZ itself so they always match the renderers, and the operations TransformGizmo reports.
matFromEuler(rot) // → matrix that rotateXYZ(p, rot) applies
eulerFromMat(m) // → rot angles for a matrix (handles looking straight along Y)
matFromAxisAngle(axis, angle) // → right-handed turn around a unit axis
mulMat(a, b) // → a · b (b applied first)
mulVec(m, v) // → m · v
applyTransformOp(t, op) // → new { pos, rot, scale }Combine rotations with matrices, then turn the result back into an object's rot:
// Turn an object 90° around the world Y axis, whatever its current rotation
const turn = matFromAxisAngle({ x: 0, y: 1, z: 0 }, Math.PI / 2);
obj.rot = eulerFromMat(mulMat(turn, matFromEuler(obj.rot)));applyTransformOp(t, op) applies a TransformGizmo operation to a transform and returns the new one (the input isn't changed).
ToolManager
From trid/tools/manager.js. Each scene creates one as scene.tools. It keeps the tool list and turns canvas pointer events into tool events. Canvas listeners are only added while at least one tool is in the list. You normally go through scene.use / scene.unuse instead.
| Member | Meaning |
|---|---|
new ToolManager(scene) | Creates a manager for a scene's canvas |
add(tool) | Adds a tool and calls its attach. Adding the same tool twice does nothing. |
remove(tool) | Removes a tool (ending its drag if it holds one) and calls its detach |
clear() | Removes every tool |
update(dt) | Calls every tool's update |
draw(ctx) | Calls every tool's draw |
list | The tools, in the order they were added |