# 3d

Part of the [scripting reference](index.md), written by the engine so it matches your `frost`. Start with [your first game](../start/first-game.md) if you are new.

Use when building a 3D scene, placing meshes, adding a point light or sun, setting sky, ground or a following camera.

| In a script | Does |
| --- | --- |
| `screen.project(camera, x, y, z)` | World point to pointer x/y (-1 to 1, y down) and signed forward depth; positive is in front. Unclipped; the camera plane is refused (E0575) |
| `screen.ray(camera, x, y)` | Pointer coordinates to world origin x/y/z and unit direction dx/dy/dz, starting at the camera. Both calls use the live 3D Camera, its parents and frame aspect; finite inputs required (E0575) |

### 3D

The `screen` calls use y down, while `[input] pointer` actions use y up.
Negate the pointer y when calling `screen.ray`, or negate the y returned by
`screen.project` when comparing it with pointer input.

A game is 3D when its project file says `space = "3d"` (left out, or `"2d"`: 2D, as
always). Then its one `Transform` has ten fields: where (`x` right, `y` up, `z` towards
the viewer, in metres), how it is turned (a quaternion `qx`, `qy`, `qz`, `qw`, no turn
`0, 0, 0, 1`) and how it is scaled (`sx`, `sy`, `sz`, 1). Axes are right-handed, y up,
as glTF's: a model faces +z, a camera and a light look along their own -z. A Transform
is in the world, or local to its `Parent`'s when that one has a Transform, as in 2D. The 2D `Rotation` and
`Scale` are not there in a 3D game. A scene writes a turn as the quaternion or as
degrees, `turn = { x = 0, y = 90, z = 0 }`: yaw about y, then pitch about x, then roll
about z, made a quaternion once as the scene loads. Numbers are 32-bit: far from the
origin they lose their fine part (at 8 km a step is about a millimetre).

| In a 3D game | Does |
| --- | --- |
| `place(entity, x, y, z, qx, qy, qz, qw)` | Writes where an entity is and how it is turned, in one call: what a script that moves many things a step uses. Scale is `set` |
| `quat.turn(yaw, pitch, roll)` | The quaternion of a turn in degrees, as a scene's `turn`: four numbers |
| `quat.look(x, y, z)` | The turn that points a thing's front (+z) along a direction, keeping it upright. A camera looks along -z: `quat.look(-x, -y, -z)` |
| `quat.mul(ax, ay, az, aw, bx, by, bz, bw)` | Turning by `b`, then by `a`, as one turn |
| `quat.slerp(ax, ay, az, aw, bx, by, bz, bw, t)` | The turn `t` of the way from `a` to `b`, the short way, at an even speed |
| `quat.rotate(qx, qy, qz, qw, x, y, z)` | The vector `x, y, z` turned: three numbers |
| `ground.at(x, z)` | In a 3D game, the ground under `x`, `z`: `{ entity, height, nx, ny, nz, layers }` of the lowest thing whose `Ground` is there (its surface's y, its normal, each picture layer's weight), or nil where no ground is. The protocol's `ground.at` answers the same |

The `quat` functions work out each number from the same 64-bit arithmetic on every
machine and in a browser, and `place` rounds to the field's 32 bits as `set` does.

### Meshes

In a 3D game (`space = "3d"`) the frame graph draws meshes, lit and tested against depth,
then every layer over them: with no `[render]`, a pass `meshes` then a pass `layers`, and a
pass `sky` before them when a scene gives a thing a `Sky`.

