# Things in space: `canvas scene=`

A `canvas` with `scene=` draws things in three dimensions with WebGL 2, in the
words three.js uses: a scene of meshes and groups, materials, lights, a
camera. It draws them plainly at once, and with `render=` works out a lit
picture (sun, sky, shadows, light bouncing, glass, metal, things that glow)
with a path tracer written in Mote's runtime. `canvas boxes=` (in the card) is
the same engine with a plainer way of saying boxes; both stay.

**z is up** (x across, y back), unlike three.js, where y is up. Lengths are the
page's own units. A position is a geometry's middle (for an outline pushed
up, `three.extrude`, it is the outline's own origin: [below](#outlines-pushed-up-threeextrude)).
Rotations are degrees about x, then y, then z.

```mote
derive oak = three.material({color: "#c8a878", roughness: 0.6})
derive steel = three.material({color: "#c9ccd1", roughness: 0.2, metalness: 1})

// A table: a top on four legs, as one group that turns and moves together.
derive table = three.group([
  three.mesh(three.box(120, 70, 4), oak, {position: [0, 0, 72], id: "top", name: "Top"}),
  three.mesh(three.cylinder(3, 70), steel, {position: [-52, -28, 35]}),
  three.mesh(three.cylinder(3, 70), steel, {position: [52, -28, 35]}),
  three.mesh(three.cylinder(3, 70), steel, {position: [-52, 28, 35]}),
  three.mesh(three.cylinder(3, 70), steel, {position: [52, 28, 35]})
], {rotation: [0, 0, 25]})

derive world = three.scene([table], {lights: [three.sun(300, 50, 1), three.sky(1)]})
derive eye = three.perspective({position: [220, -300, 200], target: [0, 0, 40], fov: 40})

row width=640 height=420
  canvas scene=world camera=eye render="real" samples=64 change=picked flex=1 min-width=0
```

Everything `three.*` makes is a plain record, so a page may write the records
itself, build them in a `fn`, or keep them in state:

| | the record |
|---|---|
| `three.box(width, depth, height)` | `{type: "box", size: [width, depth, height]}` (sizes along x, y, z) |
| `three.sphere(radius)` | `{type: "sphere", radius}` |
| `three.cylinder(radius, height)` | `{type: "cylinder", radius, height}` (upright along z until turned) |
| `three.plane(width, depth)` | `{type: "plane", width, depth}` (flat on x and y) |
| `three.extrude(points, height, {holes})` | `{type: "extrude", points: [[x, y], …], height, holes}` (an outline on x and y, pushed up along z) |
| `three.material({…})` | `{color, roughness, metalness, transmission, emissive, edges}`, and for a picture `{map, mapSize, mapOffset, mapTurn, tint}` |
| `three.mesh(geometry, material, {…})` | `{geometry, material, position, rotation, scale, id, name}`, and for a picture `{grain, sides, faces}` |
| `three.group(children, {…})` | `{children, position, rotation, scale}` |
| `three.scene(objects, {…})` | `{objects, lights, ground}` |
| `three.sun(turn, height, intensity)` | `{type: "sun", turn, height, intensity}` |
| `three.sky(intensity)` | `{type: "sky", intensity}` |
| `three.perspective({…})` | `{type: "perspective", position, target, fov}` |
| `three.orthographic({…})` | `{type: "orthographic", position, target, size}` |

**Materials.** `color` is `"#rrggbb"`. `roughness` runs from 0 (a mirror) to 1
(matte; 0.7 if not said). `metalness` is 0 or 1. `transmission` (0 to 1) is how
much light passes: glass. `emissive` is light given off, in the sun's units: a
lamp. `edges: false` leaves the outline of a box or an extrusion off the plain
drawing (`edges: "#333333"` colours it). The plain drawing uses the colour and edges; the lit
picture uses all of it. `map` puts a picture on it: [below](#pictures-on-materials-map).

**Meshes and groups.** `position: [x, y, z]`, `rotation: [x, y, z]` in degrees,
`scale` (a number, or `[x, y, z]` on a mesh). A group places everything in it
together, groups inside groups too; a group's scale is one number. `id` is what
a press reports; `name` shows on hover with the thing's size.

**Lights.** `three.sun(turn, height, intensity)`: where the sun stands, in
degrees round (0 is along x, 90 along y) and up from the horizon. With no sun
in the scene (and no `sun=` on the canvas) it stands over the left shoulder of
whoever is looking. `lights: [three.sky(1)]` alone is an overcast day: no sun.
`ground: false` takes the floor away; `ground: {color: "#b9b2a6", height: 0}`
says what it is. Anything `emissive` lights what is near it.

**The camera.** `camera=` takes `{position, target, fov}` (fov in degrees, up
and down: 40 if not said) or `{type: "orthographic", size}` (how much of the
scene's own units it sees up and down). What is not said is the scene's own:
it looks at the scene's middle from far enough to see all of it. `view=`
("iso", "front", "back", "left", "right", "plan", or `"cam:yaw,pitch,zoom,ortho"`)
still works without `camera=`. A drag orbits about what the camera looks at;
the wheel zooms.

**What the canvas tells the page**, exactly as `canvas boxes=` does: a press on
a thing sends `change` with its id (`change=picked` with `action picked(id:
string)`); `tool=`, `render=` ("still" or "real"), `samples=`, `exposure=`,
`sun=` and the `input` events ({phase: "cam" | "gpu" | "render" | "done" |
"saved", …}) are as the card says for boxes. A scene with pictures says two
more, `"materials"` and `"limit"`: [below](#loading-and-what-input-hears).

## Outlines pushed up: three.extrude

`three.extrude(points, height)` is a flat outline on x and y, pushed up along
z: a top shaped like an L, a cabinet whose front is cut across a corner, a
panel with a notch, a wedge. The outline is a list of `[x, y]` corners going
round either way, and may bend inward as well as outward (it need not be
convex); the last corner joins the first. `{holes: [[[x, y], …], …]}` cuts
outlines out of it: a sink out of a worktop.

```mote
// docs: whole
state picked = ""

derive oak = three.material({color: "#c8a878", roughness: 0.6})
derive stone = three.material({color: "#d8d6d0", roughness: 0.3})

// A cabinet in the corner of two walls, from above. The corner of the walls is 0, 0;
// the front is cut across from one arm to the other.
derive plan = [[0, 0], [90, 0], [90, 58], [58, 90], [0, 90]]
// The worktop over it and its neighbours: an L, with a sink cut out of one arm.
derive top = [[0, 0], [170, 0], [170, 62], [62, 62], [62, 170], [0, 170]]
derive sink = [[92, 12], [150, 12], [150, 50], [92, 50]]

derive corner = three.group([
  three.mesh(three.extrude(plan, 2), oak, {position: [0, 0, 11], id: "bottom", name: "Bottom"}),
  three.mesh(three.extrude(plan, 2), oak, {position: [0, 0, 46], id: "shelf", name: "Shelf"}),
  three.mesh(three.box(90, 2, 74), oak, {position: [45, 1, 47], id: "back", name: "Back"}),
  three.mesh(three.box(2, 90, 74), oak, {position: [1, 45, 47], id: "side", name: "Side"}),
  three.mesh(three.box(80, 58, 74), oak, {position: [130, 29, 47], id: "right", name: "Drawers"}),
  three.mesh(three.box(58, 80, 74), oak, {position: [29, 130, 47], id: "left", name: "Doors"}),
  three.mesh(three.extrude(top, 4, {holes: [sink]}), stone, {position: [0, 0, 86], id: "top", name: "Worktop"})
])

derive world = three.scene([corner], {lights: [three.sun(20, 50, 1), three.sky(1)]})
derive eye = three.perspective({position: [400, 360, 320], target: [70, 70, 40], fov: 40})

action pick(id: string)
  picked = id

column gap=8 padding=16 height=480
  canvas scene=world camera=eye render="real" samples=64 change=pick flex=1
  text (picked == "" ? "Press a piece" : `Picked ${picked}`)
```

**Where it sits.** A mesh's `position` is where the outline's own origin (its
0, 0) goes, half way up the height. The outline is *not* moved to its middle
as a box is, because an outline is drawn from somewhere that matters: the
corner of the walls, the hinge side, the corner a plan is measured from. So
every piece of a cabinet drawn in the cabinet's own plan takes the same x and
y (above, every outline sits at 0, 0), changing one corner of an outline moves
nothing else, and a `rotation` turns the piece about that origin. Along z it
is the middle, as for a box and a cylinder: a piece `h` tall standing on the
floor is at z `h / 2`. `scale` stretches the outline about its origin too.

An outline lies flat. A piece that stands (a side panel with a notch for the
plinth) is drawn flat and turned up: with `rotation: [90, 0, 0]` the outline's
y is the height and the piece is as thick along y as its `height` says, half
to either side of `position`.

**What is drawn.** In the plain drawing an extrusion has its top, bottom and
sides shaded as a box's are, and lines on its true edges only: round the top,
round the bottom, and up each corner. Hover gives its name and the size of its
bounds; a press reports its `id`, and only where the shape is: not in the
notch of an L, not through a hole. In the lit picture it is one solid traced
exactly, whatever its outline: shadows have its shape, and glass
(`transmission`) has no joins inside it.

**An outline that is no shape draws nothing**, and nothing else is disturbed:
fewer than three corners, no area, no height, sides that cross or touch each
other (a corner said twice among them), a hole that is not wholly inside the
outline or lies inside another hole, or more than 512 corners in all. A corner
that only repeats the one before it (or the first, said again at the end) and
a corner on a straight run are dropped, and the rest is drawn. Where the
program itself says such an outline (`three.extrude([[0, 0], [90, 0]], 4)`,
a height of `0`), the compiler says so.

## Pictures on materials: map

A material's `map` is a picture: wood grain, a laminate, stone. `mapSize`
says how much of the scene one copy of it covers, so the grain is the same
size on a panel 300 wide and on one 2400 wide; the picture repeats.

```mote
// docs: whole
// A picture 64 by 64: red and blue squares. A shop's own is a photograph of the board.
derive veneer = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAIAAAAlC+aJAAAAW0lEQVR42u3QMQ0AQAwDsUIplIdQ/lOhPIYO2SzdHjm1r6P1bLQCAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgD0gPpgwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAzn0sY4EtWbO6uAAAAABJRU5ErkJggg=="

// One copy covers 600 by 600 of the scene, whatever the panel's size.
derive oak = three.material({color: "#c8a878", map: veneer, mapSize: [600, 600], roughness: 0.6})
derive band = three.material({color: "#f2efe8"})

derive cabinet = three.group([
  // A door: the grain runs up it (z, as it is unsaid); its four thin sides are a plain band.
  three.mesh(three.box(450, 18, 720), oak, {position: [225, 9, 360], sides: band, id: "door", name: "Door"}),
  // A rail: the same material, the grain along its length.
  three.mesh(three.box(900, 18, 90), oak, {position: [450, 9, 780], grain: "x", sides: band, id: "rail", name: "Rail"}),
  // A top shaped like an L: the picture on its two caps, the band round its sides.
  three.mesh(three.extrude([[0, 0], [900, 0], [900, 300], [300, 300], [300, 600], [0, 600]], 30), oak, {position: [0, 0, 850], sides: band, id: "top", name: "Top"})
])

derive world = three.scene([cabinet], {lights: [three.sun(300, 50, 1), three.sky(1)]})
derive eye = three.perspective({position: [-700, -1500, 1300], target: [450, 150, 420], fov: 40})

column gap=8 padding=16 height=480
  canvas scene=world camera=eye render="real" samples=64 flex=1
```

**What a material says.**

| | |
|---|---|
| `map` | The picture: its address (a `data:` address, `asset("oak.jpg")`, a stored file's address, any address the page may fetch), a file's `bytes`, or a picture decoded already (`img.decode`: `{width, height, data}`, 8 bits a sample). JPEG, PNG, WebP: whatever the browser reads. |
| `color` | Still said: it is what is drawn until the picture has arrived, and if it cannot be had. |
| `tint: true` | The picture's colours are multiplied by `color`. Unsaid, the picture is drawn as it is and `color` does not touch it. |
| `mapSize: [w, h]` | How much of the scene, in its own units, one copy covers; the picture repeats. Unsaid: one copy over each face, stretched to it. |
| `mapOffset: [u, v]` | The picture moved that far right and up, in the scene's units (in parts of a face when no `mapSize` is said). |
| `mapTurn: 90` | The picture turned, in degrees, anticlockwise as seen from outside, about the face's lower left corner. Any angle. |

**What a mesh says** (after its material, with `position` and the rest):

| | |
|---|---|
| `grain: "x"`, `"y"` or `"z"` | The axis of the mesh, before its own `rotation`, that the picture's up runs along. `"z"` if not said. A door says nothing; a rail says `"x"`. The same material serves both. |
| `sides: material` | A second material for the mesh's sides: a plain band, or another picture. For a box the sides are the four faces round its thinnest way through (a panel's four edges; of two ways as thin, z before y before x); for an extrusion, its sides against its two caps. It is still one mesh. |
| `faces: "x"`, `"y"` or `"z"` | For a box: the axis its two faces look along, where it should not be the thinnest. The other four faces are its sides. |

Roughness, metalness and the colour of a mesh's sides are its `sides`
material's; what passes through it (`transmission`), what it gives off
(`emissive`) and its outline (`edges`) are its first material's.

**Where the picture falls.** Every flat face has an up. Look at the face
from outside with its up upward: the picture starts at the face's lower left
corner, its own up along the face's, and runs right and up from there. It is
never mirrored. In the mesh's own axes, before its `rotation`:

| | its up is |
|---|---|
| A box's four faces the grain does not point through | the grain's axis (z if not said) |
| A box's two faces the grain points through (its top and bottom, when the grain is z) | z; or y, where the grain is z |
| An extrusion's two caps | y; or x, where the grain is x. The face is the outline's bounds: seen from above with the grain not x, the picture starts at the bounds' least x and y |
| An extrusion's sides, the grain z | z. Each side is a face of its own, from its own corner: a side is seen from outside running left to right the way the outline goes round anticlockwise from above |
| An extrusion's sides, the grain x or y | along the side, toward that axis's positive end; or z, where the side is square to the grain |

So a box 300 wide and 720 tall with the grain z has, on its front (the face
looking along -y), the picture's lower left corner at the box's lowest x and
z, x going right and z going up; a box and an extrusion of the same
rectangle are mapped alike. A group's turn and a mesh's `rotation` carry the
picture with the thing. A mesh's `scale` and a group's stretch the thing,
not the picture: `mapSize` is in the scene's units as the thing ends up.

A ball and a drum wear their `color` only: see "Not there yet".

**Both drawings.** The plain drawing shows the picture lit as it lights a
colour, with the outline over it. The lit picture (`render=`) takes the
surface's colour from the picture; roughness, metalness and transmission
are as said. The two put the picture on the same pixels, and a picture of
one colour is drawn exactly as that `color` would be, in both. Picking,
hover, `change`, `tool=` and how the camera fits the scene do not change.
What is saved (`tool="png"`, `"png4k"`, `"pngplain"`) has the pictures in
it.

**Many meshes, few pictures.** A canvas keeps one copy of each distinct
picture, however many materials and meshes name it: an address is known by
its text, bytes and decoded pictures by their contents. The pictures are the
layers of one array texture, with mipmaps, trilinear filtering, eightfold
anisotropic filtering where the browser has it, sRGB decoding and repeat
wrapping; a dressed mesh costs the same two draws a coloured one does. The
limits, and what happens past them:

| | |
|---|---|
| Distinct pictures in one scene | 128. Past it a picture is its material's `color`, and `input` hears `{phase: "limit", limit: 128, over}` once, `over` being how many got no place. |
| A picture's larger side | 1024 pixels (512 in a scene of more than 32 pictures). A larger picture is scaled down; nothing fails. |
| Memory | Every layer is one size: the power of two that holds the scene's largest picture, 64 at least. A layer 256 a side is 0.35 MB of graphics memory, 512 is 1.4 MB, 1024 is 5.6 MB; with `render=` there is a second copy for the lit picture. A hundred pictures 256 a side are 35 MB (70 MB lit); the most a scene can take is 180 MB (360 MB lit). The decoded pictures are kept besides, once for the whole page, while a canvas shows them. |

A picture's alpha is not used: a picture is opaque.

### Loading, and what input hears

Pictures are decoded by the browser's own decoder, off the page's thread,
when a scene first names them. The scene is drawn at once in each
material's `color`, and again as pictures arrive. `input` hears

```json
{"phase": "materials", "loaded": 12, "of": 20, "failed": 0, "ready": false}
```

when a scene with pictures is set and whenever the numbers change; `ready`
is true once every picture has arrived or failed, so a page can show
"loading materials" until then. A picture that cannot be had (the address
does not answer, the bytes are no picture, 30 seconds have gone) is its
`color`; it is counted in `failed`, and `error` says which and why. Nothing
is thrown.

The lit picture **waits**: with `render="real"` it begins when the scene's
pictures are all there (or have failed), so it never starts over because one
arrived, and its `{phase: "done"}` always means the whole picture. A lit
picture being saved waits the same way.

The code for pictures is in a page only if its program says `map` or `sides`
somewhere as a field of a record (`{map: …}`, `{sides: …}`); a material
handed over whole from elsewhere (a row with a `map` column passed as the
material itself) needs one such record written out.

**Not there yet:** meshes of triangles (your own geometry, and so your own
UVs), an extrusion with slanted or rounded sides or along a path, curves in
an outline (say a curve as many corners), normal, roughness and metalness
maps, pictures on balls and drums (they wear their `color`), a video or a
canvas as a picture, a picture for each face beyond faces and sides, point
and spot lights as objects (use something small and `emissive`), a group
scaled differently along its axes, several cameras on one scene. Four shapes
are traced exactly (box, ball, drum, extrusion); a plane is a very thin box.

**Moving from `canvas boxes=`.** A box `{x, y, z, w, d, h, turn, color, rough,
metal, clear, glow, id, name}` is the mesh

```mote
three.mesh(three.box(b.w, b.d, b.h), {color: b.color, roughness: b.rough, metalness: b.metal, transmission: b.clear, emissive: b.glow},
  {position: [b.x + b.w / 2, b.y + b.d / 2, b.z + b.h / 2], rotation: [0, 0, b.turn], id: b.id, name: b.name})
```

when it turns about its own middle. A box takes a picture in the same words,
and `canvas boxes=` draws it too: a box that says `{…, map, mapSize, grain,
sides: {color: "#f2efe8"}}` (and `mapOffset`, `mapTurn`, `tint`, `faces`) is

```mote
three.mesh(three.box(b.w, b.d, b.h), {color: b.color, map: b.map, mapSize: b.mapSize, roughness: b.rough},
  {position: [b.x + b.w / 2, b.y + b.d / 2, b.z + b.h / 2], rotation: [0, 0, b.turn], grain: b.grain, sides: b.sides, id: b.id, name: b.name})
```

A box that turns about another point (`px`,
`py`: a door on its hinge) is a group at the hinge, turned, holding the mesh
at its place from the hinge. A cabinet is then a group of its panels, and a
room a group of cabinets: move or turn the group and all of it follows.

An angled piece that was several boxes standing in for it (a top shaped like
an L, a corner cabinet's cut-off front, a filler cut on a slope) is one
`three.extrude`. Its outline is said from the same corner a box's `x` and `y`
are measured from, so its position is the box's `x` and `y` as they are, with
no half sizes added; only z goes to the middle:

```mote
three.mesh(three.extrude([[0, 0], [b.w, 0], [b.w, b.d - 20], [b.w - 20, b.d], [0, b.d]], b.h), {color: b.color},
  {position: [b.x, b.y, b.z + b.h / 2], rotation: [0, 0, b.turn], id: b.id, name: b.name})
```

is box `b` with 20 cut off one corner, turned about its lowest corner as
`turn` turns a box that says no `px`, `py`.
