Skip to content

Data and utilities

Updated

The globals on this page are the toolbox a script reaches for once it does more than move objects: HttpRequest talks to web services, SURL routes a URL through the CORS proxy, Canvas draws images and turns them into textures, Random makes random numbers, picks and rotations, ObjectPool reuses short-lived objects, Singleton shares one object between scripts, Streams publishes live media, Fonts registers font files, THREE brings raw three.js code into a script, and log writes to the script log. Like every global, what they start is cleaned up when the script stops, except a registered font, which lasts for the session.

  • Network requests are asynchronous: you await them inside an async function. See Lifecycle hooks for async hooks.
  • The browser’s fetch, setTimeout and window are not available in a script. See Globals.

HttpRequest is the script’s HTTP client. Each verb returns a response promise with body readers, so you chain the reader directly: await HttpRequest.get(url).json().

Call What it sends
HttpRequest.get(url, options?) GET
HttpRequest.post(url, options?) POST
HttpRequest.put(url, options?), HttpRequest.patch(url, options?) PUT, PATCH
HttpRequest.head(url, options?), HttpRequest.delete(url, options?) HEAD, DELETE
HttpRequest.request(method, url, options?) Any of those, for a verb chosen at run time: 'get', 'post', 'put', 'patch', 'head' or 'delete'.
HttpRequest.extend(options) A client with its own defaults (base URL, headers, timeout, retries) and the same methods.

Read the body with .json(), .text(), .blob(), .arrayBuffer() or .formData().

Option What it does
json Sends a JSON body.
body Sends a body as is: FormData for an upload, URLSearchParams for a form, a Blob, a string.
searchParams Adds query parameters to the URL.
headers Request headers.
timeout Milliseconds before it fails with a timeout.
retry How many times, and on what, to retry, such as { limit: 2 }.
prefix A base URL for extend, which relative URLs are joined to.
signal An AbortSignal that cancels the request.
throwHttpErrors false resolves on a non-2xx response instead of rejecting.
proxy Routes the request through the configured CORS proxy. true by default; set false for a same-origin or already-permitted endpoint.

Errors. A non-2xx response rejects with an error whose name is 'HTTPError' and whose response.status is the status code. A timeout rejects with a 'TimeoutError', and a transport failure with a 'NetworkError'.

Lifetime. A script’s requests are aborted when the script stops, so a response never lands in a script that no longer exists.

SURL(url) returns url routed through the configured CORS proxy. Use it when you hand a URL from another site to something that loads it directly, such as a texture loader: new THREE.TextureLoader().load(SURL('https://images.example.com/poster.jpg')).

Canvas makes canvases to draw on with the 2D canvas API, and textures that show them: score boards, labels, minimaps, dynamic textures.

Call What it does
Canvas.create(width, height) A new canvas, not attached to the page. Each side is a whole number from 1 to 4096.
Canvas.texture(canvas) A texture showing canvas, in sRGB. Set needsUpdate = true on it after drawing again.
Canvas.toBlob(canvas, type?, quality?) A promise of the canvas as an image file: image/png by default; quality from 0 to 1 for JPEG and WebP; null when the browser cannot encode it.
Canvas.attach(canvas) Adds the canvas to the page, for the rare case the page itself must use it. Returns a function that removes it. Textures do not need this.

Textures made with Canvas.texture are disposed, freeing their GPU memory, when the script stops. To draw inside a UI panel, use a UI Drawing instead: see UI.

Random gives random numbers, picks, colours, directions and rotations.

Call What it returns
Random.value() A number from 0 up to, not including, 1.
Random.range(min, max) A number from min up to, not including, max.
Random.integer(min, max) A whole number from min to max, both included: Random.integer(1, 6) is a die.
Random.chance(p = 0.5) true with probability p.
Random.pick(items) One item, each as likely; undefined for an empty list.
Random.shuffle(items) A new array in a random order; items is unchanged.
Random.color() A new THREE.Color, any shade as likely.
Random.vector3(min = -1, max = 1), Random.vector2(min = -1, max = 1) A new vector with each component in the range.
Random.direction() A new unit vector, every direction as likely.
Random.inSphere(radius = 1) A new point inside a ball, spread evenly.
Random.rotation() A new THREE.Quaternion, every orientation as likely.
Random.seeded(seed) A generator with the same methods that makes the same numbers for the same seed (a number or a string) on every device.

Use Random.seeded when every player must see the same world, or for replays.

ObjectPool reuses objects instead of creating and discarding them. Creating objects is cheap once, but creating hundreds a second (bullets, particles, floating numbers) wastes memory and causes stutters. A pool keeps released objects and hands them out again.

