plum

#treesitter#compiler#wasm

git clone https://git.pyrossh.dev/plum

A statically typed, imperative programming language inspired by rust, python


ab89e24 — Peter John 2026-11-09T12:07:10+05:30
std/game_enum_tree: generic over Actor[K]; port orb_run to it; trait design doc
benchmarks/scene_trees/game_enum_tree.plum CHANGED
@@ -12,7 +12,7 @@ import std/game/Vec2
12
12
  import std/game/Affine
13
13
  import std/game/Color
14
14
  import std/game_enum_tree/ETree
15
- import std/game_enum_tree/EBody
15
+ import std/game_enum_tree/Actor
16
16
  import std/game_enum_tree/ECtx
17
17
  import std/game_enum_tree/EStage
18
18
 
@@ -50,63 +50,35 @@ struct Rng(mut s: Int) =
50
50
 
51
51
  fun float(self, k: Int) -> Float = Float(self.next(k * 10)) / 10.0
52
52
 
53
- # One struct for the scene's two kinds of body: the groups (`moves` false: a step returns
53
+ # The kind of the scene's actors (`Actor[Bod]`): the groups (`moves` false: a step returns
54
- # them as they are) and the leaves (`moves` true: they move by (vx, vy) and bounce). Its
54
+ # them as they are) and the leaves (`moves` true: they move by (vx, vy) and bounce). With
55
- # fields are master's `Leaf`: `EBody`'s and the velocity.
55
+ # the actor's own fields, it holds master's `Leaf`: master's `EBody` fields and the
56
- struct Bod(
56
+ # velocity.
57
- id: Int,
58
- x: Float, y: Float, width: Float, height: Float,
57
+ struct Bod(vx: Float, vy: Float, moves: Bool) =
59
- originX: Float, originY: Float,
60
- scaleX: Float, scaleY: Float,
61
- rotation: Float,
62
- color: Color,
63
- visible: Bool,
64
- dead: Bool,
65
- vx: Float, vy: Float,
66
- moves: Bool) =
67
58
 
68
- fun key(self) -> Int = self.id
59
+ fun paint(self, a: Actor[Bod], io: Io, m: Affine, alpha: Float) = a.paintBox(io, m, alpha)
69
60
 
70
- fun gone(self) -> Bool = self.dead
61
+ fun hit(self, a: Actor[Bod], p: Vec2) -> Bool = a.hitBox(p)
71
62
 
72
- fun shown(self) -> Bool = self.visible && !self.dead
73
-
74
- fun opacity(self) -> Float = self.color.a
75
-
76
- fun local(self) -> Affine =
77
- ebody.localOf(self.x, self.y, self.originX, self.originY, self.scaleX, self.scaleY, self.rotation)
78
-
79
- fun hit(self, p: Vec2) -> Bool = ebody.hitBox(self.width, self.height, p)
80
-
81
- fun paint(self, io: Io, m: Affine, alpha: Float) =
82
- if self.width > 0.0
83
- ebody.paintBox(io, m, alpha, self.width, self.height, self.color)
84
-
85
- fun step(self, ctx: ECtx[Bod], dt: Float) -> Bod =
63
+ fun step(self, a: Actor[Bod], ctx: ECtx[Bod], dt: Float) -> Actor[Bod] =
86
64
  if !self.moves
87
- self
65
+ a
88
66
  else
89
- nx := self.x + self.vx * dt
67
+ nx := a.x + self.vx * dt
90
- ny := self.y + self.vy * dt
68
+ ny := a.y + self.vy * dt
91
69
  vx := if nx < 0.0 || nx > 200.0 then 0.0 - self.vx else self.vx
92
70
  vy := if ny < 0.0 || ny > 200.0 then 0.0 - self.vy else self.vy
93
- Bod(..self, x: nx, y: ny, vx: vx, vy: vy)
71
+ Actor(..a, x: nx, y: ny, kind: Bod(vx: vx, vy: vy, moves: true))
94
72
 
95
- fun group(id: Int, x: Float, y: Float, s: Float, r: Float) -> Bod =
73
+ fun group(id: Int, x: Float, y: Float, s: Float, r: Float) -> Actor[Bod] =
96
- Bod(
97
- id: id, x: x, y: y, width: 0.0, height: 0.0, originX: 0.0, originY: 0.0,
98
- scaleX: s, scaleY: s, rotation: r, color: Color.White, visible: true, dead: false,
99
- vx: 0.0, vy: 0.0, moves: false)
74
+ Actor.turned(id, x, y, s, r, Bod(vx: 0.0, vy: 0.0, moves: false))
100
75
 
101
- fun newLeaf(rng: Rng, id: Int) -> ETree[Bod] =
76
+ fun newLeaf(rng: Rng, id: Int) -> ETree[Actor[Bod]] =
102
77
  x := rng.float(200)
103
78
  y := rng.float(200)
104
79
  vx := rng.float(100) - 50.0
105
80
  vy := rng.float(100) - 50.0
106
- etree.leaf(Bod(
107
- id: id, x: x, y: y, width: 20.0, height: 20.0, originX: 0.0, originY: 0.0,
108
- scaleX: 1.0, scaleY: 1.0, rotation: 0.0, color: Color.Red, visible: true, dead: false,
81
+ etree.leaf(Actor.rect(id, x, y, 20.0, 20.0, Color.Red, Bod(vx: vx, vy: vy, moves: true)))
109
- vx: vx, vy: vy, moves: true))
110
82
 
111
83
  # What the workloads change besides the stage: the live ids, the random numbers, the next
112
84
  # id to give out.
