# The game language

# The game language

A scene's logic is written as `.fgl` files in the game language (`@ferret/dataflow`) and stepped with the world's fixed step. It is text of the same shape as the motion language. A changed file takes effect in the running game on the next step, without a build, and the state stays where the names match. TypeScript is for what the language cannot say: it is given to the language as **externs** (a shader, a mesh made in code, a call into the engine).

The language runs in the game's thread, by an interpreter. Heavy calculation goes into an extern (and from there into kernels, if it is large).

## In a game
The game installs the language and gives it its files:
```ts
import type { GameContext } from '@ferret/player';
import { installGame } from '@ferret/dataflow';

export async function install(ctx: GameContext) {
  const text = await (await fetch(await ctx.url('logic/game.fgl'))).text();
  const flow = installGame(ctx.game.world);          // the files of the externs connect themselves (see Externs)
  flow.load({ 'game.fgl': text });
  await ctx.game.world.commands.execute('game.run');
  return { dispose: () => flow.dispose() };
}
```
- Keep the `.fgl` files in `logic/`, not under `src/`: the sources are bundled into code and are not copied into the package. A file goes into the `.fex` when the code names its path as written (`'logic/game.fgl'`).
- Several files are one game: they are read in the order of their names and share one set of names, so a name defined twice is refused. Give the names of a mechanism its prefix.
- `game.load` reads and checks; the game runs after `game.run`. The entities of the files' levels are made when the game is loaded.

## Streams and state
```lisp
(def counter (+ (pre counter 0) 1))
(defflow smooth (x k) (let ((y (pre x 0))) (+ y (* k (- x y)))))
(def eased (smooth (if (> counter 60) 1 0) 0.1))
(emit "eased" eased)
```
- `(def name expr)` names a stream: it has a new value each step.
- `(pre x init)` is `x` of the step before (`fby` is the same with the arguments the other way round). A value that depends on itself must go through `pre`; a loop without it is refused.
- `defflow` is a reusable piece that may keep state and act (each call has its own state); `defn` is instant and pure. A flow cannot call itself.
- `let`, `let-values`, `values`, `do`.
- Operations: `+ - * / % pow atan2 min max abs sqrt sin cos tan floor ceil round sign clamp lerp`, vectors `vec vec-x vec-y vec-z length dot dist cross normalize`, logic `< > <= >= = != and or not if`, data `list nth len obj`.

## Clocks
```lisp
(def second (every-s 1 (time)))
(emit "second" second)
(def even (= (% (step) 2) 0))
(emit "alt" (merge even (when 10 even) (when 20 (not even))))
(emit "opened" (event "door:open"))
```
A stream on a clock has a value only on some steps, and what depends on it runs only then. `(when x condition)`, `(merge condition a b)`, `(every n x)` (each n-th step), `(every-s seconds x)`, `(event "name")` (a world event, with what it carried). Streams of two different clocks cannot be combined: sample one with `when`, or join them with `merge`.

A statement whose values are all constants runs **every step**. To act once or when something happens, give it a value on a clock: `(command "world.timeScale" (when (obj :scale 0.5) (event "bell")))`.

