MALDA™ Reference Manual

The AI-First Programming Language - Version 1.0.50

28. Browser JavaScript UI Backend

MALDA also supports a browser-hosted UI model where MALDA source is transpiled to JavaScript and runs with the MALDA JS runtime. This is separate from server-side @PAGE, @AIPAGE, and server-component flows.

Start here: Read 25. Web UI Overview to compare UI models. This chapter covers browser-side MALDA execution, DOM helpers, template mode, and the canvas/game API. For server-rendered UI, see Web UI Server Components or HttpServer & HTML UI Generation.
First-read stop. The target is JavaScript in the browser, not the interpreter snippet harness. Preview with malda play. Smallest file: Examples/Web/js/hello_dom.malda. Start from 25. Web UI Overview. Course: Learn MALDA — After the core path.
Browser games: JS-only. Preview with malda play app.malda (see 2.0). Canvas is 28.9, 3D and @shader() are 28.10. Catalog: 35.3. Playable showcase: 39 (screen-only). Folder: Examples/Games/.

28.1 Chapter Map

28.2 What This Mode Provides

28.2.1 Target decorators in JS output

When compiling to JavaScript, target decorators can be used to keep browser and server concerns in one source file:

Route decorators are still server-oriented. A declaration such as @GET(...) is treated as server code and is not emitted in JavaScript output.

28.3 Compile Commands

# API mode (.malda source)
malda compile Examples/Web/js/hello_dom.malda --mode js -o Examples/Web/js/hello_dom.js

# Alias form (equivalent)
malda compile Examples/Web/js/counter.malda --target js -o Examples/Web/js/counter.js

# PWA output directory
malda compile Examples/Web/js/hello_dom.malda --target pwa -o dist/hello-dom

# Template mode (.malda.html source)
malda compile Examples/Web/js/hello_template.malda.html --mode js -o Examples/Web/js/hello_template.generated.js

--target js is an alias for --mode js. --target pwa is an alias for --mode pwa and produces a directory containing the app shell, runtime, and transpiled JavaScript.