@@ -117,23 +89,23 @@ fun bench(n: Int) -> Bench = Bench(live: Slice[Int](), rng: Rng(s: 12345), nextI
117
89
  # The scene, built bottom up as master builds it: each group's children first, then the
118
90
  # groups under the root. Ids: the root 0, the groups 1 to 10, the leaves from 11.
119
91
  fun build(n: Int, sc: Bench) -> EStage[Bod] =
120
- kids := Slice[Slice[ETree[Bod]]]()
92
+ kids := Slice[Slice[ETree[Actor[Bod]]]]()
121
93
  for g := range 10
122
- kids.push(Slice[ETree[Bod]]())
94
+ kids.push(Slice[ETree[Actor[Bod]]]())
123
95
  for i := range n - 11
124
96
  kids.at(i % 10).push(newLeaf(sc.rng, 11 + i))
125
97
  sc.live.push(11 + i)
126
- groups := Slice[ETree[Bod]]()
98
+ groups := Slice[ETree[Actor[Bod]]]()
127
99
  for g := range 10
128
100
  gb := group(g + 1, Float(100 + 300 * {g % 5}), Float(100 + 300 * {g / 5}), 1.0 + 0.05 * Float(g), 0.1 * Float(g))
129
- empty: ETree[Bod] := EEmpty
101
+ empty: ETree[Actor[Bod]] := EEmpty
130
102
  groups.push(ENode(value: gb, firstChild: etree.etreeChainFrom(kids.at(g), 0), nextSibling: empty))
131
- empty: ETree[Bod] := EEmpty
103
+ empty: ETree[Actor[Bod]] := EEmpty
132
104
  root := ENode(value: group(0, 0.0, 0.0, 1.0, 0.0), firstChild: etree.etreeChainFrom(groups, 0), nextSibling: empty)
133
105
  EStage(root: root, camX: 0.0, camY: 0.0, camScale: 1.0)
134
106
 
135
107
  # Every node's position, in preorder, folded into one number.
136
- fun hashTree(t: ETree[Bod], h: Int) -> Int =
108
+ fun hashTree(t: ETree[Actor[Bod]], h: Int) -> Int =
137
109
  t.fold(h, |r0, b|
138
110
  r := {r0 * 31 + Int(b.x * 1000.0)} % 1000000007
139
111
  {r * 31 + Int(b.y * 1000.0)} % 1000000007
@@ -199,11 +171,11 @@ fun churnsKept(stage: EStage[Bod], sc: Bench, ctx: ECtx[Bod], dt: Float, k: Int,
199
171
 
200
172
  # EStage's walk with no commands and the root's context for every body: no parent's world
201
173
  # transform is computed.
202
- fun stepFlat(t: ETree[Bod], ctx: ECtx[Bod], dt: Float) -> ETree[Bod] = match t
174
+ fun stepFlat(t: ETree[Actor[Bod]], ctx: ECtx[Bod], dt: Float) -> ETree[Actor[Bod]] = match t
203
175
  EEmpty => t
204
176
  ENode(b, k, n) =>
205
- nb := b.step(ctx, dt)
177
+ nb := b.kind.step(b, ctx, dt)
206
- if nb.gone()
178
+ if nb.dead
207
179
  stepFlat(n, ctx, dt)
208
180
  else
209
181
  k2 := if k.isEmpty() then k else stepFlat(k, ctx, dt)
@@ -211,14 +183,14 @@ fun stepFlat(t: ETree[Bod], ctx: ECtx[Bod], dt: Float) -> ETree[Bod] = match t
211
183
 
212
184
  # EStage's walk with no commands, every body's world transform computed (and checked, so
213
185
  # it is used).
214
- fun stepEager(t: ETree[Bod], ctx: ECtx[Bod], dt: Float) -> ETree[Bod] = match t
186
+ fun stepEager(t: ETree[Actor[Bod]], ctx: ECtx[Bod], dt: Float) -> ETree[Actor[Bod]] = match t
215
187
  EEmpty => t
216
188
  ENode(b, k, n) =>
217
189
  m := ctx.worldOf(b.local())
218
190
  assert m.e > -1.0e30
219
191
  cc := ctx.under(b.local(), b.opacity())
220
- nb := b.step(ctx, dt)
192
+ nb := b.kind.step(b, ctx, dt)
221
- if nb.gone()
193
+ if nb.dead
222
194
  stepEager(n, ctx, dt)
223
195
  else
224
196
  k2 := if k.isEmpty() then k else stepEager(k, cc, dt)
docs/plans/2026-11-09-actor-trait.md ADDED
@@ -0,0 +1,296 @@
1
+ # Design: traits, and the scene tree on an `Actor` trait
2
+
3
+ Date: 2026-11-09. Branch: `simpler-language`. Status: design, not started.
4
+
5
+ ## Why
6
+
7
+ std/game_enum_tree is now generic over `Actor[K]`: one struct of shared fields (id,
8
+ transform, size, colour, visible, dead) plus the game's `kind: K`, and the kind dispatches
9
+ `step`, `paint` and `hit` with one `match` over every kind. Two problems:
10
+
11
+ - Every kind's behaviour sits in one place, the `Kind` enum's three big matches.
12
+ - `Actor` carries fields that most kinds don't use: a label has no size, a button never
13
+ dies, a star is never hidden.
14
+
15
+ Wanted: each kind is its own struct with only its own fields and its own methods, the
16
+ stage holds a tree of any mix of them, and there is no type parameter on the stage.
17
+
18
+ Option chosen: add traits back to the language, with required and optional (default)
19
+ methods and trait objects. Rejected:
20
+
21
+ - Struct embedding / inheritance, as master has: it drags the fat base struct into every
22
+ kind.
23
+ - A per-kind struct behind a wrapping enum (`| OrbK(o: Orb)`): too much ceremony.
24
+ - Methods on enum variants: the kinds' code still lives in one enum.
25
+
26
+ Out of scope: a tree-literal syntax. Trait bounds are in (see below), but the stage
27
+ doesn't use them: it holds `ETree[Actor]`, a mix of kinds.
28
+
29
+ ## The language feature
30
+
31
+ ### Declaring a trait
32
+
33
+ ```plum
34
+ trait Actor =
35
+ # required: no body
36
+ fun key(self) -> Int
37
+ fun place(self) -> Place
38
+
39
+ # optional: a body is the default
40
+ fun step(self, ctx: ECtx, dt: Float) -> Self = self
41
+ fun paint(self, io: Io, m: Affine, alpha: Float) = ()
42
+ fun hit(self, p: Vec2) -> Bool = false
43
+ fun shown(self) -> Bool = true
44
+ fun gone(self) -> Bool = false
45
+ fun opacity(self) -> Float = 1.0
46
+ ```
47
+
48
+ - A trait is a list of method signatures. A method with no body is required; a method
49
+ with a body is optional, and the body is its default.
50
+ - A default body may call the trait's other methods on `self` (`self.key()`), and nothing
51
+ else of `self`. A trait has no fields.
52
+ - `Self` in a signature is the implementing type.
53
+
54
+ ### Implementing a trait
55
+
56
+ ```plum
57
+ struct Label(id: Int, at: Place, text: Str, size: Float, color: Color) is Actor =
58
+ fun key(self) -> Int = self.id
59
+ fun place(self) -> Place = self.at
60
+ fun paint(self, io: Io, m: Affine, alpha: Float) =
61
+ paintText(io, m, self.text, 0.0, 0.0, self.size, self.color.withAlpha(alpha))
62
+ ```
63
+
64
+ - `is Actor` (or `is A, B`) after a struct's or enum's fields. The type must define every
65
+ required method, with the trait's signature with `Self` replaced by the type. It may
66
+ define any optional method; the others take the default.
67
+ - A method the type defines that has the name of a trait method but a different signature
68
+ is an error, so a typo can't silently fall back to the default.
69
+ - An enum can implement a trait too, with its usual `match self` bodies.
70
+ - A type implements a trait only where it is declared. There are no implementations
71
+ added from outside the type (that may come later).
72
+
73
+ ### Trait objects
74
+
75
+ - A trait's name used as a type (`Actor`, `ETree[Actor]`, `Slice[Actor]`, `fn(Actor) ->
76
+ Actor`) is a value of any type that implements it. A value of an implementing type is
77
+ accepted wherever the trait is expected (`etree.leaf(label)` into an `ETree[Actor]`),
78
+ with no cast.
79
+ - On a trait object you can call the trait's methods and nothing else. A call goes to the
80
+ value's own type: its method, or the trait's default.
81
+ - A method returning `Self`, called on a trait object, returns a trait object (`step`
82
+ returns an `Actor`). Called on a concrete type, it returns that type (`orb.step(..)` is
83
+ an `Orb`).
84
+ - `==` on trait objects: same type and equal values, or false. It is used by
85
+ `ETree.filter` and `replace` to keep an untouched subtree as it was.
86
+
87
+ ### Getting the concrete type back
88
+
89
+ ```plum
90
+ match a
91
+ Orb as o => Orb(..o, vx: 0.0) # `a` is an Orb: `o` is it, typed `Orb`
92
+ _ => a
93
+ ```
94
+
95
+ - A pattern `Type as name` on a trait object matches when the value is that type, and
96
+ binds it with the concrete type. That is the only downcast. The stage's own walk never
97
+ downcasts; `EStage` offers `updateAs` and `findAs` (below) to game code, which wrap it,
98
+ so game code rarely writes the pattern.
99
+ - Open: the exact pattern spelling. `Orb as o` is the proposal. `Orb(..) as o` would say
100
+ "any fields". Decide when writing the parser change, by what the pattern grammar takes
101
+ without ambiguity.
102
+
103
+ ### Traits with type parameters
104
+
105
+ ```plum
106
+ trait Reducer[M] =
107
+ fun update(self, msg: M) -> Self # required
108
+ fun handle(self, io: Io, msg: M) = () # optional: effects, after update
109
+
110
+ struct RunState(score: Int, lives: Int) is Reducer[Msg] =
111
+ fun update(self, msg: Msg) -> RunState = ...
112
+ ```
113
+
114
+ - A trait may take type parameters, like a struct: `trait Reducer[M]`. Inside it, `M` is
115
+ used like any type parameter.
116
+ - `is Reducer[Msg]` names the arguments. A type may implement the same trait with
117
+ different arguments (`is Reducer[Msg], Reducer[Key]`) only if every method still has a
118
+ distinct signature; otherwise it is an error.
119
+ - `Reducer[Msg]` as a type is a trait object, as for a trait with no parameters. Two
120
+ trait objects are the same type when their arguments are equal.
121
+ - A generic function can take a trait object whose arguments are its own parameters:
122
+ `fun replay[M](r: Reducer[M], msgs: Slice[M]) -> Reducer[M]`.
123
+ - Codegen: an implementer set per (trait, arguments), so dispatch on `Reducer[Msg]`
124
+ branches only over the types that implement `Reducer[Msg]`.
125
+
126
+ ### Trait bounds
127
+
128
+ ```plum
129
+ struct Store[S: Reducer[M], M](state: S, queue: Slice[M]) =
130
+ fun dispatch(self, msg: M) -> Store[S, M] =
131
+ self.queue.push(msg)
132
+ Store(..self, state: self.state.update(msg)) # update returns S
133
+
134
+ fun replay[S: Reducer[M], M](s: S, msgs: Slice[M]) -> S = msgs.fold(s, |a, m| a.update(m))
135
+
136
+ score := store.state.score # S is RunState here: no downcast
137
+ ```
138
+
139
+ - `[T: Tr]` or `[T: Tr[X]]` on a struct, enum, function or method: `T` must implement
140
+ the trait. `[T: A + B]` for several. A bound's arguments may name the other parameters
141
+ (`S: Reducer[M]`).
142
+ - In the body, a `T` value can call the trait's methods; a method returning `Self` returns
143
+ `T`.
144
+ - At a use, the checker infers `T` as now and checks it implements the bound; error if
145
+ not, naming the missing trait.
146
+ - Codegen: generics are compiled once per set of type arguments, so a call on a bounded
147
+ `T` is a direct call to that type's method or default. No dispatch, and FBIP is as for
148
+ any concrete call.
149
+ - Bounds and trait objects are separate: `ETree[Actor]` holds a mix; `Store[RunState, Msg]`
150
+ holds exactly a `RunState`.
151
+ - `std/game/Store.plum` gives `Reducer[M]` and `Store[S, M]` (`dispatch`, then `flush(io)`
152
+ calling `handle` for each queued message, in order). Games may keep their own update
153
+ loop; orb_run and orb_run_tree move to `Store` in task 7.
154
+
155
+ ### Code generation
156
+
157
+ - Each trait object is a pointer to the value plus the value's type tag; the tag is in
158
+ the object header if the runtime already has one. Decide when reading the backend.
159
+ - A call on a trait object is a branch on the type tag over the types that implement the
160
+ trait in the program, each arm calling that type's method or the default: whole-program
161
+ dispatch, the same code a `match` makes, with no method tables. The program is
162
+ compiled whole, so the set of implementers is known. If that set is large, a table of
163
+ function pointers per trait is the fallback. Measure both on the scene-tree benchmark
164
+ before choosing.
165
+ - A call on a concrete type is a direct call, as today.
166
+ - Defaults are compiled once per implementing type that doesn't override them (so
167
+ `self.key()` inside a default is a direct call).
168
+
169
+ ### Uniqueness and in-place reuse (FBIP)
170
+
171
+ - A trait object owns its value like any other boxed value: when nothing else holds it, a
172
+ spread of the concrete value (`Orb(..self, ..)` inside `Orb.step`) writes into the old
173
+ cell.
174
+ - The stage's walk (`estep`) gets an `Actor`, calls `step` and rebuilds the node; the
175
+ returned `Actor` is the same type as the one it got. The reuse analysis
176
+ (compiler/core/src/uniqueness.rs and its neighbours) must see through the dispatch so
177
+ that the `Orb` arm's spread still reuses the cell. Check this with the benchmark under
178
+ default and `--no-fbip`: the `step` workload must not start allocating per node.
179
+ - Downcast patterns (`Orb as o`) move the value into `o`, so `Orb(..o, ..)` can still
180
+ reuse it.
181
+
182
+ ### Checker and errors
183
+
184
+ New errors, each with a test:
185
+ - missing required method;
186
+ - method signature differs from the trait's;
187
+ - `Self` used outside a trait;
188
+ - calling a method that isn't in the trait on a trait object;
189
+ - a type used as `Actor` that doesn't implement it;
190
+ - a downcast pattern naming a type that doesn't implement the trait;
191
+ - a duplicate `is` entry.
192
+
193
+ ## The scene tree on it
194
+
195
+ ```plum
196
+ # std/game_enum_tree/Place.plum
197
+ struct Place(x: Float, y: Float, scaleX: Float = 1.0, scaleY: Float = 1.0,
198
+ rotation: Float = 0.0, originX: Float = 0.0, originY: Float = 0.0) =
199
+ fun local(self) -> Affine
200
+ fun moveTo(self, x: Float, y: Float) -> Place
201
+ fun moveBy(self, dx: Float, dy: Float) -> Place
202
+ fun rotateTo(self, r: Float) -> Place
203
+ fun scaleTo(self, sx: Float, sy: Float) -> Place
204
+
205
+ fun at(x: Float, y: Float) -> Place
206
+
207
+ # std/game_enum_tree/Actor.plum: the trait above
208
+
209
+ # std/game_enum_tree/EStage.plum
210
+ struct EStage(root: ETree[Actor], camX: Float, camY: Float, camScale: Float) =
211
+ # unchanged: of, withRoot, pan, zoom, count, find, add, update, kill, step, apply,
212
+ # flatten, hit, hitId, draw
213
+ fun updateAs[T](self, id: Int, f: fn(T) -> T) -> EStage # f runs only if `id` is a T
214
+ fun findAs[T](self, id: Int) -> Option[T]
215
+ ```
216
+
217
+ - `ETree[T]` is unchanged and stays a plain generic tree.
218
+ - `ECtx` and `ECmd` lose their type parameter: `ESpawn(parent: Int, node: ETree[Actor])`.
219
+ - The stage uses only the trait: `key`, `place().local()`, `opacity`, `shown`, `gone`,
220
+ `step`, `paint`, `hit`. Behaviour stays as it is now: command order, the bitset `EWalk`,
221
+ dead actors dropped with their subtree, hidden actors still stepped, draw and hit order.
222
+ - `updateAs` and `findAs` need a generic used only to downcast (`T` appears in no
223
+ argument other than `f`). If the checker can't infer `T` from `f`, it is written
224
+ `stage.updateAs[Orb](..)`.
225
+ - std gives two ready-made actors: `Group(id, at)`, which paints nothing, and
226
+ `Box(id, at, w, h, color)`, which paints and hits its box.
227
+ - Box helpers for kinds: `boxHit(w, h, p)` and `boxPaint(io, m, alpha, w, h, c)`.
228
+ - `EBox.plum` and the `Actor[K]` struct go away.
229
+
230
+ ## One scene system
231
+
232
+ The user wants one scene system, not three (immediate `std/game/scene`, the stage, the
233
+ tree). After this work:
234
+
235
+ - `ETree` moves to `std/collections/functional/FRoseTree.plum` as `FRoseTree[T]`, a plain
236
+ generic collection.
237
+ - `std/game/scene` is the retained scene on `FRoseTree[Actor]`. The names drop the `E`:
238
+ `Scene` (was `EStage`), `Actor`, `Place`, `Ctx`, `Cmd`, `Spawn`, `Kill`, `Drawn`,
239
+ `Group`, `Box`.
240
+ - Deleted: std/game_enum_tree, and the immediate-mode `SceneNode[M]` with `Clickable`
241
+ and `msgOf`.
242
+ - `std/game/ui.plum` becomes actors (its widgets are `is Actor`; a click is found with
243
+ `Scene.hitId`, as the port's button does now).
244
+ - Ported to the new scene: examples/games/orb_run.plum (orb_run_tree.plum becomes it,
245
+ after a last headless comparison of the two), examples/games/kids/balloon_pop.plum,
246
+ the web-test stress fixtures, docs/game.md.
247
+ - Compiler: the scene-tree fusion that fuses `SceneNode` away (compiler/core/src/drive.rs,
248
+ wasm-codegen's fusion_alloc_test, the LSP's references) is removed or retargeted, by
249
+ what it still buys on the retained tree.
250
+ - benchmarks/scene_trees: one branch entry, the new scene.
251
+
252
+ ## The port
253
+
254
+ - examples/games/orb_run_tree.plum: the `Kind` enum becomes structs (`Star`, `Orb`,
255
+ `Mine`, `Ship`, `Icon`, `Label`, `Title`, `Panel`, `Button`), each `is Actor` with only
256
+ its fields and the methods it overrides. The backdrop is a std `Box`; the layers and the
257
+ root are `Group`s.
258
+ - `State` uses `updateAs` and `findAs` where it reads or changes one kind's own fields
259
+ (the ship's steering and hurt time, a label's text, the button's look, orbs and mines
260
+ moved or stilled).
261
+ - Same tests, and the same headless check against orb_run.plum: identical positions,
262
+ score, lives and game over across seeds.
263
+ - benchmarks/scene_trees/game_enum_tree.plum: `Bod` becomes a struct `is Actor`. It must
264
+ print the same checksums in every mode; compare its timings with the `Actor[K]` version
265
+ and report them.
266
+
267
+ ## Tasks
268
+
269
+ 1. Parser and AST: `trait` declarations (with type parameters), `is A, B[X]` on structs
270
+ and enums, `Self`, and the downcast pattern.
271
+ 2. Checker: trait conformance, trait bounds, trait objects as types, coercion of an implementer to the
272
+ trait, method calls on trait objects, `Self`, the downcast pattern, and the errors
273
+ above.
274
+ 3. Codegen: the trait object representation, dispatch over tag branches (and the table
275
+ fallback if measured better), defaults compiled per implementer, `==`.
276
+ 4. Uniqueness and FBIP through dispatch and downcasts, with tests that show reuse.
277
+ 5. Docs: docs/language.md's section on traits; examples/traits.plum. std/game/Store.plum
278
+ (`Reducer[M]`, `Store[S, M]`) with tests.
279
+ 6. std/game_enum_tree on the trait: `Place`, `Actor`, `Group`, `Box`, `ECtx`, `ECmd`,
280
+ `EStage` (with `updateAs` and `findAs`), with the tests ported.
281
+ 7. The port of orb_run_tree.plum and the benchmark, with the headless comparison.
282
+ 8. One scene system: the new scene becomes `std/game/scene`; ui.plum, orb_run,
283
+ balloon_pop, the web-test fixtures and docs/game.md move to it; `SceneNode`, its
284
+ fusion, and std/game_enum_tree are deleted.
285
+
286
+ Tasks 1 to 4 are compiler work. Agree them with the session porting master's changes
287
+ (plum-63) before starting, since it edits the parser and checker.
288
+
289
+ Each task ends with compiler/scripts/test-all.sh at `ALL PASSED`.
290
+
291
+ ## Open questions
292
+
293
+ - The downcast pattern's spelling (`Orb as o`).
294
+ - Tag-branch dispatch or method tables (decide by measuring).
295
+ - Whether `key` and `place` can be derived from fields named `id` and `at`, so a kind
296
+ only writes the methods it overrides. Not in the first cut.
examples/games/orb_run_tree.plum ADDED
@@ -0,0 +1,898 @@
1
+ # Orb Run on the persistent scene tree (`plum run examples/games/orb_run_tree.plum`): the
2
+ # same game as examples/games/orb_run.plum. Steer the ship with the arrow keys or WASD,
3
+ # collect the drifting orbs and avoid the mines. Three lives; Enter, R or the "Again"
4
+ # button restarts after the game is over.
5
+ #
6
+ # orb_run.plum keeps the game in plain lists (`orbs: List[Orb]`) and builds a fresh
7
+ # `SceneNode` picture of it every frame. This version keeps the game *in* the scene: an
8
+ # `EStage[Kind]` from std/game_enum_tree, a tree of actors that lives from frame to frame.
9
+ # Every body is an `Actor[Kind]`: the actor holds what every body has (its id, its place
10
+ # in its parent, its colour, whether it is shown), and `Kind` is what this game adds, one
11
+ # variant per kind of body (`Ship`, `Orb`, `Mine`, `Star`, a `Label`, the `Button`, ..),
12
+ # each with its behaviour (`step`), its drawing (`paint`) and its hit test (`hit`). The
13
+ # stage's `step` walks the tree once a tick and gives every actor its next version;
14
+ # `draw` and `hit` walk it again with the parents' transforms and alphas multiplied down.
15
+ #
16
+ # 0 root (the camera that fits the arena on screen)
17
+ # ├─ 1 backdrop
18
+ # ├─ 2 stars ─ 20..59
19
+ # ├─ 3 mines ─ 200..
20
+ # ├─ 4 orbs ─ 100..102
21
+ # ├─ 5 ship
22
+ # ├─ 6 hud ─ 8 score, 9 best, 300..302 lives
23
+ # └─ 7 panel (hidden while playing) ─ 13 dim, 11 title, 12 prompt, 14 "Again"
24
+ #
25
+ # What is between bodies (an orb is touched, a mine hits the ship, the score and the
26
+ # lives) stays in `State`, which looks actors up by id after the step and changes them
27
+ # with `EStage.update`, `updateKind`, `add` and `kill`. The stage is a value like the rest
28
+ # of `State`: a kept old state still has its old tree.
29
+ #
30
+ # Differences from orb_run.plum: the game-over panel fades by multiplying its opacity
31
+ # into each of its children instead of drawing through a render-target filter (so
32
+ # overlapping children are each translucent), and the ship's hurt flash, the title's
33
+ # pulse and the panel's fade keep their own clocks in their kinds.
34
+ module orb_run_tree
35
+ import std/Str
36
+ import std/Int
37
+ import std/Float
38
+ import std/Bool
39
+ import std/Slice
40
+ import std/Option
41
+ import std/List
42
+ import std/math
43
+ import std/Random
44
+ import std/game/Vec2
45
+ import std/game/Affine
46
+ import std/game/Color
47
+ import std/game/gfx
48
+ import std/game/audio
49
+ import std/game/Anim
50
+ import std/game/ui
51
+ import std/game/input
52
+ import std/game_enum_tree/ETree
53
+ import std/game_enum_tree/Actor
54
+ import std/game_enum_tree/ECtx
55
+ import std/game_enum_tree/EStage
56
+ import std/Io
57
+
58
+ ArenaW = 800.0
59
+ ArenaH = 600.0
60
+ ShipRadius = 10.0
61
+ OrbRadius = 10.0
62
+ MineRadius = 11.0
63
+ Thrust = 900.0
64
+ Drag = 2.2
65
+ OrbCount = 3
66
+ StartLives = 3
67
+ HurtTime = 1.5
68
+ OrbPoints = 10
69
+ SheetCell = 16.0
70
+ SpriteSize = 48.0
71
+ SpriteHalf = 24.0
72
+ StarCount = 40
73
+
74
+ # Actor ids: the tree's fixed nodes, then the ranges. Orb `i` is `OrbId + i`, mine `i` is
75
+ # `MineId + i`, star `i` is `StarId + i` and life icon `i` is `LifeId + i`.
76
+ RootId = 0
77
+ BackId = 1
78
+ StarLayer = 2
79
+ MineLayer = 3
80
+ OrbLayer = 4
81
+ ShipId = 5
82
+ HudId = 6
83
+ PanelId = 7
84
+ ScoreId = 8
85
+ BestId = 9
86
+ TitleId = 11
87
+ PromptId = 12
88
+ DimId = 13
89
+ RestartId = 14
90
+ StarId = 20
91
+ OrbId = 100
92
+ MineId = 200
93
+ LifeId = 300
94
+
95
+ # A position and velocity: what a spawn returns and what drifters are bounced with.
96
+ struct Motion(x: Float, y: Float, vx: Float, vy: Float)
97
+
98
+ # A random spot and the generator to continue from.
99
+ struct Spawned(at: Motion, rng: Random)
100
+
101
+ # --- small pure helpers (as in orb_run.plum) ---
102
+
103
+ # Which of `count` animation frames is showing after `clock` seconds at `fps` frames per second.
104
+ fun frameOf(clock: Float, count: Int, fps: Float) -> Int =
105
+ Int(clock * fps) % count
106
+
107
+ fun overlaps(ax: Float, ay: Float, ra: Float, bx: Float, by: Float, rb: Float) -> Bool =
108
+ math.hypot(ax - bx, ay - by) < ra + rb
109
+
110
+ # A random spot at least `gap` away from (ax, ay), drifting at up to `speed`.
111
+ fun spawn(rng: Random, ax: Float, ay: Float, gap: Float, speed: Float) -> Spawned =
112
+ spot := findSpot(rng, ax, ay, gap, 20)
113
+ dh := spot.rng.nextFloat()
114
+ dp := dh.rng.nextFloat()
115
+ heading := dh.value * Float.Tau
116
+ pace := speed * {0.4 + 0.6 * dp.value}
117
+ Spawned(at: Motion(x: spot.at.x, y: spot.at.y, vx: math.cos(heading) * pace, vy: math.sin(heading) * pace), rng: dp.rng)
118
+
119
+ # A random spot at least `gap` away from (ax, ay); after `tries` draws the last one stands.
120
+ fun findSpot(rng: Random, ax: Float, ay: Float, gap: Float, tries: Int) -> Spawned =
121
+ margin := 30.0
122
+ dx := rng.nextFloat()
123
+ dy := dx.rng.nextFloat()
124
+ x := margin + dx.value * {ArenaW - 2.0 * margin}
125
+ y := margin + dy.value * {ArenaH - 2.0 * margin}
126
+ if tries <= 1 || math.hypot(x - ax, y - ay) >= gap
127
+ Spawned(at: Motion(x: x, y: y, vx: 0.0, vy: 0.0), rng: dy.rng)
128
+ else
129
+ findSpot(dy.rng, ax, ay, gap, tries - 1)
130
+
131
+ # `b` moved for `dt` seconds and bounced off the arena walls.
132
+ fun driftOf(b: Motion, r: Float, dt: Float) -> Motion =
133
+ x0 := b.x + b.vx * dt
134
+ y0 := b.y + b.vy * dt
135
+ x := x0.max(r).min(ArenaW - r)
136
+ y := y0.max(r).min(ArenaH - r)
137
+ Motion(x: x, y: y, vx: if x != x0 then 0.0 - b.vx else b.vx, vy: if y != y0 then 0.0 - b.vy else b.vy)
138
+
139
+ # How many mines are out: more as the score grows.
140
+ fun mineCount(score: Int) -> Int =
141
+ {3 + score / 50}.min(8)
142
+
143
+ # The hurt flash: the ship shrinks and recovers every 0.1 s (the scale returns to 1 each lap).
144
+ fun hitFlash() -> Anim =
145
+ Forever(anim: Seq(steps: [ScaleTo(sx: 0.4, sy: 0.4, secs: 0.05), ScaleTo(sx: 2.5, sy: 2.5, secs: 0.05)]))
146
+
147
+ fun flashPose(t: Float) -> AnimPose =
148
+ Anim.at(hitFlash(), t)
149
+
150
+ # The game-over title: grows to 1.3x, then pulses between 1.17x and 1.3x.
151
+ fun titleAnim() -> Anim =
152
+ Seq(
153
+ steps: [
154
+ ScaleTo(sx: 1.3, sy: 1.3, secs: 0.3),
155
+ Forever(anim: Seq(steps: [ScaleTo(sx: 0.9, sy: 0.9, secs: 0.5), ScaleTo(sx: 1.0 / 0.9, sy: 1.0 / 0.9, secs: 0.5)]))
156
+ ]
157
+ )
158
+
159
+ fun titlePose(t: Float) -> AnimPose =
160
+ Anim.at(titleAnim(), t)
161
+
162
+ # The zoom that fits the arena into a `sw` by `sh` screen, and where its corner lands.
163
+ fun fitZoom(sw: Float, sh: Float) -> Float =
164
+ {sw / ArenaW}.min(sh / ArenaH)
165
+
166
+ fun fitX(sw: Float, sh: Float) -> Float =
167
+ {sw - fitZoom(sw, sh) * ArenaW} / 2.0
168
+
169
+ fun fitY(sw: Float, sh: Float) -> Float =
170
+ {sh - fitZoom(sw, sh) * ArenaH} / 2.0
171
+
172
+ # The root actor placed as the camera for a `sw` by `sh` screen.
173
+ fun fitted(a: Actor[Kind], sw: Float, sh: Float) -> Actor[Kind] =
174
+ z := fitZoom(sw, sh)
175
+ a.at(fitX(sw, sh), fitY(sw, sh)).scaleTo(z, z)
176
+
177
+ # --- painting helpers: an actor paints in its own coordinates, seen through `m` ---
178
+
179
+ # A `size` square cell (col, row) of the sprite sheet with its top-left at (x, y).
180
+ fun paintCell(io: Io, m: Affine, alpha: Float, sheet: Texture, x: Float, y: Float, size: Float, col: Int, row: Int) =
181
+ sw := size * m.scaleX()
182
+ sh := size * m.scaleY()
183
+ c := m.apply(Vec2(x: x + size / 2.0, y: y + size / 2.0))
184
+ gfx.drawTextureEx(
185
+ io, sheet.id, Float(col) * SheetCell, Float(row) * SheetCell, SheetCell, SheetCell,
186
+ c.x - sw / 2.0, c.y - sh / 2.0, sw, sh, m.rotation(), false, Color.White.withAlpha(alpha))
187
+
188
+ fun paintCircle(io: Io, m: Affine, x: Float, y: Float, r: Float, c: Color) =
189
+ p := m.apply(Vec2(x: x, y: y))
190
+ gfx.drawCircle(io, p.x, p.y, r * m.scaleX(), c)
191
+
192
+ fun paintText(io: Io, m: Affine, text: Str, x: Float, y: Float, size: Float, c: Color) =
193
+ p := m.apply(Vec2(x: x, y: y))
194
+ gfx.drawText(io, text, p.x, p.y, size * m.scaleY(), c)
195
+
196
+ # --- the kinds ---
197
+
198
+ # What this game adds to an actor, one variant per kind of body. The actor has the
199
+ # position, rotation, scale, colour and visibility; a variant has the rest of the kind's
200
+ # state. Orbs, mines and the ship are centred on their actor's (x, y) and turn about it.
201
+ enum Kind =
202
+ # a group, or a plain rectangle of the actor's size and colour
203
+ | Box
204
+ | Star(i: Int, clock: Float)
205
+ | Orb(vx: Float, vy: Float, phase: Float, clock: Float, sheet: Texture)
206
+ | Mine(vx: Float, vy: Float, spin: Float, clock: Float, sheet: Texture)
207
+ # `ax`, `ay`: the steering axes for the next step, set by the game before it
208
+ | Ship(vx: Float, vy: Float, ax: Float, ay: Float, hurt: Float, hurtAge: Float, clock: Float, sheet: Texture)
209
+ | Icon(size: Float, col: Int, row: Int, sheet: Texture)
210
+ | Label(text: Str, size: Float)
211
+ # the game-over title: its actor's scale is `titlePose` of its age
212
+ | Title(age: Float)
213
+ # the game-over panel: its actor's alpha fades in over half a second of its age, and so
214
+ # do its children
215
+ | Panel(age: Float)
216
+ # `look` is 0 idle, 1 hovered, 2 pressed (from the `UiState`)
217
+ | Button(label: Str, look: Int)
218
+
219
+ # --- what the stage asks of a kind ---
220
+
221
+ fun step(self, a: Actor[Kind], ctx: ECtx[Kind], dt: Float) -> Actor[Kind] = match self
222
+ Star(i, c) => a.withKind(Star(i: i, clock: c + dt))
223
+ Orb(vx, vy, ph, c, sh) =>
224
+ m := driftOf(Motion(x: a.x, y: a.y, vx: vx, vy: vy), OrbRadius, dt)
225
+ Actor(..a, x: m.x, y: m.y, kind: Orb(vx: m.vx, vy: m.vy, phase: ph, clock: c + dt, sheet: sh))
226
+ Mine(vx, vy, sp, c, sh) =>
227
+ m := driftOf(Motion(x: a.x, y: a.y, vx: vx, vy: vy), MineRadius, dt)
228
+ Actor(..a, x: m.x, y: m.y, rotation: a.rotation + sp * dt, kind: Mine(vx: m.vx, vy: m.vy, spin: sp, clock: c + dt, sheet: sh))
229
+ Ship(vx, vy, ax, ay, h, ha, c, sh) =>
230
+ if a.visible then shipStep(a, vx, vy, ax, ay, h, ha, c, sh, dt) else a
231
+ Title(age) =>
232
+ p := titlePose(age + dt)
233
+ Actor(..a, scaleX: p.scaleX, scaleY: p.scaleY, kind: Title(age: age + dt))
234
+ Panel(age) => Actor(..a, color: a.color.withAlpha({{age + dt} * 2.0}.min(1.0)), kind: Panel(age: age + dt))
235
+ _ => a
236
+
237
+ fun paint(self, a: Actor[Kind], io: Io, m: Affine, alpha: Float) = match self
238
+ Box => a.paintBox(io, m, alpha)
239
+ Star(i, c) =>
240
+ twinkle := 0.25 + 0.2 * math.sin(c * 2.0 + Float(i))
241
+ paintCircle(io, m, 0.0, 0.0, 1.0 + Float(i % 3) * 0.5, Color(r: 0.7, g: 0.8, b: 1.0, a: twinkle * alpha))
242
+ Orb(_, _, ph, c, sh) =>
243
+ # the glow is drawn additively, then the sprite on top
244
+ gfx.blendMode(io, Blend.Add)
245
+ paintCircle(io, m, 0.0, 0.0, 26.0, Color(r: 0.35, g: 0.22, b: 0.0, a: 0.5 * alpha))
246
+ paintCircle(io, m, 0.0, 0.0, 17.0, Color(r: 0.6, g: 0.4, b: 0.05, a: 0.5 * alpha))
247
+ gfx.blendMode(io, Blend.Normal)
248
+ paintCell(io, m, alpha, sh, 0.0 - SpriteHalf, 0.0 - SpriteHalf, SpriteSize, frameOf(c + ph, 4, 8.0), 1)
249
+ Mine(_, _, _, c, sh) =>
250
+ paintCell(io, m, alpha, sh, 0.0 - SpriteHalf, 0.0 - SpriteHalf, SpriteSize, frameOf(c, 4, 4.0), 2)
251
+ Ship(_, _, _, _, _, _, c, sh) =>
252
+ if !self.blinking()
253
+ paintCircle(io, m, 0.0, 0.0, 17.0, Color(r: 0.4, g: 0.8, b: 1.0, a: 0.12 * alpha))
254
+ paintCell(io, m, alpha, sh, 0.0 - SpriteHalf, 0.0 - SpriteHalf, SpriteSize, frameOf(c, 4, 14.0), 0)
255
+ Icon(s, col, row, sh) => paintCell(io, m, alpha, sh, 0.0, 0.0, s, col, row)
256
+ Label(t, s) => paintText(io, m, t, 0.0, 0.0, s, a.color.withAlpha(alpha))
257
+ Title(_) => paintText(io, m, "Game over", -100.0, -24.0, 48.0, a.color.withAlpha(alpha))
258
+ Panel(_) => 0
259
+ Button(l, k) =>
260
+ actor.boxPaint(io, m, alpha, a.width, a.height, buttonColor(k))
261
+ paintText(io, m, l, 4.0, 4.0, a.height * 0.5, Color.White.withAlpha(alpha))
262
+
263
+ # Only the button can be clicked.
264
+ fun hit(self, a: Actor[Kind], p: Vec2) -> Bool = match self
265
+ Button(_, _) => a.hitBox(p)
266
+ _ => false
267
+
268
+ # --- what the game asks of a kind ---
269
+
270
+ fun isOrb(self) -> Bool = match self
271
+ Orb(_, _, _, _, _) => true
272
+ _ => false
273
+
274
+ fun isMine(self) -> Bool = match self
275
+ Mine(_, _, _, _, _) => true
276
+ _ => false
277
+
278
+ # The ship's hurt time left (0 for every other kind).
279
+ fun hurtLeft(self) -> Float = match self
280
+ Ship(_, _, _, _, h, _, _, _) => h
281
+ _ => 0.0
282
+
283
+ # The ship blinks off while hurt.
284
+ fun blinking(self) -> Bool = match self
285
+ Ship(_, _, _, _, h, ha, _, _) => h > 0.0 && flashPose(ha).scaleX < 0.7
286
+ _ => false
287
+
288
+ fun clockOf(self) -> Float = match self
289
+ Orb(_, _, _, c, _) => c
290
+ Mine(_, _, _, c, _) => c
291
+ Ship(_, _, _, _, _, _, c, _) => c
292
+ Star(_, c) => c
293
+ _ => 0.0
294
+
295
+ # An orb or a mine drifting at (vx, vy).
296
+ fun drifting(self, vx: Float, vy: Float) -> Kind = match self
297
+ Orb(_, _, ph, c, sh) => Orb(vx: vx, vy: vy, phase: ph, clock: c, sheet: sh)
298
+ Mine(_, _, sp, c, sh) => Mine(vx: vx, vy: vy, spin: sp, clock: c, sheet: sh)
299
+ _ => self
300
+
301
+ # An orb or a mine that stops moving and spinning; it still animates.
302
+ fun still(self) -> Kind = match self
303
+ Orb(_, _, ph, c, sh) => Orb(vx: 0.0, vy: 0.0, phase: ph, clock: c, sheet: sh)
304
+ Mine(_, _, _, c, sh) => Mine(vx: 0.0, vy: 0.0, spin: 0.0, clock: c, sheet: sh)
305
+ _ => self
306
+
307
+ # The ship steered by the axes for its next step.
308
+ fun steered(self, ax: Float, ay: Float) -> Kind = match self
309
+ Ship(vx, vy, _, _, h, ha, c, sh) => Ship(vx: vx, vy: vy, ax: ax, ay: ay, hurt: h, hurtAge: ha, clock: c, sheet: sh)
310
+ _ => self
311
+
312
+ # The ship just hit: hurt for `HurtTime`, its flash from the start.
313
+ fun struck(self) -> Kind = match self
314
+ Ship(vx, vy, ax, ay, _, _, c, sh) => Ship(vx: vx, vy: vy, ax: ax, ay: ay, hurt: HurtTime, hurtAge: 0.0, clock: c, sheet: sh)
315
+ _ => self
316
+
317
+ fun relabel(self, t: Str) -> Kind = match self
318
+ Label(_, s) => Label(text: t, size: s)
319
+ _ => self
320
+
321
+ fun looked(self, k: Int) -> Kind = match self
322
+ Button(l, _) => Button(label: l, look: k)
323
+ _ => self
324
+
325
+ # The ship's next actor: it accelerates by the axes, drag slows it and the walls stop it.
326
+ fun shipStep(a: Actor[Kind], vx: Float, vy: Float, ax: Float, ay: Float, hurt: Float, hurtAge: Float, clock: Float, sheet: Texture, dt: Float) -> Actor[Kind] =
327
+ keep := {1.0 - Drag * dt}.max(0.0)
328
+ r := ShipRadius
329
+ vx0 := {vx + ax * Thrust * dt} * keep
330
+ vy0 := {vy + ay * Thrust * dt} * keep
331
+ x0 := a.x + vx0 * dt
332
+ y0 := a.y + vy0 * dt
333
+ x := x0.max(r).min(ArenaW - r)
334
+ y := y0.max(r).min(ArenaH - r)
335
+ nvx := if x != x0 then 0.0 else vx0
336
+ nvy := if y != y0 then 0.0 else vy0
337
+ rot := if nvx * nvx + nvy * nvy > 400.0 then math.atan2(nvx, 0.0 - nvy) else a.rotation
338
+ Actor(
339
+ ..a, x: x, y: y, rotation: rot,
340
+ kind: Ship(vx: nvx, vy: nvy, ax: ax, ay: ay, hurt: {hurt - dt}.max(0.0), hurtAge: hurtAge + dt, clock: clock + dt, sheet: sheet))
341
+
342
+ # An orb or a mine put at `to`, drifting with its velocity.
343
+ fun placed(a: Actor[Kind], to: Motion) -> Actor[Kind] =
344
+ Actor(..a, x: to.x, y: to.y, kind: a.kind.drifting(to.vx, to.vy))
345
+
346
+ # Shown, its clock from 0: the panel (faded out) and the title (unscaled) at game over.
347
+ fun revealed(a: Actor[Kind]) -> Actor[Kind] = match a.kind
348
+ Title(_) => Actor(..a, visible: true, scaleX: 1.0, scaleY: 1.0, kind: Title(age: 0.0))
349
+ Panel(_) => Actor(..a, visible: true, color: a.color.withAlpha(0.0), kind: Panel(age: 0.0))
350
+ _ => a.withVisible(true)
351
+
352
+ fun hidden(a: Actor[Kind]) -> Actor[Kind] = a.withVisible(false)
353
+
354
+ fun buttonColor(look: Int) -> Color =
355
+ if look == 2
356
+ ui.uiPressedColor()
357
+ else if look == 1
358
+ ui.uiHoverColor()
359
+ else
360
+ ui.uiIdleColor()
361
+
362
+ fun buttonLook(u: UiState) -> Int =
363
+ if ui.pressed(u, RestartId)
364
+ 2
365
+ else if ui.hovered(u, RestartId)
366
+ 1
367
+ else
368
+ 0
369
+
370
+ # --- building the tree ---
371
+
372
+ fun box(a: Actor[Kind]) -> ETree[Actor[Kind]] = etree.leaf(a)
373
+
374
+ fun group(id: Int, kids: List[ETree[Actor[Kind]]]) -> ETree[Actor[Kind]] = etree.of(Actor.group(id, 0.0, 0.0, Box), kids)
375
+
376
+ fun label(id: Int, text: Str, x: Float, y: Float, size: Float, c: Color) -> ETree[Actor[Kind]] =
377
+ etree.leaf(Actor.group(id, x, y, Label(text: text, size: size)).tint(c))
378
+
379
+ # Stars `i` and up to `StarCount`, each at its fixed spot.
380
+ fun starNodes(i: Int) -> List[ETree[Actor[Kind]]] =
381
+ if i >= StarCount
382
+ Nil
383
+ else
384
+ star := Actor.group(StarId + i, Float({i * 7919} % 800), Float({i * 104729} % 600), Star(i: i, clock: 0.0))
385
+ Cons(head: etree.leaf(star), tail: starNodes(i + 1))
386
+
387
+ # Life icons `i` and up to `StartLives`, from the right edge going left.
388
+ fun lifeNodes(i: Int, sheet: Texture) -> List[ETree[Actor[Kind]]] =
389
+ if i >= StartLives
390
+ Nil
391
+ else
392
+ icon := Actor.group(LifeId + i, ArenaW - 40.0 - Float(i) * 36.0, 12.0, Icon(size: 32.0, col: 0, row: 0, sheet: sheet))
393
+ Cons(head: etree.leaf(icon), tail: lifeNodes(i + 1, sheet))
394
+
395
+ fun shipActor(x: Float, y: Float, sheet: Texture) -> Actor[Kind] =
396
+ Actor.group(ShipId, x, y, Ship(vx: 0.0, vy: 0.0, ax: 0.0, ay: 0.0, hurt: 0.0, hurtAge: 0.0, clock: 0.0, sheet: sheet))
397
+
398
+ # The stage of a fresh run: no orbs or mines yet (`State.start` adds them).
399
+ fun buildStage(sheet: Texture, sw: Float, sh: Float) -> EStage[Kind] =
400
+ hud := group(HudId, Cons(
401
+ head: label(ScoreId, "Score 0", 16.0, 12.0, 28.0, Color.White),
402
+ tail: Cons(head: label(BestId, "Best 0", 16.0, 44.0, 20.0, Color.Yellow), tail: lifeNodes(0, sheet))))
403
+ panel := etree.of(Actor.group(PanelId, 0.0, 0.0, Panel(age: 0.0)).withVisible(false), [
404
+ box(Actor.rect(DimId, 0.0, 230.0, ArenaW, 170.0, Color(r: 0.0, g: 0.0, b: 0.0, a: 0.6), Box)),
405
+ etree.leaf(Actor.group(TitleId, 400.0, 268.0, Title(age: 0.0)).tint(Color.Red)),
406
+ label(PromptId, "Press Enter to play again", 270.0, 300.0, 24.0, Color.White),
407
+ etree.leaf(Actor.rect(RestartId, 340.0, 342.0, 120.0, 44.0, Color.White, Button(label: "Again", look: 0)))])
408
+ root := etree.of(fitted(Actor.group(RootId, 0.0, 0.0, Box), sw, sh), [
409
+ box(Actor.rect(BackId, 0.0, 0.0, ArenaW, ArenaH, Color.rgb(0.07, 0.08, 0.16), Box)),
410
+ group(StarLayer, starNodes(0)),
411
+ group(MineLayer, Nil),
412
+ group(OrbLayer, Nil),
413
+ etree.leaf(shipActor(ArenaW / 2.0, ArenaH / 2.0, sheet)),
414
+ hud,
415
+ panel])
416
+ EStage(root: root, camX: 0.0, camY: 0.0, camScale: 1.0)
417
+
418
+ # --- the game ---
419
+
420
+ # What can happen to the state.
421
+ enum Msg =
422
+ | Tick(dt: Float, ax: Float, ay: Float)
423
+ | Resize(w: Float, h: Float)
424
+ | Restart(seed: Int)
425
+ | Event(input: InputEvent)
426
+ | RestartClicked
427
+
428
+ # The scene and what is between its actors. `mines` is how many mines are out (the next
429
+ # one's id is `MineId + mines`).
430
+ struct State(
431
+ stage: EStage[Kind],
432
+ rng: Random,
433
+ score: Int,
434
+ best: Int,
435
+ lives: Int,
436
+ over: Bool,
437
+ clock: Float,
438
+ mines: Int,
439
+ ui: UiState,
440
+ held: Held,
441
+ sw: Float,
442
+ sh: Float,
443
+ sheet: Texture
444
+ ) =
445
+
446
+ # A fresh run: the orbs and the mines spread over the arena away from the ship.
447
+ fun start(seed: Int, best: Int, sheet: Texture, sw: Float, sh: Float) -> State =
448
+ State(
449
+ stage: buildStage(sheet, sw, sh),
450
+ rng: Random.seeded(seed),
451
+ score: 0,
452
+ best: best,
453
+ lives: StartLives,
454
+ over: false,
455
+ clock: 0.0,
456
+ mines: 0,
457
+ ui: ui.init(),
458
+ held: Held.none(),
459
+ sw: sw,
460
+ sh: sh,
461
+ sheet: sheet
462
+ ).fillOrbs(0).growMines().showScore()
463
+
464
+ fun update(self, msg: Msg) -> State = match msg
465
+ Tick(dt, ax, ay) => self.tick(dt, ax, ay)
466
+ Resize(w, h) => State(..self, sw: w, sh: h, stage: self.stage.update(RootId, |a| fitted(a, w, h)))
467
+ Restart(seed) => self.restarted(seed)
468
+ Event(input) => self.onInput(input)
469
+ RestartClicked => if self.over then self.restarted(self.rng.nextInt().value) else self
470
+
471
+ # One frame: the stage steps every actor (the ship with this frame's axes), then the
472
+ # game looks at what they did. Once the game is over the actors only animate.
473
+ fun tick(self, dt: Float, ax: Float, ay: Float) -> State =
474
+ stepped := self.stage.updateKind(ShipId, |k| k.steered(ax, ay)).step(ECtx[Kind](), dt)
475
+ moved := State(..self, stage: stepped, clock: self.clock + dt)
476
+ if self.over then moved else moved.collect().growMines().hurt().settle()
477
+
478
+ # The actor with this id (every fixed id is always on the stage).
479
+ fun body(self, id: Int) -> Actor[Kind] = self.stage.find(id).unwrap()
480
+
481
+ fun ship(self) -> Actor[Kind] = self.body(ShipId)
482
+
483
+ # The actors whose kind passes `pick`, in tree order.
484
+ fun bodiesWhere(self, pick: fn(Kind) -> Bool) -> List[Actor[Kind]] =
485
+ self.stage.root.fold(Nil, |acc, a| if pick(a.kind) then Cons(head: a, tail: acc) else acc).reverse()
486
+
487
+ fun touches(self, a: Actor[Kind], radius: Float) -> Bool =
488
+ sh := self.ship()
489
+ overlaps(sh.x, sh.y, ShipRadius, a.x, a.y, radius)
490
+
491
+ # The ship collects every orb it touches.
492
+ fun collect(self) -> State =
493
+ self.bodiesWhere(|k| k.isOrb()).fold(self, |s, o| if s.touches(o, OrbRadius) then s.respawnOrb(o.id) else s)
494
+
495
+ # Scores the orb `id` and puts it at a new random spot.
496
+ fun respawnOrb(self, id: Int) -> State =
497
+ sh := self.ship()
498
+ sp := spawn(self.rng, sh.x, sh.y, 120.0, 40.0)
499
+ State(..self, stage: self.stage.update(id, |a| placed(a, sp.at)), rng: sp.rng, score: self.score + OrbPoints).showScore()
500
+
501
+ # The hud's labels from the score.
502
+ fun showScore(self) -> State =
503
+ score := "Score {self.score}"
504
+ best := "Best {self.best.max(self.score)}"
505
+ State(..self, stage: self.stage.updateKind(ScoreId, |k| k.relabel(score)).updateKind(BestId, |k| k.relabel(best)))
506
+
507
+ # Orbs `i` and up to OrbCount, each at a random spot away from the ship.
508
+ fun fillOrbs(self, i: Int) -> State =
509
+ if i >= OrbCount then self else self.addOrb(i).fillOrbs(i + 1)
510
+
511
+ fun addOrb(self, i: Int) -> State =
512
+ sh := self.ship()
513
+ sp := spawn(self.rng, sh.x, sh.y, 120.0, 40.0)
514
+ orb := Actor.group(OrbId + i, sp.at.x, sp.at.y, Orb(vx: sp.at.vx, vy: sp.at.vy, phase: Float(i) * 0.1, clock: 0.0, sheet: self.sheet))
515
+ State(..self, stage: self.stage.add(OrbLayer, etree.leaf(orb)), rng: sp.rng)
516
+
517
+ # Mines are added (on top of the others) until there are as many as the score asks for.
518
+ fun growMines(self) -> State =
519
+ if self.mines >= mineCount(self.score) then self else self.addMine().growMines()
520
+
521
+ fun addMine(self) -> State =
522
+ sh := self.ship()
523
+ sp := spawn(self.rng, sh.x, sh.y, 220.0, 90.0)
524
+ mine := Actor.group(MineId + self.mines, sp.at.x, sp.at.y, Mine(vx: sp.at.vx, vy: sp.at.vy, spin: 2.0, clock: 0.0, sheet: self.sheet))
525
+ State(..self, stage: self.stage.add(MineLayer, etree.leaf(mine)), rng: sp.rng, mines: self.mines + 1)
526
+
527
+ fun touchesMine(self) -> Bool =
528
+ self.bodiesWhere(|k| k.isMine()).fold(false, |hit, m| hit || self.touches(m, MineRadius))
529
+
530
+ # A mine costs a life (and its icon), makes the ship flash and, at the last life, ends
531
+ # the game: the ship goes and the panel comes up.
532
+ fun hurt(self) -> State =
533
+ if self.ship().kind.hurtLeft() <= 0.0 && self.touchesMine() then self.struck() else self
534
+
535
+ fun struck(self) -> State =
536
+ lives := self.lives - 1
537
+ done := lives <= 0
538
+ hit := self.stage.updateKind(ShipId, |k| k.struck()).kill(LifeId + lives)
539
+ stage := if done then hit.update(ShipId, hidden).update(PanelId, revealed).update(TitleId, revealed) else hit
540
+ State(..self, stage: stage, lives: lives, over: done, best: if done then self.best.max(self.score) else self.best)
541
+
542
+ # After game over the orbs and mines stop: they only animate.
543
+ fun settle(self) -> State =
544
+ if self.over then State(..self, stage: self.stage.withRoot(self.stage.root.map(|a| a.withKind(a.kind.still())))) else self
545
+
546
+ # A fresh run that keeps the best score, the Ui and the held keys; the button shows the
547
+ # Ui's state.
548
+ fun restarted(self, seed: Int) -> State =
549
+ fresh := State.start(seed, self.best.max(self.score), self.sheet, self.sw, self.sh)
550
+ look := buttonLook(self.ui)
551
+ State(..fresh, ui: self.ui, held: self.held, stage: fresh.stage.updateKind(RestartId, |k| k.looked(look)))
552
+
553
+ # A player input: keys update the held keys (Enter or R restarts a finished game),
554
+ # a pointer input goes through the Ui.
555
+ fun onInput(self, e: InputEvent) -> State =
556
+ s := State(..self, held: self.held.after(e))
557
+ if e.isPointer()
558
+ s.feed(e)
559
+ else if s.over && isRestartKey(e)
560
+ s.restarted(s.rng.nextInt().value)
561
+ else
562
+ s
563
+
564
+ # The steering axes from the held arrow or WASD keys.
565
+ fun axisX(self) -> Float =
566
+ axis(self.held.isDown(Key.Left) || self.held.isDown(Key.KeyA), self.held.isDown(Key.Right) || self.held.isDown(Key.KeyD))
567
+
568
+ fun axisY(self) -> Float =
569
+ axis(self.held.isDown(Key.Up) || self.held.isDown(Key.KeyW), self.held.isDown(Key.Down) || self.held.isDown(Key.KeyS))
570
+
571
+ # One pointer input: the stage finds the actor under it (through the root's camera),
572
+ # the Ui turns that into press, hover and click, the button shows the result, and a
573
+ # click on it restarts.
574
+ fun feed(self, input: InputEvent) -> State =
575
+ po := input.position()
576
+ if po.isNone()
577
+ self
578
+ else
579
+ pos := po.unwrap()
580
+ r := ui.step(self.ui, input, self.stage.hitId(pos.x, pos.y))
581
+ look := buttonLook(r.ui)
582
+ s := State(..self, ui: r.ui, stage: self.stage.updateKind(RestartId, |k| k.looked(look)))
583
+ clicked := r.events.fold(false, |c, e| c || {e.kind == Click && e.id == RestartId})
584
+ if clicked then s.update(RestartClicked) else s
585
+
586
+ # True when (x, y) in screen pixels is on the restart button.
587
+ fun onRestart(self, x: Float, y: Float) -> Bool =
588
+ self.stage.hitId(x, y).unwrapOr(-1) == RestartId
589
+
590
+ # Enter or R going down.
591
+ fun isRestartKey(e: InputEvent) -> Bool = match e
592
+ KeyDown(k) => k == Key.Enter || k == Key.KeyR
593
+ _ => false
594
+
595
+ fun axis(negative: Bool, positive: Bool) -> Float =
596
+ if negative && !positive
597
+ -1.0
598
+ else if positive && !negative
599
+ 1.0
600
+ else
601
+ 0.0
602
+
603
+ # --- the host shell ---
604
+
605
+ struct OrbGame(state: State, input: Input, pickupSound: Sound, hitSound: Sound, overSound: Sound, musicSound: Sound) =
606
+
607
+ # Restarts the music loop from the top.
608
+ fun startMusic(self, io: Io) =
609
+ self.musicSound.stop(io)
610
+ self.musicSound.loop(io, 0.3)
611
+
612
+ # Sends the tick's input events to the state, then one tick steered by the held keys;
613
+ # plays sounds for what changed. Returns the game with the next state.
614
+ fun update(self, io: Io, input: Input, dt: Float) -> OrbGame =
615
+ polled := input
616
+ s := self.state.update(Resize(w: gfx.screenWidth(io), h: gfx.screenHeight(io)))
617
+ inputs := polled.events
618
+ clicked := 0.until(inputs.length()).fold(s, |current, i| current.update(Event(input: inputs.at(i))))
619
+ if s.over && !clicked.over
620
+ self.startMusic(io)
621
+ OrbGame(..self, state: clicked, input: polled)
622
+ else
623
+ t := clicked.update(Tick(dt: dt, ax: clicked.axisX(), ay: clicked.axisY()))
624
+ if t.score > clicked.score
625
+ self.pickupSound.play(io, 0.8)
626
+ if t.lives < clicked.lives
627
+ if t.over
628
+ self.musicSound.stop(io)
629
+ self.overSound.play(io, 1.0)
630
+ else
631
+ self.hitSound.play(io, 1.0)
632
+ OrbGame(..self, state: t, input: polled)
633
+
634
+ fun draw(self, io: Io) =
635
+ gfx.clear(io, Color.rgb(0.04, 0.05, 0.1))
636
+ self.state.stage.draw(io)
637
+
638
+ fun main(io: Io) -> OrbGame =
639
+ s := State.start(io.randomSeed(), 0, gfx.loadTexture(io, "sprites.png"), ArenaW, ArenaH)
640
+ game := OrbGame(
641
+ state: s,
642
+ input: Input.create(),
643
+ pickupSound: audio.loadSound(io, "pickup.wav"),
644
+ hitSound: audio.loadSound(io, "hit.wav"),
645
+ overSound: audio.loadSound(io, "gameover.wav"),
646
+ musicSound: audio.loadSound(io, "music.wav")
647
+ )
648
+ game.startMusic(io)
649
+ game
650
+
651
+ # --- tests ---
652
+
653
+ fun near(a: Float, b: Float) -> Bool =
654
+ {a - b}.abs() < 0.01
655
+
656
+ fun tickOf(s: State, ax: Float, ay: Float, dt: Float) -> State =
657
+ s.update(Tick(dt: dt, ax: ax, ay: ay))
658
+
659
+ # `n` ticks in a row with the same steering.
660
+ fun ticksOf(s: State, n: Int, ax: Float, ay: Float, dt: Float) -> State =
661
+ 0.until(n).fold(s, |current, _| tickOf(current, ax, ay, dt))
662
+
663
+ # How many frames the ship was hidden and shown while ticking `state`.
664
+ struct Blinks(state: State, hidden: Int, shown: Int)
665
+
666
+ fun away() -> Motion =
667
+ Motion(x: 5000.0, y: 0.0, vx: 0.0, vy: 0.0)
668
+
669
+ fun newState(seed: Int) -> State =
670
+ State.start(seed, 0, Texture(id: -1), ArenaW, ArenaH)
671
+
672
+ fun moveBody(s: State, id: Int, m: Motion) -> State =
673
+ State(..s, stage: s.stage.update(id, |a| placed(a, m)))
674
+
675
+ # A state with the orbs and mines moved out of the way.
676
+ fun emptyState() -> State =
677
+ s := newState(7)
678
+ State(..s, stage: s.stage.withRoot(s.stage.root.map(|a| if a.kind.isOrb() || a.kind.isMine() then placed(a, away()) else a)))
679
+
680
+ fun onShip(s: State) -> Motion =
681
+ Motion(x: s.ship().x, y: s.ship().y, vx: 0.0, vy: 0.0)
682
+
683
+ fun forceOver(s: State) -> State =
684
+ stage := s.stage.update(ShipId, hidden).update(PanelId, revealed).update(TitleId, revealed)
685
+ State(..s, stage: stage, lives: 0, over: true, best: s.best.max(s.score))
686
+
687
+ fun lone(a: Actor[Kind]) -> EStage[Kind] = EStage.of(a)
688
+
689
+ fun shipAt(x: Float, y: Float) -> Actor[Kind] = shipActor(x, y, Texture(id: -1))
690
+
691
+ fun shipVx(a: Actor[Kind]) -> Float = match a.kind
692
+ Ship(vx, _, _, _, _, _, _, _) => vx
693
+ _ => 0.0
694
+
695
+ fun labelText(s: State, id: Int) -> Str = match s.body(id).kind
696
+ Label(t, _) => t
697
+ _ => ""
698
+
699
+ fun buttonLookOf(s: State) -> Int = match s.body(RestartId).kind
700
+ Button(_, k) => k
701
+ _ => -1
702
+
703
+ # One actor's step on its own.
704
+ fun stepOne(a: Actor[Kind], dt: Float) -> Actor[Kind] = a.kind.step(a, ECtx[Kind](), dt)
705
+
706
+ test "the scene starts as a tree of 63 actors, 58 of them drawn"
707
+ s := newState(7)
708
+ assert s.stage.count() == 63
709
+ assert s.stage.flatten().length() == 58
710
+ over := forceOver(s)
711
+ assert over.stage.flatten().length() == 58 - 1 + 5
712
+
713
+ test "steering accelerates and drag slows the ship"
714
+ s := lone(shipAt(ArenaW / 2.0, ArenaH / 2.0)).updateKind(ShipId, |k| k.steered(1.0, 0.0)).step(ECtx[Kind](), 0.1)
715
+ sh := s.find(ShipId).unwrap()
716
+ assert sh.x > ArenaW / 2.0
717
+ assert shipVx(sh) > 0.0
718
+ coast := s.updateKind(ShipId, |k| k.steered(0.0, 0.0))
719
+ t := 0.until(30).fold(coast, |cur, _| cur.step(ECtx[Kind](), 0.1))
720
+ assert shipVx(t.find(ShipId).unwrap()) < shipVx(sh) / 4.0
721
+ assert t.find(ShipId).unwrap().x - sh.x < 50.0
722
+
723
+ test "the ship stops at the arena walls"
724
+ start := lone(shipAt(20.0, 20.0)).updateKind(ShipId, |k| k.steered(-1.0, -1.0))
725
+ s := 0.until(20).fold(start, |cur, _| cur.step(ECtx[Kind](), 0.1))
726
+ sh := s.find(ShipId).unwrap()
727
+ assert sh.x == ShipRadius
728
+ assert sh.y == ShipRadius
729
+ assert shipVx(sh) == 0.0
730
+
731
+ test "orbs bounce off the walls and mines spin as they drift"
732
+ orb := Actor.group(OrbId, 795.0, 300.0, Orb(vx: 100.0, vy: 0.0, phase: 0.0, clock: 0.0, sheet: Texture(id: -1)))
733
+ o := stepOne(orb, 0.1)
734
+ assert near(o.x, ArenaW - 10.0)
735
+ mine := Actor.group(MineId, 400.0, 300.0, Mine(vx: 10.0, vy: 0.0, spin: 2.0, clock: 0.0, sheet: Texture(id: -1)))
736
+ k := stepOne(mine, 0.5)
737
+ assert near(k.rotation, 1.0)
738
+ assert near(k.x, 405.0)
739
+ assert near(mine.rotation, 0.0)
740
+
741
+ test "collecting an orb scores, respawns it elsewhere and updates the hud"
742
+ e := emptyState()
743
+ s := moveBody(e, OrbId, onShip(e))
744
+ t := tickOf(s, 0.0, 0.0, 0.016)
745
+ orb := t.body(OrbId)
746
+ assert t.score == OrbPoints
747
+ assert math.hypot(orb.x - t.ship().x, orb.y - t.ship().y) >= 120.0
748
+ assert orb.x < 5000.0
749
+ assert t.bodiesWhere(|k| k.isOrb()).length() == OrbCount
750
+ assert labelText(t, ScoreId) == "Score 10"
751
+ assert labelText(s, ScoreId) == "Score 0"
752
+
753
+ test "a mine costs one life and its icon, and makes the ship flash"
754
+ e := emptyState()
755
+ s := moveBody(e, MineId, onShip(e))
756
+ hit := tickOf(s, 0.0, 0.0, 0.016)
757
+ assert hit.lives == StartLives - 1
758
+ assert hit.ship().kind.hurtLeft() > 0.0
759
+ assert hit.stage.find(LifeId + 2).isNone()
760
+ assert hit.stage.find(LifeId + 1).isSome()
761
+ start := Blinks(state: moveBody(hit, MineId, away()), hidden: 0, shown: 0)
762
+ blinks := 0.until(100).fold(start, |b, _|
763
+ next := tickOf(b.state, 0.0, 0.0, 0.016)
764
+ if next.ship().kind.blinking()
765
+ Blinks(state: next, hidden: b.hidden + 1, shown: b.shown)
766
+ else
767
+ Blinks(state: next, hidden: b.hidden, shown: b.shown + 1)
768
+ )
769
+ assert blinks.hidden > 0
770
+ assert blinks.shown > 0
771
+ assert blinks.state.ship().kind.hurtLeft() == 0.0
772
+ assert !blinks.state.ship().kind.blinking()
773
+ assert blinks.state.lives == StartLives - 1
774
+
775
+ test "the ship is briefly safe after a hit"
776
+ e := emptyState()
777
+ hit := tickOf(moveBody(e, MineId, onShip(e)), 0.0, 0.0, 0.016)
778
+ assert tickOf(hit, 0.0, 0.0, 0.016).lives == StartLives - 1
779
+
780
+ test "the game ends at zero lives: the ship goes, the panel comes up, steps are ignored"
781
+ e := emptyState()
782
+ s := State(..e, lives: 1, score: 40)
783
+ t := tickOf(moveBody(s, MineId, onShip(s)), 0.0, 0.0, 0.016)
784
+ assert t.over
785
+ assert t.lives == 0
786
+ assert t.best == 40
787
+ assert !t.ship().shown()
788
+ assert t.body(PanelId).shown()
789
+ x := t.ship().x
790
+ assert tickOf(t, 1.0, 0.0, 0.5).ship().x == x
791
+
792
+ test "after game over nothing moves but the animations keep running"
793
+ e := emptyState()
794
+ s := State(..e, lives: 1)
795
+ ended := tickOf(moveBody(s, MineId, Motion(x: s.ship().x, y: s.ship().y, vx: 10.0, vy: 0.0)), 0.0, 0.0, 0.016)
796
+ assert ended.over
797
+ mine := ended.body(MineId)
798
+ t := ticksOf(ended, 10, 1.0, 0.0, 0.1)
799
+ after := t.body(MineId)
800
+ assert after.x == mine.x
801
+ assert after.rotation == mine.rotation
802
+ assert t.ship().x == ArenaW / 2.0
803
+ assert after.kind.clockOf() > mine.kind.clockOf() + 0.9
804
+ assert t.body(OrbId).kind.clockOf() > 0.9
805
+ assert t.clock > 0.9
806
+ assert t.score == 0
807
+
808
+ test "restart builds a fresh tree and keeps the best score"
809
+ e := emptyState()
810
+ s := forceOver(State(..e, score: 90))
811
+ r := s.update(Restart(seed: 5))
812
+ assert !r.over
813
+ assert r.score == 0
814
+ assert r.best == 90
815
+ assert r.lives == StartLives
816
+ assert r.ship().x == ArenaW / 2.0
817
+ assert r.ship().shown()
818
+ assert !r.body(PanelId).shown()
819
+ assert r.bodiesWhere(|k| k.isMine()).length() == mineCount(0)
820
+ assert labelText(r, BestId) == "Best 90"
821
+
822
+ test "more mines are added to the tree as the score grows"
823
+ assert mineCount(0) == 3
824
+ assert mineCount(100) == 5
825
+ assert mineCount(10000) == 8
826
+ e := emptyState()
827
+ t := tickOf(State(..e, score: 100), 0.0, 0.0, 0.016)
828
+ assert t.bodiesWhere(|k| k.isMine()).length() == 5
829
+ assert t.stage.find(MineId + 4).isSome()
830
+ assert t.update(Restart(seed: 3)).bodiesWhere(|k| k.isMine()).length() == 3
831
+
832
+ test "the same seed plays out the same way"
833
+ a := ticksOf(newState(11), 120, 1.0, -1.0, 0.016)
834
+ b := ticksOf(newState(11), 120, 1.0, -1.0, 0.016)
835
+ assert a.ship().x == b.ship().x
836
+ assert a.score == b.score
837
+ assert a.body(MineId).x == b.body(MineId).x
838
+ assert newState(12).body(OrbId).x != a.body(OrbId).x
839
+
840
+ test "a kept old state still has its old tree"
841
+ s := emptyState()
842
+ x := s.ship().x
843
+ t := tickOf(s, 1.0, 0.0, 0.1)
844
+ assert t.ship().x > x
845
+ assert s.ship().x == x
846
+
847
+ test "the root fits the arena on the screen"
848
+ s := emptyState().update(Resize(w: 1600.0, h: 600.0))
849
+ root := s.body(RootId).local()
850
+ assert near(root.a, 1.0)
851
+ assert near(root.e, 400.0)
852
+ assert near(root.f, 0.0)
853
+
854
+ test "the restart button is hidden while playing and found through the root's camera"
855
+ s := emptyState()
856
+ assert !s.onRestart(400.0, 364.0)
857
+ o := forceOver(s)
858
+ assert o.onRestart(400.0, 364.0)
859
+ assert !o.onRestart(100.0, 100.0)
860
+ assert !o.onRestart(400.0, 260.0)
861
+ wide := o.update(Resize(w: 1600.0, h: 600.0))
862
+ assert wide.onRestart(800.0, 364.0)
863
+ assert !wide.onRestart(400.0, 364.0)
864
+
865
+ test "a click on the button restarts through the ui"
866
+ e := emptyState()
867
+ s := forceOver(State(..e, score: 90))
868
+ down := s.feed(PointerDown(x: 400.0, y: 364.0))
869
+ assert down.over
870
+ assert ui.pressed(down.ui, RestartId)
871
+ assert buttonLookOf(down) == 2
872
+ up := down.feed(PointerUp(x: 400.0, y: 364.0))
873
+ assert !up.over
874
+ assert up.score == 0
875
+ assert up.best == 90
876
+ assert up.lives == StartLives
877
+ assert s.feed(PointerDown(x: 400.0, y: 364.0)).feed(PointerUp(x: 100.0, y: 100.0)).over
878
+ assert s.feed(PointerDown(x: 100.0, y: 100.0)).feed(PointerUp(x: 100.0, y: 100.0)).over
879
+
880
+ test "the title pulses and the panel fades in by their own clocks"
881
+ t := ticksOf(forceOver(emptyState()), 15, 0.0, 0.0, 0.02)
882
+ assert near(t.body(PanelId).opacity(), 0.6)
883
+ assert near(t.body(TitleId).local().a, 1.3)
884
+ assert near(titlePose(0.8).scaleX, 1.17)
885
+ assert near(flashPose(0.05).scaleX, 0.4)
886
+
887
+ test "held keys steer, and enter restarts a finished game and nothing else"
888
+ s := emptyState().update(Event(input: KeyDown(key: Key.Left))).update(Event(input: KeyDown(key: Key.KeyS)))
889
+ assert s.axisX() == -1.0
890
+ assert s.axisY() == 1.0
891
+ assert s.update(Event(input: KeyUp(key: Key.Left))).axisX() == 0.0
892
+ playing := emptyState().update(Event(input: KeyDown(key: Key.Enter)))
893
+ assert !playing.over
894
+ e := emptyState()
895
+ r := forceOver(State(..e, score: 40)).update(Event(input: KeyDown(key: Key.Enter)))
896
+ assert !r.over
897
+ assert r.best == 40
898
+ assert r.held.isDown(Key.Enter)
std/game_enum_tree/Actor.plum ADDED
@@ -0,0 +1,167 @@
1
+ module std
2
+
3
+ import std/Int
4
+ import std/Float
5
+ import std/Bool
6
+ import std/math
7
+ import std/Io
8
+ import std/game/Vec2
9
+ import std/game/Affine
10
+ import std/game/Color
11
+ import std/game/gfx
12
+
13
+ # One body of a persistent scene tree (`ETree[Actor[K]]` in an `EStage[K]`): what every
14
+ # body has, its id, its place in its parent (position, size, origin, scale, rotation), its
15
+ # colour and its two flags, plus `kind: K`, the game's own payload. The stage does
16
+ # everything these fields describe by itself: it finds bodies by `id`, drops a `dead` one
17
+ # with its subtree, skips a hidden one (and its subtree) when it draws and hit tests,
18
+ # turns the fields into the body's transform (`local`) and multiplies `color.a` down the
19
+ # tree as the alpha. It asks the kind only for behaviour, through three methods:
20
+ #
21
+ # step(self, a: Actor[K], ctx: ECtx[K], dt: Float) -> Actor[K] # the next actor
22
+ # paint(self, a: Actor[K], io: Io, m: Affine, alpha: Float) # m: a's own coords to the stage
23
+ # hit(self, a: Actor[K], p: Vec2) -> Bool # p in a's own coordinates
24
+ #
25
+ # `self` is `a.kind`, so a kind matches on itself and reads the common fields from `a`:
26
+ #
27
+ # enum Kind =
28
+ # | Box
29
+ # | Walker(speed: Float)
30
+ #
31
+ # fun step(self, a: Actor[Kind], ctx: ECtx[Kind], dt: Float) -> Actor[Kind] = match self
32
+ # Walker(speed) => a.moveBy(speed * dt, 0.0)
33
+ # Box => a
34
+ #
35
+ # fun paint(self, a: Actor[Kind], io: Io, m: Affine, alpha: Float) = a.paintBox(io, m, alpha)
36
+ #
37
+ # fun hit(self, a: Actor[Kind], p: Vec2) -> Bool = a.hitBox(p)
38
+ #
39
+ # `paintBox` and `hitBox` are the plain behaviour (a filled `width` by `height` box, none
40
+ # for a group with no size); std/game_enum_tree/EBox is a kind that has only that, for
41
+ # scenes with no behaviour of their own. An actor is a value: a step returns the next one,
42
+ # made with the copy helpers below or a spread (`Actor(..a, x: 1.0, kind: k)`), which the
43
+ # compiler writes in place when nothing else holds the old one.
44
+ struct Actor[K](
45
+ id: Int,
46
+ x: Float, y: Float, width: Float, height: Float,
47
+ originX: Float, originY: Float,
48
+ scaleX: Float, scaleY: Float,
49
+ rotation: Float,
50
+ color: Color,
51
+ visible: Bool,
52
+ dead: Bool,
53
+ kind: K) =
54
+
55
+ # A group at (x, y), unscaled and unrotated: no size, so `paintBox` and `hitBox` do
56
+ # nothing for it.
57
+ fun group(id: Int, x: Float, y: Float, kind: K) -> Actor[K] =
58
+ Actor(
59
+ id: id, x: x, y: y, width: 0.0, height: 0.0, originX: 0.0, originY: 0.0,
60
+ scaleX: 1.0, scaleY: 1.0, rotation: 0.0, color: Color.White, visible: true, dead: false,
61
+ kind: kind)
62
+
63
+ # A group at (x, y), scaled by `s` and turned by `r` radians about its own (0, 0).
64
+ fun turned(id: Int, x: Float, y: Float, s: Float, r: Float, kind: K) -> Actor[K] =
65
+ Actor(
66
+ id: id, x: x, y: y, width: 0.0, height: 0.0, originX: 0.0, originY: 0.0,
67
+ scaleX: s, scaleY: s, rotation: r, color: Color.White, visible: true, dead: false,
68
+ kind: kind)
69
+
70
+ # A `w` by `h` rectangle with its top-left at (x, y).
71
+ fun rect(id: Int, x: Float, y: Float, w: Float, h: Float, c: Color, kind: K) -> Actor[K] =
72
+ Actor(
73
+ id: id, x: x, y: y, width: w, height: h, originX: 0.0, originY: 0.0,
74
+ scaleX: 1.0, scaleY: 1.0, rotation: 0.0, color: c, visible: true, dead: false,
75
+ kind: kind)
76
+
77
+ # Whether this actor and its subtree are drawn and hit: visible and not dead.
78
+ fun shown(self) -> Bool = self.visible && !self.dead
79
+
80
+ # Its own alpha, multiplied down the tree.
81
+ fun opacity(self) -> Float = self.color.a
82
+
83
+ # The transform into the parent's coordinates: translate to the position, rotate and
84
+ # scale about the origin.
85
+ fun local(self) -> Affine =
86
+ localOf(self.x, self.y, self.originX, self.originY, self.scaleX, self.scaleY, self.rotation)
87
+
88
+ # Whether `p`, a point in this actor's own coordinates, is inside its width by height
89
+ # box; a group with no size is never hit.
90
+ fun hitBox(self, p: Vec2) -> Bool = boxHit(self.width, self.height, p)
91
+
92
+ # Its width by height box at (0, 0), seen through `m`, in its colour at `alpha` (the
93
+ # accumulated alpha, which already includes its own `color.a`). Nothing for a group.
94
+ fun paintBox(self, io: Io, m: Affine, alpha: Float) =
95
+ if self.width > 0.0 && self.height > 0.0
96
+ boxPaint(io, m, alpha, self.width, self.height, self.color.withAlpha(1.0))
97
+
98
+ # Copies with one thing changed.
99
+
100
+ fun at(self, x: Float, y: Float) -> Actor[K] = Actor(..self, x: x, y: y)
101
+
102
+ fun moveBy(self, dx: Float, dy: Float) -> Actor[K] = Actor(..self, x: self.x + dx, y: self.y + dy)
103
+
104
+ fun rotateTo(self, r: Float) -> Actor[K] = Actor(..self, rotation: r)
105
+
106
+ fun scaleTo(self, sx: Float, sy: Float) -> Actor[K] = Actor(..self, scaleX: sx, scaleY: sy)
107
+
108
+ fun resize(self, w: Float, h: Float) -> Actor[K] = Actor(..self, width: w, height: h)
109
+
110
+ # Its rotation and scale about (ox, oy), in its own coordinates.
111
+ fun pivotAt(self, ox: Float, oy: Float) -> Actor[K] = Actor(..self, originX: ox, originY: oy)
112
+
113
+ fun tint(self, c: Color) -> Actor[K] = Actor(..self, color: c)
114
+
115
+ # Its colour with the alpha `a`: its opacity, and its subtree's.
116
+ fun fade(self, a: Float) -> Actor[K] = Actor(..self, color: self.color.withAlpha(a))
117
+
118
+ fun withVisible(self, v: Bool) -> Actor[K] = Actor(..self, visible: v)
119
+
120
+ # Dead: returned from `step`, its parent drops it with its subtree.
121
+ fun killed(self) -> Actor[K] = Actor(..self, dead: true)
122
+
123
+ fun withKind(self, k: K) -> Actor[K] = Actor(..self, kind: k)
124
+
125
+ # The transform of a body at (x, y) with its origin, scale and rotation (master's
126
+ # `Actor.local`): translate to the position, rotate and scale about the origin.
127
+ fun localOf(x: Float, y: Float, originX: Float, originY: Float, scaleX: Float, scaleY: Float, rotation: Float) -> Affine =
128
+ cs := math.cos(rotation)
129
+ sn := math.sin(rotation)
130
+ a := cs * scaleX
131
+ b := sn * scaleX
132
+ c := 0.0 - sn * scaleY
133
+ d := cs * scaleY
134
+ Affine(
135
+ a: a, b: b, c: c, d: d,
136
+ e: x + originX - {a * originX + c * originY},
137
+ f: y + originY - {b * originX + d * originY})
138
+
139
+ # Whether `p` is inside a `w` by `h` box at (0, 0); a box with no size is never hit.
140
+ fun boxHit(w: Float, h: Float, p: Vec2) -> Bool =
141
+ w > 0.0 && h > 0.0 && p.x >= 0.0 && p.x <= w && p.y >= 0.0 && p.y <= h
142
+
143
+ # A `w` by `h` box at (0, 0) seen through `m`, filled with `c` at `c.a * alpha`.
144
+ fun boxPaint(io: Io, m: Affine, alpha: Float, w: Float, h: Float, c: Color) =
145
+ sx := w * m.scaleX()
146
+ sy := h * m.scaleY()
147
+ p := m.apply(Vec2(x: w / 2.0, y: h / 2.0))
148
+ gfx.drawRect(io, p.x - sx / 2.0, p.y - sy / 2.0, sx, sy, c.withAlpha(c.a * alpha))
149
+
150
+ test "a rect actor is its size and hides when it is dead"
151
+ r := Actor.rect(7, 1.0, 2.0, 4.0, 3.0, Color.Red, 0)
152
+ assert r.width == 4.0 && r.height == 3.0 && r.id == 7
153
+ assert r.shown()
154
+ assert !r.killed().shown()
155
+ assert !r.withVisible(false).shown()
156
+ assert r.moveBy(1.0, 2.0).x == 2.0
157
+ assert r.hitBox(Vec2(x: 2.0, y: 1.0))
158
+ assert !Actor.group(1, 0.0, 0.0, 0).hitBox(Vec2(x: 0.0, y: 0.0))
159
+ assert r.fade(0.25).opacity() == 0.25
160
+ assert r.withKind(5).kind == 5 && r.kind == 0
161
+
162
+ test "local translates, then turns and scales about the origin"
163
+ b := Actor.turned(1, 10.0, 20.0, 2.0, 0.0, 0).pivotAt(1.0, 1.0)
164
+ p := b.local().apply(Vec2(x: 1.0, y: 1.0))
165
+ assert p.x == 11.0 && p.y == 21.0
166
+ q := b.local().apply(Vec2(x: 2.0, y: 1.0))
167
+ assert q.x == 13.0 && q.y == 21.0
std/game_enum_tree/EBody.plum DELETED
@@ -1,148 +0,0 @@
1
- module std
2
-
3
- import std/Int
4
- import std/Float
5
- import std/Bool
6
- import std/math
7
- import std/Io
8
- import std/game/Vec2
9
- import std/game/Affine
10
- import std/game/Color
11
- import std/game/gfx
12
- import std/game_enum_tree/ECtx
13
-
14
- # A plain body for a persistent scene tree (`ETree[EBody]` in an `EStage[EBody]`): the
15
- # transform, size, colour and flags of master's std/game_enum_tree `EBody`, with no
16
- # behaviour. A body with a size paints a filled rectangle; one without (a group) paints
17
- # nothing and is never hit.
18
- #
19
- # The branch has no inheritance, so a game with behaviour defines its own body type and
20
- # the stage is generic over it. Any type with these methods can be the stage's `T`:
21
- #
22
- # key(self) -> Int # its id: how kills, spawns and updates find it
23
- # gone(self) -> Bool # dead: its parent drops it with its subtree
24
- # shown(self) -> Bool # drawn and hit: visible and not dead
25
- # local(self) -> Affine # into its parent's coordinates (`ebody.localOf`)
26
- # opacity(self) -> Float # its alpha, multiplied down the tree
27
- # hit(self, p: Vec2) -> Bool # `p` in its own coordinates is inside it
28
- # step(self, ctx: ECtx[T], dt: Float) -> T # its next version (itself if unchanged)
29
- # paint(self, io: Io, m: Affine, alpha: Float)
30
- #
31
- # An enum of kinds that each hold an `EBody` (`| Walker(body: EBody, speed: Float)`), or
32
- # one struct with the fields a game needs, both work; std/game_enum_tree's tests use the
33
- # first, benchmarks/scene_trees the second. A body is a value: nothing changes it after
34
- # it is built, and a step makes its next version with a spread, which the compiler writes
35
- # in place when nothing else holds the old one.
36
- struct EBody(
37
- id: Int,
38
- x: Float, y: Float, width: Float, height: Float,
39
- originX: Float, originY: Float,
40
- scaleX: Float, scaleY: Float,
41
- rotation: Float,
42
- color: Color,
43
- visible: Bool,
44
- dead: Bool) =
45
-
46
- # A group at (x, y), unscaled and unrotated: no size, paints nothing.
47
- fun group(id: Int, x: Float, y: Float) -> EBody =
48
- EBody(
49
- id: id, x: x, y: y, width: 0.0, height: 0.0, originX: 0.0, originY: 0.0,
50
- scaleX: 1.0, scaleY: 1.0, rotation: 0.0, color: Color.White, visible: true, dead: false)
51
-
52
- # A group at (x, y), scaled by `s` and turned by `r` radians about its own (0, 0).
53
- fun turned(id: Int, x: Float, y: Float, s: Float, r: Float) -> EBody =
54
- EBody(
55
- id: id, x: x, y: y, width: 0.0, height: 0.0, originX: 0.0, originY: 0.0,
56
- scaleX: s, scaleY: s, rotation: r, color: Color.White, visible: true, dead: false)
57
-
58
- # A `w` by `h` rectangle with its top-left at (x, y).
59
- fun rect(id: Int, x: Float, y: Float, w: Float, h: Float, c: Color) -> EBody =
60
- EBody(
61
- id: id, x: x, y: y, width: w, height: h, originX: 0.0, originY: 0.0,
62
- scaleX: 1.0, scaleY: 1.0, rotation: 0.0, color: c, visible: true, dead: false)
63
-
64
- fun key(self) -> Int = self.id
65
-
66
- fun gone(self) -> Bool = self.dead
67
-
68
- # Whether this body and its subtree are drawn and hit: visible and not dead.
69
- fun shown(self) -> Bool = self.visible && !self.dead
70
-
71
- fun opacity(self) -> Float = self.color.a
72
-
73
- # The transform into the parent's coordinates: translate to the position, rotate and
74
- # scale about the origin.
75
- fun local(self) -> Affine =
76
- localOf(self.x, self.y, self.originX, self.originY, self.scaleX, self.scaleY, self.rotation)
77
-
78
- # Whether `p`, a point in this body's own coordinates, is inside its width by height box.
79
- fun hit(self, p: Vec2) -> Bool = hitBox(self.width, self.height, p)
80
-
81
- # A plain body doesn't change.
82
- fun step(self, ctx: ECtx[EBody], dt: Float) -> EBody = self
83
-
84
- fun paint(self, io: Io, m: Affine, alpha: Float) =
85
- if self.width > 0.0 && self.height > 0.0
86
- paintBox(io, m, alpha, self.width, self.height, self.color)
87
-
88
- # Copies with one thing changed.
89
-
90
- fun at(self, x: Float, y: Float) -> EBody = EBody(..self, x: x, y: y)
91
-
92
- fun moveBy(self, dx: Float, dy: Float) -> EBody = EBody(..self, x: self.x + dx, y: self.y + dy)
93
-
94
- fun rotateTo(self, r: Float) -> EBody = EBody(..self, rotation: r)
95
-
96
- fun scaleTo(self, sx: Float, sy: Float) -> EBody = EBody(..self, scaleX: sx, scaleY: sy)
97
-
98
- # Its rotation and scale about (ox, oy), in its own coordinates.
99
- fun pivotAt(self, ox: Float, oy: Float) -> EBody = EBody(..self, originX: ox, originY: oy)
100
-
101
- fun tint(self, c: Color) -> EBody = EBody(..self, color: c)
102
-
103
- fun withVisible(self, v: Bool) -> EBody = EBody(..self, visible: v)
104
-
105
- # Dead: returned from `step`, its parent drops it with its subtree.
106
- fun killed(self) -> EBody = EBody(..self, dead: true)
107
-
108
- # The transform of a body at (x, y) with its origin, scale and rotation (master's
109
- # `Actor.local`): translate to the position, rotate and scale about the origin.
110
- fun localOf(x: Float, y: Float, originX: Float, originY: Float, scaleX: Float, scaleY: Float, rotation: Float) -> Affine =
111
- cs := math.cos(rotation)
112
- sn := math.sin(rotation)
113
- a := cs * scaleX
114
- b := sn * scaleX
115
- c := 0.0 - sn * scaleY
116
- d := cs * scaleY
117
- Affine(
118
- a: a, b: b, c: c, d: d,
119
- e: x + originX - {a * originX + c * originY},
120
- f: y + originY - {b * originX + d * originY})
121
-
122
- # Whether `p` is inside a `w` by `h` box at (0, 0); a box with no size is never hit.
123
- fun hitBox(w: Float, h: Float, p: Vec2) -> Bool =
124
- w > 0.0 && h > 0.0 && p.x >= 0.0 && p.x <= w && p.y >= 0.0 && p.y <= h
125
-
126
- # A `w` by `h` box at (0, 0) seen through `m`, filled with `c` at `alpha`.
127
- fun paintBox(io: Io, m: Affine, alpha: Float, w: Float, h: Float, c: Color) =
128
- sx := w * m.scaleX()
129
- sy := h * m.scaleY()
130
- p := m.apply(Vec2(x: w / 2.0, y: h / 2.0))
131
- gfx.drawRect(io, p.x - sx / 2.0, p.y - sy / 2.0, sx, sy, c.withAlpha(c.a * alpha))
132
-
133
- test "a rect body is its size and hides when it is dead"
134
- r := EBody.rect(7, 1.0, 2.0, 4.0, 3.0, Color.Red)
135
- assert r.width == 4.0 && r.height == 3.0 && r.key() == 7
136
- assert r.shown()
137
- assert !r.killed().shown()
138
- assert !r.withVisible(false).shown()
139
- assert r.moveBy(1.0, 2.0).x == 2.0
140
- assert r.hit(Vec2(x: 2.0, y: 1.0))
141
- assert !EBody.group(1, 0.0, 0.0).hit(Vec2(x: 0.0, y: 0.0))
142
-
143
- test "local translates, then turns and scales about the origin"
144
- b := EBody.turned(1, 10.0, 20.0, 2.0, 0.0).pivotAt(1.0, 1.0)
145
- p := b.local().apply(Vec2(x: 1.0, y: 1.0))
146
- assert p.x == 11.0 && p.y == 21.0
147
- q := b.local().apply(Vec2(x: 2.0, y: 1.0))
148
- assert q.x == 13.0 && q.y == 21.0
std/game_enum_tree/EBox.plum ADDED
@@ -0,0 +1,42 @@
1
+ module std
2
+
3
+ import std/Int
4
+ import std/Float
5
+ import std/Bool
6
+ import std/Io
7
+ import std/game/Vec2
8
+ import std/game/Affine
9
+ import std/game/Color
10
+ import std/game_enum_tree/Actor
11
+ import std/game_enum_tree/ECtx
12
+
13
+ # The plain kind: an actor with no behaviour of its own. One with a size paints a filled
14
+ # rectangle in its colour and is hit inside it; one without (a group) paints nothing and is
15
+ # never hit. A scene with no behaviour is an `EStage[EBox]`:
16
+ #
17
+ # s := EStage.of(EBox.group(0, 0.0, 0.0)).add(0, etree.leaf(EBox.rect(1, 10.0, 5.0, 40.0, 20.0, Color.Red)))
18
+ struct EBox() =
19
+
20
+ # A group of plain actors at (x, y).
21
+ fun group(id: Int, x: Float, y: Float) -> Actor[EBox] = Actor.group(id, x, y, EBox())
22
+
23
+ # A plain group at (x, y), scaled by `s` and turned by `r` radians about its (0, 0).
24
+ fun turned(id: Int, x: Float, y: Float, s: Float, r: Float) -> Actor[EBox] = Actor.turned(id, x, y, s, r, EBox())
25
+
26
+ # A plain `w` by `h` rectangle with its top-left at (x, y).
27
+ fun rect(id: Int, x: Float, y: Float, w: Float, h: Float, c: Color) -> Actor[EBox] = Actor.rect(id, x, y, w, h, c, EBox())
28
+
29
+ # A plain actor doesn't change.
30
+ fun step(self, a: Actor[EBox], ctx: ECtx[EBox], dt: Float) -> Actor[EBox] = a
31
+
32
+ fun paint(self, a: Actor[EBox], io: Io, m: Affine, alpha: Float) = a.paintBox(io, m, alpha)
33
+
34
+ fun hit(self, a: Actor[EBox], p: Vec2) -> Bool = a.hitBox(p)
35
+
36
+ test "a plain box steps to itself and is hit inside its size"
37
+ r := EBox.rect(3, 1.0, 1.0, 4.0, 2.0, Color.Blue)
38
+ assert r.kind.step(r, ECtx[EBox](), 1.0).x == 1.0
39
+ assert r.kind.hit(r, Vec2(x: 3.0, y: 1.0))
40
+ assert !r.kind.hit(r, Vec2(x: 5.0, y: 1.0))
41
+ g := EBox.group(4, 0.0, 0.0)
42
+ assert !g.kind.hit(g, Vec2(x: 0.0, y: 0.0))
std/game_enum_tree/ECtx.plum CHANGED
@@ -5,23 +5,26 @@ import std/Float
5
5
  import std/Slice
6
6
  import std/game/Affine
7
7
  import std/game_enum_tree/ETree
8
+ import std/game_enum_tree/Actor
8
9
 
9
- # What a step changes besides the bodies, applied once the step's walk is over
10
+ # What a step changes besides the actors, applied once the step's walk is over
10
- # (`EStage.apply`): a new node under the body `parent` (by id), on top of its children, or
11
+ # (`EStage.apply`): a new node under the actor `parent` (by id), on top of its children,
11
- # the end of the body `id` and its subtree.
12
+ # or the end of the actor `id` and its subtree. `K` is the stage's kind.
12
- enum ECmd[T] =
13
+ enum ECmd[K] =
13
- | ESpawn(parent: Int, node: ETree[T])
14
+ | ESpawn(parent: Int, node: ETree[Actor[K]])
14
15
  | EKill(id: Int)
15
16
 
16
- # What the step hands each body in place of a parent link: the context of the body's
17
+ # What the step hands each actor's kind in place of a parent link: the context of the
17
- # parent. `up` is the parent's world transform and `alpha` its accumulated opacity, so a
18
+ # actor's parent. `up` is the parent's world transform and `alpha` its accumulated
18
- # body's own world transform is `ctx.worldOf(self.local())` and its alpha
19
+ # opacity, so an actor's own world transform is `ctx.worldOf(a.local())` and its alpha
19
- # `ctx.alphaOf(self.opacity())`, computed only when it asks. `out` takes the commands a
20
+ # `ctx.alphaOf(a.opacity())`, computed only when it asks. `out` takes the commands a kind
20
- # body pushes for after the walk (`ctx.out.push(ESpawn(..))`, `ctx.out.push(EKill(..))`).
21
+ # pushes for after the walk (`ctx.out.push(ESpawn(..))`, `ctx.out.push(EKill(..))`).
21
22
  #
22
- # fun step(self, ctx: ECtx[Body], dt: Float) -> Body =
23
+ # fun step(self, a: Actor[Kind], ctx: ECtx[Kind], dt: Float) -> Actor[Kind] = match self
24
+ # Gun(rate) =>
23
- # ctx.out.push(ESpawn(parent: 0, node: etree.leaf(Bullet(..))))
25
+ # ctx.out.push(ESpawn(parent: 0, node: etree.leaf(Actor.group(id, a.x, a.y, Bullet))))
24
- # Ship(..self, x: self.x + self.vx * dt)
26
+ # a
27
+ # ..
25
28
  #
26
29
  # A context is a value. The walk makes one for each parent with children (`under`), with
27
30
  # one multiply, and hands it to every child: the lazy world transform of master's `ECtx`
@@ -29,11 +32,11 @@ enum ECmd[T] =
29
32
  #
30
33
  # Master's context also carries the game's dispatcher (`actions`); the branch's game
31
34
  # library has none, so this one doesn't.
32
- struct ECtx[T](up: Affine, alpha: Float, out: Slice[ECmd[T]]) =
35
+ struct ECtx[K](up: Affine, alpha: Float, out: Slice[ECmd[K]]) =
33
36
 
34
37
  # The context above a stage's root: the identity transform, full opacity, no commands.
35
- fun init() -> ECtx[T] =
38
+ fun init() -> ECtx[K] =
36
- ECtx(up: Affine.Identity, alpha: 1.0, out: Slice[ECmd[T]]())
39
+ ECtx(up: Affine.Identity, alpha: 1.0, out: Slice[ECmd[K]]())
37
40
 
38
41
  # The world transform of a child whose own transform is `local`.
39
42
  fun worldOf(self, local: Affine) -> Affine = self.up.mul(local)
@@ -43,7 +46,7 @@ struct ECtx[T](up: Affine, alpha: Float, out: Slice[ECmd[T]]) =
43
46
 
44
47
  # The context for the children of a child with the transform `local` and opacity `a`:
45
48
  # the same commands, the child's world transform above them.
46
- fun under(self, local: Affine, a: Float) -> ECtx[T] =
49
+ fun under(self, local: Affine, a: Float) -> ECtx[K] =
47
50
  ECtx(up: self.up.mul(local), alpha: self.alpha * a, out: self.out)
48
51
 
49
52
  test "under multiplies the child's transform into the parent's"
std/game_enum_tree/EStage.plum CHANGED
@@ -17,24 +17,29 @@ import std/game/Affine
17
17
  import std/game/Color
18
18
  import std/game/gfx
19
19
  import std/game_enum_tree/ETree
20
+ import std/game_enum_tree/Actor
20
- import std/game_enum_tree/EBody
21
+ import std/game_enum_tree/EBox
21
22
  import std/game_enum_tree/ECtx
22
23
 
23
- # A persistent scene tree: master's std/game_enum_tree `EStage`, generic over the body
24
+ # A persistent scene tree: master's std/game_enum_tree `EStage`, over actors of the kind
24
- # type `T` (see std/game_enum_tree/EBody for the methods a body needs). The root is an
25
+ # `K` (see std/game_enum_tree/Actor). The root is an `ETree[Actor[K]]`, a left-child,
25
- # `ETree[T]`, a left-child, right-sibling tree of bodies, and a stage is a value: every
26
+ # right-sibling tree of actors, and a stage is a value: every change returns a new stage.
26
- # change returns a new stage. While something holds the old stage it stays as it was, a
27
+ # While something holds the old stage it stays as it was, a snapshot; when nothing does,
27
- # snapshot; when nothing does, the compiler reuses its cells for the new one.
28
+ # the compiler reuses its cells for the new one.
28
29
  #
29
- # s := EStage.of(EBody.group(0, 0.0, 0.0)) # a root group, id 0
30
+ # s := EStage.of(EBox.group(0, 0.0, 0.0)) # a root group, id 0
30
- # s2 := s.add(0, etree.leaf(EBody.rect(1, 10.0, 5.0, 40.0, 20.0, Color.Red)))
31
+ # s2 := s.add(0, etree.leaf(EBox.rect(1, 10.0, 5.0, 40.0, 20.0, Color.Red)))
31
- # ctx := ECtx[EBody]()
32
+ # ctx := ECtx[EBox]()
32
- # s3 := s2.step(ctx, dt) # every body's next version, then the commands in ctx.out
33
+ # s3 := s2.step(ctx, dt) # every actor's next version, then the commands in ctx.out
33
34
  # s3.draw(io)
34
35
  #
36
+ # The stage handles what every actor has: it finds actors by `id` (`add(parent, n)`,
35
- # Bodies are referred to by `key()`: `add(parent, n)`, `update(id, f)`, `find(id)`,
37
+ # `update(id, f)`, `find(id)`, `kill(id)`, `ESpawn(parent, n)`, `EKill(id)`, each by a
36
- # `kill(id)`, `ESpawn(parent, n)`, `EKill(id)`. Each finds its body by searching down from
37
- # the root, O(n); `step` applies all of a tick's commands in its own walk.
38
+ # search down from the root, O(n); `step` applies all of a tick's commands in its own
39
+ # walk), drops a `dead` actor with its subtree, skips a hidden one with its subtree when it
40
+ # draws and hit tests, and multiplies the transforms (`Actor.local`) and alphas
41
+ # (`color.a`) down the tree. The kind `K` gives the behaviour: `a.kind.step(a, ctx, dt)`,
42
+ # `a.kind.paint(a, io, m, alpha)` and `a.kind.hit(a, p)`.
38
43
  #
39
44
  # Children are kept in draw order: a parent is drawn before its children, and siblings
40
45
  # first to last. Hit testing goes the other way, topmost first: children before their
@@ -45,83 +50,92 @@ import std/game_enum_tree/ECtx
45
50
  # and that use would stop the compiler from writing the new node into the old one's cell.
46
51
  # A step over a stage nothing else holds therefore allocates no link nodes at all, and
47
52
  # one over a kept stage copies all of them.
48
- struct EStage[T](root: ETree[T], camX: Float, camY: Float, camScale: Float) =
53
+ struct EStage[K](root: ETree[Actor[K]], camX: Float, camY: Float, camScale: Float) =
49
54
 
50
- # A stage whose root is the body `top`.
55
+ # A stage whose root is the actor `top`.
51
- fun of(top: T) -> EStage[T] =
56
+ fun of(top: Actor[K]) -> EStage[K] =
52
57
  EStage(root: etree.leaf(top), camX: 0.0, camY: 0.0, camScale: 1.0)
53
58
 
54
59
  # The same camera over another tree.
55
- fun withRoot(self, r: ETree[T]) -> EStage[T] = EStage(..self, root: r)
60
+ fun withRoot(self, r: ETree[Actor[K]]) -> EStage[K] = EStage(..self, root: r)
56
61
 
57
- fun pan(self, x: Float, y: Float) -> EStage[T] = EStage(..self, camX: x, camY: y)
62
+ fun pan(self, x: Float, y: Float) -> EStage[K] = EStage(..self, camX: x, camY: y)
58
63
 
59
- fun zoom(self, s: Float) -> EStage[T] = EStage(..self, camScale: s)
64
+ fun zoom(self, s: Float) -> EStage[K] = EStage(..self, camScale: s)
60
65
 
61
- # The number of bodies.
66
+ # The number of actors.
62
67
  fun count(self) -> Int = self.root.count()
63
68
 
64
- # The body with this id, if any.
69
+ # The actor with this id, if any.
65
- fun find(self, id: Int) -> Option[T] = self.root.find(|b| b.key() == id)
70
+ fun find(self, id: Int) -> Option[Actor[K]] = self.root.find(|a| a.id == id)
66
71
 
67
- # The stage with `n` added as the last child of the body `parent`; unchanged if there is
72
+ # The stage with `n` added as the last child of the actor `parent`; unchanged if there
68
- # no such body.
73
+ # is no such actor.
69
- fun add(self, parent: Int, n: ETree[T]) -> EStage[T] =
74
+ fun add(self, parent: Int, n: ETree[Actor[K]]) -> EStage[K] =
70
- self.withRoot(self.root.replace(|b| b.key() == parent, |p| p.addChild(n)))
75
+ self.withRoot(self.root.replace(|a| a.id == parent, |p| p.addChild(n)))
71
76
 
72
- # The stage with the body `id` replaced by `f(body)`; everything off its path is shared.
77
+ # The stage with the actor `id` replaced by `f(actor)`; everything off its path is
78
+ # shared.
73
- fun update(self, id: Int, f: fn(T) -> T) -> EStage[T] =
79
+ fun update(self, id: Int, f: fn(Actor[K]) -> Actor[K]) -> EStage[K] =
74
- self.withRoot(self.root.update(|b| b.key() == id, f))
80
+ self.withRoot(self.root.update(|a| a.id == id, f))
75
81
 
76
- # The stage without the body `id` and its subtree.
82
+ # The stage with the kind of the actor `id` replaced by `f(kind)`.
77
- fun kill(self, id: Int) -> EStage[T] = self.withRoot(self.root.filter(|b| b.key() != id))
83
+ fun updateKind(self, id: Int, f: fn(K) -> K) -> EStage[K] =
84
+ self.withRoot(self.root.update(|a| a.id == id, |a| a.withKind(f(a.kind))))
78
85
 
86
+ # The stage without the actor `id` and its subtree.
87
+ fun kill(self, id: Int) -> EStage[K] = self.withRoot(self.root.filter(|a| a.id != id))
88
+
79
- # The next tick: every live body's `step`, parents before children, siblings in order,
89
+ # The next tick: every live actor's `a.kind.step(a, ..)`, parents before children,
80
- # each given its parent's context under `ctx` (the context above the root). A body that
90
+ # siblings in order, each given its parent's context under `ctx` (the context above the
81
- # returns a dead version is dropped with its subtree. Every command in `ctx.out` takes
91
+ # root). An actor whose step returns it dead is dropped with its subtree. Every command in `ctx.out` takes
82
92
  # effect after the step, as `apply` would apply it, and `ctx.out` is left empty. Those
83
- # pushed before the step are applied in its own walk: a body killed this way is dropped
93
+ # pushed before the step are applied in its own walk: an actor killed this way is
84
- # without its `step`, and a spawned node goes on top of its parent's children
94
+ # dropped without its step, and a spawned node goes on top of its parent's children
85
- # unstepped. Those pushed during the step (by the bodies) are applied by `apply` once
95
+ # unstepped. Those pushed during the step (by the kinds) are applied by `apply` once
86
- # the walk is over, as a second batch.
96
+ # the walk is over, as a second batch. Hidden actors are stepped too.
87
- fun step(self, ctx: ECtx[T], dt: Float) -> EStage[T] =
97
+ fun step(self, ctx: ECtx[K], dt: Float) -> EStage[K] =
88
98
  w := EWalk.of(ctx.out)
89
99
  ctx.out.clear()
90
- empty: ETree[T] := EEmpty
100
+ empty: ETree[Actor[K]] := EEmpty
91
101
  r := estep(self.root, ctx, dt, w, empty)
92
102
  s := EStage(..self, root: r).apply(ctx.out)
93
103
  ctx.out.clear()
94
104
  s
95
105
 
96
- # The stage with the commands applied, in one pass over the tree: every `EKill` body
106
+ # The stage with the commands applied, in one pass over the tree: every `EKill` actor
97
107
  # goes with its subtree, and every `ESpawn` node goes on top of its parent's children,
98
108
  # in the order pushed. A spawn whose parent is not on the stage, or is killed by the
99
109
  # same batch, is dropped.
100
- fun apply(self, cmds: Slice[ECmd[T]]) -> EStage[T] =
110
+ fun apply(self, cmds: Slice[ECmd[K]]) -> EStage[K] =
101
111
  if cmds.length() == 0
102
112
  self
103
113
  else
104
114
  w := EWalk.of(cmds)
105
- empty: ETree[T] := EEmpty
115
+ empty: ETree[Actor[K]] := EEmpty
106
116
  EStage(..self, root: eapply(self.root, w, empty))
107
117
 
108
- # What `draw` would draw, in order: each shown body with its stage transform and alpha,
118
+ # What `draw` would draw, in order: each shown actor with its stage transform and alpha,
109
119
  # a parent before its children, siblings first to last.
110
- fun flatten(self) -> Slice[EDrawn[T]] =
120
+ fun flatten(self) -> Slice[EDrawn[K]] =
111
- out := Slice[EDrawn[T]]()
121
+ out := Slice[EDrawn[K]]()
112
122
  ecollect(self.root, Affine.Identity, 1.0, out)
113
123
  out
114
124
 
115
- # The topmost shown body at a stage point.
125
+ # The topmost shown actor at a stage point whose kind says it is hit there
126
+ # (`a.kind.hit(a, p)`, with `p` in the actor's own coordinates).
116
- fun hit(self, x: Float, y: Float) -> Option[T] = ehit(self.root, Vec2(x: x, y: y))
127
+ fun hit(self, x: Float, y: Float) -> Option[Actor[K]] = ehit(self.root, Vec2(x: x, y: y))
128
+
129
+ # The id of that actor, if any.
130
+ fun hitId(self, x: Float, y: Float) -> Option[Int] = self.hit(x, y).map(|a| a.id)
117
131
 
118
132
  fun draw(self, io: Io) =
119
133
  gfx.setCamera(io, self.camX, self.camY, self.camScale)
120
134
  edraw(self.root, io, Affine.Identity, 1.0)
121
135
  gfx.resetCamera(io)
122
136
 
123
- # One entry of the draw list: a shown body, its stage transform and its alpha.
137
+ # One entry of the draw list: a shown actor, its stage transform and its alpha.
124
- struct EDrawn[T](body: T, m: Affine, alpha: Float)
138
+ struct EDrawn[K](actor: Actor[K], m: Affine, alpha: Float)
125
139
 
126
140
  # The largest id range the bitsets cover is [0, 2^22).
127
141
  BitsCap = 4194304
@@ -135,18 +149,18 @@ struct EScan(mut top: Int, mut ok: Bool) =
135
149
  self.top = id
136
150
 
137
151
  # A batch of commands as a walk uses them: the ids to drop, and the nodes to add under
138
- # each parent id, in the order pushed. The walk asks about every body, so beside the set
152
+ # each parent id, in the order pushed. The walk asks about every actor, so beside the set
139
153
  # and the map it keeps a bitset of each (one bit per id up to the batch's largest): most
140
- # answers are a shift and a mask, and only a body with spawns does a hash lookup. Ids
154
+ # answers are a shift and a mask, and only an actor with spawns does a hash lookup. Ids
141
155
  # below 0 or from 2^22 up make that batch use the set and the map alone.
142
- struct EWalk[T](
156
+ struct EWalk[K](
143
- kills: Set[Int], spawns: Map[Int, Slice[ETree[T]]],
157
+ kills: Set[Int], spawns: Map[Int, Slice[ETree[Actor[K]]]],
144
158
  hasKills: Bool, hasSpawns: Bool,
145
159
  bitsOk: Bool, killBits: Array[Int], spawnBits: Array[Int]) =
146
160
 
147
- fun of(cmds: Slice[ECmd[T]]) -> EWalk[T] =
161
+ fun of(cmds: Slice[ECmd[K]]) -> EWalk[K] =
148
162
  kills := Set[Int]()
149
- spawns: Map[Int, Slice[ETree[T]]] := Map.empty()
163
+ spawns: Map[Int, Slice[ETree[Actor[K]]]] := Map.empty()
150
164
  scan := EScan(top: 0, ok: true)
151
165
  for c := range cmds
152
166
  match c
@@ -158,7 +172,7 @@ struct EWalk[T](
158
172
  if Some(xs) := spawns.get(parent)
159
173
  xs.push(node)
160
174
  else
161
- ys := Slice[ETree[T]]()
175
+ ys := Slice[ETree[Actor[K]]]()
162
176
  ys.push(node)
163
177
  spawns.set(parent, ys)
164
178
  words := if scan.ok && cmds.length() > 0 then scan.top / 64 + 1 else 0
@@ -174,7 +188,7 @@ struct EWalk[T](
174
188
  hasKills: kills.length() > 0, hasSpawns: spawns.length() > 0,
175
189
  bitsOk: scan.ok, killBits: killBits, spawnBits: spawnBits)
176
190
 
177
- # Whether the body `id` is killed by this batch.
191
+ # Whether the actor `id` is killed by this batch.
178
192
  fun killed(self, id: Int) -> Bool =
179
193
  if !self.hasKills
180
194
  false
@@ -183,8 +197,8 @@ struct EWalk[T](
183
197
  else
184
198
  self.kills.has(id)
185
199
 
186
- # The nodes to add under the body `id`, as a chain in the order pushed (empty if none).
200
+ # The nodes to add under the actor `id`, as a chain in the order pushed (empty if none).
187
- fun spawnsUnder(self, id: Int) -> ETree[T] =
201
+ fun spawnsUnder(self, id: Int) -> ETree[Actor[K]] =
188
202
  if !self.hasSpawns || {self.bitsOk && !ewalkHas(self.spawnBits, id)}
189
203
  EEmpty
190
204
  else
@@ -201,165 +215,146 @@ fun ewalkHas(bits: Array[Int], id: Int) -> Bool =
201
215
  if id < 0 || w >= bits.length() then false else {{bits.get(w) >> {id % 64}} & 1} == 1
202
216
 
203
217
  # The chain `t` one step on, under `ctx` (the context of the chain's parent), without the
204
- # bodies `w` kills, and followed by `extra` (the parent's spawns, unstepped). A body with
218
+ # actors `w` kills, and followed by `extra` (the parent's spawns, unstepped). An actor with
205
219
  # children (or spawns) gets one context for them, made from its transform before its
206
220
  # step. Every kept node is rebuilt: in place when nothing else holds `t`.
207
- fun estep[T](t: ETree[T], ctx: ECtx[T], dt: Float, w: EWalk[T], extra: ETree[T]) -> ETree[T] = match t
221
+ fun estep[K](t: ETree[Actor[K]], ctx: ECtx[K], dt: Float, w: EWalk[K], extra: ETree[Actor[K]]) -> ETree[Actor[K]] = match t
208
222
  EEmpty => extra
209
- ENode(b, k, n) =>
223
+ ENode(a, k, n) =>
210
- if b.gone() || {w.hasKills && w.killed(b.key())}
224
+ if a.dead || {w.hasKills && w.killed(a.id)}
211
225
  estep(n, ctx, dt, w, extra)
212
226
  else
213
- xs := if w.hasSpawns then w.spawnsUnder(b.key()) else EEmpty
227
+ xs := if w.hasSpawns then w.spawnsUnder(a.id) else EEmpty
214
228
  walkKids := !k.isEmpty() || !xs.isEmpty()
215
- cc := if walkKids then ctx.under(b.local(), b.opacity()) else ctx
229
+ cc := if walkKids then ctx.under(a.local(), a.opacity()) else ctx
216
- nb := b.step(ctx, dt)
230
+ na := a.kind.step(a, ctx, dt)
217
- if nb.gone()
231
+ if na.dead
218
232
  estep(n, ctx, dt, w, extra)
219
233
  else
220
234
  k2 := if walkKids then estep(k, cc, dt, w, xs) else k
221
- ENode(value: nb, firstChild: k2, nextSibling: estep(n, ctx, dt, w, extra))
235
+ ENode(value: na, firstChild: k2, nextSibling: estep(n, ctx, dt, w, extra))
222
236
 
223
- # The chain `t` without the bodies `w` kills and followed by `extra`, with the same done
237
+ # The chain `t` without the actors `w` kills and followed by `extra`, with the same done
224
238
  # in every subtree: `apply`'s walk.
225
- fun eapply[T](t: ETree[T], w: EWalk[T], extra: ETree[T]) -> ETree[T] = match t
239
+ fun eapply[K](t: ETree[Actor[K]], w: EWalk[K], extra: ETree[Actor[K]]) -> ETree[Actor[K]] = match t
226
240
  EEmpty => extra
227
- ENode(b, k, n) =>
241
+ ENode(a, k, n) =>
228
- if w.killed(b.key())
242
+ if w.killed(a.id)
229
243
  eapply(n, w, extra)
230
244
  else
231
- xs := w.spawnsUnder(b.key())
245
+ xs := w.spawnsUnder(a.id)
232
246
  k2 := if k.isEmpty() && xs.isEmpty() then k else eapply(k, w, xs)
233
- ENode(value: b, firstChild: k2, nextSibling: eapply(n, w, extra))
247
+ ENode(value: a, firstChild: k2, nextSibling: eapply(n, w, extra))
234
-
248
+
235
- fun ecollect[T](t: ETree[T], parent: Affine, alpha: Float, out: Slice[EDrawn[T]]) =
249
+ fun ecollect[K](t: ETree[Actor[K]], parent: Affine, alpha: Float, out: Slice[EDrawn[K]]) =
236
- if ENode(b, k, n) := t
250
+ if ENode(a, k, n) := t
237
- if b.shown()
251
+ if a.shown()
238
- m := parent.mul(b.local())
252
+ m := parent.mul(a.local())
239
- a := alpha * b.opacity()
253
+ al := alpha * a.opacity()
240
- out.push(EDrawn(body: b, m: m, alpha: a))
254
+ out.push(EDrawn(actor: a, m: m, alpha: al))
241
- ecollect(k, m, a, out)
255
+ ecollect(k, m, al, out)
242
256
  ecollect(n, parent, alpha, out)
243
257
 
244
- fun edraw[T](t: ETree[T], io: Io, parent: Affine, alpha: Float) =
258
+ fun edraw[K](t: ETree[Actor[K]], io: Io, parent: Affine, alpha: Float) =
245
- if ENode(b, k, n) := t
259
+ if ENode(a, k, n) := t
246
- if b.shown()
260
+ if a.shown()
247
- m := parent.mul(b.local())
261
+ m := parent.mul(a.local())
248
- a := alpha * b.opacity()
262
+ al := alpha * a.opacity()
249
- b.paint(io, m, a)
263
+ a.kind.paint(a, io, m, al)
250
- edraw(k, io, m, a)
264
+ edraw(k, io, m, al)
251
265
  edraw(n, io, parent, alpha)
252
266
 
253
- # The topmost shown body under `p` (a point in the chain's parent's coordinates): later
267
+ # The topmost shown actor under `p` (a point in the chain's parent's coordinates) that its
254
- # siblings first, and in each, its children before itself.
268
+ # kind says is hit: later siblings first, and in each, its children before itself.
255
- fun ehit[T](t: ETree[T], p: Vec2) -> Option[T] = match t
269
+ fun ehit[K](t: ETree[Actor[K]], p: Vec2) -> Option[Actor[K]] = match t
256
270
  EEmpty => None
257
- ENode(b, k, n) =>
271
+ ENode(a, k, n) =>
258
272
  match ehit(n, p)
259
273
  Some(found) => Some(found)
260
274
  None =>
261
- if b.shown()
275
+ if a.shown()
262
- q := b.local().inverse().apply(p)
276
+ q := a.local().inverse().apply(p)
263
277
  match ehit(k, q)
264
278
  Some(found) => Some(found)
265
- None => if b.hit(q) then Some(b) else None
279
+ None => if a.kind.hit(a, q) then Some(a) else None
266
280
  else
267
281
  None
268
282
 
269
283
  # --- tests ---
270
284
 
271
- # A body for the tests: a plain one, or one of four kinds with behaviour, each around an
285
+ # The kinds for the tests: a plain one, or one of four with behaviour.
272
- # `EBody`.
273
- enum TBody =
286
+ enum TKind =
274
- | TPlain(body: EBody)
287
+ | TPlain
275
288
  # moves by vx per second; dies when `ttl` runs out (never if it starts at -1)
276
- | TDrifter(body: EBody, vx: Float, ttl: Int)
289
+ | TDrifter(vx: Float, ttl: Int)
277
290
  # spawns a drifter under the root (id 0) each step, with ids from `next` on
278
- | TSpawner(body: EBody, next: Int)
291
+ | TSpawner(next: Int)
279
292
  # keeps the world transform and alpha its context gave it in its last step
280
- | TProbe(body: EBody, seen: Affine, seenA: Float)
293
+ | TProbe(seen: Affine, seenA: Float)
281
294
  # pushes `EKill(target)` in each step
282
- | TKiller(body: EBody, target: Int)
295
+ | TKiller(target: Int)
283
-
284
- fun base(self) -> EBody = match self
285
- TPlain(b) => b
286
- TDrifter(b, _, _) => b
287
- TSpawner(b, _) => b
288
- TProbe(b, _, _) => b
289
- TKiller(b, _) => b
290
-
291
- fun key(self) -> Int = self.base().id
292
-
293
- fun gone(self) -> Bool = self.base().dead
294
-
295
- fun shown(self) -> Bool = self.base().shown()
296
-
297
- fun opacity(self) -> Float = self.base().color.a
298
-
299
- fun local(self) -> Affine = self.base().local()
300
296
 
301
- fun hit(self, p: Vec2) -> Bool = self.base().hit(p)
302
-
303
- fun paint(self, io: Io, m: Affine, alpha: Float) = self.base().paint(io, m, alpha)
304
-
305
- fun step(self, ctx: ECtx[TBody], dt: Float) -> TBody = match self
297
+ fun step(self, a: Actor[TKind], ctx: ECtx[TKind], dt: Float) -> Actor[TKind] = match self
306
- TPlain(_) => self
298
+ TPlain => a
307
- TDrifter(b, vx, ttl) =>
299
+ TDrifter(vx, ttl) =>
308
300
  if ttl == 0
309
- TDrifter(body: b.killed(), vx: vx, ttl: ttl)
301
+ a.killed()
310
302
  else
311
- TDrifter(body: b.moveBy(vx * dt, 0.0), vx: vx, ttl: if ttl > 0 then ttl - 1 else ttl)
303
+ Actor(..a, x: a.x + vx * dt, kind: TDrifter(vx: vx, ttl: if ttl > 0 then ttl - 1 else ttl))
312
- TSpawner(b, next) =>
304
+ TSpawner(next) =>
313
305
  ctx.out.push(ESpawn(parent: 0, node: tdrifter(next, 0.0, 0.0, -1)))
314
- TSpawner(body: b, next: next + 1)
306
+ a.withKind(TSpawner(next: next + 1))
315
- TProbe(b, _, _) => TProbe(body: b, seen: ctx.worldOf(b.local()), seenA: ctx.alphaOf(b.color.a))
307
+ TProbe(_, _) => a.withKind(TProbe(seen: ctx.worldOf(a.local()), seenA: ctx.alphaOf(a.opacity())))
316
- TKiller(b, target) =>
308
+ TKiller(target) =>
317
309
  ctx.out.push(EKill(id: target))
318
- self
310
+ a
311
+
312
+ fun paint(self, a: Actor[TKind], io: Io, m: Affine, alpha: Float) = a.paintBox(io, m, alpha)
319
313
 
320
- fun tdrifter(id: Int, x: Float, vx: Float, ttl: Int) -> ETree[TBody] =
314
+ fun hit(self, a: Actor[TKind], p: Vec2) -> Bool = a.hitBox(p)
321
- b := EBody(
322
- id: id, x: x, y: 0.0, width: 10.0, height: 10.0, originX: 0.0, originY: 0.0,
323
- scaleX: 1.0, scaleY: 1.0, rotation: 0.0, color: Color.White, visible: true, dead: false)
324
- etree.leaf(TDrifter(body: b, vx: vx, ttl: ttl))
325
315
 
326
- fun tspawner(id: Int, next: Int) -> ETree[TBody] = etree.leaf(TSpawner(body: EBody.group(id, 0.0, 0.0), next: next))
316
+ fun tdrifter(id: Int, x: Float, vx: Float, ttl: Int) -> ETree[Actor[TKind]] =
317
+ etree.leaf(Actor.rect(id, x, 0.0, 10.0, 10.0, Color.White, TDrifter(vx: vx, ttl: ttl)))
327
318
 
328
- fun tkiller(id: Int, target: Int) -> ETree[TBody] = etree.leaf(TKiller(body: EBody.group(id, 0.0, 0.0), target: target))
319
+ fun tspawner(id: Int, next: Int) -> ETree[Actor[TKind]] = etree.leaf(Actor.group(id, 0.0, 0.0, TSpawner(next: next)))
329
320
 
321
+ fun tkiller(id: Int, target: Int) -> ETree[Actor[TKind]] = etree.leaf(Actor.group(id, 0.0, 0.0, TKiller(target: target)))
322
+
330
- fun tprobe(id: Int, x: Float, y: Float, r: Float) -> TBody =
323
+ fun tprobe(id: Int, x: Float, y: Float, r: Float) -> Actor[TKind] =
331
- b := EBody(
324
+ Actor(
332
325
  id: id, x: x, y: y, width: 1.0, height: 1.0, originX: 2.0, originY: 1.0,
333
- scaleX: 0.5, scaleY: 3.0, rotation: r, color: Color.White.withAlpha(0.5), visible: true, dead: false)
326
+ scaleX: 0.5, scaleY: 3.0, rotation: r, color: Color.White.withAlpha(0.5), visible: true, dead: false,
334
- TProbe(body: b, seen: Affine.Identity, seenA: 0.0)
327
+ kind: TProbe(seen: Affine.Identity, seenA: 0.0))
328
+
329
+ fun trect(id: Int, x: Float, y: Float, w: Float) -> ETree[Actor[TKind]] = etree.leaf(Actor.rect(id, x, y, w, w, Color.Red, TPlain))
335
330
 
336
- fun trect(id: Int, x: Float, y: Float, w: Float) -> ETree[TBody] = etree.leaf(TPlain(body: EBody.rect(id, x, y, w, w, Color.Red)))
331
+ fun tturned(id: Int, x: Float, y: Float, s: Float, r: Float) -> Actor[TKind] = Actor.turned(id, x, y, s, r, TPlain)
337
332
 
338
- fun tgroup(id: Int, x: Float, y: Float, s: Float, r: Float, kids: List[ETree[TBody]]) -> ETree[TBody] =
333
+ fun tgroup(id: Int, x: Float, y: Float, s: Float, r: Float, kids: List[ETree[Actor[TKind]]]) -> ETree[Actor[TKind]] =
339
- etree.of(TPlain(body: EBody.turned(id, x, y, s, r)), kids)
334
+ etree.of(tturned(id, x, y, s, r), kids)
340
335
 
341
- fun tstage() -> EStage[TBody] = EStage.of(TPlain(body: EBody.group(0, 0.0, 0.0)))
336
+ fun tstage() -> EStage[TKind] = EStage.of(Actor.group(0, 0.0, 0.0, TPlain))
342
337
 
343
- fun tids(s: EStage[TBody]) -> Str = s.root.fold("", |a, b| if a == "" then "{b.key()}" else "{a},{b.key()}")
338
+ fun tids(s: EStage[TKind]) -> Str = s.root.fold("", |acc, a| if acc == "" then "{a.id}" else "{acc},{a.id}")
344
339
 
345
- fun tx(s: EStage[TBody], id: Int) -> Float = s.find(id).unwrap().base().x
340
+ fun tx(s: EStage[TKind], id: Int) -> Float = s.find(id).unwrap().x
346
341
 
347
342
  fun tnear(a: Float, b: Float) -> Bool = {a - b}.abs() < 0.0001
348
343
 
349
344
  fun tsameM(a: Affine, b: Affine) -> Bool =
350
345
  tnear(a.a, b.a) && tnear(a.b, b.b) && tnear(a.c, b.c) && tnear(a.d, b.d) && tnear(a.e, b.e) && tnear(a.f, b.f)
351
346
 
352
- fun tseen(s: EStage[TBody], id: Int) -> Affine = match s.find(id).unwrap()
347
+ fun tseen(s: EStage[TKind], id: Int) -> Affine = match s.find(id).unwrap().kind
353
- TProbe(_, seen, _) => seen
348
+ TProbe(seen, _) => seen
354
349
  _ => Affine.Identity
355
350
 
356
- fun tseenA(s: EStage[TBody], id: Int) -> Float = match s.find(id).unwrap()
351
+ fun tseenA(s: EStage[TKind], id: Int) -> Float = match s.find(id).unwrap().kind
357
- TProbe(_, _, a) => a
352
+ TProbe(_, a) => a
358
353
  _ => 0.0
359
354
 
360
355
  test "step returns a new stage and leaves a kept one as it was"
361
356
  s0 := tstage().add(0, tdrifter(1, 0.0, 10.0, -1)).add(0, tdrifter(2, 5.0, -10.0, -1))
362
- ctx := ECtx[TBody]()
357
+ ctx := ECtx[TKind]()
363
358
  s1 := s0.step(ctx, 0.5)
364
359
  s2 := s1.step(ctx, 0.5)
365
360
  assert tx(s0, 1) == 0.0
@@ -369,25 +364,35 @@ test "step returns a new stage and leaves a kept one as it was"
369
364
  assert tids(s0) == "0,1,2"
370
365
  assert tids(s2) == "0,1,2"
371
366
 
372
- test "a step that changes nothing keeps every body"
367
+ test "a step that changes nothing keeps every actor"
373
368
  s0 := tstage().add(0, trect(1, 0.0, 0.0, 5.0)).add(0, tgroup(2, 0.0, 0.0, 1.0, 0.0, [trect(3, 0.0, 0.0, 5.0)]))
374
- s1 := s0.step(ECtx[TBody](), 1.0)
369
+ s1 := s0.step(ECtx[TKind](), 1.0)
375
370
  assert tids(s1) == "0,1,2,3"
376
371
  assert s1.find(3).unwrap() == s0.find(3).unwrap()
377
372
 
378
- test "a body that returns a dead version is dropped with its subtree in the same step"
373
+ test "an actor whose step returns it dead is dropped with its subtree in the same step"
379
374
  s := tstage().add(0, tdrifter(1, 0.0, 1.0, 1)).add(0, trect(2, 0.0, 0.0, 5.0)).add(1, trect(3, 0.0, 0.0, 5.0))
380
375
  assert tids(s) == "0,1,3,2"
381
- ctx := ECtx[TBody]()
376
+ ctx := ECtx[TKind]()
382
377
  s1 := s.step(ctx, 1.0)
383
378
  assert tids(s1) == "0,1,3,2"
384
379
  s2 := s1.step(ctx, 1.0)
385
380
  assert tids(s2) == "0,2"
386
381
  assert s2.find(3).isNone()
387
382
 
383
+ test "a dead or hidden actor: dead ones go with their subtree, hidden ones still step"
384
+ s := tstage().add(0, tdrifter(1, 0.0, 1.0, -1)).add(1, trect(2, 0.0, 0.0, 5.0)).add(0, trect(3, 0.0, 0.0, 5.0))
385
+ hidden := s.update(1, |a| a.withVisible(false))
386
+ h1 := hidden.step(ECtx[TKind](), 1.0)
387
+ assert tx(h1, 1) == 1.0
388
+ assert h1.flatten().length() == 2
389
+ assert h1.hit(1.0, 1.0).unwrap().id == 3
390
+ dead := s.update(1, |a| a.killed()).step(ECtx[TKind](), 1.0)
391
+ assert tids(dead) == "0,3"
392
+
388
393
  test "spawns pushed to ctx.out are added after the step, on top"
389
394
  s := tstage().add(0, tspawner(1, 10))
390
- ctx := ECtx[TBody]()
395
+ ctx := ECtx[TKind]()
391
396
  s1 := s.step(ctx, 1.0)
392
397
  assert tids(s1) == "0,1,10"
393
398
  assert ctx.out.length() == 0
@@ -395,7 +400,7 @@ test "spawns pushed to ctx.out are added after the step, on top"
395
400
 
396
401
  test "apply kills and spawns in one pass, in order"
397
402
  s := tstage().add(0, tgroup(1, 0.0, 0.0, 1.0, 0.0, [trect(2, 0.0, 0.0, 1.0), trect(3, 0.0, 0.0, 1.0)])).add(0, trect(4, 0.0, 0.0, 1.0))
398
- cmds := Slice[ECmd[TBody]]()
403
+ cmds := Slice[ECmd[TKind]]()
399
404
  cmds.push(EKill(id: 2))
400
405
  cmds.push(ESpawn(parent: 1, node: trect(5, 0.0, 0.0, 1.0)))
401
406
  cmds.push(ESpawn(parent: 0, node: trect(6, 0.0, 0.0, 1.0)))
@@ -406,68 +411,73 @@ test "apply kills and spawns in one pass, in order"
406
411
  assert tids(s) == "0,1,2,3,4"
407
412
  assert s.kill(1).count() == 2
408
413
 
409
- test "update by id changes one body and shares its untouched siblings"
414
+ test "update by id changes one actor and shares its untouched siblings"
410
415
  s := tstage().add(0, tgroup(1, 0.0, 0.0, 1.0, 0.0, [trect(2, 0.0, 0.0, 1.0), trect(3, 0.0, 0.0, 1.0)]))
411
416
  s1 := s.add(0, tgroup(4, 0.0, 0.0, 1.0, 0.0, [trect(5, 0.0, 0.0, 1.0)]))
412
- u := s1.update(2, |b| TPlain(body: EBody.rect(b.key(), 9.0, 9.0, 1.0, 1.0, Color.Blue)))
417
+ u := s1.update(2, |a| a.at(9.0, 9.0).tint(Color.Blue))
413
418
  assert tx(u, 2) == 9.0
414
419
  assert tx(s1, 2) == 0.0
415
420
  # 2's later sibling (3) and 1's later sibling (the group 4) are the same nodes
416
421
  assert u.root.kids().kids().rest() == s1.root.kids().kids().rest()
417
422
  assert u.root.kids().rest() == s1.root.kids().rest()
423
+ k := s1.updateKind(5, |_| TDrifter(vx: 2.0, ttl: -1)).step(ECtx[TKind](), 1.0)
424
+ assert tx(k, 5) == 2.0
418
425
 
419
- test "flatten gives each shown body its stage transform, parents first"
426
+ test "flatten gives each shown actor its stage transform, parents first"
420
427
  g := tgroup(1, 100.0, 0.0, 2.0, Float.HalfPi, [trect(2, 10.0, 0.0, 10.0), trect(3, 0.0, 0.0, 30.0)])
421
428
  s := tstage().add(0, g).add(0, trect(4, 5.0, 5.0, 1.0))
422
429
  d := s.flatten()
423
430
  assert d.length() == 5
424
431
  ids := Slice[Int]()
425
432
  for e := range d
426
- ids.push(e.body.key())
433
+ ids.push(e.actor.id)
427
434
  assert ids.toStr() == "[0,1,2,3,4]"
428
435
  # (0, 0) of rect 2 is (10, 0) in the group, turned a quarter and doubled: (100, 20)
429
436
  p := d.at(2).m.apply(Vec2(x: 0.0, y: 0.0))
430
437
  assert tnear(p.x, 100.0) && tnear(p.y, 20.0)
431
438
  assert tnear(d.at(4).m.e, 5.0)
432
- hidden := s.update(1, |b| TPlain(body: EBody.group(b.key(), 100.0, 0.0).withVisible(false)))
439
+ hidden := s.update(1, |a| a.withVisible(false))
433
440
  assert hidden.flatten().length() == 2
441
+ # alphas multiply down the tree
442
+ faded := s.update(1, |a| a.fade(0.5)).update(2, |a| a.fade(0.5)).flatten()
443
+ assert faded.at(2).alpha == 0.25 && faded.at(3).alpha == 0.5 && faded.at(4).alpha == 1.0
434
444
 
435
- test "hit finds the topmost body: later siblings and children first"
445
+ test "hit finds the topmost actor: later siblings and children first"
436
446
  g := tgroup(1, 100.0, 0.0, 2.0, Float.HalfPi, [trect(2, 0.0, 0.0, 30.0), trect(3, 10.0, 0.0, 10.0)])
437
447
  s := tstage().add(0, g)
438
- assert s.hit(90.0, 30.0).unwrap().key() == 3
448
+ assert s.hit(90.0, 30.0).unwrap().id == 3
439
- assert s.hit(70.0, 10.0).unwrap().key() == 2
449
+ assert s.hit(70.0, 10.0).unwrap().id == 2
440
450
  assert s.hit(10.0, 10.0).isNone()
441
451
  t := tstage().add(0, trect(5, 0.0, 0.0, 50.0)).add(0, trect(6, 25.0, 0.0, 50.0)).add(6, trect(7, 0.0, 0.0, 10.0))
442
- assert t.hit(10.0, 10.0).unwrap().key() == 5
452
+ assert t.hit(10.0, 10.0).unwrap().id == 5
443
- assert t.hit(30.0, 5.0).unwrap().key() == 7
453
+ assert t.hit(30.0, 5.0).unwrap().id == 7
444
- assert t.hit(40.0, 10.0).unwrap().key() == 6
454
+ assert t.hitId(40.0, 10.0).unwrap() == 6
445
455
 
446
- test "a body's world transform is computed when it asks, and matches the eager product"
456
+ test "an actor's world transform is computed when it asks, and matches the eager product"
447
- gb := EBody.turned(1, 100.0, 30.0, 2.0, 0.7)
457
+ gb := tturned(1, 100.0, 30.0, 2.0, 0.7)
448
- hb := EBody.turned(2, -20.0, 5.0, 1.5, -1.1).pivotAt(3.0, 4.0)
458
+ hb := tturned(2, -20.0, 5.0, 1.5, -1.1).pivotAt(3.0, 4.0)
449
459
  p := tprobe(3, 7.0, -2.0, 2.5)
450
460
  q := tprobe(4, 1.0, 1.0, 0.0)
451
- s := tstage().add(0, etree.of(TPlain(body: gb), [etree.of(TPlain(body: hb), [etree.leaf(p), etree.leaf(q)])]))
461
+ s := tstage().add(0, etree.of(gb, [etree.of(hb, [etree.leaf(p), etree.leaf(q)])]))
452
- s1 := s.step(ECtx[TBody](), 1.0)
462
+ s1 := s.step(ECtx[TKind](), 1.0)
453
463
  assert tsameM(tseen(s1, 3), gb.local().mul(hb.local()).mul(p.local()))
454
464
  assert tnear(tseenA(s1, 3), 0.5)
455
465
  # the sibling got its own transform from the same context
456
466
  assert tsameM(tseen(s1, 4), gb.local().mul(hb.local()).mul(q.local()))
457
467
 
458
468
  test "siblings with children each give their children their own world transform"
459
- g1 := EBody.turned(1, 100.0, 30.0, 2.0, 0.7)
469
+ g1 := tturned(1, 100.0, 30.0, 2.0, 0.7)
460
- g2 := EBody.turned(2, -40.0, 5.0, 0.5, -1.2)
470
+ g2 := tturned(2, -40.0, 5.0, 0.5, -1.2)
461
471
  p1 := tprobe(3, 7.0, -2.0, 2.5)
462
472
  p2 := tprobe(4, 1.0, 9.0, 0.3)
463
- s := tstage().add(0, etree.of(TPlain(body: g1), [etree.leaf(p1)])).add(0, etree.of(TPlain(body: g2), [etree.leaf(p2)]))
473
+ s := tstage().add(0, etree.of(g1, [etree.leaf(p1)])).add(0, etree.of(g2, [etree.leaf(p2)]))
464
- s1 := s.step(ECtx[TBody](), 1.0)
474
+ s1 := s.step(ECtx[TKind](), 1.0)
465
475
  assert tsameM(tseen(s1, 3), g1.local().mul(p1.local()))
466
476
  assert tsameM(tseen(s1, 4), g2.local().mul(p2.local()))
467
477
 
468
- test "a kill pushed before the step drops the body in the step's own walk, unstepped"
478
+ test "a kill pushed before the step drops the actor in the step's own walk, unstepped"
469
479
  s := tstage().add(0, tspawner(1, 10)).add(0, tgroup(2, 0.0, 0.0, 1.0, 0.0, [trect(3, 0.0, 0.0, 1.0)]))
470
- ctx := ECtx[TBody]()
480
+ ctx := ECtx[TKind]()
471
481
  ctx.out.push(EKill(id: 1))
472
482
  s2 := s.step(ctx, 1.0)
473
483
  # the spawner was not stepped, so it spawned nothing
@@ -482,7 +492,7 @@ test "a kill pushed before the step drops the body in the step's own walk, unste
482
492
  test "spawns pushed before the step go on top of their parents, in order, unstepped"
483
493
  s := tstage().add(0, tgroup(1, 0.0, 0.0, 1.0, 0.0, [trect(2, 0.0, 0.0, 1.0), trect(3, 0.0, 0.0, 1.0)]))
484
494
  s1 := s.add(0, trect(4, 0.0, 0.0, 1.0)).add(0, tgroup(9, 0.0, 0.0, 1.0, 0.0, [trect(10, 0.0, 0.0, 1.0)]))
485
- ctx := ECtx[TBody]()
495
+ ctx := ECtx[TKind]()
486
496
  ctx.out.push(ESpawn(parent: 1, node: tdrifter(5, 0.0, 10.0, -1)))
487
497
  ctx.out.push(ESpawn(parent: 4, node: trect(6, 0.0, 0.0, 1.0)))
488
498
  ctx.out.push(ESpawn(parent: 1, node: trect(7, 0.0, 0.0, 1.0)))
@@ -496,15 +506,15 @@ test "spawns pushed before the step go on top of their parents, in order, unstep
496
506
  for i := range 50
497
507
  ctx.out.push(ESpawn(parent: 4, node: trect(100 + i, 0.0, 0.0, 1.0)))
498
508
  s3 := s2.step(ctx, 1.0)
499
- ids := s3.root.kids().rest().kids().fold(Slice[Int](), |acc, b|
509
+ ids := s3.root.kids().rest().kids().fold(Slice[Int](), |acc, a|
500
- acc.push(b.key())
510
+ acc.push(a.id)
501
511
  acc
502
512
  )
503
513
  assert ids.length() == 51 && ids.at(0) == 6 && ids.at(1) == 100 && ids.at(50) == 149
504
514
 
505
- test "a kill and a spawn of the same id before the step: the old body goes, the new one stays"
515
+ test "a kill and a spawn of the same id before the step: the old actor goes, the new one stays"
506
516
  s := tstage().add(0, tgroup(1, 0.0, 0.0, 1.0, 0.0, [trect(2, 0.0, 0.0, 1.0), trect(3, 0.0, 0.0, 1.0)]))
507
- ctx := ECtx[TBody]()
517
+ ctx := ECtx[TKind]()
508
518
  ctx.out.push(EKill(id: 2))
509
519
  ctx.out.push(ESpawn(parent: 1, node: trect(2, 7.0, 0.0, 1.0)))
510
520
  s2 := s.step(ctx, 1.0)
@@ -519,8 +529,8 @@ test "a kill and a spawn of the same id before the step: the old body goes, the
519
529
 
520
530
  test "commands pushed during the step apply after those pushed before it"
521
531
  s := tstage().add(0, tkiller(1, 5)).add(0, tgroup(2, 0.0, 0.0, 1.0, 0.0, []))
522
- ctx := ECtx[TBody]()
532
+ ctx := ECtx[TKind]()
523
- # spawned by the batch before the step, then killed by a body during it
533
+ # spawned by the batch before the step, then killed by an actor during it
524
534
  ctx.out.push(ESpawn(parent: 2, node: trect(5, 0.0, 0.0, 1.0)))
525
535
  s2 := s.step(ctx, 1.0)
526
536
  assert tids(s2) == "0,1,2"
@@ -530,7 +540,7 @@ test "the bitsets cover ids up to 2^22 - 1, and the set and map take the ids pas
530
540
  big := 4194303
531
541
  s := tstage().add(0, tgroup(big, 0.0, 0.0, 1.0, 0.0, [trect(big - 1, 0.0, 0.0, 1.0)]))
532
542
  s1 := s.add(0, tgroup(big + 1, 0.0, 0.0, 1.0, 0.0, [trect(63, 0.0, 0.0, 1.0), trect(64, 0.0, 0.0, 1.0)]))
533
- ctx := ECtx[TBody]()
543
+ ctx := ECtx[TKind]()
534
544
  # in the bitsets' range: the last bit of the last word, and a word boundary
535
545
  ctx.out.push(EKill(id: big - 1))
536
546
  ctx.out.push(EKill(id: 64))
@@ -547,9 +557,9 @@ test "the bitsets cover ids up to 2^22 - 1, and the set and map take the ids pas
547
557
  ctx.out.push(EKill(id: big + 100))
548
558
  assert tids(s3.step(ctx, 1.0)) == "0,{big},{big + 1},9"
549
559
 
550
- test "a plain EBody stage: add, step, draw list"
560
+ test "a plain EBox stage: add, step, draw list"
551
- s := EStage.of(EBody.group(0, 0.0, 0.0)).add(0, etree.leaf(EBody.rect(1, 10.0, 5.0, 40.0, 20.0, Color.Red)))
561
+ s := EStage.of(EBox.group(0, 0.0, 0.0)).add(0, etree.leaf(EBox.rect(1, 10.0, 5.0, 40.0, 20.0, Color.Red)))
552
- s1 := s.step(ECtx[EBody](), 1.0)
562
+ s1 := s.step(ECtx[EBox](), 1.0)
553
563
  assert s1.count() == 2
554
564
  assert s1.flatten().at(1).m.e == 10.0
555
565
  assert s1.hit(20.0, 10.0).unwrap().id == 1