## Sensors and effectors
- Always there: `(time)`, `(dt)`, `(step)`.
- Answered by the engine: `(pressed "action")`, `(axis "action")` (the game's input actions), `(position "name")` (an entity or a node), `(exposed "name")` (what the game shows with `world.expose`). The language also knows `speed`, `in-zone`, `flow-at` and `ray`; the game answers those it uses in `installGame(world, { sensors })`, as it may add or replace any.
- Done by the engine: `(emit "name" x)` (a world event), `(command "engine.command" (obj :key value))`. The language also knows `animate`, `play-sound`, `move`, `force`, `motor` and `(effect "name" x ...)`; the game gives the ones it uses in `installGame(world, { effects })`.

## Kinds of entities
```lisp
(defkind lamp :fields ((position (vec 0 0 0)) (heat 0) (lit #f))
  (def power (collect "power" :sum))
  (set-field heat (clamp (+ (field heat) (- power (* 0.1 (field heat)))) 0 100))
  (set-field lit (> (field heat) 5)))
(defkind wire :fields ((position (vec 0 0 0)) (to 0 entity))
  (send (field to) "power" 1))
(level "Hall" :scene "scene.glb"
  (entity "lamp1" :kind lamp :position (vec 2 0 0))
  (entity "wire1" :kind wire :position (vec 0 0 0) :fields (obj :to 1)))
```
- A field is `(name start)` or `(name start type)`; the types are `num bool vec3 str entity list any`.
- Each entity has its own state. Reads of fields see them as they were at the start of the step; `set-field`, `send`, `spawn`, `despawn` and the effectors are applied at the end of the step.
- Mail: `(send target "name" x)` is read in the next step by `(collect "name" :sum)` (also `:min :max :count :list`, with a value for an empty box as the third argument).
- `self`, `(of entity field)`, `(nearest kind position)`, `(query kind :near position radius)` (these two read the field `position`), `(spawn kind :at position :fields ((name value)))`, `(despawn entity)`.

## Motion programs
```lisp
(defmotion blink () (seq (wait 0.5) (emit "blink" 1)))
(def blinking (motion blink))
```
A program of the motion language (skill `ferret-motion`, its own guide) is one node of the graph: `(motion name)` of a `defmotion`, or a `seq`, `par`, `race`, `states`, `loop` ... written in place. The node's value says whether the program is done. What it emits becomes a world event.

## Externs
An extern is a TypeScript or JavaScript function called from the language:
```lisp
(extern wave-height :from "logic/sea/externs.ts" :kind pure :args (num num) :returns num)
(def swell (wave-height (time) 3))
(emit "swell" swell)
```
```ts
// logic/sea/externs.ts
export const waveHeight = (t: number, x: number): number => Math.sin(t + x);
```
- **The file named by `:from` connects itself.** The path is from the project's root. The build of a project (`ferret build`, the editor) and of an example puts the file into the game's code; nothing is imported or passed in by hand. The file may import other files of the game and `@ferret/*`, and they are the same instances as in the rest of the game.
- The function is exported under the extern's name; a name with hyphens is exported in camel case (`wave-height` as `waveHeight`).
- A function the game gives in `installGame(world, { externs })` comes before the file's, then one given later by `binding.provide({ name: fn })`. A file that is not in the project is expected from one of these two. A built game whose code does not hold the module loads it from `code/<from>.js` beside the page (`installGame(world, { modules })` loads it another way), and `game.load` waits for it.
- **Everywhere in the language.** The same name works in streams, flows and motion programs. In a motion program a `pure` or `world` extern is called at once; a `lasting` one makes the program wait until the `{ done(), result }` or the promise it returned is done; an `action` returns `{ step, stop }` and runs while its form is active. A word the motion language or the host already has keeps its meaning there.
- `installGame(world, { motion })` takes a motion runtime that holds the host's own words (the forms of models, of the physics), so the game's motion programs can use them.

`:kind` is `pure` (no state, no effect), `world`, `lasting` or `action`; an extern that is not `pure` cannot be called from a `defn`. `:args` and `:returns` are checked. A node whose extern throws is stopped, `game:error` is emitted with the form, and the rest of the game goes on.

## The scene as forms
`(level "Name" :key value ... (spawn-point ...) (entity ...) (zone ...) (collider ...) (environment ...) (physics ...) (link ...))` and `(game "name" :start "level" ...)` say what a `manifest.json` says; the two are the same data (`manifestToForm`, `formToManifest`, `game.manifest`). An `entity` with a `:kind` becomes an entity of that kind with its `:fields` and `:position`. The engine's level service loads the manifest: where a level must be loaded by it, write the manifest from `game.manifest`.

## Commands
| Command | What it does |
|---|---|
| `game.check {source}` | reads and checks without loading: the error with `file:line:col`, or what the file defines |
| `game.load {source}` or `{files}` | reads, checks and loads; `game.run`, `game.stop`, `game.step {n}` |
| `edit.game.set {name, source}` or `{files, remove}` | changes the running game; `edit.game.list`, `edit.game.remove {name}` |
| `game.eval {expr}` | the value of one expression of the current step; nothing changes |
| `game.trace {steps, nodes}` | the values of named streams over steps |
| `game.entities {kind}`, `game.entity {id}`, `game.spawn`, `game.despawn` | the entities |
| `game.graph {kind}`, `game.tokens {kind, id}` | the nodes with their measured cost, and the values of the last step |
| `game.manifest {level}` | a level of the forms as manifest JSON |

Long lists take `{offset, count}` and then answer `{total, offset, rows}` (`game.graph` pages its nodes). `perf.report` gets a `game` part with the cost of each graph and extern.

## Changing a running game
`edit.game.set` puts the new text into the running game from the next step. Kept, where names match: the values of `pre`, the entities and their fields, the mail, the time and the running motion programs. A field takes its new start value only when its declared start value or type changed. A motion program restarts only when its definition changed. An entity taken out of the level leaves, a new one comes, one made while running stays, one removed while running stays removed. A game with an error is refused whole and the old one goes on. Files that depend on each other are changed together: `{files: {...}, remove: [...]}`.

State is found by where it stands: the name of the `def`, the statement (its word and first name) and the flows called on the way. Renaming those starts that state anew.

## Testing
- Headless, in a unit test: `compile(text)` and `new Machine(game, host)`, then `machine.step(1 / 60)`; or `installGame(world)` in a test world and `world.step()`.
- In the running scene, by a Ferretic test (skill `ferret-ferretic`): `WAIT EVENT "name"` for what the game emits, and `COMMAND "game.eval" WITH expr = "total" INTO v` for a value.

## A mechanism as a module
A mechanism that a scene needs and neither the engine nor the library has is written as its own piece, so that the next scene takes it as it is:
- `logic/<mechanism>/<mechanism>.fgl`: its flows and kinds, with the mechanism's name as the prefix of its names, and its parameters as arguments of its flows or fields of its kinds;
- its externs in one TypeScript file, only for what the language cannot say;
- a short description at the top of the `.fgl` file: what it does, its parameters, the sensors, effectors and events it uses;
- its own test.
The scene's own files only choose mechanisms, give them parameters, place things and say what happens on which event.
