3D scenes

@wardic/three/solid brings Wardic's hooks to a three.js scene. ward, the sensors, createBatch and createFrameEffect are the hooks you know from the page, given a scene's object instead of an element. There's no canvas component and no renderer of Wardic's own. You make the scene, its camera and its renderer with three.js, and a Stage runs Wardic on them. Solid 2 only, from Wardic 1.3.

bun add @wardic/three three

A Stage

import { createStage, WardicStage } from "@wardic/three/solid"
import * as THREE from "three"

const scene = new THREE.Scene()
const camera = new THREE.PerspectiveCamera(35, 4 / 3, 0.1, 50)
const stage = createStage({
  renderer: () => new THREE.WebGLRenderer({ antialias: true, alpha: true }),
  scene,
  camera,
  frameloop: "demand",
})

<WardicStage value={stage}>
  <div class="scene" ref={stage} />
  <Crate />
</WardicStage>
  • ref={stage} mounts the renderer's canvas in the element, kept at its size. resize: false leaves the size to you.
  • renderer is a function the browser calls once the page has settled. On the server a Stage is inert: its element renders empty, so hydration matches, and its hooks animate nothing.
  • frameloop: "demand" draws a frame only when something moves: a ward, a Batch, a Frame effect's write, the pointer. For a change Wardic didn't make, call stage.invalidate(). "always" draws every frame.
  • features are what a Stage does beyond a ward's motion: stageDrag drags a scene's objects, and stageBatches makes Batches of them. Each one's code ships only where it's given.

Under <WardicStage>, the hooks run in its scene: a ward's frame is the Stage's, and a sensor hears the pointer through the scene's raycast. Import them from @wardic/three/solid, which carries none of the page's code. @wardic/solid's own ward takes a mesh too, for a page that has both (WardicStage).

A ward on a mesh

Live demo
scene-turn/solid2.tsx
import { createDrag, createFrameEffect, createStage, ward, WardicStage } from "@wardic/three/solid"
import { createSignal, For } from "solid-js"
import * as THREE from "three"

const COLOURS = ["#e6dfd3", "#2f63b0", "#c2502f", "#4f8a63"]

/** A vase's profile, as [radius, height]: its outside up from the foot to a rolled lip, then its inside back down. */
const PROFILE = new THREE.SplineCurve(
  [
    [0.36, 0],
    [0.62, 0.3],
    [0.78, 0.75],
    [0.6, 1.2],
    [0.3, 1.5],
    [0.32, 1.7],
    [0.26, 1.66],
    [0.22, 1.4],
  ].map(([radius, height]) => new THREE.Vector2(radius, height)),
).getPoints(64)

/** Degrees the vase turns a pixel the pointer moves. */
const TURN = 0.5

/** A vase on a turntable: hover lifts it, a drag turns it, and its glaze is the colour picked. */
function Scene(props: { readonly colour: string }) {
  const scene = new THREE.Scene()
  scene.add(new THREE.HemisphereLight("#ffffff", "#8c8173", 2.2))
  const key = new THREE.DirectionalLight("#ffffff", 2)
  key.position.set(-3, 5, 4)
  scene.add(key)
  const camera = new THREE.PerspectiveCamera(30, 4 / 3, 0.1, 50)
  camera.position.set(0, 1.7, 6.4)
  camera.lookAt(0, 0.85, 0)
  // Fourteen facets, flat-shaded: a turn shows as the light moves across them.
  const vase = new THREE.Mesh(new THREE.LatheGeometry(PROFILE, 14), new THREE.MeshStandardMaterial({ color: COLOURS[0], roughness: 0.3, flatShading: true, side: THREE.DoubleSide }))
  const turntable = new THREE.Group()
  turntable.add(vase)
  scene.add(turntable)

  // The scene's Stage: its renderer, made in the browser, and a frame drawn only when something moves.
  const stage = createStage({ renderer: () => new THREE.WebGLRenderer({ antialias: true, alpha: true }), scene, camera, frameloop: "demand" })

  const Vase = () => {
    // A ward on the mesh: lifted under the pointer, its glaze springing to the colour picked, in linear light.
    const lifted = ward(vase, {
      whileHover: { y: 0.15 },
      animate: () => ({ color: props.colour }),
      transition: { type: "spring", bounce: 0.3, visualDuration: 0.4 },
    })
    // The turntable's angle, read as a number: what a drag starts from.
    const angle = ward(turntable, {}).read("rotateY")
    // The drag's samples, through the scene's raycast: each turns the turntable by how far the pointer has
    // gone, and the release glides on at the pointer's speed.
    const drag = createDrag(vase)
    let from = 0
    createFrameEffect(drag, (sample) => {
      if (sample === null) return
      if (sample.phase === "start") from = angle()
      const rotateY = from + sample.offset.x * TURN
      if (sample.phase === "end") {
        void stage.animate(turntable, { rotateY }, { type: "inertia", velocity: sample.velocity.x * TURN, timeConstant: 700 })
        return
      }
      void stage.animate(turntable, { rotateY }, { duration: 0 })
    })
    return lifted.held
  }

  return (
    <WardicStage value={stage}>
      <div class="sample-scene" ref={stage} />
      <Vase />
    </WardicStage>
  )
}