The malda-js-runtime.js written beside the output keeps the game.*, three.* and glsl (host-called kernels) parts only when the program uses them, so a program without them ships a runtime about half the size. Programs compiled into the same folder share the file and it keeps every part any of them uses; its first line lists them (// malda-js-runtime areas: game). A call into a part that was left out stops with malda-js-runtime.js was written without the 'game' area.

The inner loop for canvas games is malda play. It compiles --mode js, writes a host page, and serves a local URL so you do not have to author HTML. Edits to the source, sibling index.html, and assets/ rebuild and reload the browser (--no-watch serves the first compile only). Packaging for itch.io stays --mode pwa.

malda new game my-game
cd my-game
malda play app.malda

Canvas plus a score API is malda new game --fullstack. That emits @client() / @GET / @POST and schema Score in one file. Compile with --mode fullstack; malda play refuses those sources.

malda new game my-scores --fullstack
cd my-scores
malda compile app.malda --mode fullstack -o dist

28.3.1 ES modules (--mode esm)

--mode esm (alias --target esm) writes an ES module, .mjs by default, next to malda-js-runtime.js and an index.html that imports it. Use it to call MALDA from JavaScript, or to split an app into several MALDA modules.

malda compile geometry.malda --mode esm -o web/geometry.mjs   # writes geometry.mjs + malda-js-runtime.js
malda compile scene.malda --mode esm -o web/scene.mjs         # same folder: one runtime for both
// geometry.malda
export var UNIT = 10;
export function area(w, h) {
    return w * h * UNIT;
}
function helper() {          // not exported
    return 1;
}
import { area, UNIT } from "./web/geometry.mjs";
console.log(area(2, 3), UNIT);   // 60 10

28.3.2 Production builds (--minify) and size report

Every js, esm and pwa build prints the size of the program, the runtime (with the areas it kept) and the UI client, raw and gzipped. --minify minifies them with esbuild when it finds one (MALDA_ESBUILD, then a node_modules/.bin above the working or output folder, then PATH); the program's source map is chained, so DevTools and the Desktop IDE still map to the .malda lines. Without esbuild, --minify drops comments and indentation from the runtime files and leaves the program as written, and the report says so.

malda compile app.malda --mode js --minify -o dist/app.js
# JavaScript size (minified with esbuild):
#   app.js                  5.8 KB  (gzip 2.3 KB)
#   malda-js-runtime.js   158.5 KB  (gzip 46.4 KB)  areas: ui
#   malda-ui-client.js     59.6 KB  (gzip 19.0 KB)
#   total                 224.0 KB  (gzip 67.7 KB)

A guard test keeps the runtime written beside a program without optional areas under a fixed size (Compiler.CoreRuntimeBudgetCharacters); new runtime code that only some programs need goes into an area.

28.4 Required Script Loading Order

The host page must include a container such as #app, then load scripts in this order. Same file: Examples/Web/js/host.html.

  1. Any required browser dependency for the chosen namespace, for example three.js for three.*
  2. malda-js-runtime.js
  3. The compiled MALDA script
  4. The bootstrap call, such as MaldaApp.main()
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>MALDA JS host</title>
</head>
<body>
  <div id="app"></div>
  <script src="../wwwroot/malda-js-runtime.js"></script>
  <script src="./counter.js"></script>
  <script>
    if (window.MaldaApp && typeof window.MaldaApp.main === "function") {
      window.MaldaApp.main();
    }
  </script>
</body>
</html>

println is a JavaScript-backend console helper. The interpreter has no println (use io.print / print there — see 12. Input/Output).

28.5 API Mode DOM Helpers

The JavaScript runtime exposes browser helpers under dom for direct DOM manipulation. Same program: Examples/Web/js/counter.malda (compile with the command in 28.3, then open the host page from 28.4).

var panel = dom.query("#panel");
dom.addClass(panel, "busy");
dom.style(panel, { "width": "320px", "--accent": "#60a5fa" });
dom.attr(panel, "aria-busy", "true");
var stop = dom.onResize(panel, function (size) { println(size["width"]); });
dom.on(panel, "pointerdown", function (e) { dom.capturePointer(panel, e.pointerId); });
dom.on(panel, "keydown", function (e) {
    if (dom.keyCombo(e) == "Ctrl+C") {
        dom.copyText("copied");
    }
});
var root = dom.query("#app");

if (root == null) {
    println("No #app container found.");
} else {
    dom.clear(root);

    var count = 0;

    var title = dom.create("h1");
    dom.setText(title, "Counter example");
    dom.append(root, title);

    var valueLabel = dom.create("p");
    dom.append(root, valueLabel);

    function renderCount() {
        dom.setText(valueLabel, "Count: " + string(count));
    }

    var button = dom.create("button");
    dom.setText(button, "Increment");
    dom.append(root, button);

    function onIncrementClick() {
        count = count + 1;
        renderCount();
    }

    dom.on(button, "click", onIncrementClick);
    renderCount();
}

28.6 Sum Types and Pattern Matching in JS Mode

You can use the same sum-type and pattern-matching model in JavaScript backend mode as in interpreted mode.

type Result = Ok(value) | Err(message);

function divide(a, b) {
    if (b == 0) return Err("divide by zero");
    return Ok(a / b);
}

var outcome = divide(10, 2);
var text = match outcome {
    case Ok(v): "ok: " + v;
    case Err(msg): "error: " + msg;
};
println(text);

All pattern families are supported in JS mode: literals, identifiers, wildcard, variant payloads, array patterns with ...rest, and nested object patterns.

28.7 Actors in JS Mode

The JavaScript backend includes local actor runtime support through mlRuntime.actors. This provides browser-side or Node-local actor concurrency with mailbox semantics aligned to MALDA actor behavior.

Boundary: this is local actor runtime support only. Direct transparent communication between browser JS actors and server-side actors is not enabled by default.

Storage and files: io.store* keeps values in IndexedDB across reloads, and io.openFile / io.saveFile / io.downloadFile / io.onFileDrop read and write the user's files. See 12.11.

Off the main thread: an actor marked @worker() runs in a Web Worker that the runtime starts from its own source (no extra file; a page opened from file:// works), with messages copied by structured clone and buf.transfer to move buffers. See 18.13 Worker Actors.

28.8 Template Mode Syntax

Template mode uses .malda.html files. Use {{ ... }} for interpolation and {% ... %} for statements.

<div class="hello-template">
  <h1>Hello from template mode</h1>
  <p>User: {{ "Andrea" }}</p>
  {% var count = 2; %}
  <p>Count value: {{ count }}</p>
</div>

See Examples/Web/js/host.html for a minimal static page that demonstrates runtime loading and compiled-script bootstrap.

28.9 Game Canvas API

The JavaScript backend includes a browser canvas/game API under game.* for simple 2D interactive loops.

Image and camera guidance: game.loadImage returns a handle immediately; decode is async. Draws no-op until game.imageIsReady is true (missing files stay unready, no throw). game.imageWidth / game.imageHeight return the bitmap size, or 0 until ready. game.drawImageEx(handle, x, y, options?) adds atlas source, dest size, origin, rotation, flip, and tint: { sx?, sy?, sw?, sh?, w?, h?, ox?, oy?, angle?, flipX?, flipY?, tint?, tintFill? }. x/y are the origin (default dest top-left). angle is radians; canvas Y+ down so positive is clockwise. flipX around ox = 0 draws to the left of x — set ox to w / 2 for in-place facing. tint is a CSS color on an offscreen copy (omit / empty → no tint). Default tint is multiply (white is identity). tintFill: true replaces RGB and keeps alpha — white fill is a hit-flash. game.setBlend(mode) / game.getBlend() set the canvas composite for subsequent world draws: "alpha" (default), "add", "multiply", "screen" (unknown → "alpha"). Blend sticks until changed, like setAlpha; clear() always composites as alpha and does not reset the mode; createCanvas resets to "alpha". Blend does not affect setPixel / blitPixels. game.setCamera subtracts from subsequent world draws (fillRect, drawImage, drawImageEx, lines, text, strokeCircle). game.followCamera(targetX, targetY, viewW, viewH, worldW, worldH, options?) sets pan so the target sits at (screenX, screenY) then clamps the view inside (0, 0)–(worldW, worldH) (options { screenX?, screenY?, snap? }; default screen is view center; snap: true floors pan; does not change zoom). game.setCameraZoom(z) then scales those world sizes (default 1; clamp [0.05, 100]; non-positive → 1). Camera does not move setPixel / blitPixels. game.measureText(text, font?) returns { width, height } in unscaled font pixels (ignores pan/zoom — use it for HUD after zoom 1). game.setPixelated(true) disables smoothing and sets CSS image-rendering: pixelated; createCanvas resets it. getMouseX / getTouches stay in canvas pixels; getMouseWorldX / getMouseWorldY / screenToWorld honor pan and zoom. HUD: pushCamera, setCamera(0, 0), setCameraZoom(1), draw, popCamera (empty pop is a no-op; the stack stores pan and zoom). See Examples/Games/game_sprite_smoke.malda.

Input guidance: Key, mouse, and gamepad edges are snapshotted at the start of update and are false in render. Read wasKeyPressed / wasKeyReleased / wasGamepadButtonPressed / wasGamepadButtonReleased / wasMousePressed / wasMouseReleased in update only (same key names as isKeyDown; mouse default button 0). getTouches() returns { id, x, y } in canvas pixels (empty when none). The first active touch still aliases mouse button 0, so a new touch also edges wasMousePressed(0). Missing Gamepad API or disconnected pads return disconnected / axis 0. game.getGamepadAxis(index, axis, deadzone?) keeps the two-arg form raw; optional deadzone (clamp [0, 1]) returns 0 when |v| ≤ deadzone with no radial rescale. game.stop() clears keys, mouse edges, and button edges. See Examples/Games/game_input_smoke.malda.

Collision guidance: Overlap helpers are inclusive (touching edges count) and return false when any width, height, or radius is ≤ 0. They are pure functions: no canvas, and they do not subtract setCamera. They do not stop a mover that ends the tick past a thin wall. game.sweepRect(x, y, w, h, dx, dy, ox, oy, ow, oh) returns { hit, t, nx, ny, x, y } at the first contact along the delta (miss: t 1 and the end pose). game.sweepRects(x, y, w, h, dx, dy, obstacles) is the same against an array of { x, y, w, h } (earliest t; ties keep the first; empty/non-array is a miss). game.tileAt(cells, col, row, options?) returns the id at cell coordinates (nested rows or a flat array plus columns; out of range is out, default 0). game.drawTiles(handle, cells, tileW, tileH, options?) blits non-empty ids from an atlas (id 0 skips; atlas index is id - firstId, default 1; unready no-op; camera applies). game.sweepTiles(...) is sweepRect against solid cells (default: any id other than empty; optional solids array). Canvas Y+ is down, so a floor normal is ny = -1. Already penetrating (positive-area overlap) yields t 0 and a minimum-translation normal. Walking along a touching floor while sweeping X is not a hit. Not a physics engine or Tiled/LDtk. See Examples/Games/game_collision_smoke.malda and Examples/Games/game_tiles_smoke.malda.

Loop guidance: updateFn receives dtMs. Scale movement by dtMs so animation stays frame-rate independent. game.startFixed(updateFn, renderFn?, tickMs?) defaults tickMs to 1000 / 60, accrues wall time, and calls update(tickMs) zero or more times per frame (max 5), then render once. It cannot run at the same time as game.start. See Examples/Games/game_fixed_save_smoke.malda.

Save guidance: game.save / game.load / game.removeSave store JSON in origin-scoped localStorage under a malda.game. prefix (not files). Missing storage, quota errors, or corrupt JSON: load returns null and save is a no-op (no throw).

Audio guidance: call game.audioInit() after a user gesture to satisfy browser autoplay policies. game.audioPlaySample(url, volume?, options?) decodes a WAV/OGG once per URL and caches it (volume default 1, clamp [0, 1]; options { loop?: bool, pan?: number, playbackRate?: number }; pan clamp [-1, 1], default 0; playbackRate default 1, clamp [0.25, 4]). Overlapping one-shots are allowed. game.audioStopSample(url?) stops samples only — it does not stop the v1 track, pattern, or tones. game.stop() still does not implicit-stop audio. Samples share the 32-node cap with tones. See Examples/Games/game_audio_sample_smoke.malda.

Voices and 3D sound. A voice is a sound that keeps playing until you stop it, such as an engine, wind, or a hum. game.audioCreateVoice({ "wave": "sawtooth", "freq": 80, "cutoff": 900, "volume": 0.2 }) returns a handle. "wave" is sine, square, triangle, sawtooth (default), or noise. "cutoff" is a low-pass filter in Hz (default 20000, so no filtering), and "glide" is how many seconds a change takes to settle (default 0.03). game.audioSetVoice(voice, { "freq": 140, "volume": 0.3 }) glides to the new values, so you can call it every update without clicks. game.audioStopVoice(voice) fades the voice out. Voices do not count toward the 32 one-shot cap, and game.audioStopAll() stops them too. Give a voice "position": [x, y, z] when you create it, and it plays through a 3D panner instead of the stereo pan. It is at full volume within "refDistance" (default 5), then quieter with distance, faster when "rolloff" is higher (default 1). Move it with audioSetVoice(voice, { "position": [...] }). game.audioPlaySample takes the same position / refDistance / rolloff options for a placed one-shot. game.audioSetListener(position, forward?, up?) places the ears, usually at the camera (default facing −Z with +Y up). These calls work from a three.* game as well; Examples/Games/three_shader_race_car_neural.malda gives each car its own engine voice and puts the listener on the camera.

For a full quick start and best practices, see docs/javascript-backend.md. For a complete sample, see Examples/Games/game_bounce.malda. For PNG atlas blit plus a scrolling camera, setCameraZoom, drawImageEx flip/rotate/tint/tintFill, setBlend add/multiply, pushCamera HUD, measureText / imageWidth / setPixelated / strokeCircle, and a click-to-world marker, see Examples/Games/game_sprite_smoke.malda. For key edges, wasMousePressed, touches, and gamepad (including wasGamepadButtonReleased and analog deadzone), see Examples/Games/game_input_smoke.malda. For AABB overlap plus swept AABB (sweepRects), see Examples/Games/game_collision_smoke.malda. For a 2D id grid (drawTiles / tileAt / sweepTiles), see Examples/Games/game_tiles_smoke.malda. For overlapping WAV one-shots with pan / playbackRate next to a looping pattern, see Examples/Games/game_audio_sample_smoke.malda. For a fixed timestep plus a high score that survives reload, see Examples/Games/game_fixed_save_smoke.malda. For a short side-scroller that uses the kit together (atlas tiles, followCamera, sweepRects, key edges, sample SFX, startFixed) plus spinning coins, a facing player via drawImageEx, coin-hit tintFill flash, and an additive spark, see Examples/Games/malda_platform.malda. For a canvas client plus schema / validate scores, use malda new game --fullstack. For a Boulder Dash-style tile cave that uses the kit together (drawTiles / tileAt / sweepTiles, followCamera, drawImageEx flip/tint, setBlend add/multiply, key/gamepad/touch, sample SFX, startFixed, saved high score), see Examples/Games/maldadash.malda. For a turn-based chess board (click/touch moves, sliding pieces with a knight hop, legal-square highlights, castling / en passant / queen promotion, checkmate, optional 1–3 ply CPU, game.save), see Examples/Games/chess.malda. For a CPU ray tracer that writes pixels into an ImageData buffer and blits once per frame, see Examples/Games/ray_tracer.malda.

28.10 three.js Scene API

The JavaScript backend includes a curated 3D scene API under three.*. Use it when you want a browser-hosted scene in MALDA without writing raw THREE.* calls. The namespace is JavaScript mode only; interpreter and C# transpile do not run these helpers. Calls map to mlRuntime.three.* in the generated script.

Build a scene in this order: renderer, scene, camera, then meshes and lights, then three.start. three.createRenderer(width, height, mountSelector?) creates the WebGL canvas and appends it to the host element (default "#app"). Call it once, before three.render or three.start. If you need a new size or a second canvas, call three.stop() first — do not create another renderer while the loop is running.

Fixed step and input edges. three.startFixed(update, render?, tickMs?) is the same loop as game.startFixed: update(dtMs) runs at a fixed tick (default 60 Hz, clamped to 1–1000 ms, at most 5 catch-up ticks per frame), and render() runs once per animation frame. Physics and training then do not depend on the display rate. In render, three.getFixedAlpha() returns how far the frame sits between the last tick and the next (0 to 1), which you can use to interpolate positions. The press, release, and gamepad calls have the same names and rules as their game.* twins. A press or release is visible in exactly one update, under three.start as well as three.startFixed, and reads in render return false. Gamepad reads outside a loop poll the pad directly and see no edges. three.stop() clears all input.

Instancing, shadows, and fog. three.createInstancedMesh(geometry, material, count) draws up to count copies of one mesh in a single draw call. Every copy starts at the origin. three.setInstance(mesh, index, x, y, z, options?) places copy index. The options are "rotation" (a Y angle, or [rx, ry, rz]), "scale" (a number or [sx, sy, sz]), and "color" (#rrggbb or [r, g, b] from 0 to 1, multiplied with the material color). Copies that never get a color keep the material color. three.setInstanceCount(mesh, n) draws only the first n copies. Shadows need three switches. three.setShadows(renderer, true) turns on the shadow map. three.setLightShadow(sun, { "extent": 20 }) makes a directional light cast shadows over a square that reaches extent world units from its target, with optional near, far, mapSize (256 to 4096, default 1024), bias, and normalBias. three.setShadow(object, cast, receive?) marks a mesh, group, or glTF model and all its children; receive defaults to cast. three.lookAt(light, x, y, z) aims a directional or spot light by moving its target. Move the light and its target with the player to keep a small, sharp shadow square around the action. three.setFog(scene, color, near, far) fades to color between two distances, three.setFogExp(scene, color, density) fades exponentially, and a null color clears the fog. Use the clear color as the fog color so the horizon blends into the sky. Switching shadows or fog on or off rebuilds the scene's materials on the next three.render. Shader materials ignore fog and shadows. See Examples/Games/three_forest.malda.

Two passes: shader plus meshes. A fullscreen shader can draw the main scene while ordinary meshes add the rest on top. Have the fragment shader write gl_FragDepth for its first hit, using the projection of a perspective camera with the same near / far: (far + near) / (far - near) - 2 * far * near / ((far - near) * d), mapped from −1..1 to 0..1, where d is the distance along the view direction (write 1.0 for the sky). Then call three.render(renderer, meshScene, perspectiveCamera, { "clear": false }): without the clear, the meshes keep the shader's colors and depth-test against them, so shader objects and meshes hide each other correctly. Aim that camera with three.lookAt(camera, x, y, z, [upX, upY, upZ]), using the shader camera's up vector, which also works when the camera looks straight down. three.createCylinderGeometry(radiusTop, radiusBottom, height, segments?) is an upright cylinder centered on the origin (radiusTop 0 makes a cone). Examples/Games/three_shader_race_car_neural.malda ray-traces the track and cars, then draws trees, buildings, and signs as instanced meshes this way.

Render scale and stats. The drawing buffer is the renderer size times devicePixelRatio (capped at 2) times the render scale. The canvas keeps its size on the page and the browser stretches the picture. three.setRenderScale(renderer, 0.5) draws a quarter of the pixels, which matters most for per-pixel shaders such as a ray tracer. The range is 0.25 to 2. three.setAutoRenderScale(renderer, 60, 0.5, 1) adjusts the scale for you. It drops by 15% when the frame rate stays under 90% of the target, and it rises by 0.05 after 3 seconds at the target. After a drop the scale holds for 4 seconds, and the first second after the loop starts or the tab comes back is ignored. Keep targetFps at or below the display rate, or the scale only goes down. three.setRenderScale turns the automatic mode off. three.getStats() returns fps, frameMs, renderScale, autoScale, the drawing-buffer width / height, drawCalls, and triangles, measured over half-second windows. three.showStats(true) shows the same numbers in the canvas corner. Opening the page with #malda-stats in the URL does the same without code. three.getMouseX() / getMouseY() are in renderer units (the size passed to createRenderer or setRendererSize), so neither the render scale nor a HiDPI screen changes them.

Positions, scales, and camera near/far are world units. Rotations are radians (a floor lying in XZ is about -1.5708 on X). Standard-material options that the wrapper understands include "color" (#rrggbb), "roughness", "metalness", and "map" (a three.createTexture handle). createTexture returns immediately; decode is async and missing files stay unready (no throw). The material leaves map unset until the handle is ready. three.createDataTexture(width, height, pixels, options?) is ready immediately (RGBA; default float32, or "type": "byte"; nearest, no mipmaps). three.updateDataTexture(handle, pixels) rewrites that buffer. three.mandelbrotOrbit(real, imag, maxIter) is JavaScript-only BigInt: pass decimal strings for C (MALDA numbers are IEEE double), walk Zn+1 = Zn² + C at 256 fraction bits, and pack (re, im, alive, 1) into a 1-row float texture. Shader-material uniforms unwrap those handles for sampler2D. three.loadGLTF(url) returns a group you can add immediately; children appear when three.modelIsReady(handle) is true (JSON .gltf or .glb; failures stay unready). The runtime owns the loader — host pages do not add a fourth <script>. three.lookAt(object, x, y, z) requires lookAt on the three.js object. Groups parent meshes so you can move a cluster with one setPosition / setRotation. Input keys use the same names as the canvas API ("arrowleft", "arrowright", …).

A first scene with a spinning cube, one key light, and a dtMs loop:

var width = 800;
var height = 500;
var aspect = width / height;

var renderer = three.createRenderer(width, height, "#app");
three.setClearColor(renderer, "#101722");
three.setRendererSize(renderer, width, height);

var scene = three.createScene();
var camera = three.createPerspectiveCamera(70, aspect, 0.1, 100.0);
three.setCameraAspect(camera, aspect);
three.setPosition(camera, 0, 0, 5);

var geometry = three.createBoxGeometry(1, 1, 1);
var material = three.createStandardMaterial({ "color": "#44aaff" });
var cube = three.createMesh(geometry, material);
three.add(scene, cube);

var light = three.createDirectionalLight("#ffffff", 1.1);
three.setPosition(light, 2, 3, 4);
three.add(scene, light);

var angle = 0.0;

function update(dtMs) {
    angle = angle + ((dtMs * 1.2) / 1000);
    three.setRotation(cube, angle, angle * 0.8, 0.0);
}

function render() {
    three.render(renderer, scene, camera);
}

three.start(update, render);

Loop guidance: updateFn receives dtMs, same as game.start. Scale spin and motion by dtMs / 1000 so animation stays frame-rate independent. Cap huge dtMs values after a tab was backgrounded if a single step would jump too far. Put drawing in renderFn (or omit it and render at the end of update).

Loading order: the host page must load a compatible browser bundle that defines globalThis.THREE before malda-js-runtime.js and before the compiled MALDA script, then call MaldaApp.main(). The repository includes Examples/Web/wwwroot/vendor/three.min.js for this purpose. malda compile --mode js (and malda play, --mode esm, --mode pwa) copies that bundle beside the page and inserts the script tag when the program calls three.*. A hand-written host page still loads it first.

  1. Examples/Web/wwwroot/vendor/three.min.js
  2. malda-js-runtime.js
  3. compiled MALDA script
  4. MaldaApp.main()

Resize guidance: if the host page changes the render viewport after setup, update both the renderer and the camera: three.setRendererSize(renderer, width, height) and three.setCameraAspect(camera, width / height).

Scope: geometry from buffers, picking, orbit controls and render targets are in 28.10.2; raw WebGL and other three.js classes go through import js. Textures and glTF loading are in: see Examples/Games/three_textured.malda. Lit meshes use three.createStandardMaterial. Custom GLSL uses three.createShaderMaterial and three.setUniform — see 28.10.1.

Compile the cube demo with:

malda compile Examples/Games/three_cube.malda --mode js -o Examples/Games/three_cube.js

See Examples/Games/three_cube.malda and Examples/Games/three_runtime_smoke_test.html for the end-to-end host page. For a PNG material map, a glTF cube, and lookAt, see Examples/Games/three_textured.malda. Folder index: 35.3 Game. Working notes: docs/javascript-backend.md.

28.10.1 Shader kernels (MALDA to GLSL)

When CPU game.setPixel is too slow, put per-pixel work on the GPU. This is a JavaScript compile-time subset, not a fourth execution backend. Host MALDA still owns the three.* loop and uniform updates. The kernel owns the rays.

Mark GPU functions with @shader() and gather them into a GLSL string with glsl.compile({ ... }). Those functions are not emitted as C#, and as JavaScript only when host code calls them (see Calling a kernel from the host). Interpreter and C# transpile skip them.

@shader()
function vertexMain() {
    vUv = uv;
    gl_Position = vec4(position.xy, 0.0, 1.0);
}

var vert = glsl.compile({
    varyings: ["vec2 vUv"],
    functions: ["vertexMain"],
    main: "vertexMain"
});

var material = three.createShaderMaterial({
    "vertexShader": vert,
    "fragmentShader": frag,
    "uniforms": { "uTime": 0 }
});
three.setUniform(material, "uTime", t);

glsl.compile takes a single object literal. Keys:

Pass the resulting strings to three.createShaderMaterial as "vertexShader" / "fragmentShader". Uniform values from host MALDA are wrapped as { value }. Arrays of length 2/3/4 become Vector2 / Vector3 / Vector4. #rrggbb strings become Color. Texture handles from createTexture / createDataTexture / mandelbrotOrbit unwrap to THREE.Texture for sampler2D. Optional flags: "depthWrite": false, "depthTest": false, "transparent": true.

For a fullscreen pass, use three.createOrthographicCamera(-1, 1, 1, -1, 0, 1) and three.createPlaneGeometry(2, 2).

Uniform arrays. Declare one with a size, for example "vec3 uCars[CAR_COUNT]" beside consts: ["int CAR_COUNT = 8"], and index it in a kernel: return uCars[index];. glsl.compile writes consts before uniforms so a const can size an array. createShaderMaterial reads the uniform T name[N] declarations from the shader strings, so three.setUniform(material, "uAngles", carH) fills a float[8] instead of turning the list into a Vector4. Supported element types are float, int, bool, vec2/vec3/vec4, and ivec2/ivec3/ivec4. Vector arrays take a nested list ([[x, y, z], ...]) or a flat one ([x, y, z, x, y, z, ...]). Missing entries become zero, extra entries are ignored, and an array that is never set starts at zero. Updates write into the existing values, so calling it every frame does not allocate new vectors.

var frag = glsl.compile({
    uniforms: ["vec3 uCars[CAR_COUNT]", "float uAngles[CAR_COUNT]"],
    consts: ["int CAR_COUNT = 8"],
    functions: ["carPosition", "fragmentMain"],
    main: "fragmentMain"
});
three.setUniform(material, "uCars", [[0, 0, -5], [-3, 0, -8]]);
three.setUniform(material, "uAngles", carH);

Types in kernels

vec2, vec3, vec4, and other GLSL vector/matrix names are not MALDA types. They are GLSL names stored as type hints and copied into the shader. Outside @shader(), var p: vec3 = ... is an unknown-hint Error. Names that already exist in both languages — float, int, bool, void — remain ordinary MALDA hints.

Shader parameters and locals need a GLSL type hint. Parameters that GLSL would write with out use a two-word hint: tHit: out float. Host uniforms stay MALDA arrays such as [camX, camY, camZ], not vec3 values.

Local arrays and typed loops. A local can be a fixed-size array: var stack: float[8]; emits float stack[8];. The size is an int literal or a const name (vec3[STACK]), and the initializer is optional. A for loop variable takes a hint too: for (var i: int = 0; i < 64; i++) emits a GLSL for, so continue still runs the increment. Array hints are a GLSL feature: outside @shader(), var s: float[8]; is a parse error. A local array holds per-pixel working data, for example the list of shapes a ray passes near in Examples/Games/three_sdf_interpreter.malda, a raymarcher that runs a scene stored as bytecode in a data texture.

Language subset

Allowed: if / else, while, for, return, arithmetic and comparisons, and / or / not (emitted as && / || / !), member swizzles such as position.xy, GLSL constructors and builtins (vec3, dot, normalize, mix, clamp, …), and math.sqrt → GLSL sqrt (same for the other mapped math.* names).

Not allowed in kernels: actors, prompts, match, strings, foreach, await, classes, and MALDA I/O. A construct the GLSL emitter does not know fails JS compile with a GLSL transpile error at the MALDA line.

Calling a kernel from the host

Host MALDA may call an @shader() function by name. The compiler then also emits that function, and the kernels it calls, as JavaScript, so one source feeds the GPU and the host: a raymarched game can test a shot or pick the surface under the mouse with the same distance function the fragment shader marches. A kernel that host code never calls is still GLSL-only, and a program without such calls compiles to the same JavaScript as before.

@shader()
function sdBox(q: vec3, s: float) -> float {
    var d: vec3 = abs(q) - vec3(s, s, s);
    return length(max(d, vec3(0.0, 0.0, 0.0))) + min(max(d.x, max(d.y, d.z)), 0.0);
}

var frag = glsl.compile({ functions: ["sdBox", "fragmentMain"], main: "fragmentMain" });

// The same function on the host: a vec3 is a list of three numbers.
var distance = sdBox([shotX - boxX, shotY - boxY, shotZ - boxZ], 0.5);
if (distance < 0.05) {
    io.print("hit");
}

Consts. A kernel may name a top-level MALDA const whose value is an int, float or bool literal (a leading - is allowed). glsl.compile and glsl.source write const int OP_UNION = 1; into the GLSL for every such const their functions use, before the uniforms, typed from the literal: 0 is an int, 2.2 a float, and const HALF: float = 2; a float. The host twin uses the same value, so one declaration serves both sides. A computed const (const TWO_PI = math.pi * 2;) is not visible to kernels. A name that is also in the consts strings of glsl.compile keeps the string in the GLSL; a host-called kernel that reads it is an error when the two values differ, and a const declared only as a string cannot be read by a host-called kernel.

Uniforms and data textures: glsl.host. glsl.host("name", material) returns a host function for that kernel, bound to a material from three.createShaderMaterial. The kernel and the kernels it calls may then read the uniforms declared in the uniforms strings of glsl.compile in the file, and texelFetch a sampler2D uniform that holds a three.createDataTexture. Values are read from the material at each call, so three.setUniform and three.updateDataTexture are seen without binding again, and two materials bound to the same kernel give two independent functions.

const OP_UNION = 1;                       // one declaration, host and shader

@shader()
function runProgram(p: vec3, color: out vec3) -> float {
    var acc: float = 100000.0;
    for (var i: int = 0; i < uCount; i++) {
        var head: vec4 = texelFetch(uProgram, ivec2(i, 0), 0);
        if (int(head.x + 0.5) == OP_UNION) {
            acc = min(acc, length(p - head.yzw) - uSize);
        }
    }
    color = vec3(1.0, 0.5, 0.25);
    return acc;
}

// The host cannot receive `out`: it enters through a kernel that returns what it needs.
@shader()
function sceneDistance(p: vec3) -> float {
    var color: vec3 = vec3(0.0, 0.0, 0.0);
    return runProgram(p, color);
}

var frag = glsl.compile({
    uniforms: ["sampler2D uProgram", "int uCount", "float uSize"],
    functions: ["runProgram", "sceneDistance", "fragmentMain"],
    main: "fragmentMain"
});
var material = three.createShaderMaterial({
    "vertexShader": vert,
    "fragmentShader": frag,
    "uniforms": { "uProgram": programTexture, "uCount": 2, "uSize": 0.5 }
});

var sceneAt = glsl.host("sceneDistance", material);
var d = sceneAt([x, y, z]);               // reads the material's uniforms and data texture now

Two examples show both ways in. Examples/Games/three_sdf_interpreter.malda binds its sceneDistance kernel with glsl.host and marches the mouse ray on the host through the same bytecode texture the pixels read, to find the surface under the pointer; it also calls shapeRadius by name when it sorts the shapes into groups. Examples/Games/three_sdf_invaders.malda calls pure kernels by name: a shot is tested against a shield with the shader's sdShield, and each crater is carved with cutDistance, the kernel the fragment shader uses for the same cut. Examples/Games/three_sdf_pacman.malda is the same interpreter as a maze and calls shapeRadius by name when it groups the walls, dots and actors. All three declare the opcodes and shape kinds once, as MALDA consts.

IDE

Because kernels are ordinary MALDA function declarations, Desktop IDE and LSP rename, find references, highlights, and outline apply to identifiers in the kernel — unlike raw GLSL inside a """ string, which is one token. Rename still matches the lexeme across the file (same as the rest of MALDA). It does not rewrite string entries in glsl.compile (functions: ["hitSphere"], uniforms: ["vec3 uCamPos"], main: "fragmentMain"). After renaming a kernel or uniform identifier, update those strings. GLSL builtins (dot, gl_FragColor, type name vec3) have no MALDA declaration, so go to definition has nowhere to go.

Raw GLSL

Triple-quoted GLSL strings still work when you need syntax the subset does not emit. Use """, not $""", so braces stay literal. Prefer @shader() when the kernel fits the subset so rename and outline can see it.

Shaders assembled at runtime

glsl.compile needs literal options. To build a shader while the program runs, take the GLSL of @shader() functions as strings and join them with generated code: glsl.source("a", "b", ...) is the GLSL of those functions in that order (put callees first), and glsl.functions() is a dict from every @shader() function name in the file to its GLSL. Both are resolved when the program compiles; the result is an ordinary string for three.createShaderMaterial.

@shader()
function ripple(uv: vec2, time: float) -> float {
    return 0.5 + 0.25 * (sin(uv.x * 40.0 + time) + sin(uv.y * 31.0 - time));
}

var tint = "vec3(0.15, 0.35, 0.65)";         // chosen at runtime
var fragment = "varying vec2 vUv;\nuniform float uTime;\n" + glsl.source("ripple")
    + "void main() { gl_FragColor = vec4(" + tint + " * ripple(vUv, uTime), 0.7); }";

var library = glsl.functions();              // { "ripple": "float ripple(...) { ... }" }

Compile the realtime GPU ray tracer with:

malda compile Examples/Games/three_shader_raytracer.malda --mode js -o Examples/Games/three_shader_raytracer.js
malda compile Examples/Games/three_shader_billiards.malda --mode js -o Examples/Games/three_shader_billiards.js
malda compile Examples/Games/three_shader_path_tunnel.malda --mode js -o Examples/Games/three_shader_path_tunnel.js
malda compile Examples/Games/three_shader_mandelbrot.malda --mode js -o Examples/Games/three_shader_mandelbrot.js

Load three.min.js first, same as other three.* demos. Samples live under Examples/Games/ — see 35.3. Working notes: docs/javascript-backend.md. The billiards sample is playable: host MALDA steps 2D physics (zoom, orbit stop, and sliders for cushion/ball restitution and felt friction) and the kernel traces ball/cue uniforms. The compiled table is an appendix: 39. Appendix: GPU Billiards. The path-tunnel sample is CC-BY-NC-SA-4.0 (Frostbyte). The Mandelbrot sample is an infinite Seahorse Valley zoom: the host builds a BigInt reference orbit (three.mandelbrotOrbit) and the kernel applies scaled perturbation so the dive stays sharp past float32 ulp. Page sliders set iterate budget and wrap decades.

28.10.2 Geometry from buffers, picking, controls and render targets

These calls cover what modelling, CAD and data tools need on top of the scene graph. Raw WebGL2 stays with import js.

var positions = buf.float32(vertexCount * 3);   // computed by the program
var colors = buf.float32(vertexCount * 3);
var ground = three.createBufferGeometry({ "position": positions, "color": colors, "index": indices });
var terrain = three.createMesh(ground, three.createStandardMaterial({ "vertexColors": true }));

var controls = three.createOrbitControls(camera, { "target": [0, 0, 0], "maxPolarAngle": 1.5 });
three.fitToBounds(controls, terrain);

// in update(): a click that did not drag the view picks a face and paints it in place
if (three.wasMouseReleased(0) && !three.controlsMoved(controls)) {
    var hit = three.pick(camera, terrain, three.getMouseX(), three.getMouseY());
    if (hit != null) {
        for (var v in hit["vertices"]) {
            colors[v * 3] = 0.85;
            colors[v * 3 + 1] = 0.2;
            colors[v * 3 + 2] = 0.15;
        }
        three.updateGeometry(ground, "color");
    }
}

var minimap = three.createRenderTarget(256, 256);
three.renderToTarget(renderer, minimap, scene, topCamera);
var panel = three.createStandardMaterial({ "map": three.getTargetTexture(minimap) });
var pixel = three.readPixels(renderer, minimap, 128, 128, 1, 1);   // buf.bytes: r, g, b, a

Geometry from buffers. three.createBufferGeometry(attributes, options?) builds a geometry from buf.* buffers or arrays: "position" (required), "normal" and "color" hold 3 numbers per vertex, "uv" 2, any other name 1 unless "itemSizes": { "name": n } says otherwise, and "index" lists three vertex numbers per triangle. A buf.float32 buffer becomes the attribute's own storage: write it, then call three.updateGeometry(geometry, name) and the mesh changes in place. Other buffers and arrays are copied; three.updateGeometry(geometry, name, values) copies new values in (a different length replaces the attribute, "index" takes a new index) and three.getAttribute(geometry, name) returns the storage to write. Normals are computed when none are given ("computeNormals": false skips them) and recomputed after a position update; "dynamic": true marks the buffers for frequent updates. three.setDrawRange(geometry, start, count) draws part of it. The same geometry draws as a mesh (createMesh, with "vertexColors": true on the material to use the colors), as lines with three.createLines(geometry, options?) (pairs of vertices, or a strip with "strip": true) or as dots with three.createPoints(geometry, options?) ("size", "sizeAttenuation"). Both take "color", "vertexColors" (on by default when there is a color buffer) and "opacity".

Picking. three.pick(camera, target, x, y, options?) casts a ray through renderer pixel (x, y), the coordinates getMouseX / getMouseY give, against a scene, an object or an array of objects (children included, hidden objects skipped). It returns the nearest hit as a dict, or null: "object", "distance", "point" and "normal" (world [x, y, z]), "faceIndex" and "vertices" (the face's three vertex numbers) for meshes, "index" for lines and points, "instanceId" for instanced meshes, and "uv". Options: "all": true (every hit, nearest first), "lineThreshold" / "pointThreshold" (how close a ray must pass, in world units, default 0.1), "far", and "width" / "height" when x and y are not renderer pixels. three.raycast(target, origin, direction, options?) is the same for a world-space ray. For a large scene, three.pickId(renderer, camera, scene, x, y) draws the scene once into a 1×1 target with every mesh, line and point cloud (and every instance of an instanced mesh) in its own flat color and reads the pixel back: its cost does not grow with the number of objects, and it returns { "object", "instanceId" } without a point.

Camera controls. three.createOrbitControls(camera, options?) turns the camera around a target: left drag orbits, right drag, middle drag or shift + drag pans, the wheel and a two-finger pinch zoom. Options: "target", "minDistance" / "maxDistance", "minPolarAngle" / "maxPolarAngle" (radians from straight up), "rotateSpeed", "panSpeed", "zoomSpeed", "enabled". The program can make the same moves: three.orbitControls(controls, azimuth, polar) in radians, three.panControls(controls, dx, dy) in world units, three.zoomControls(controls, factor) (2 halves the distance), three.setControlsTarget(controls, x, y, z), and three.setControlsEnabled(controls, false) while another tool owns the pointer. three.controlsMoved(controls) is true when the latest press dragged the view, so a click that ended a drag is not taken as a pick. three.fitToBounds(controls or camera, object, margin?) frames an object (margin 1.2 leaves 20%). three.setProjection(controls, "orthographic" or "perspective") switches the camera, keeping what is at the target the same size, and returns the camera to render with (three.getControlsCamera(controls) gives it later). three.disposeControls(controls) removes the listeners.

Render targets and readback. three.createRenderTarget(width, height, options?) makes an offscreen image ("samples" for antialiasing, "depth": false, "linear": true to keep linear colors instead of the screen's sRGB). three.renderToTarget(renderer, target, scene, camera) draws into it; three.getTargetTexture(target) maps a material ("map") or feeds a sampler2D uniform. three.readPixels(renderer, target, x?, y?, width?, height?) returns RGBA bytes as a buf.bytes buffer, rows from the top like an image; three.setTargetSize resizes. three.screenshot(renderer, scene, camera, type?) draws a frame and returns the canvas as a data URL ("image/png" by default). See Examples/Games/three_terrain.malda.

28.11 JavaScript Interop (import js)

import js binds JavaScript modules and globals so a MALDA program can call any library: an npm package, a local .js / .mjs / .cjs file, a WASM module through its JavaScript glue, or a browser API. It is JavaScript-only: the interpreter and C# transpile stop with an error that points to --mode js. In a full-stack source it belongs to the client half.

import js THREE = "three";                       // the module namespace
import js { Vector3, Mesh } from "three";       // named exports
import js geom = "./geom.wasm.js";             // a local module (here a WASM wrapper)
import js global document, window;             // properties of globalThis

var v = new THREE.Vector3(1, 2, 3);              // new accepts a dotted path
v.normalize();
var lib = await geom.init();                     // await a JavaScript Promise
var button = document.createElement("button");
button.addEventListener("click", function (e) { io.print(e.clientX); });
document.body.append(button);

28.11.1 What each form binds

28.11.2 Loading and module specifiers

28.11.3 Values across the boundary

28.11.4 Testing on JavaScript

malda test --target js compiles each test file to JavaScript and runs it in Node (set MALDA_NODE_PATH if node is not on PATH). The compiled program is written next to the test file for the run, so relative import js specifiers and node_modules resolve as they will for the compiled program. A failing assert or throw reports its message and its .malda line through the source map. property tests run on the interpreter only.

malda test tests/ --target js

28.12 Common Pitfalls and Guidance

See Also