# Drawing

A canvas your own code draws on: `surface` (2D), `surface gl` (WebGL 2), and
the 3D canvas (`canvas boxes=`, `canvas scene=`). Also a drawing read back as
a picture, typing on a surface, and a picture through a shader. Pictures and painting are in [media.md](media.md).
Back to the [map](README.md).

```mote
// docs: whole
state values = [4, 8, 15, 16, 23, 42]
state hot = -1

fn chart(g: pen, size: {width: number, height: number, time: number})
  draw.clear(g, "card")
  let w = size.width / values.length
  let top = Math.max(...values)
  let i = 0
  for v in values
    let h = v / top * (size.height - 24)
    draw.rect(g, i * w + 4, size.height - h, w - 8, h, {fill: i == hot ? "accent" : "dim", radius: 4})
    draw.text(g, `${v}`, i * w + w / 2, size.height - h - 16, {color: "fg", size: 12, align: "center"})
    i += 1

action over(p: {x: number, width: number})
  hot = Math.floor(p.x / (p.width / values.length))

surface draw=chart pointermove=over pointerleave={hot = -1} width=100% height=240
```

## Mental model

`surface draw=chart` is a `<canvas>` and a fn of yours that draws it. The fn
is an effect ([reactivity.md](reactivity.md)): it is called

- when the surface is made,
- **whenever state it read changes** (`values` and `hot` above),
- when the element's size changes,
- and every frame while `animate=running` is true.

So a drawing is a pure picture of state: change the state and it is drawn
again. Nothing of the drawing is kept between calls: a 2D surface is
cleared before each call; a GL surface is not, so start with `gl.clear`.

The fn is handed a **pen** and a **size**:

```mote
fn chart(g: pen, size: {width: number, height: number, time: number})
```

`size.width` and `size.height` are the element's size in CSS pixels;
`size.time` is seconds since the surface was made. Lengths are CSS pixels on
any screen: the canvas holds as many device pixels as its box shows, and the
pen is scaled to match.

A drawing fn reads state, so it stays on the main thread. Keep heavy work
out of it: work things out in a derive or an action and draw the result.

Size a surface with styles (`width=100% height=240`, or flex). It is
`display: block` unless you say otherwise.

## surface (2D)

Every call takes the pen first.

