3D

Models from .glb files, with a sun, shadows and lights

A cart can put 3D models behind its UI: load a .glb, spawn copies of it, move and animate them. The scene draws behind everything the cart renders, so a score or a nameplate sits on top of the world with no extra work.

import { useEffect } from "react"
import { mount, useScene, useModel } from "oj"

function Haunt() {
    const scene = useScene()
    const ghost = useModel("ghost.glb")
    useEffect(() => {
        if (!scene || !ghost) return
        for (let i = 0; i < 5; i++) scene.spawn(ghost, { position: [i * 1.5 - 3, 0, 0], play: "idle" })
    }, [scene, ghost])
    return null
}

mount(<Haunt />)

useScene() and useModel() are both null on the first render and fill in a frame or two later, which is why the spawning waits for both.

A cart has one scene. Call useScene once, near the top of the cart, and pass the scene down to whatever spawns into it; a second useScene while one is live throws and says so. Each model file loads once however many components ask for it, and the copies share it.

What you get for writing nothing

A scene with no options already looks right:

Camera At [0, 4, -8], looking at the origin, 50 degree field of view
Sun Warm white, from above and behind the camera, casting soft shadows
Ambient Light from everywhere: a cool sky from above, a dark ground from below
Models Cast shadows and receive them
Background The stage's dark grey

Materials come from the file as it was exported: base colour, metallic and roughness, normal, occlusion and emission maps, alpha (masked and blended), double sided and unlit. Positive y is up and the units are the file's, which for most exports means metres.

A .glb stores a base colour as linear values, not the sRGB a colour picker or a hex code gives, so a cart that writes its own model converts each channel first, or its colours come out washed out: c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4, with c from 0 to 1. A model exported from Blender or another tool has this done already.

Tuning the scene

Every option turns one default off or adjusts it. A colour is anything oj takes as one: "#ffe9c4", "rgb(255, 233, 196)", "orange" or a Color.

const scene = useScene({
    camera: { position: [0, 6, -6], lookAt: [0, 0, 1], fov: 45 },
    sun: { direction: [-0.3, -1, 0.5], color: "#ffe9c4", intensity: 1.4 },
    ambient: { sky: "#9fb4d6", ground: "#3a3028", intensity: 0.8 },
    background: "#1a1626",
    fog: { near: 8, far: 30 },
})
Option Default
camera { position: [0, 4, -8], lookAt: [0, 0, 0], fov: 50 } scene.camera(...) moves it later
sun { direction: [-0.32, -0.77, 0.56], color: "#fff4d6", intensity: 1.2, shadows: true } false for no sun at all; shadows: false keeps the light; shadows: { distance } reaches further, below
ambient { sky: "#b8c6d9", ground: "#4a443d", intensity: 0.9 } Like three.js's HemisphereLight
background "#14181d"
fog off Thickens from near to far, in the background colour unless given a color
sky off A sky instead of the background colour, below
wind { direction: [1, 0], strength: 1, gust: 0.3 } Moves a mesh made with sway, below

All of it can change while the scene runs, and each call changes only what it names:

scene.sun({ intensity: 0.3 })               // dusk
scene.ambient({ sky: "#3b4a6b" })
scene.background("#0b0d16")                 // the fog follows unless it has its own colour
scene.fog({ near: 4, far: 18 })             // or scene.fog(false) to clear it
scene.sun(false)                            // or put the sun out

A sky

const scene = useScene({ sky: { top: "#0b1a3a", horizon: "#f4a261" } })
scene.sky({ stars: 0.6 })                   // later, changing only what it names
scene.sky(false)                            // back to the background colour