- `Mesh = { file = "racers/halo.glb", tint = 0xffffff }` draws the named `.glb` or
  `.gltf` scene's meshes, cooked at load (`E0436`: unreadable), placed by the entity's
  and parents' `Transform`. Corner colour is `COLOR_0` times material base colour and
  base colour picture times entity and ancestor `Tint`, as in 2D. Write `Tint`;
  legacy `Mesh.tint` still multiplies it.
  Linear lighting uses metal, roughness, normal, occlusion and glow pictures and factors;
  occlusion may share the metal/roughness picture or have its own. All pictures use the
  base colour picture's `KHR_texture_transform`. Masked materials omit pixels below
  their cutoff; blended ones use alpha, drawn after opaque things, farthest position
  first. A thing's faces are unsorted; intersecting see-through things draw in
  position order, not intersection order. All faces draw; double-sided materials
  light backs like fronts. Under a `Sky`, metal reflects only its zenith,
  horizon and ground, in the metal's colour, blurred by roughness: no sun or surroundings,
  no reflection without Sky. Unread: second uvs, texture samplers, other extensions.
  `Mesh.far` is how many metres from the eye the thing is drawn (0: the project's `[lods]
  far`): a brazier's fire can outlive the crates round it. Past it the thing, its shadow and
  what it holds are not drawn, faded out over its last tenth; the world is as it was.
  Override the model's look by setting `Mesh.roughness` and `Mesh.metallic` (0 to 1;
  below 0, the default, uses the model's) and `Mesh.blend` (`"blend"`: alpha transparency,
  `"opaque"`: whole, `""`: the model's), like any value. `Opacity` fades 3D as in 2D
  (see Opacity). Exports carry and draw cooked models (`NAME.vmsh`).
  `Tints = { list = "wax_seal = 0xff3020, #2 = 0x2050ff" }` beside a `Mesh` multiplies
  each named material's parts by a colour too (over `tint` and `Tint`); others are as
  they were. A material is its name in the file (bare, or in double quotes) or `#` and its
  place from 0; a colour is `0xRRGGBB` (no alpha: `Opacity` covers); commas part them,
  spaces and a last comma are allowed. `E0483`: not tints, or a material the model has
  not. `set(e, "Tints", "list", "...")` (C#: `World.Set`) changes it; things tinted
  alike or not are drawn together as before.
  A picture inside a model longer than 2048 on a side is halved for the web until it fits
  (`W0455` says which, and its size there): the checksums are the same in a browser, its
  frames are not, and `frost test` takes a game's shots natively only, so nothing compares
  them to the browser's.

- **Shapes.** `Mesh = { file = "box" }` draws one of the engine's own shapes with no file:
  `"box"`, `"sphere"`, `"plane"`, `"capsule"` or `"cylinder"`, each one metre across about
  its middle so the thing's scale sizes it as it sizes a `Collider` of 1 (a plane lies flat
  facing up; a sphere and an upright cylinder are 1 high; a capsule is 1 across and 2 high,
  as `Collider = { shape = "capsule", w = 1, h = 2 }`), white and rough, so `tint` is its
  colour. A word with no `.glb` or `.gltf` ending names a shape, and no other is one. It
  is made in every program, a player too, and is no file of the game: nothing is exported
  for it. `assets.cooked {path = "box"}` answers its parts.

- `Emission = { color = 0xffffff, strength = 0 }` beside a `Mesh` adds its own
  linear-light colour times `strength`, regardless of lighting, plus every ancestor's
  emission (`Parent`). One root write flashes a figure's parts:
  `set(e, "Emission", "strength", 2)`, then back to 0. Above 1, colour saturates;
  a blooming `[render]` graph (`bright`, threshold 0.6 unless given, then `blur` and
  `add`) spreads a halo: the engine's `flash` example. The default 0 adds nothing. 2D ignores
  `Emission` for now. As with `Opacity`, give `Emission = {}` in the scene or when spawning.

- `Camera = { zoom = 1, fov = 60, near = 0.1, far = 0 }` is the eye: it looks along its turn's -z,
  `fov` degrees from the frame's bottom to its top, from `near` to `far` (0: no far end).
  The lowest entity with a Camera and a Transform sees.

- `Light = { kind = "point", color = 0xffffff, energy = 1, range = 10, inner = 20, outer = 30 }`:
  `"ambient"` everywhere, `"sun"` along local -z, `"point"` from its place fading to
  nothing at `range`, `"spot"` likewise in a cone along local -z: whole within `inner`
  degrees, fading to nothing at `outer`. Each frame lights the 16 points/spots that give
  the view the most light (brightness, nearness to the eye for the range); off ones and
  ones reaching nothing in view take no place; ties go to the lower entity. With more,
  the last drawn dim toward the best left out, so none pops in or out.
  A sun with `shadows = true` first draws a 2048² map of the ball `range` units round
  the point `range` ahead of the Camera; it lights only points with nothing nearer in
  that map, soft over one map pixel at shadow edges. A shadowing spot uses a 1024²
  perspective map of its cone to `range`, equally soft. Among the lights drawn,
  the lowest entity spot requesting shadows with `0 < outer < 90` wins.
  Its near plane is range/100; closer casters are clipped.
  Other drawn points and spots with `shadows = true` share one 2048² atlas, the same on
  every device: a point six 512² faces, a spot 1024², two points and a spot at most;
  those giving the view most light first, the rest unshadowed, each fading as it nears
  the best left out. A mesh is drawn into the faces its bounds meet; posed ones, all.
  Off by default: no extra pass. A `Sky` controls its sun's shadows.
  The winning spot's `cookie = "art/mask.png"` projects a PNG across its cone (top at
  local +y), multiplying linear RGB and alpha with the picture filter. `""` (default)
  skips sampling; other lights ignore cookies. `frame.at` names the cookie unread.
  A point/spot with `night = true` shines as the Sky's sun goes down: none while a little
  up, all just under the horizon, smoothly. Its `energy` stays as written; only the
  picture follows time. Without Sky it always shines.