export default function TurnIt() {
  const [colour, setColour] = createSignal(COLOURS[0]!)
  return (
    <div class="sample-stack">
      <Scene colour={colour()} />
      <div class="sample-actions" role="group" aria-label="Glaze">
        <For each={COLOURS}>
          {(choice) => <button type="button" class="sample-glaze" style={{ background: choice }} aria-label={choice} aria-pressed={String(colour() === choice) as "true" | "false"} onClick={() => setColour(choice)} />}
        </For>
      </div>
    </div>
  )
}

ward(mesh, config) takes a ward's initial, animate, transition, variants, whileHover, whileTap and custom. A key of the page's alone (whileInView, layout, style) is an error in development that names it.

  • Its keys are the object's:

    • the transforms (x, y, z, rotateX, scale and the rest), in degrees for a turn;
    • its own numbers: a light's intensity, a camera's fov, a number on an object of your own;
    • its material's: roughness, clearcoat, emissive;
    • its vectors' axes: positionX.

    A misspelt one is a type error that names it.

  • A colour blends in linear light, as three.js draws it, so a white glaze turning cobalt doesn't pass through grey. Give it as a string, or animate its channels: colorR, colorG and colorB.

  • read(key) is the object's value as Wardic draws it, at its type: ward(turntable, {}).read("rotateY") is an Accessor<number>. A key the ward hasn't moved reads what the object holds.

  • held renders nothing. Return it from a component that renders nothing else, and a <Loading> above it waits for a ward still loading its object or its config.

  • stage.animate(object, target, options) is Motion's animate, on a scene's object. A ward on that object takes the key back at its next change. The demo's turn is one per drag sample, and the release is an inertia transition at the pointer's speed.

The pointer

createHover(mesh), createPress(mesh) and createDrag(mesh) hear the pointer through the scene's raycast. Each returns an accessor and moves nothing, as the page's sensors do. A ward's whileHover and whileTap lift or press an object under it, and its when("tap") hears each tap.

With stageDrag among the Stage's features, a ward drags its object itself:

const stage = createStage({ renderer, scene, camera, features: [stageDrag] })

ward(crate, {
  drag: true, // on the plane through the point grabbed, facing the camera
  dragConstraints: { x: [-2, 2], z: [-2, 2] },
  dragPlane: new THREE.Plane(new THREE.Vector3(0, 1, 0), 0), // or across the ground
})

drag takes "x", "y" or "z" for one axis of its parent's space. dragElastic, dragMomentum, dragTransition and dragSnapToOrigin are the page's.

Frame effects

Under a Stage, createFrameEffect(compute, apply) runs in its Host loop, after Wardic's writes and before the scene is drawn. What it writes is drawn in the frame that moved it:

import { createFrameEffect, ward } from "@wardic/three/solid"
import type * as THREE from "three"

declare const piece: THREE.Mesh
declare const shadow: THREE.Mesh<THREE.PlaneGeometry, THREE.MeshBasicMaterial>

const vase = ward(piece, { whileHover: { y: 0.12 } })
// Its shadow under it, smaller and fainter the higher it lifts.
createFrameEffect(vase.read("y"), (y) => {
  shadow.scale.setScalar(1 - y * 0.9)
  shadow.material.opacity = 1 - y * 3
})

A label pinned over an object is the same: read its x, y and z in compute, and in apply project its place through the camera onto the page.

Objects that enter and leave

Live demo
scene-objects/solid2.tsx
import { createSceneObject, createStage, WardicStage } from "@wardic/three/solid"
import { createEffect, createSignal, For } from "solid-js"
import * as THREE from "three"