Member What it does
new ObjectPool(create, reset?) create() makes an object when none is free; reset(item) cleans one as it is released.
acquire() A free object, or a new one.
release(item) Gives it back: reset runs and it waits for the next acquire. Releasing one twice, or one the pool never made, throws.
free, inUse How many objects are waiting, and how many are handed out.

Singleton holds named objects shared by every script of the app, created by whichever script asks first: Singleton.get('score', () => ({ points: 0 })). Instances survive scene switches. Modules covers it in full, along with exports and imports.

Member What it does
Singleton.get(key, factory) The instance under key, created by factory() the first time.
Singleton.get(key) The instance, or undefined when there is none.
Singleton.key The same instance, read as a property. Read-only.
Singleton.has(key) Whether there is an instance under key.
Singleton.delete(key) Removes it, calling its dispose() when it has one.

Streams publishes live media streams by name. A Media Stream component on an audio or video entity plays whatever is published under its name. The component is covered in Media and text.

Call What it does
Streams.create(id, { video?: { width, height }, audio?: { sampleRate, channels } }) Makes a stream from data, published under id. Returns an object with writeVideoFrame(source), writeAudioFrame(samples) and close().
Streams.publish(id, stream) Publishes a MediaStream under id, such as Input.camera.stream(). Returns a function that unpublishes it.
Streams.ids() The ids published now, by anyone.
Streams.has(id) Whether something is published under id now.
Streams.on(id, listener) Calls listener(live) at once, and each time a stream under id is published or goes. Returns a function that stops it.
  • writeVideoFrame takes RGBA pixels at the stream’s size (a Uint8ClampedArray), an ImageData, or a canvas or image drawn to fill the frame.
  • writeAudioFrame takes interleaved samples: a Float32Array from -1 to 1, or an Int16Array. Audio is dropped until the user’s first click or key press unlocks the page’s sound.
  • A script can replace or unpublish only the ids it published. Everything it published goes when it stops.

Fonts registers a font file as a font family for the session. Every text whose font prop names that family draws with it from then on: Text, Text 3D, UI text and the ASCII effect.

Call What it does
await Fonts.register(family, url, { weight?, label? }) Loads a .ttf, .otf or .woff file and registers it as family, in the named weight ('normal' by default); label is the name an editor shows. Registering the same family and weight again replaces it. Rejects when the file is not a usable font, or family is a bundled family or not a name of 1 to 64 characters.
Fonts.unregister(family) Removes a registered family; texts using it go back to their default font. Returns false for a bundled or unknown family.
Fonts.has(family) Whether family can be drawn with now.
Fonts.families Every family as { name, label, look }, the bundled ones first.

A registered family lasts for the session, even after the script stops, and is never saved. A text that names a family before it is registered draws with its default font and switches once the family arrives. Font families are covered in UI.

THREE lets a Behavior use raw three.js code. Build meshes, materials, vectors, colours and math objects with the three.js API you already know, and add them to the scene with scene.add or under an entity with entity.add. Objects added this way are plain objects, not entities: they have no components and are not saved.

Global What it does
log(...values) Writes a line to the script log.
console.log, console.info, console.warn, console.error The same, at a level.
Logger.log, Logger.info, Logger.warn, Logger.error The same as console.

Fetch a list of items when the script starts, and report errors clearly.

LoadItems.jx
#pragma lifecycle(startup)
async function startup() {
try {
const items = await HttpRequest.get('https://api.example.com/items', {
searchParams: { limit: 10 },
timeout: 5000,
}).json();
log('Loaded', items.length, 'items');
emit('items/loaded', { items: items });
} catch (error) {
if (error.name === 'HTTPError') log('Server answered', error.response.status);
else if (error.name === 'TimeoutError') log('The server took too long');
else log('Request failed:', error.message);
}
}

How it works

  • startup is async, so it can await the request.
  • .json() is chained on the request and parses the body.
  • searchParams adds ?limit=10 to the URL; timeout gives up after five seconds.
  • The catch branch tells server errors, timeouts and network failures apart by error.name.

Build a client once with a base URL and headers, then read and post with short relative paths.

VisitTracker.jx
#pragma lifecycle(startup)
const api = HttpRequest.extend({
prefix: 'https://api.example.com',
headers: { authorization: `Bearer ${Environment.get('API_TOKEN', '')}` },
timeout: 5000,
retry: { limit: 2 },
});
async function startup() {
try {
await api.post('visits', { json: { scene: scene.name, at: Date.now() } });
const stats = await api.get('visits/today').json();
log('Visits today:', stats.count);
} catch (error) {
log('Could not record the visit:', error.message);
}
}