- `Sky = { time = 12, turn = 0, shadows = false, reach = 30, haze = 0, haze_far = 0 }`:
  `time` is hours modulo 24 (scripts may add forever), determining sun direction, colour
  and strength, sky colours and ambient light (added to any `"ambient"` Light), without
  a picture. The sun rises along +x at 6, stands 50 degrees up towards -z at 12 and sets
  along -x at 18. `turn` rotates that path about +y in degrees. At night a dim blue moon
  shines from the opposite side. Sky replaces a `"sun"` Light and its shadows.
  `shadows = true` casts its sun/moon's shadows as that light does, `reach` replacing
  `range`: the same map, moving with time.
  With `haze_far > haze`, meshes and ground fade smoothly into the current horizon
  colour from `haze` units from the eye to fully at `haze_far`. Below the horizon the
  sky becomes horizon colour too, melting the world's edge into it.
  A `draw = "sky"` pass draws horizon, zenith, ground and sun disc over its whole target,
  before meshes. Games whose scripts alone make Sky, or with their own `[render]`,
  name that pass: `{ name = "sky", draw = "sky" }`. A scene's Sky with explicit passes
  but no sky pass is `W0458` (check and load): lit, unseen.
  The lowest entity's Sky wins. Like any component, `world.set`, script
  `set(find("sky"), "Sky", "time", 18)`, recordings and checksums see it.

- `Fog = { color = 0x000000, density = 0 }`: without Sky, the lowest entity's Fog fades
  lit meshes and ground towards its sRGB colour by `1 - exp(-(density * distance)^2)`,
  distance from the eye in world units. Nonpositive density is off; try `0.058`.
  Sky takes precedence. Background stays unchanged; set it to the fog colour if wanted.
  `frame.at` explains fog; no beam scattering. Example: the engine's `torch/fog.toml` example.