interface Block {
  readonly id: number
  readonly colour: string
}

const PALETTE = ["#e07a5f", "#3d5a80", "#81b29a", "#f2cc8f", "#9a8c98"]
const MOST = 8
const SLAB = new THREE.BoxGeometry(1.5, 0.36, 0.9)

/** A block of the stack: it joins the scene dropping in, and slides off before it leaves. A tap takes it out. */
function Slab(props: { readonly block: Block; readonly level: number; readonly base: THREE.Object3D; readonly onTap: () => void }) {
  const mesh = new THREE.Mesh(SLAB, new THREE.MeshStandardMaterial({ color: props.block.colour, roughness: 0.55 }))
  const slab = createSceneObject(mesh, {
    parent: props.base,
    initial: { y: 4.5, rotateY: -40 },
    // Its place in the stack: the blocks above one taken out drop to close the gap.
    animate: () => ({ y: props.level * 0.38 + 0.2, rotateY: (props.level % 2) * 10 - 5 }),
    exit: { x: 3.5, rotateZ: -60, transition: { type: "tween", duration: 0.45, ease: "easeIn" } },
    whileHover: { x: 0.15 },
    transition: { type: "spring", bounce: 0.3, visualDuration: 0.5 },
  })
  createEffect(slab.when("tap"), () => {
    props.onTap()
  })
  return slab.held
}

/** The stack on its base, a block for each of `blocks`. */
function Scene(props: { readonly blocks: ReadonlyArray<Block>; readonly onTake: (id: number) => void }) {
  const scene = new THREE.Scene()
  scene.add(new THREE.HemisphereLight("#ffffff", "#7a7068", 2.2))
  const key = new THREE.DirectionalLight("#ffffff", 1.6)
  key.position.set(3, 6, 4)
  scene.add(key)
  const camera = new THREE.PerspectiveCamera(34, 4 / 3, 0.1, 50)
  camera.position.set(2.2, 3, 6.8)
  camera.lookAt(0, 1.35, 0)
  const base = new THREE.Mesh(new THREE.CylinderGeometry(1.3, 1.4, 0.12, 48), new THREE.MeshStandardMaterial({ color: "#cfc8bd", roughness: 0.8 }))
  base.position.y = -0.06
  scene.add(base)
  const stage = createStage({ renderer: () => new THREE.WebGLRenderer({ antialias: true, alpha: true }), scene, camera, frameloop: "demand" })
  return (
    <WardicStage value={stage}>
      <div class="sample-scene" ref={stage} />
      <For each={props.blocks}>{(block, i) => <Slab block={block} level={i()} base={base} onTap={() => props.onTake(block.id)} />}</For>
    </WardicStage>
  )
}

export default function EnterAndLeave() {
  let made = 0
  const blockOf = (): Block => ({ id: made, colour: PALETTE[made++ % PALETTE.length]! })
  const [blocks, setBlocks] = createSignal<ReadonlyArray<Block>>([blockOf(), blockOf(), blockOf()])
  const take = (id: number) => setBlocks((now) => now.filter((block) => block.id !== id))
  return (
    <div class="sample-stack">
      <Scene blocks={blocks()} onTake={take} />
      <div class="sample-actions">
        <button type="button" class="sample-button" disabled={blocks().length >= MOST} onClick={() => setBlocks((now) => [...now, blockOf()])}>
          Add a block
        </button>
        <button type="button" class="sample-button" disabled={blocks().length === 0} onClick={() => take(blocks()[blocks().length - 1]!.id)}>
          Take the top one off
        </button>
      </div>
      <p class="sample-note">Tap a block to take it out.</p>
    </div>
  )
}

createSceneObject(object, config) is an object's membership of the scene, with a ward for its motion:

  • It joins once its ward can start, so its first frame is its initial.
  • It leaves when its owner ends, after playing its exit, from where it is and at the speed it has.
  • Its parent is parent, else the one it already has, else the Stage's scene.
  • dispose: true disposes its geometries and materials once it has left.

Given an accessor, it follows each object the accessor gives: the next one enters as the last one exits. Its handle is its ward's, with exitStart and exitComplete among its events.

Many objects at once

Live demo
scene-batch/solid2.tsx
import { stagger } from "@wardic/solid"
import { createBatch, createStage, stageBatches, ward, WardicStage } from "@wardic/three/solid"
import { createSignal, For } from "solid-js"
import * as THREE from "three"

const COUNT = 1000