How it works

  • extend returns a client with the same methods and its own defaults; prefix is joined to the relative paths visits and visits/today.
  • Environment.get reads the token from the project’s variables, so it is not written in the script. See Scene and entities.
  • json sends a JSON body. retry tries failed requests up to twice more.

Draw a score on a canvas, show it on a plane above the parent object, and redraw it on every coin.

ScoreBoard.jx
#pragma lifecycle(startup)
let canvas = null;
let texture = null;
let score = 0;
function draw() {
const ctx = canvas.getContext('2d');
ctx.fillStyle = '#0f172a';
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = '#f8fafc';
ctx.font = '48px sans-serif';
ctx.fillText(`Score: ${score}`, 24, 80);
texture.needsUpdate = true;
}
function startup() {
canvas = Canvas.create(512, 128);
texture = Canvas.texture(canvas);
const board = new THREE.Mesh(
new THREE.PlaneGeometry(2, 0.5),
new THREE.MeshBasicMaterial({ map: texture }),
);
board.position.y = 1.5;
self.parent.add(board);
draw();
on('coin:collected', (data) => {
score += data.value;
draw();
});
}

How it works

  • Canvas.create makes an off-page canvas; its 2D context draws the background and text.
  • Canvas.texture turns it into a texture, used as the map of a plain mesh.
  • After each redraw, texture.needsUpdate = true sends the new pixels to the GPU.
  • The texture is disposed when the script stops.

4. Scatter a forest the same way for everyone

Section titled “4. Scatter a forest the same way for everyone”

Place twenty copies of a tree template at seeded random positions, so every player sees the same forest, and drop loot by chance.

Forest.jx
#pragma slot(ref=seed, type=String, default="level-3")
#pragma slot(ref=count, type=Integer, min=1, max=200, default=20)
#pragma lifecycle(startup)
function startup() {
const level = Random.seeded(seed);
for (let i = 0; i < count; i++) {
const tree = spawn('Tree', {
position: { x: level.range(-50, 50), y: 0, z: level.range(-50, 50) },
scale: level.range(0.8, 1.4),
enabled: true,
});
tree.rotation.y = level.range(0, M_TAU);
}
if (Random.chance(0.1)) {
emit('loot/drop', { item: Random.pick(['sword', 'shield', 'potion']) });
}
}

How it works

  • Random.seeded(seed) gives a generator that makes the same sequence for the same seed on every device, so the forest is identical everywhere.
  • range gives positions, a scale and a turn between 0 and M_TAU (a full turn).
  • The loot uses the shared Random, which differs each time: a one-in-ten chance, then a random item.

Fire bullets from the parent object without creating a new mesh for each shot.

Blaster.jx
#pragma lifecycle(startup, update)
const geometry = new THREE.SphereGeometry(0.05);
const material = new THREE.MeshBasicMaterial({ color: '#fbbf24' });
const bullets = new ObjectPool(
() => new THREE.Mesh(geometry, material),
(bullet) => bullet.removeFromParent(),
);
const flying = [];
function fire() {
const bullet = bullets.acquire();
self.parent.getWorldPosition(bullet.position);
scene.add(bullet);
flying.push({ mesh: bullet, age: 0 });
}
const fireLimited = throttle(fire, 150);
function startup() {
log('Hold F to fire');
}
function update(dt) {
if (Input.keyboard.isKeyPressed(Key.F)) fireLimited();
for (let i = flying.length - 1; i >= 0; i--) {
const shot = flying[i];
shot.age += dt;
shot.mesh.position.z -= 20 * dt;
if (shot.age > 2) {
bullets.release(shot.mesh);
flying.splice(i, 1);
}
}
}

How it works

  • One geometry and one material are shared by every bullet.
  • acquire hands out a free mesh or makes a new one; release runs the reset function, which takes the mesh out of the scene, and keeps it for the next shot.
  • After a few seconds of firing, the pool stops creating meshes: bullets.free and bullets.inUse show the balance.
  • throttle limits the rate of fire.
Wrong
const data = await fetch('https://api.example.com/items').then((r) => r.json()); // fetch is undefined
Right
async function load() {
const data = await HttpRequest.get('https://api.example.com/items').json();
return data;
}
Wrong
const config = await HttpRequest.get('https://api.example.com/config').json(); // does not compile
Right
#pragma lifecycle(startup)
let config = null;
async function startup() {
config = await HttpRequest.get('https://api.example.com/config').json();
}

A canvas texture shows the pixels it had when last uploaded. After drawing on the canvas again, set texture.needsUpdate = true, or the texture keeps showing the old picture.

release throws when an object is already free. Remove an object from your own list at the same moment you release it, as in the pool example above.

The shared Random gives different numbers on every run and on every device. Use Random.seeded(seed) for anything every player, or every replay, must see the same.