- `Ground = { file = "art/hill.ground.toml", color = 0x7c8a5c }` is a height field, drawn
  lit in one colour where its thing's Transform puts its middle (its turn and scale are not
  read). The file is a few lines of TOML: `heights = "hill.png"` (a grey PNG beside it,
  16 bits a sample or 8, square, its side even and from 4 to 1024 samples, row 0 at -z),
  `size = [64, 64]` (metres across x and z), `low = 0` and `high = 4` (the heights of
  black and white). The cook makes it into metres once (`frost export` ships it cooked,
  `NAME.vgrd`); each cell is two triangles split from its corner nearest -x and -z. It is
  drawn in tiles of 64 by 64 cells, each only when its box is in the view (one draw a
  tile, which `render.passes` counts; the sun's shadow pass draws those the sun sees), with
  every corner, every second or every fourth: the fewest that move its surface less than
  half a pixel from where the eye sees it (a coarser tile hangs a skirt a metre down its
  edges, so no crack shows beside a finer one). Each corner keeps its normal in two 16-bit
  numbers and its place is worked out on the device, so a ground's picture may differ by
  one level in up to about one pixel in a thousand from the same ground drawn as one mesh.
  The
  protocol's `ground.at {x, z}` says the height and the slope there. `E0490`: a ground the
  cook cannot read. `W0459` (`frost check`, `frost export web`): a ground over 512 samples a side, said
  with what its tiles hold on the device with every level: about 12 MB of buffers at 1024
  (one mesh of it would hold 80 MB), which a phone or a browser may need for the rest of
  the game. A `Collider = { shape = "ground" }` beside it makes the 3D physics
  collide with it (Jolt's height field, each height kept to 8 bits within its 2 by 2
  block, so it is off what `ground.at` says by at most a 510th of how much the block's
  heights differ).
  `layers = [{ image = "grass.png", tile = 4 }, { image = "rock.png", tile = 6, slope =
  [25, 38] }, { image = "snow.png", tile = 8, height = [15, 17] }]` (at most 4) draws it in
  pictures, each repeating every `tile` metres over x and z, in place of its `color`: the
  first everywhere, each later one over those before it from none at its first number to
  all at its second (smoothly), by the slope in degrees (of the drawn surface, its normal
  mixed across each triangle) or by the height in the world. Its pictures are cooked into
  the ground with every level. `ground.at` says each layer's weight there by the same rule.

- The 2D layers are drawn over the meshes as in a 2D game: seen from the Camera's `x`
  and `y` with its `zoom`, and a `Screen` thing stays where the frame puts it. `zoom`
  never touches the meshes' view: to frame a 3D scene, move the Camera or change `fov`.

- **Materials.** `Mesh = { ..., material = "road" }` draws with a material that
  `[render.materials]` declares: `road = { vertex = "road.wgsl", fragment = "sea.wgsl" }`,
  one or both, each file one WGSL function. `fn vertex(world: vec3<f32>, p:
  array<vec4<f32>, 2>) -> vec3<f32>` moves a point already placed in the world; `fn
  fragment(world: vec3<f32>, normal: vec3<f32>, uv: vec2<f32>, color: vec4<f32>, p:
  array<vec4<f32>, 2>) -> vec4<f32>` is a surface's colour before it is lit. `p` is
  `Material = { of = "road", p0..p7 }` on one thing, which a script writes; a Mesh's own
  `p0..p3` are `thing` (a `vec4<f32>`) there, one heat or flash a thing. A material's
  function has no clock: what moves, moves because a script wrote its numbers this step,
  so a frame put back is the same picture. A click finds a thing where it is, not where
  a material draws it. At most 8. `E0437`: an undeclared material, or two things giving
  one its numbers.

- Two surfaces at one depth (a pillar standing exactly on a floor, along its foot) are a tie
  that each graphics backend may break its own way: WebGL2 takes depth through GL's -1 to 1
  and rounds it differently, so a picture can differ there by a pixel. Sink a thing a little
  into what it stands on (a hundredth of a unit) to have one picture everywhere.

- With `[render] msaa = 4`, a pixel on a smoothed edge may be one level (of 255) off in
  WebGL2 from the native and WebGPU pictures, which are the same: the browser's GL
  averages the four samples itself and rounds its own way. Nothing else differs.

- A model only a script names goes in the project's `models` (`E0438`: a Mesh names one
  not loaded; `frost check` says `E0439` of a script naming one).

| Component | Field | Type | Default | Meaning |
| --- | --- | --- | --- | --- |
| `Follow` | `of` | text | `""` | The name of the thing it follows. Empty, or a name no thing has: it stays where it is |
| `Follow` | `back` | number | 6 | How far behind the thing it is, in metres |
| `Follow` | `up` | number | 3 | How far above the thing's place it is |
| `Follow` | `aim` | number | 1 | How far above the thing's place the point it looks at is: its shoulders, not its feet |
| `Follow` | `speed` | number | 5 | How much of the way to its place it closes in a second: 5 is a fifth of a second's lag. 0: at once |
| `Follow` | `walls` | whole number | 65535 | The collider layers it is kept in front of: where a solid collider on one stands between the point it looks at and its place, it is put 0.2 in front of it at once, not eased (a ray, past the thing it follows; sensors are not seen). 0: none |