type Shape = "grid" | "sphere" | "helix"

/** Where cube `i` of the thousand stands in each shape. */
const SHAPES: Readonly<Record<Shape, (i: number) => { readonly x: number; readonly y: number; readonly z: number }>> = {
  // A cube of cubes, ten a side.
  grid: (i) => ({ x: ((i % 10) - 4.5) * 0.24, y: (Math.floor(i / 10) % 10) * 0.24 - 1.08, z: (Math.floor(i / 100) - 4.5) * 0.24 }),
  // Evenly over a sphere, on the golden angle.
  sphere: (i) => {
    const y = 1 - (2 * (i + 0.5)) / COUNT
    const around = i * Math.PI * (3 - Math.sqrt(5))
    const radius = Math.sqrt(1 - y * y) * 1.5
    return { x: Math.cos(around) * radius, y: y * 1.5, z: Math.sin(around) * radius }
  },
  // Two strands, every other cube on the second.
  helix: (i) => {
    const around = (i / COUNT) * Math.PI * 8 + (i % 2) * Math.PI
    return { x: Math.cos(around) * 1, y: (i / COUNT) * 3.2 - 1.6, z: Math.sin(around) * 1 }
  },
}

/** A thousand cubes, one InstancedMesh: one draw call, and one Batch that moves them all. */
function Scene(props: { readonly shape: Shape }) {
  const scene = new THREE.Scene()
  scene.add(new THREE.HemisphereLight("#ffffff", "#606070", 2.4))
  const camera = new THREE.PerspectiveCamera(36, 4 / 3, 0.1, 50)
  camera.position.set(0, 1.2, 6.2)
  camera.lookAt(0, 0, 0)
  const cubes = new THREE.InstancedMesh(new THREE.BoxGeometry(0.13, 0.13, 0.13), new THREE.MeshStandardMaterial({ roughness: 0.5 }), COUNT)
  const colour = new THREE.Color()
  for (let i = 0; i < COUNT; i++) cubes.setColorAt(i, colour.setHSL(0.55 + (i / COUNT) * 0.35, 0.65, 0.55))
  const turning = new THREE.Group()
  turning.add(cubes)
  scene.add(turning)

  // A scene's Batches are a feature of its Stage: `stageBatches` brings them.
  const stage = createStage({ renderer: () => new THREE.WebGLRenderer({ antialias: true, alpha: true }), scene, camera, frameloop: "demand", features: [stageBatches] })

  const Cubes = () => {
    // Each instance a member: a new shape is one change of what `animate` reads, each cube from where it is.
    createBatch({
      instances: cubes,
      count: COUNT,
      animate: (i) => SHAPES[props.shape](i),
      whileHover: { scale: 2.4 },
      transition: { type: "spring", bounce: 0.2, visualDuration: 0.8, delay: stagger(0.0012) },
    })
    // The whole turns slowly: a transform, which reduced motion holds still.
    ward(turning, { animate: { rotateY: 360 }, transition: { duration: 40, ease: "linear", repeat: Infinity } })
    return null
  }

  return (
    <WardicStage value={stage}>
      <div class="sample-scene" ref={stage} />
      <Cubes />
    </WardicStage>
  )
}

export default function AThousandAtOnce() {
  const [shape, setShape] = createSignal<Shape>("grid")
  return (
    <div class="sample-stack">
      <Scene shape={shape()} />
      <div class="sample-actions" role="group" aria-label="Shape">
        <For each={["grid", "sphere", "helix"] as const}>
          {(next) => (
            <button type="button" class="sample-button" aria-pressed={String(shape() === next) as "true" | "false"} onClick={() => setShape(next)}>
              {next}
            </button>
          )}
        </For>
      </div>
    </div>
  )
}

With stageBatches among the Stage's features, createBatch animates a scene's objects as one run, as a Batch does a page's elements:

  • instances: an InstancedMesh's instances, each a member, count of them. That's one draw call. Each frame Wardic writes the matrices of the instances that moved, and uploads only that span.
  • object: a three.js object per member, keyed by each and key. Each joins the scene as it enters and leaves once its exit has landed, as the storefront's shelf filters its pieces.

A new shape is one change of what animate reads, each member from where it is at the speed it has. whileHover and whileTap work per member, through the raycast. when("tap") says which member was tapped: tap.i, or tap.item for a keyed Batch.