| Call | Draws |
|---|---|
| `draw.clear(g, colour?)` | Clears; fills with a colour if one is given. |
| `draw.rect(g, x, y, w, h, {fill, stroke, width, radius, dash})` | A rectangle; `radius` rounds its corners. |
| `draw.circle(g, x, y, r, {…})` | A circle, the same options. |
| `draw.line(g, x0, y0, x1, y1, {color, width, dash, cap})` | A line. |
| `draw.path(g, points, {fill, stroke, width, closed, rule, join, miter})` | A path. A point is `[x, y]`, or `[c1x, c1y, c2x, c2y, x, y]` for a curve to x, y. `points` may be a list of such contours (a ring, a letter and its counter). |
| `draw.text(g, "words", x, y, {color, size, weight, font, italic, align, baseline, spacing, stroke, width})` | Words. `align`: left (default), center, right. `baseline`: top (default), middle, alphabetic, bottom. `spacing`: room between letters. |
| `draw.measure(g, "words", {size, weight, font, italic, spacing})` | Their `{width, height, ascent, descent}`. With no pen, `draw.measure("words", {…})`, it works anywhere: a fn, an action, a derive. |
| `draw.image(g, picture or sheet, x, y, w?, h?, {smooth}?)` | An `image` or a `paint` sheet; its own size if none is given. `smooth: false` keeps hard pixels. |
| `draw.push(g)` … `draw.pop(g)` | Keep and restore the pen's state around: |
| `draw.move(g, x, y)` · `draw.scale(g, x, y?)` · `draw.turn(g, degrees)` · `draw.transform(g, a, b, c, d, e, f)` | Move, scale, turn what follows, or apply a matrix (the canvas's six numbers). |
| `draw.clip(g, x, y, w, h)` · `draw.clip(g, points, {rule}?)` | Keep what follows inside a rectangle, or inside a path (points as `draw.path` takes them). |
| `draw.layer(g, {opacity, blend, shadow})` … `draw.pop(g)` | What is drawn between them is put down as one thing ([below](#layers)). |
| `draw.read(g)` · `draw.read(g, x, y, w, h)` · `draw.read(box)` | What is drawn, as an `image` ([below](#a-drawing-as-a-picture)). |
| `draw.picture(width, height, chart, pixels?)` | An `image` a draw fn draws where no one sees it ([below](#a-drawing-as-a-picture)). |

**Every drawing's options** (rect, circle, line, path, text, image) also
take:

| Option | Means |
|---|---|
| `opacity` | 0 to 1. |
| `blend` | How it meets what is there: `"multiply"`, `"screen"`, `"overlay"`, `"lighter"` … (the canvas's own names). |
| `shadow: {x, y, blur, color}` | A shadow under it, in the pen's own lengths. |

None of the three stays on the pen: the next drawing starts plain.

- **A colour** is any CSS colour (`"#0a84ff"`, `"rgb(0 0 0 / 0.5)"`), or one
  of the page's roles as a string (`"fg"`, `"accent"`, `"dim"`, `"card"`,
  `"line"`, …), which follows light and dark.
- A rect or circle with neither `fill` nor `stroke` is filled black. A path
  with neither draws nothing: give it a `stroke` or a `fill`.
- **Several contours.** A path of several contours is one shape. With
  `rule: "evenodd"` a contour inside another is a hole; without it
  (non-zero), it is a hole only if it turns the other way. `closed: true`
  closes each contour before it is stroked.
- `dash` is a list of lengths (`[4, 4]`); `cap` is `"butt"`, `"round"` or
  `"square"`; `join` is `"miter"` (a path's default), `"round"` or
  `"bevel"`, and `miter` its limit; text is 14 px system-ui, weight 400,
  unless said.
- **Text with a line.** `stroke` (and `width`) lines the letters as well as
  filling them; with `stroke` and no `color`, they are only lined.
- **`draw.measure`** gives `ascent` and `descent`: how far a line reaches
  above and below its alphabetic baseline; `height` is the two together.
- It takes `pointerdown`, `pointermove`, `wheel` and the rest like any
  element ([events.md](events.md)): `{x, y}` are in the same pixels the pen
  draws in.

```mote
// docs: whole
state running = true
state at = {x: 120, y: 80}

fn scene(g: pen, size: {width: number, height: number, time: number})
  draw.clear(g, "bg")
  draw.line(g, 0, size.height - 0.5, size.width, size.height - 0.5, {color: "line", dash: [4, 4]})
  draw.path(g, [[10, 60], [60, 20], [80, 20, 100, 100, 140, 60]], {stroke: "ok", width: 2})
  draw.push(g)
  draw.move(g, at.x, at.y)
  draw.turn(g, size.time * 90)
  draw.rect(g, -20, -20, 40, 40, {fill: "accent", radius: 6})
  draw.pop(g)
  let label = `${Math.round(at.x)}, ${Math.round(at.y)}`
  let m = draw.measure(g, label, {size: 12})
  draw.text(g, label, size.width - m.width - 8, 8, {color: "dim", size: 12})

action moved(p: {x: number, y: number})
  at = {x: p.x, y: p.y}

column gap=8 padding=16
  surface draw=scene animate=running pointerdown=moved pointermove=moved height=200
  button (running ? "Stop" : "Spin") press={running = !running}
```

### Gradients and patterns

A `fill` or a `stroke` (and a text's `color`) is a colour, or one of:

| Fill | Is |
|---|---|
| `{linear: [x0, y0, x1, y1], stops}` | A gradient along that line. |
| `{radial: [cx, cy, r], stops}` | One from a centre out to a radius (`[cx, cy, r, fx, fy]` starts it from another point). |
| `{conic: [cx, cy, degrees?], stops}` | One round a centre, from that angle. |
| `{pattern: picture, x?, y?, scale?}` | A picture or a sheet laid side by side, from (x, y), each pixel `scale` units. |

`stops` are colours spread evenly (`["#fff", "#000"]`), or `[at, colour]`
pairs with `at` from 0 to 1 (two pairs at one place make a hard edge). A
stop may be a role (`"accent"`). The places are in the lengths the shape
itself is drawn in, so a gradient moves and turns with `draw.move` and
`draw.turn`.

### Layers

```mote
draw.layer(g, {opacity: 0.5})
draw.rect(g, 80, 60, 40, 40, {fill: "#ff0000"})
draw.rect(g, 100, 60, 40, 40, {fill: "#0000ff"})
draw.pop(g)
```

What is drawn between `draw.layer` and its `draw.pop` is drawn to one side
and put down as one thing, with the layer's `opacity`, `blend` and
`shadow`. Two shapes at half opacity each show through each other; the same
two in a layer at half opacity do not. A layer blended, or shadowed, is so
as a whole. Layers nest, and `draw.push` / `draw.pop` pair inside one as
outside. A layer left open when the fn ends is put down all the same.

### A drawing as a picture

```mote
// docs: whole
state shot: bytes? = none

fn ring(x: number, y: number, r: number) = [[[x - r, y - r], [x + r, y - r], [x + r, y + r], [x - r, y + r]], [[x - r / 2, y - r / 2], [x + r / 2, y - r / 2], [x + r / 2, y + r / 2], [x - r / 2, y + r / 2]]]

fn card(g: pen, size: {width: number, height: number, time: number})
  draw.rect(g, 0, 0, size.width, size.height, {fill: {linear: [0, 0, size.width, size.height], stops: ["#0a84ff", "#5e5ce6"]}})
  draw.circle(g, 70, 70, 50, {fill: {radial: [70, 70, 50], stops: [[0, "#ffffff"], [1, "#ffffff00"]]}})
  draw.path(g, ring(200, 70, 40), {fill: "#ffffff", rule: "evenodd", shadow: {y: 4, blur: 12, color: "#0006"}})
  draw.layer(g, {opacity: 0.5})
  draw.rect(g, 270, 30, 60, 60, {fill: "#ff3b30"})
  draw.rect(g, 300, 50, 60, 60, {fill: "#ffcc00"})
  draw.pop(g)
  draw.push(g)
  draw.clip(g, ring(430, 70, 40), {rule: "evenodd"})
  draw.rect(g, 390, 30, 80, 80, {fill: "#34c759", blend: "screen"})
  draw.pop(g)
  let label = "Mote"
  let m = draw.measure(label, {size: 32, weight: 700, spacing: 2})
  draw.text(g, label, size.width - m.width - 16, size.height - 16 - m.descent, {size: 32, weight: 700, spacing: 2, baseline: "alphabetic", color: "#ffffff", stroke: "#0008", width: 1})

action save
  shot = img.png(draw.picture(500, 140, card, 2))?
  fs.save(shot, "card.png")?

column gap=8 padding=16
  surface draw=card width=500 height=140 max-width=100%
  button "Save as a PNG" press=save disabled=pending(save)
```

- `draw.read(g)` in a draw fn is what has been drawn so far, as an `image`
  in the screen's own pixels (a surface 300 wide on a screen of density 2
  gives 600). `draw.read(g, x, y, w, h)` is a part, given in the surface's
  lengths.
- `draw.read(box)` is the same of a surface on the page, held with
  `ref=box`, from an action. Before the surface has drawn, or of a
  `surface gl`, it is an empty picture (width 0): read a GL surface with
  `gl.image`.
- `draw.picture(width, height, chart, pixels?)` calls a draw fn on a
  surface no one sees, `width` by `height` units, each `pixels` pixels (1 if
  not said), and gives the `image`. The fn's `size.time` is 0.
- Neither waits. The picture is pixels: encode it in a worker
  (`img.png(…)?`) to save or show it ([media.md](media.md#img)).

### Typing on a surface

A surface can take the keyboard, so a page can draw its own text and caret
and still get typing, input methods and paste as the platform gives them.

```mote
// docs: whole
state words = ""
state draft = ""
state inside = false
derive spot = {x: 8 + draw.measure(words + draft, {size: 18}).width, y: 12, height: 22}

fn paper(g: pen, size: {width: number, height: number, time: number})
  draw.clear(g, "card")
  draw.text(g, words + draft, 8, 12, {size: 18, color: "fg"})
  if inside draw.rect(g, spot.x, spot.y, 1, spot.height, {fill: "accent"})

action wrote(said: string)
  words += said

action keyed(k: string)
  if k == "Backspace" words = words.slice(0, -1)
  if k == "Enter" words = ""

surface draw=paper typed=wrote composing={draft = it} caret=spot key=keyed focus={inside = true} blur={inside = false} width=100% height=48
```

| Attribute | Is |
|---|---|
| `typed=wrote` | The surface takes the keyboard (by a press on it, `el.focus`, or `focus("id")`). The handler is handed what is typed, composed with an input method, or pasted, as a string; a line end is `"\n"`. |
| `composing=drafting` | Handed what is being composed as it changes, and `""` when it ends. |
| `caret=spot` | `{x, y, height}` from the surface's corner: where the page draws its caret. The input method's window sits there. |

- `key=` on the surface, or on an element above it, hears every key as
  before (letters too): take words from `typed`, and the rest (arrows,
  Backspace, Enter, shortcuts) from `key`. Enter is a key, not a typed line
  end. Keys an input method takes for a composition are not heard.
- `focus=` and `blur=` on the surface say when it has the keyboard.
- `composing` and `caret` are optional; `typed` is what makes the surface
  take the keyboard. Either without `typed=` is refused (`H098`).

Source: `runtime/page/surface.mote`, part `SF` (`DW` is `draw.…`), `SFL`
(layers, `read`, `picture`), `SFT` (typing).

## surface gl

`surface gl draw=frame` is the same with WebGL 2. The pen is its context,
and one call is a whole drawing:

```text
gl.draw(g, {vs: "…", fs: "…",
  attributes: {p: {data: numbers, size: 2, instanced?}},
  uniforms: {tint: [1, 0, 0], scale: 2, map: {texture: picture}},
  count: 3, instances?,
  mode: "triangles" | "strip" | "lines" | "points",
  depth?, blend?, target?: "name"})
```

```mote
// docs: whole
state quad = [-1, -1, 1, -1, -1, 1, 1, 1]
state tint = [1, 0.4, 0.1]

fn frame(g: pen, size: {width: number, height: number, time: number, pixels: number})
  gl.clear(g, "#000000ff")
  gl.draw(g, {vs: "in vec2 p; out vec2 uv; void main(){ uv = p * 0.5 + 0.5; gl_Position = vec4(p, 0.0, 1.0); }", fs: "in vec2 uv; uniform vec3 tint; uniform float time; out vec4 o; void main(){ o = vec4(tint * (0.5 + 0.5 * sin(time + uv.x * 6.0)), 1.0); }", attributes: {p: {data: quad, size: 2}}, uniforms: {tint, time: size.time}, count: 4, mode: "strip"})

surface gl draw=frame animate=true width=100% height=300
```

- **Shaders** are GLSL ES 3. The `#version` line and the precision are added
  for you.
- **Nothing is made by hand.** A program is kept by its two sources. A
  buffer is kept by the list it came from: the same list is the same buffer,
  so to change the data, make a new list (assign state a new list; do not
  `push` to the old one). A texture is kept by its picture.
- **Attributes**: `{data: numbers, size, instanced?}`; `size` is how many
  numbers a vertex takes (2 if not said).
- **Uniforms**: a number, a bool, a list (2, 3 or 4 numbers: a vector; 9 or
  16: a matrix; any other length: floats), `{int: n}`, or a texture.
- **A texture** is a picture (`image`), a sheet, `{width, height, data:
  numbers, float?, smooth?}`, or `{target: "name"}`. Write it as
  `{texture: …}` in the uniforms (`{texture: p, smooth: true}` to smooth
  it).
- **A sheet as a texture follows the sheet.** It is the sheet as it is now:
  painted on, it is sent again, and a surface showing it draws again.
- **Targets.** `gl.target(g, "name", width, height, {float?, depth?})` is a
  place to draw that is not the screen (made, or made again at a new size);
  `target: "name"` in a drawing draws there, and `{target: "name"}` as a
  texture reads it.
- `gl.clear(g, "#rrggbbaa", {target?})` clears colour and depth.
- `gl.pixel(g, x, y, {target?})` reads one pixel back as `[r, g, b, a]`,
  0 to 255.
- `gl.image(g, {target?, x?, y?, width?, height?})` is what was drawn, as
  an `image`: the screen or a target, all of it or a part (from its top
  left, in its own pixels), upright, the bytes as drawn.
- `gl.floats(g, {…})` is the same as `{width, height, data: numbers,
  float: true}`: a float target's own values, not held to 0 to 1. It is a
  texture again.
- `depth: true` tests depth; `blend: true` blends premultiplied alpha.
- `size` has `pixels` too: device pixels to one CSS pixel.

### A pen that is not on the page

```mote
// docs: whole
state tri = [-1, -1, 1, -1, 0, 1]
state said = ""

action render
  let g = gl.pen(64, 64)
  gl.clear(g, "#000000ff")
  gl.draw(g, {vs: "in vec2 p; void main(){ gl_Position = vec4(p, 0.0, 1.0); }", fs: "out vec4 o; void main(){ o = vec4(1.0, 0.5, 0.0, 1.0); }", attributes: {p: {data: tri, size: 2}}, count: 3})
  let p = gl.image(g)
  let mid = gl.pixel(g, 32, 40)
  said = `${p.width} by ${p.height}, the middle is ${mid.join(" ")}`

button "Render" press=render
text said
```

`gl.pen(width, height)` is a WebGL pen with no surface: draw with it
anywhere (an action too) and read it back with `gl.image`, `gl.floats` or
`gl.pixel`. There is one such pen: every call gives the same one, made the
size asked for. So read what you drew before another part of the page asks
for it. Its targets are kept by name like any pen's.

### A picture through a shader

```mote
// docs: whole
state shot: bytes? = none
state strength = 1

fn sepia(): string = "uniform sampler2D src; uniform float strength; in vec2 at; out vec4 o; void main(){ vec4 c = texture(src, at); float g = dot(c.rgb, vec3(0.299, 0.587, 0.114)); o = vec4(mix(c.rgb, g * vec3(1.07, 0.74, 0.43), strength), c.a); }"

action choose
  let file = fs.pick("image/png,image/jpeg")?
  if file == none return
  let p = img.decode(file.data)?
  shot = img.jpeg(gl.filter(p, sepia(), {strength}), 85)?

column gap=8 padding=16
  button "Choose a picture" press=choose disabled=pending(choose)
  if shot
    image shot.url("image/jpeg") max-width=100%
  text (failure(choose) ?? "") color=danger
```

`gl.filter(picture or sheet, fs, {uniforms}?, {width?, height?}?)` runs a
picture through a fragment shader and gives the result as an `image`. It
does not wait. The shader has:

| Name | Is |
|---|---|
| `uniform sampler2D src` | The picture. |
| `uniform vec2 size` | Its width and height in pixels. |
| `in vec2 at` | Where: (0, 0) is its top left, (1, 1) its bottom right. |

and the uniforms given. The result is as large as the picture, or as
`{width, height}` says. Encode it in a worker next:
`img.jpeg(gl.filter(p, fs), 90)?`.

Source: `runtime/page/surface.mote`, part `GLS` (`GLW` is `gl.…`).

## The 3D canvas: canvas boxes=

```mote
// docs: whole
shape Box
  id: string
  name: string
  x: number
  y: number
  z: number
  w: number
  d: number
  h: number
  color: string?

state boxes: Box[] = [{id: "a", name: "Base", x: 0, y: 0, z: 0, w: 600, d: 560, h: 720, color: "#c8a26b"}, {id: "b", name: "Tall", x: 600, y: 0, z: 0, w: 400, d: 560, h: 2100}]
state view = "iso"
state picked = ""

action pick(id: string)
  picked = id

column gap=8 padding=16 height=480
  row gap=8
    for v in ["iso", "front", "left", "plan"]
      button v press={view = v}
  canvas boxes=boxes view=view change=pick flex=1
  text (picked == "" ? "Press a box" : `Picked ${picked}`)
```

`canvas boxes=list view="iso"` draws boxes in space with WebGL 2.

- **A box** is `{x, y, z, w, d, h}`: x across, y back, z up; its lowest
  corner and its size. If wanted: `color`, `turn` (degrees about the upright
  through `px`, `py`), `id` and `name`.
- **A picture on a box**: `map` (a picture's address, its bytes, or one
  decoded) with `mapSize: [w, h]` (how much of the scene one copy covers),
  `mapOffset`, `mapTurn`, `tint`, `grain: "x"` (which way the picture's up
  runs; z if not said), and `sides: {color: "#f2efe8"}` for its four thin
  faces: the words a `three.material` and a mesh say, with the same
  meaning, limits and `input` events
  ([scene.md](scene.md#pictures-on-materials-map)).
- **`view`**: `iso` `front` `back` `left` `right` `plan`.
  `view="cam:yaw,pitch,zoom,ortho"` sets the camera outright.
- A drag turns it, the wheel zooms. A press on a box sends `change` with its
  id (`change=picked` with `action picked(id: string)`). Its name and size
  show on hover.
- **It takes its size from the page**: give it room with flex or a sized
  parent.
- **`tool`**. `tool="orbit"` is the above. Any other word makes the pointer
  a tool instead: down, move and up send `input` with JSON
  `{phase, x, y, id}`: where on the floor (z = 0) the pointer is, and the
  box under it (`input=worked` with `action worked(e: string)`, then
  `JSON.parse`).
- `tool="png"` (or `"png4k"`) saves what is drawn as a picture.

### The lit picture: render=

`render="still"` or `render="real"` adds the lit picture: sun, sky, shadows,
light bouncing, a floor under the scene.

- `"still"` keeps the drawing plain and lights what `tool="png"` saves (send
  `"pngplain"` for the plain one).
- `"real"` also works the lit picture out over the drawing whenever it
  stands still.
- `samples=64`, `exposure=1`, `sun="turn,height,strength"` in degrees
  (unsaid: over the looker's left shoulder).
- A box may then say `rough` (0 mirror to 1 matte), `metal` (0 or 1),
  `clear` (0 to 1, lets light through), `glow` (gives light).
- `input` hears `{phase: "gpu", ok, ms}` once (`ms` for one sample of a fixed
  small scene: how quick the machine is at it), `{phase: "render", samples,
  of}`, `{phase: "done"}`, `{phase: "saved"}`.

Only a canvas that says `render` carries the tracer.

Source: `runtime/page/boxes.mote` (part `BX`), `runtime/page/trace.mote`
(part `BT`), `runtime/page/pictures.mote` (parts `BXP`, `BTP`: pictures on
materials).

## The 3D canvas: canvas scene=

`canvas scene=world camera=eye` is the same engine in three.js's words: a
scene of meshes and groups, materials, lights, a camera. z is up. Its whole
story is on its own page: **[scene.md](scene.md)**.

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

derive oak = three.material({color: "#c8a878", roughness: 0.6})
derive steel = three.material({color: "#c9ccd1", roughness: 0.2, metalness: 1})
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]})], {rotation: [0, 0, turn]})
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})

action pick(id: string)
  picked = id

column gap=8 padding=16 height=480
  canvas scene=world camera=eye change=pick flex=1
  row gap=8
    button "Turn" press={turn += 15}
    text (picked == "" ? "Press a thing" : `Picked ${picked}`)
```

In brief:

- `three.mesh(three.box(w, d, h), {color, roughness, metalness,
  transmission, emissive}, {position: [x, y, z], rotation: [0, 0, 25], id,
  name})` · `three.sphere(r)` · `three.cylinder(r, h)` · `three.plane(w, d)`
- `three.extrude([[x, y], …], height, {holes})`: an outline pushed up (an L,
  a cut corner, a wedge); its position is the outline's own 0, 0, half way up
- `three.material({…})` · `three.group([…], {position, rotation, scale})`
- A picture on a material: `three.material({color, map, mapSize: [600, 600]})`,
  and on the mesh `{grain: "x", sides: band}`
  ([scene.md](scene.md#pictures-on-materials-map))
- `three.scene([…], {lights: [three.sun(turn, height, 1), three.sky(1)],
  ground})`
- `three.perspective({position, target, fov})` ·
  `three.orthographic({position, target, size})`
- A position is a thing's middle; a group moves and turns all that is in
  it. Everything `three.*` makes is a plain record.
- `render=`, `tool=`, `change` and `input` are as for boxes.

The records, materials, lights, the camera, what is not there yet, and
moving from `canvas boxes=`: [scene.md](scene.md). Source:
`runtime/page/three.mote` (part `TH`), `runtime/page/boxes.mote`.

## Pitfalls

- **A drawing fn must not write state.** It is a fn: writes are refused.
  Hear the pointer with an action and draw from state.
- **Reading state is what redraws.** State the fn did not read on its last
  run does not redraw it. A fn that returns early before reading something
  will not follow it.
- **`animate` costs a frame every frame.** Turn it off when nothing moves.
  With `animate`, `size.time` moves the drawing; without it, `time` is only
  the moment of the last redraw.
- **GL buffers are kept by list identity.** Building a new list every frame
  uploads a new buffer every frame. Keep vertex lists in state and replace
  them only when they change.
- **A `surface` needs `draw=`** (one without is refused), and a size from
  styles; a canvas with no height shows nothing.
- **`draw.read` gives the screen's pixels, not CSS pixels.** Its width is
  the surface's width times the screen's density. For a picture of a known
  size, use `draw.picture(width, height, fn, pixels)`.
- **A gradient's places are the shape's own lengths**, not parts of the
  shape: `{linear: [0, 0, 100, 0]}` runs over 100 units from the pen's
  origin, wherever the rectangle is.
- **A picture read back is 4 bytes a pixel.** Do not keep many in state;
  encode them ([media.md](media.md#pitfalls)).
- **The 3D canvas needs room.** In a `column` with no height it has none.

## Where a new call goes

`draw.*` calls go in the `surface (2D)` table (a subject of its own, like
layers or typing, gets a `###` under it); `gl.*` under `surface gl`;
anything about `canvas boxes=` or its renderer under `The 3D canvas`;
`three.*` and `canvas scene=` in [scene.md](scene.md), with a line in the
brief list here. Painting on pixels (`paint.*`) is
[media.md](media.md#paint), not here.

## In the source

| What | Where |
|---|---|
| `surface`, `draw=`, `animate=`, `gl` | `compiler/src/view.rs`: `Gen::el` (the `surface` branch) |
| `draw.*`, `gl.*` names | `compiler/src/types.rs`: `Checker::call`; `compiler/src/emit.rs`: `Gen::call` |
| The 2D pen | `runtime/page/surface.mote`: part `SF` (`ink` is fills, `mood` opacity, blend and shadow) |
| Layers, `draw.read`, `draw.picture` | `runtime/page/surface.mote`: part `SFL` |
| Typing on a surface | `runtime/page/surface.mote`: part `SFT`; `compiler/src/view.rs` (`typed`, `composing`, `caret`) |
| WebGL | `runtime/page/surface.mote`: part `GLS` (`block` reads back; `away` is `gl.pen`; `filter`) |
| Boxes | `runtime/page/boxes.mote`; attributes checked in `compiler/src/types.rs`, `Checker::el` |
| The lit picture | `runtime/page/trace.mote` |
| `three.*`, `canvas scene=` | `runtime/page/three.mote`; `compiler/src/types.rs` and `emit.rs` (`three`) |
| Recorded behaviour | `tests/surface`, `tests/draw2`, `tests/glread`, `tests/boxes`, `examples/playground/pages/surface.mote`, `charts.mote`, `boxes.mote` |