A sky is a gradient from horizon up to top, and down to bottom below the horizon (the horizon's colour unless given one), with the sun's disc in it and stars from 0 to 1. sky: {} is a clear day. The disc sits where the scene's sun shines from, in its colour, so moving the sun moves the disc. The sky's own sun option is the disc, not the light: sky: { sun: { size: 2, glow: 10 } } sets how many degrees across it is and how far its glow reaches, and sky: { sun: false } leaves the disc out and the light on. Fog given no colour of its own takes the sky's horizon, so the ground fades into the sky rather than meeting it at a line.

Shadows across a big world

The sun's shadows reach 50 metres from the camera and fade out there. That suits a room or an arena, and shows nothing at all to a camera high over a landscape, whose nearest ground is further away than that. shadows takes an object to reach further. From runtime 1.7.

scene.sun({ shadows: { distance: 150, cascades: 4 } })
Option Default
distance 50 Metres from the camera that shadows reach
cascades 2 1 to 4. Each splits the distance again, so shadows near the camera stay sharp while far ones still fall
softness "high" "hard", or how wide a soft edge is: "low", "medium" or "high"
resolution 2048 1024, 2048 or 4096 pixels a side for the map the shadows are read from

Each one left out is the default, and shadows: true is all four. A new shadows replaces the last one whole. Each cascade draws every shadow caster again, so cascades are what cost: on a desktop GPU with WebGPU, four cascades to 150 metres took about 3 ms a frame more than the default in a forest of 15,000 trees, and 600 metres about 5 ms, while WebGL 2 paid under 2 ms for either. Softness costs almost nothing.

Models

const boo = scene.spawn(ghost, { position: [0, 0, 2], yaw: 90, scale: 1.2, play: "idle" })

boo.position = [1, 0, 2]                    // move it
boo.yaw = 180                               // turn it, in degrees
boo.rotation = { yaw: 180, pitch: -10 }     // or on all three axes: yaw, pitch and roll
boo.scale = 2                               // twice the model's own size
boo.play("run", { fade: 0.2 })              // crossfade to another clip
boo.play("dissolve", { loop: false })       // play once and hold the last frame
boo.speed = 0.5                             // its clips and dissolve at half speed; 0 holds them
await boo.dissolve()                        // fade out with a glowing edge, in 0.8 seconds
await boo.dissolve({ to: 0, seconds: 1.2 }) // and back in, slower
boo.destroy()

ghost.clips lists the animation names the file has, and ghost.height is how tall it is, which is handy for a label above it.

A clip moves only the parts it has keys for. A part a clip leaves out stays wherever the last clip put it, so after a crossfade from run to idle an arm that idle never keys stays mid-swing. When you make or export a model, key every part in every clip, even the parts that hold still.

Shadows are per model: spawn(ghost, { castShadows: false }), or boo.receiveShadows = false later.

Pausing

scene.paused = true holds every clip and every dissolve where it is, for a pause menu, and a dissolve's promise waits with it. Each model keeps its own speed for when the scene goes again. The camera and lights are untouched, so a pause screen can still move the camera.

Clicking and labels

<View style={{ position: "absolute", left: 0, top: 0, right: 0, bottom: 0 }}
      onPointerDown={(e) => scene?.pick(e.x, e.y)?.dissolve()} />

scene.pick(x, y) is the model under a point, or null. boo.screenPoint() is where the top of a model is on screen, in window pixels like a pointer event's, so a label with position: "absolute" at that left and top follows it. Read it in useFrame while things move. It is null when the model is behind the camera.

Lights

const lamp = scene.pointLight({ position: [0, 2, 0], color: "#ffb36b", intensity: 2, range: 6 })
lamp.position = [1, 2, 0]
lamp.destroy()

Point lights do not cast shadows; the sun does.

Light that bounces, so a doorway darkens and a red wall tints the floor beside it, is baked once and saved with the cart.

Models made from numbers

scene.mesh makes a model from arrays: a terrain, a shape worked out in code, a shadow that changes every frame. It spawns like a loaded one.

import { useEffect } from "react"
import { mount, random, useScene } from "oj"

const CELLS = 64, SIZE = 80              // 64 squares a side, 80 metres across

function Hills() {
    const scene = useScene({ sky: {}, camera: { position: [0, 25, -60], lookAt: [0, 0, 0] } })
    useEffect(() => {
        if (!scene) return
        const height = random("hills").noise({ layers: 4 })
        const side = CELLS + 1
        const positions = new Float32Array(side * side * 3)
        for (let i = 0; i < side; i++) {
            for (let j = 0; j < side; j++) {
                const x = (i / CELLS - 0.5) * SIZE, z = (j / CELLS - 0.5) * SIZE
                positions.set([x, 6 * height(x / 20, z / 20), z], (i * side + j) * 3)
            }
        }
        const indices = new Uint32Array(CELLS * CELLS * 6)
        for (let i = 0; i < CELLS; i++) {
            for (let j = 0; j < CELLS; j++) {
                const a = i * side + j, b = a + side       // two triangles a square
                indices.set([a, a + 1, b, b, a + 1, b + 1], (i * CELLS + j) * 6)
            }
        }
        scene.spawn(scene.mesh({ positions, indices, color: "#6b8f4e" }))
    }, [scene])
    return null
}

mount(<Hills />)

positions is x, y and z for each corner, and indices three corners a triangle, counted from 0. Plain arrays work too; a Float32Array and a Uint32Array cross to the engine faster, and a Uint16Array is half the bytes when there are fewer than 65,536 corners. A triangle is seen from the side its corners go round clockwise, Unity's way, and from the other side it is not drawn at all: if a mesh is missing, reverse two corners of each triangle. normals are worked out from the triangles when you leave them out. A corner that several triangles share gets one normal between them, so the surface shades smoothly across it, which is what hills want; a box wants hard edges, so give each face its own four corners. uvs give a texture somewhere to sit.

color colours the whole model, white by default, and an alpha below 1 makes it see through. colors gives each corner its own, three or four numbers each from 0 to 1, and is multiplied by color. These are the sRGB colours a picker gives, like every other colour in oj, so the advice about a .glb's linear colours above does not apply here.

shadow.set({ positions }) redraws a mesh with new corners, and every copy spawned from it changes with it. It keeps its memory between calls, so one that changes every frame stops allocating once it has seen its largest size. Leave out indices to keep the last ones. A mesh given to the physics world keeps its shape, and set on it throws rather than let the collider drift from what is drawn. destroy() frees a mesh once nothing spawned from it is left.

scene.mesh(data, { depthOnly: true }) draws nothing and hides whatever is behind it: the shadow a wall casts in a top down cart, drawn as a dark shape under the world and cut by this. A sky is hidden too, so where nothing else is behind it, it shows the background colour.

Textured ground

texture tiles one picture from loadTexture across a mesh's uvs, under its colours. tiling says how often it repeats across a uv of 0 to 1: one number for both directions, or [u, v]. A 64 metre chunk with uvs from 0 to 1 and tiling: 8 repeats the picture every 8 metres, and the next chunk's uvs starting where this one's end make the seam disappear.

const grass = await loadTexture("grass.png")
scene.spawn(scene.mesh({ positions, indices, uvs, colors, texture: grass, tiling: 8 }))

splat paints up to four pictures together by weights a corner, one a picture, so the grid says where the grass gives way to dirt and the pictures carry the detail inside each square. The weights need not add up to 1. mesh.set({ positions, weights }) repaints it: a path worn into the grass is one set.

const [grass, dirt, rock] = await Promise.all(["grass.png", "dirt.png", "rock.png"].map(loadTexture))
const ground = scene.mesh({ positions, indices, uvs, splat: { layers: [grass, dirt, rock], weights, tiling: 8, heightBlend: 0.2 } })

heightBlend reads each picture's alpha as its height. Left at 0, the weights alone mix the pictures, so an edge is as soft as the grid is wide. Above 0, a picture shows where its height and weight come within that much of the highest, so stones stand out of the grass round them and the edge follows the stones rather than the grid. Smaller is crisper; 0.1 to 0.3 suits most ground. A picture without alpha has one height everywhere, which a height blend only sharpens.

Steep faces. A layer read at the uvs stretches down a cliff, since a cliff's corners sit close together in plan and its uvs barely change down it. Give a layer as { picture, triplanar: metres } and it is projected from the sides instead, in world space, repeating every that many metres on every face whatever its slope; the splat's tiling does not apply to it. Mix it with layers read at the uvs: grass and dirt on the flat, rock triplanar on the cliffs. It costs three reads of its picture where a layer at the uvs costs one. A face looking along a negative axis shows the picture mirrored, which rock, scree and moss hide. From runtime 1.6.

const ground = scene.mesh({ positions, indices, uvs, splat: { layers: [grass, dirt, { picture: rock, triplanar: 4 }], weights, tiling: 8 } })

colors still multiply in, so occlusion and tint noise baked into the corners keep working. Both take the sun's shadows and baked light as any mesh does, and a bake bounces the pictures' colours: grass lights what stands on it green.

The pictures. PNG or JPEG, square, a power of two on a side: 256 or 512 for ground seen from above, 1024 at most. Each is drawn from a copy with its own mipmaps, so it stays sharp up close and calm in the distance, and the copy is shared by every mesh given the same picture. A picture costs its size in memory twice over, the picture and the copy: four of 512 by 512 are about 7 MB on the GPU. For a height blend, keep the height in the alpha of a PNG, white high and black low, as a material tool exports a height map. Tile the pictures seamlessly, since every edge meets its opposite. A picture's numbers are sRGB, as every colour in oj is, and they multiply the colour under them: a pixel of 128 draws as #808080 would, so a grey picture whose pixels average 230 (0.9) darkens a ground colour about as much as scaling that colour's hex by 0.9 does.

Leaves and wind

A tree's crown is a few dozen cards, each a quad with a picture of leaves on it. Three options make them read as foliage, and all three hold for every copy of a scatter. From runtime 1.7.

const leaves = await loadTexture("leaves.png")
const crown = scene.mesh({ positions, indices, normals, uvs, texture: leaves, cutout: 0.5, twoSided: true, sway })

cutout cuts away every pixel whose alpha is below it, from 0 to 1: the picture's alpha, color's and the corners' colors, multiplied. What is left draws solid, with hard edges, and casts a shadow the same shape. A mesh with a cutout draws opaque even when its alpha would have made it see through, so a thousand overlapping cards need no sorting. A splat has no alpha and is refused.

twoSided: true draws the back of every triangle too, and its shadow from both. The back is lit with the normal you gave, not turned round, so a crown whose normals point out from its middle shades the same from inside and out, and a card seen from behind does not go dark.

sway is a number a corner: how far the wind moves that corner, in the mesh's own units, at a strength of 1. Give 0 at a trunk's foot and more toward the rim of the crown, about 0.1 to 0.4 for a tree a few metres tall; a copy scaled up sways that much further. The corners move on the GPU, so a forest sways for nothing in JS, and each copy swings at its own phase, worked out from where it stands. mesh.set({ positions, sway }) gives new sway; left out, the last stays. A mesh made without sway takes none later, since the number rides with its corners.

scene.wind({ direction: [1, 0.3], strength: 1.5, gust: 0.5 })

scene.wind changes only what it names. direction is the way it blows as [x, z], any length but 0. strength scales every sway, and 0 stills the scene. gust from 0 to 1 is how much a slow swell rolling along the wind adds and takes away, so a gust crosses a field rather than shaking every tree at once. The wind keeps the scene's clock: it stops while scene.paused is true, and a recording of the same frames sways the same way twice. Baked light is baked with the trees at rest; the sway is small enough that their shading does not drift from it.

Many copies that never move

const trees = []
for (let i = 0; i < 2000; i++) trees.push({ x: rng.range(-40, 40), z: rng.range(-40, 40), yaw: rng.range(0, 360) })
const forest = scene.scatter(pine, trees)
forest.destroy()

scene.scatter(model, copies) draws a model at every place in the list, each { x, y, z, yaw, scale } with y and yaw 0 and scale 1 when left out. It costs a fraction of spawning each one: two thousand trees are a handful of draws. Copies never move and have nothing an actor has: no pick, no clips, no body. A model with an animated skeleton is refused, since its copies could never play. A Float32Array of five numbers a copy (x, y, z, yaw, scale) works too, for a list made in a loop. The model can be a .glb or one from scene.mesh, textured or a splat.

Tilted and tinted copies. A copy also takes a pitch and a roll, in degrees as an actor's rotation does, so a rock settles into its slope rather than standing level on it, and a tint, any colour, multiplied into its own colours as colors are. A few greens and browns a little apart turn one rock or one tree into a hundred. A list with any copy tilted or tinted is sent ten numbers a copy; to build one in a loop, give a Float32Array of x, y, z, yaw, pitch, roll, scale, then the tint's r, g and b from 0 to 1 in sRGB, with { stride: 10 }. A copy's tint is drawn over its baked light rather than baked into it. From runtime 1.7.

const rocks = scene.scatter(boulder, spots.map((p) => ({ ...p, pitch: rng.range(-12, 12), roll: rng.range(-12, 12), tint: rng.pick(["#d8d2c8", "#b9b3a6", "#a8ab98"]) })))
const forest = scene.scatter(oak, data, { stride: 10 })

Near and far. { from, to } draws each copy only while the camera is between that many metres of its foot. Give a tree's detailed mesh to and a cheaper one the same edge as from, both from the same list of places, and each copy changes from one to the other as the camera passes. fade is the metres across which they cross, centred on the edge: inside it, each copy is drawn as a scatter of pixels from both meshes in patterns that fit together, so every pixel comes from exactly one and there is nothing to sort. Its shadow changes at the edge in one step. The choice is made on the GPU every frame from the camera's distance, so nothing is rebuilt in JS as the camera moves, and a block of copies wholly outside the range is not sent at all. The pair costs about what each mesh costs on its own, so the far one saves what it is cheaper by: fewer pixels to cut out and a smaller shadow as well as fewer triangles. Two large cards with holes cost almost what a crown of small ones does. From runtime 1.7.

const near = scene.scatter(oak, oaks, { to: 140, fade: 12 })
const far = scene.scatter(oakCard, oaks, { from: 140, fade: 12 })

Cameras you drag

Two hooks move the camera for you. Spread bind on the View the player drags in; usually that is the whole stage, under the HUD.

import { mount, useScene, useOrbit, View } from "oj"

function Turntable() {
    const scene = useScene()
    const orbit = useOrbit({ distance: 6, idleSpin: 10, camera: scene })
    return <View {...orbit.bind} style={{ flexGrow: 1 }} />
}

mount(<Turntable />)

useOrbit turns around a point, the target (the origin by default). A drag or one finger turns it, degreesPerPixel degrees for each pixel dragged (0.3 by default, so the same hand movement turns as far in a small window as full screen), and the wheel or two fingers bring it closer and further, within distanceRange. pitchRange keeps it from going over the top. idleSpin turns it by itself, in degrees a second, until the first drag. With camera: scene it moves the scene's camera; without, orbit.eye and orbit.target say where it is, for a shader that draws its own world with lookRay. The component re-renders as it moves, and onMove is called each time, for a path tracer that starts its picture again.

useFollowCamera follows something that moves: an actor, a character's me.actor or a car's car.body.actor, looked at height metres above where it stands. A left drag looks around it, a right drag turns the camera and sets heading, the way the player wants to face (with no right drag held, heading is the way the actor already faces), and both buttons held set forward, so a cart can walk on that. With a world from useWorld, the camera comes in front of a wall rather than going behind it; filter: { skip: ["glass"] } says what is not a wall, as a world query does. Its object never re-renders; read it in useFrame, where it has already turned by that frame's drag, so a character steered from heading faces exactly where the camera looks.

What is in the way. The camera keeps clearance metres (0.4 by default) between itself and anything, measured along the whole way back from what it looks at and not only where it stands, so it does not cut into a slope it passes over. A wall brings it in at once, so it never stands in one (WoW eases a wall in over 0.06 s). Ground, a hit that faces up, comes in more gently, and while it does, the way back can pass a sharp crest a little nearer than clearance for a moment (a few centimetres, for about a quarter of a second), though never through it. Held short for a while, the zoom itself comes in behind the camera and is given back a second after the way is clear, so walking along a hillside does not push the camera in and out with every step. A world streamed in chunks has colliders only near the player: ground: (x, z) => height gives the camera the ground's height everywhere, and it keeps clear of that too, looks a little higher when it comes low over the ground, and never stands nearer than clearance over it.

A click does not turn the view: a press turns nothing until it has moved 5 pixels. Each wheel notch moves the camera 15% of its distance, and at least 0.3 m, easing there in a fifth of a second. cam.distance is always the distance the player chose.

These are runtime 1.6's defaults, and they are WoW's feel. A cart on 1.5 keeps the camera it had. To let the camera closer to walls and slopes, as 1.5's came within 0.2 m, give clearance: 0.2.

Jumps and falls on 1.6. me.jump(1.2) tops out at 1.2 m, and a jump's airtime and a fall's are what the formulas say, at any rate. Up to 1.5 a jump stopped about 4% short of its height (1.33 m of 1.39 at 60 steps a second), and landed a little sooner. So a cart that moves to 1.6 jumps about 4% higher than it did, toward what it asked for; a cart that asked for more to make up for it can ask for its real height now.

A car's camera is one line, since behind: true settles it behind the way the car faces whenever nothing is held:

const cam = useFollowCamera(car?.body.actor, { behind: true, world, camera: scene })

A character the player walks round a level with the keys and the mouse, the camera behind it, is a whole cart. The character is a world.character, which walks along the ground and climbs steps; its actor is the model the camera follows.

import { useEffect, useState } from "react"
import { mount, useScene, useModel, useWorld, useFollowCamera, useFrame, input, View, type Character } from "oj"

function Game() {
    const scene = useScene({ sky: {} })
    const world = useWorld()
    const hero = useModel("hero.glb")
    const level = useModel("level.glb")
    const [me, setMe] = useState<Character | null>(null)

    useEffect(() => {
        if (!scene || !world || !hero || !level) return
        world.mesh(level)                                                   // the ground and the walls
        setMe(world.character({ at: [0, 0, 0], actor: scene.spawn(hero) }))
    }, [scene, world, hero, level])

    const cam = useFollowCamera(me?.actor, { turnWith: true, behind: "moving", world, camera: scene })

    useFrame((dt) => {
        const actor = me?.actor
        if (!me || !actor) return
        const keys = input.keyboard
        if (input.mouse.rightButton) actor.yaw = cam.heading               // a right drag steers
        const turn = (keys.isKeyDown("D") ? 1 : 0) - (keys.isKeyDown("A") ? 1 : 0)
        actor.yaw += turn * 180 * dt                                        // A and D turn, the camera with them
        const speed = keys.isKeyDown("W") || cam.forward ? 5 : keys.isKeyDown("S") ? -2.5 : 0
        const facing = actor.yaw * (Math.PI / 180)                          // a yaw of 0 faces +z
        me.walk([Math.sin(facing) * speed, 0, Math.cos(facing) * speed])
        if (me.grounded && keys.wasKeyPressed("Space")) me.jump(1.2)
    })

    return <View {...cam.bind} style={{ flexGrow: 1 }} />
}

mount(<Game />)

me is null until the models and the world have loaded, and the camera holds still until it has a target, then starts behind it. turnWith: true turns the camera by exactly what the character turned since the last frame, so A and D turn the two together; hold a drag and turn, and the camera stays where your hand holds it. behind: "moving" brings the camera back behind the character after a look round, but only once it walks; standing still, the view you left stays.

turnWith is off by default: a character that faces the way a stick points turns on every change of direction, and a camera locked to it would swing with each one.

On a phone there is no right button, so a finger on the View only looks around. Walk with a stick instead, turned by the camera's yaw so up on the stick is away from the camera, and face the way the character walks. Leave turnWith off on a touch screen, or the camera turns with every step and the stick with it: turnWith: input.pointerType !== "touch".

const move = useStick("left")                                               // and <Stick stick={move} /> in the View

// in useFrame, before the keys
if (move.active) {
    const yaw = cam.yaw * (Math.PI / 180), x = move.x, z = -move.y          // a stick's y is -1 at the top
    const east = x * Math.cos(yaw) + z * Math.sin(yaw), north = z * Math.cos(yaw) - x * Math.sin(yaw)
    me.walk([east * 5, 0, north * 5])
    actor.yaw = Math.atan2(east, north) * (180 / Math.PI)                   // face the way it walks
    return
}

To drag past the edge of the screen, lock the pointer while a button is held. The camera reads how far the mouse moved, which a lock still reports, so it turns the same locked or not (Mouse look has the browser's rules for a lock):

const mouse = input.mouse
if ((mouse.wasLeftPressed || mouse.wasRightPressed) && !mouse.overUI && !mouse.locked) mouse.lock()
if (!mouse.leftButton && !mouse.rightButton && mouse.locked) mouse.unlock()

The options pitch and distance, and useOrbit's yaw, say where a camera starts, and are read once; a follow camera starts behind its target. To move it later, write the same fields on the object the hook returns: cam.distance = 3 for a zoom key, cam.yaw += 90 for a quarter turn. Written in useFrame, they take effect that frame, held to pitchRange and distanceRange. Either hook holds pitchRange within 89 degrees either way, whatever it is given: a camera looking straight down at its target has no way to tell which way is up, and the view turns over. A cart that passed a new distance option on every render would undo every zoom the player made with the wheel, which is why the options are not live.

Give either hook the actor, never the body: the actor is what is drawn, and on a fast screen it is up to a step behind the body. Both move the camera after the world has stepped, so the picture never lags a frame behind the thing it follows. A camera of your own wants the same moment, which is useLateFrame (Writing a Cart).

A drag that starts on a button or a stick is the button's, not the camera's, so a HUD over the View works with nothing more.

The scene as a picture

scene.texture is the scene drawn into a texture instead of the screen, for a shader to read: a colour grade, a blur, an outline over the whole world.

// grade.sl
texture2D scene;
uniform float amount = 1;

float4 main() {
    float3 c = tex2D(scene, uv).rgb;
    float grey = dot(c, float3(0.2126, 0.7152, 0.0722));
    return float4(lerp(c, float3(grey, grey, grey), amount), 1);
}
{scene && <ShaderProgram program={grade} textures={{ scene: scene.texture }}
    style={{ position: "absolute", left: 0, top: 0, right: 0, bottom: 0 }} />}

While a program reads it, the scene is only where that program draws it, so the program usually covers the stage. When the last program that reads it goes, the scene draws to the screen again. Until then it costs nothing, and the program always reads this frame's picture, never the last one.

Files

Add .glb files like any other: they sit in the cart's files and load by name, so useModel("ghost.glb") or useModel("models/ghost.glb"). A .glb carries its own textures and animations, so one file is one model. The file limits apply: 100 MB for one file.

A model bought from a store may come with a licence that lets you use it in what you make but not hand out the file, and anyone can read, clone and fork a public cart's files. Check the licence before you make such a cart public.

In Unity

npx ojplay add brings a cart with models into a Unity project as it does any other, and adds the glTFast package (com.unity.cloud.gltfast) to the project if it is not there yet. The models draw with the same shader in both places, so the scene looks the same in URP. In the built-in render pipeline they use Unity's Standard lighting.

In Play mode the cart's scene takes over: its camera and sun replace the scene's own until Play stops. Without Play, in the Game view preview, the cart adds its camera and models but leaves your scene's lights and settings alone, so the preview is lit by your scene's sun.