What it costs: Wardic's three.js benchmark moved 10,000 instances in 0.64 ms a frame on Bun. That's what three.js takes to update 10,000 meshes' own matrices with nothing animating them. Ten thousand meshes as one Batch were 11.6 times cheaper a frame than a run each.

Variants down the scene

A ward with variants and no animate of its own follows the nearest ward above its object in the scene's graph, as an element follows its parent on the page. Its stagger slot is its place among that ward's object's children:

const CARD = { closed: { transition: { staggerChildren: 0.06 } }, open: { transition: { staggerChildren: 0.08 } } }
const PIP = { closed: { scale: 0.2 }, open: { scale: 1 } }

createSceneObject(card, { variants: CARD, initial: "closed", animate: () => (open() ? "open" : "closed") })
// Each pip is a child of the card in three's graph: it follows the card's variant.
for (const pip of card.children) createSceneObject(pip, { variants: PIP })

A sequence as an action

stage.animate's controls are a promise of its landing, so a Solid 2 action can yield each step. Each step starts as the last one lands:

const fire = action(function* () {
  setStep("closing") // a `createOptimistic` signal: it shows at once, and goes back as the action ends
  yield stage.animate(lid, { rotateX: 0 }, { type: "spring", bounce: 0.2 })
  setStep("heating")
  yield stage.animate(kiln, { heat: 1240 }, { duration: 5 })
  setStep("cooling")
  yield stage.animate(kiln, { heat: 20 }, { duration: 4.5, ease: "easeOut" })
})

The action holds its other writes until its last step has landed (Sequences as actions). The storefront's kiln fires this way. The heat is a number on the kiln's own object, and a Frame effect turns it into the glow and the controller's figures.

Loading

three.js is most of a scene's weight, so a page can show something lighter first. The storefront's scenes do it this way:

  1. The server's page shows the piece's photo.
  2. Once the page has settled, where the browser can draw WebGL, it mounts the scene, with three.js in the route's own chunk.
  3. The canvas fades in over the photo once it has drawn its first frame. three.js tells a mesh each time it draws it, through its onAfterRender.
  4. With no WebGL, the photo stays.
const [drawn, setDrawn] = createSignal(false)
vase.onAfterRender = () => {
  vase.onAfterRender = () => {}
  setDrawn(true)
}
<w.div class="scene" animate={{ opacity: Number(drawn()) }}>…</w.div>

Reduced motion

Under reduced motion, a scene's transforms snap, and so do a camera's fov and zoom: an infinite turn holds still. A colour, an opacity and a material's numbers still animate, since they don't move anything.

Testing

TestStage runs a Stage in Node, with no DOM and no WebGL. You step its frames, and its pointer goes through the same raycast a canvas's would:

import { createHover, TestStage, WardicStage } from "@wardic/three/solid"
import { flush } from "solid-js"

const stage = TestStage.make({ scene, camera, size: { width: 800, height: 600 } })
let hovered!: () => boolean
const Probe = () => {
  hovered = createHover(mesh)
  return null
}
// Mounted as an app mounts it: <WardicStage value={stage}><Probe /></WardicStage>
stage.pointer.over(mesh)
stage.frame()
flush() // the sensor's signal, written in the frame, read now
expect(hovered()).toBe(true)

stage.pointer also has at(x, y), down() and up(), and stage.frame() steps the scene by one frame, its wards' and Batches' motion with it.

What a scene ships

Gzipped, for an app built for production:

AppKB
three.js alone, a mesh drawn134.8
a createStage scene with one ward(mesh, …)243.2
the same, with stageDrag, stageBatches and a Batch250.9

Import the hooks from @wardic/three/solid. @wardic/solid's ward is the page's Complete ward, which brings every one of the page's Features, 57.6 KB more.

In the storefront

The storefront's examples that show it, live and with their code:

  • Turn the vase in 3D: The Moon Vase as a three.js scene: drag it round and it spins on with your hand's momentum, and each glaze you pick flows over it.
  • Kintsugi: 3,000 shards, one Batch: Tap the crackled celadon bowl and it bursts into shards from where you touched it; mend it and they fly home in a wave, its cracks turned gold.
  • The studio's pieces on a round shelf: All twelve pieces turned in 3D on a round display: pick a category and the rest sink away while the others slide round; tap one and the display turns it to you.
  • Fire the kiln: a sequence as an action: Three pieces in raw glaze on a kiln's shelf: fire it and the lid shuts, everything glows from dull red to white-hot, then cools to show each glaze.