plum

#treesitter#compiler#wasm

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

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


fb07a1a — Peter John 2026-11-09T15:58:38+05:30
One scene system: std/game/scene's SceneTree (actor-trait task 8)
benchmarks/scene_trees/run.py CHANGED
@@ -18,7 +18,7 @@ Versions:
18
18
  game, game_tree master's benchmarks/scene_trees/game.plum and game_tree.plum
19
19
  enum_tree benchmarks/scene_trees/master/game_enum_tree_kept.plum: master's
20
20
  game_enum_tree.plum plus workloads 8 and 9 (master's compiler)
21
- branch benchmarks/scene_trees/game_enum_tree.plum, this branch's default
21
+ branch benchmarks/scene_trees/scene_tree.plum, this branch's default
22
22
  branch --no-fbip the same without in-place updates or cell reuse
23
23
  branch --no-fusion the same without fusion
24
24
 
@@ -77,7 +77,7 @@ def main():
77
77
  build(mplum, os.path.join(HERE, "master/game_enum_tree_kept.plum"), exes["enum_tree"], [], master, master)
78
78
  for name, flags in BRANCH:
79
79
  exes[name] = os.path.join(out, "b" + "".join(flags).replace("-", "_"))
80
- build("target/debug/plum", os.path.join(HERE, "game_enum_tree.plum"), exes[name], flags, ".")
80
+ build("target/debug/plum", os.path.join(HERE, "scene_tree.plum"), exes[name], flags, ".")
81
81
  versions = MASTER + [b for b, _ in BRANCH]
82
82
  sizes = [int(x) for x in args.sizes.split(",")]
83
83
  workloads = [int(x) for x in args.workloads.split(",")]
benchmarks/scene_trees/{game_enum_tree.plum → scene_tree.plum} RENAMED
@@ -12,14 +12,14 @@ import std/game/Vec2
12
12
  import std/game/Affine
13
13
  import std/game/Color
14
14
  import std/collections/functional/FRoseTree
15
- import std/game_enum_tree/Place
15
+ import std/game/scene/Place
16
- import std/game_enum_tree/Actor
16
+ import std/game/scene/Actor
17
- import std/game_enum_tree/ECtx
17
+ import std/game/scene/Ctx
18
- import std/game_enum_tree/EStage
18
+ import std/game/scene/SceneTree
19
19
 
20
20
  # Scene-tree benchmark, branch version: master's benchmarks/scene_trees/game_enum_tree.plum
21
21
  # (a persistent tree of immutable bodies, referred to by id) in the branch's language, on
22
- # the branch's std/game_enum_tree. It builds the same scene from the same random numbers as
22
+ # the branch's scene tree (std/game/scene). It builds the same scene from the same random numbers as
23
23
  # master's three programs and prints the same checksums; see
24
24
  # docs/benchmarks/2026-11-08-scene-trees-branch.md and run.py.
25
25
  #
@@ -39,7 +39,7 @@ import std/game_enum_tree/EStage
39
39
  # world transform is computed.
40
40
  # 6 step, eager transforms: every body's world transform is computed each tick.
41
41
  # 7 churn, apply after: the kills and spawns are pushed after the step and applied with
42
- # a second walk (`EStage.apply`).
42
+ # a second walk (`SceneTree.apply`).
43
43
  # 8 step, 60 kept: 1 with the last 60 stages kept (a ring of snapshots), so nothing is
44
44
  # only held once and no cell can be reused.
45
45
  # 9 churn, 60 kept: 2 with the last 60 stages kept.
@@ -52,7 +52,7 @@ struct Rng(mut s: Int) =
52
52
  fun float(self, k: Int) -> Float = Float(self.next(k * 10)) / 10.0
53
53
 
54
54
  # The scene's actors are `Actor[Int]` (the benchmark sends no messages): the groups are
55
- # std's `Group`, which a step returns as it is, and the leaves are `Bod`s, master's `Leaf`
55
+ # `Turned`s, which a step returns as they are, and the leaves are `Bod`s, master's `Leaf`
56
56
  # (master's `EBody` fields and the velocity): a 20 by 20 red box that moves by (vx, vy) and
57
57
  # bounces. A leaf keeps its position in its own fields and makes its `Place` when asked:
58
58
  # with a `Place` field moved by a nested spread (`Bod(..self, at: self.at.moveTo(..))`)
@@ -67,15 +67,21 @@ struct Bod(id: Int, x: Float, y: Float, vx: Float, vy: Float) is Actor[Int] =
67
67
 
68
68
  fun hit(self, p: Vec2) -> Bool = actor.boxHit(20.0, 20.0, p)
69
69
 
70
- fun step(self, ctx: ECtx[Int], dt: Float) -> Bod =
70
+ fun step(self, ctx: Ctx[Int], dt: Float) -> Bod =
71
71
  nx := self.x + self.vx * dt
72
72
  ny := self.y + self.vy * dt
73
73
  vx := if nx < 0.0 || nx > 200.0 then 0.0 - self.vx else self.vx
74
74
  vy := if ny < 0.0 || ny > 200.0 then 0.0 - self.vy else self.vy
75
75
  Bod(..self, x: nx, y: ny, vx: vx, vy: vy)
76
76
 
77
+ # A group at (x, y), scaled by `s` and turned by `r` radians: it paints nothing.
78
+ struct Turned(id: Int, x: Float, y: Float, s: Float, r: Float) is Actor[Int] =
79
+ fun key(self) -> Int = self.id
80
+
81
+ fun place(self) -> Place = place.turned(self.x, self.y, self.s, self.r)
82
+
77
83
  fun group(id: Int, x: Float, y: Float, s: Float, r: Float) -> Actor[Int] =
78
- Group(id: id, at: place.turned(x, y, s, r))
84
+ Turned(id: id, x: x, y: y, s: s, r: r)
79
85
 
80
86
  fun newLeaf(rng: Rng, id: Int) -> FRoseTree[Actor[Int]] =
81
87
  x := rng.float(200)
@@ -92,7 +98,7 @@ fun bench(n: Int) -> Bench = Bench(live: Slice[Int](), rng: Rng(s: 12345), nextI
92
98
 
93
99
  # The scene, built bottom up as master builds it: each group's children first, then the
94
100
  # groups under the root. Ids: the root 0, the groups 1 to 10, the leaves from 11.
95
- fun build(n: Int, sc: Bench) -> EStage[Int] =
101
+ fun build(n: Int, sc: Bench) -> SceneTree[Int] =
96
102
  kids := Slice[Slice[FRoseTree[Actor[Int]]]]()
97
103
  for g := range 10
98
104
  kids.push(Slice[FRoseTree[Actor[Int]]]())
@@ -103,10 +109,10 @@ fun build(n: Int, sc: Bench) -> EStage[Int] =
103
109
  for g := range 10
104
110
  gb := group(g + 1, Float(100 + 300 * {g % 5}), Float(100 + 300 * {g / 5}), 1.0 + 0.05 * Float(g), 0.1 * Float(g))
105
111
  empty: FRoseTree[Actor[Int]] := FRoseEmpty
106
- groups.push(FRoseNode(value: gb, firstChild: estage.echainFrom(kids.at(g), 0), nextSibling: empty))
112
+ groups.push(FRoseNode(value: gb, firstChild: scenetree.chainFrom(kids.at(g), 0), nextSibling: empty))
107
113
  empty: FRoseTree[Actor[Int]] := FRoseEmpty
108
- root := FRoseNode(value: group(0, 0.0, 0.0, 1.0, 0.0), firstChild: estage.echainFrom(groups, 0), nextSibling: empty)
114
+ root := FRoseNode(value: group(0, 0.0, 0.0, 1.0, 0.0), firstChild: scenetree.chainFrom(groups, 0), nextSibling: empty)
109
- EStage(root: root, camX: 0.0, camY: 0.0, camScale: 1.0)
115
+ SceneTree(root: root, camX: 0.0, camY: 0.0, camScale: 1.0)
110
116
 
111
117
  # Every node's position, in preorder, folded into one number.
112
118
  fun hashTree(t: FRoseTree[Actor[Int]], h: Int) -> Int =
@@ -117,18 +123,18 @@ fun hashTree(t: FRoseTree[Actor[Int]], h: Int) -> Int =
117
123
  )
118
124
 
119
125
  # `t` ticks of `stage.step`.
120
- fun steps(stage: EStage[Int], ctx: ECtx[Int], dt: Float, t: Int) -> EStage[Int] =
126
+ fun steps(stage: SceneTree[Int], ctx: Ctx[Int], dt: Float, t: Int) -> SceneTree[Int] =
121
127
  if t == 0 then stage else steps(stage.step(ctx, dt), ctx, dt, t - 1)
122
128
 
123
129
  # `steps` with each tick's stage also stored in `kept`, a ring of the last 60.
124
- fun stepsKept(stage: EStage[Int], ctx: ECtx[Int], dt: Float, t: Int, kept: Slice[EStage[Int]]) -> EStage[Int] =
130
+ fun stepsKept(stage: SceneTree[Int], ctx: Ctx[Int], dt: Float, t: Int, kept: Slice[SceneTree[Int]]) -> SceneTree[Int] =
125
131
  if t == 0
126
132
  stage
127
133
  else
128
134
  keep(kept, stage, t)
129
135
  stepsKept(stage.step(ctx, dt), ctx, dt, t - 1, kept)
130
136
 
131
- fun keep(kept: Slice[EStage[Int]], stage: EStage[Int], t: Int) =
137
+ fun keep(kept: Slice[SceneTree[Int]], stage: SceneTree[Int], t: Int) =
132
138
  if kept.length() < 60
133
139
  kept.push(stage)
134
140
  else
@@ -136,23 +142,23 @@ fun keep(kept: Slice[EStage[Int]], stage: EStage[Int], t: Int) =
136
142
 
137
143
  # Pushes the tick's kills and spawns to `ctx.out`: `k` random live leaves die and `k` new
138
144
  # ones are born under random groups.
139
- fun pushChurn(sc: Bench, ctx: ECtx[Int], k: Int) =
145
+ fun pushChurn(sc: Bench, ctx: Ctx[Int], k: Int) =
140
146
  for j := range k
141
147
  i := sc.rng.next(sc.live.length())
142
148
  victim := sc.live.at(i)
143
149
  _ := sc.live.set(i, sc.live.at(sc.live.length() - 1))
144
150
  _ := sc.live.pop()
145
- ctx.out.push(EKill(id: victim))
151
+ ctx.out.push(Kill(id: victim))
146
152
  for j := range k
147
153
  g := sc.rng.next(10)
148
154
  id := sc.nextId
149
155
  sc.nextId = id + 1
150
- ctx.out.push(ESpawn(parent: g + 1, node: newLeaf(sc.rng, id)))
156
+ ctx.out.push(Spawn(parent: g + 1, node: newLeaf(sc.rng, id)))
151
157
  sc.live.push(id)
152
158
 
153
159
  # `t` ticks of churn: the commands pushed, then a step that applies them in its walk, or
154
160
  # (`after`) a step, then the commands pushed and applied with a second walk.
155
- fun churns(stage: EStage[Int], sc: Bench, ctx: ECtx[Int], dt: Float, k: Int, t: Int, after: Bool) -> EStage[Int] =
161
+ fun churns(stage: SceneTree[Int], sc: Bench, ctx: Ctx[Int], dt: Float, k: Int, t: Int, after: Bool) -> SceneTree[Int] =
156
162
  if t == 0
157
163
  stage
158
164
  else if after
@@ -166,7 +172,7 @@ fun churns(stage: EStage[Int], sc: Bench, ctx: ECtx[Int], dt: Float, k: Int, t:
166
172
  churns(stage.step(ctx, dt), sc, ctx, dt, k, t - 1, after)
167
173
 
168
174
  # `churns` (commands before the step) with each tick's stage also kept in a ring of 60.
169
- fun churnsKept(stage: EStage[Int], sc: Bench, ctx: ECtx[Int], dt: Float, k: Int, t: Int, kept: Slice[EStage[Int]]) -> EStage[Int] =
175
+ fun churnsKept(stage: SceneTree[Int], sc: Bench, ctx: Ctx[Int], dt: Float, k: Int, t: Int, kept: Slice[SceneTree[Int]]) -> SceneTree[Int] =
170
176
  if t == 0
171
177
  stage
172
178
  else
@@ -174,9 +180,9 @@ fun churnsKept(stage: EStage[Int], sc: Bench, ctx: ECtx[Int], dt: Float, k: Int,
174
180
  pushChurn(sc, ctx, k)
175
181
  churnsKept(stage.step(ctx, dt), sc, ctx, dt, k, t - 1, kept)
176
182
 
177
- # EStage's walk with no commands and the root's context for every body: no parent's world
183
+ # SceneTree's walk with no commands and the root's context for every body: no parent's world
178
184
  # transform is computed.
179
- fun stepFlat(t: FRoseTree[Actor[Int]], ctx: ECtx[Int], dt: Float) -> FRoseTree[Actor[Int]] = match t
185
+ fun stepFlat(t: FRoseTree[Actor[Int]], ctx: Ctx[Int], dt: Float) -> FRoseTree[Actor[Int]] = match t
180
186
  FRoseEmpty => t
181
187
  FRoseNode(b, k, n) =>
182
188
  nb := b.step(ctx, dt)
@@ -186,9 +192,9 @@ fun stepFlat(t: FRoseTree[Actor[Int]], ctx: ECtx[Int], dt: Float) -> FRoseTree[A
186
192
  k2 := if k.isEmpty() then k else stepFlat(k, ctx, dt)
187
193
  FRoseNode(value: nb, firstChild: k2, nextSibling: stepFlat(n, ctx, dt))
188
194
 
189
- # EStage's walk with no commands, every body's world transform computed (and checked, so
195
+ # SceneTree's walk with no commands, every body's world transform computed (and checked, so
190
196
  # it is used).
191
- fun stepEager(t: FRoseTree[Actor[Int]], ctx: ECtx[Int], dt: Float) -> FRoseTree[Actor[Int]] = match t
197
+ fun stepEager(t: FRoseTree[Actor[Int]], ctx: Ctx[Int], dt: Float) -> FRoseTree[Actor[Int]] = match t
192
198
  FRoseEmpty => t
193
199
  FRoseNode(b, k, n) =>
194
200
  m := ctx.worldOf(b.place().local())
@@ -201,7 +207,7 @@ fun stepEager(t: FRoseTree[Actor[Int]], ctx: ECtx[Int], dt: Float) -> FRoseTree[
201
207
  k2 := if k.isEmpty() then k else stepEager(k, cc, dt)
202
208
  FRoseNode(value: nb, firstChild: k2, nextSibling: stepEager(n, ctx, dt))
203
209
 
204
- fun walks(stage: EStage[Int], ctx: ECtx[Int], dt: Float, t: Int, eager: Bool) -> EStage[Int] =
210
+ fun walks(stage: SceneTree[Int], ctx: Ctx[Int], dt: Float, t: Int, eager: Bool) -> SceneTree[Int] =
205
211
  if t == 0
206
212
  stage
207
213
  else if eager
@@ -210,7 +216,7 @@ fun walks(stage: EStage[Int], ctx: ECtx[Int], dt: Float, t: Int, eager: Bool) ->
210
216
  walks(stage.withRoot(stepFlat(stage.root, ctx, dt)), ctx, dt, t - 1, eager)
211
217
 
212
218
  # 1000 flattens: the entries over all of them plus the summed translations of the last.
213
- fun draws(stage: EStage[Int], r: Int, total: Int) -> Int =
219
+ fun draws(stage: SceneTree[Int], r: Int, total: Int) -> Int =
214
220
  d := stage.flatten()
215
221
  if r == 999
216
222
  last := lastSum(d, 0, 0.0)
@@ -218,11 +224,11 @@ fun draws(stage: EStage[Int], r: Int, total: Int) -> Int =
218
224
  else
219
225
  draws(stage, r + 1, total + d.length())
220
226
 
221
- fun lastSum(d: Slice[EDrawn[Int]], i: Int, acc: Float) -> Float =
227
+ fun lastSum(d: Slice[Drawn[Int]], i: Int, acc: Float) -> Float =
222
228
  if i >= d.length() then acc else lastSum(d, i + 1, acc + d.at(i).m.e + d.at(i).m.f)
223
229
 
224
230
  # 1000 hit tests at random stage points: the positions of the bodies hit, in order.
225
- fun hits(stage: EStage[Int], rng: Rng, q: Int, sum: Int) -> Int =
231
+ fun hits(stage: SceneTree[Int], rng: Rng, q: Int, sum: Int) -> Int =
226
232
  if q == 1000
227
233
  sum
228
234
  else
@@ -236,9 +242,9 @@ fun hits(stage: EStage[Int], rng: Rng, q: Int, sum: Int) -> Int =
236
242
  hits(stage, rng, q + 1, next)
237
243
 
238
244
  # Runs workload `w` on `stage`, a scene of `n` nodes, and returns its checksum.
239
- fun work(stage: EStage[Int], sc: Bench, w: Int, n: Int) -> Int =
245
+ fun work(stage: SceneTree[Int], sc: Bench, w: Int, n: Int) -> Int =
240
246
  dt := 1.0 / 60.0
241
- ctx := ECtx[Int]()
247
+ ctx := Ctx[Int]()
242
248
  k := {{n - 11} / 100}.max(1)
243
249
  if w == 1
244
250
  hashTree(steps(stage, ctx, dt, 1000).root, 0)
@@ -251,9 +257,9 @@ fun work(stage: EStage[Int], sc: Bench, w: Int, n: Int) -> Int =
251
257
  else if w == 5 || w == 6
252
258
  hashTree(walks(stage, ctx, dt, 1000, w == 6).root, 0)
253
259
  else if w == 8
254
- hashTree(stepsKept(stage, ctx, dt, 1000, Slice[EStage[Int]]()).root, 0)
260
+ hashTree(stepsKept(stage, ctx, dt, 1000, Slice[SceneTree[Int]]()).root, 0)
255
261
  else
256
- hashTree(churnsKept(stage, sc, ctx, dt, k, 1000, Slice[EStage[Int]]()).root, 0) + sc.live.length()
262
+ hashTree(churnsKept(stage, sc, ctx, dt, k, 1000, Slice[SceneTree[Int]]()).root, 0) + sc.live.length()
257
263
 
258
264
  # Builds the scene, then times the workload alone with the wall clock.
259
265
  fun run(io: Io, w: Int, n: Int) -> Int =
@@ -262,7 +268,7 @@ fun run(io: Io, w: Int, n: Int) -> Int =
262
268
  t0 := io.rawNowMillis()
263
269
  sum := work(stage, sc, w, n)
264
270
  ms := io.rawNowMillis() - t0
265
- io.printLn("game_enum_tree w{w} n{n} ms {ms} checksum {sum}")
271
+ io.printLn("scene_tree w{w} n{n} ms {ms} checksum {sum}")
266
272
  sum
267
273
 
268
274
  fun main(io: Io) =
compiler/core/src/drive.rs CHANGED
@@ -785,7 +785,7 @@ impl Driver {
785
785
  if t.contains('.') {
786
786
  return vec![]; // a method on a constant (`Color.White.withAlpha(..)`)
787
787
  }
788
- // a static method, `SceneNode.drawKids(io, kids, ..)`, or a method of
788
+ // a static method, `Tree.drawKids(io, kids, ..)`, or a method of
789
789
  // a nullary variant value (`Nil.lengthFrom(n)` once a built list is
790
790
  // unfolded down to its end): its enum's method, `self` the variant
791
791
  let key = self.typeNameMethodKey(t, &c.name);
@@ -1769,7 +1769,7 @@ impl Driver {
1769
1769
  let sc = self.scopeOf(&c.f).merge(&self.scopeOf(&p.f));
1770
1770
  let mut map: HashMap<String, Type> = HashMap::new();
1771
1771
  // a generic only the producer has (`List.map`'s `B`) is fixed by the consumer's
1772
- // matched type (`List[SceneNode]`): the producer side is instantiated with it
1772
+ // matched type (`List[Node]`): the producer side is instantiated with it
1773
1773
  let mut pmap: HashMap<String, Type> = fixed;
1774
1774
  pret = substType(&pret, &pmap);
1775
1775
  unify2(&sc, csub, &pret, &mut map, &mut pmap).ok_or("producer result type does not unify with the matched parameter")?;
compiler/game/web-test/fixtures/stress_scene_port.plum CHANGED
@@ -1,20 +1,26 @@
1
- # The functional port of master's imperative stress_scene, drawing the same scene call for
1
+ # The scene-tree port of master's imperative stress_scene, drawing the same scene call
2
- # call: 5000 sprites in 50 slowly rotating groups, 500 rect shapes, 200 circle shapes and
2
+ # for call: 5000 sprites in 50 slowly rotating groups, 500 rect shapes, 200 circle shapes
3
- # 50 texts with a changing number, through a 0.8 camera. The state is plain lists of plain
3
+ # and 50 texts with a changing number, through a 0.8 camera. The scene is a
4
- # structs; `update` returns the next state with `List.map` and spreads, and `view` rebuilds
5
- # the scene tree every frame. Motion is per frame, as in the original. The text is rebuilt
4
+ # `SceneTree[Int]` of actors that lives from frame to frame; each kind moves itself by a
5
+ # fixed step in its own `step` (a spread), and the tree's `draw` paints them. Motion is
6
- # in `update` and input is polled every frame, also as in the original, so the
6
+ # per frame, as in the original. The text is rebuilt in the step and input is polled
7
+ # every frame, also as in the original, so the update and draw split stays comparable.
7
- # update and draw split stays comparable. Written the plain way and not tuned for speed.
8
+ # Written the plain way and not tuned for speed.
8
9
  module stress_scene_port
9
10
  import std/Str
10
11
  import std/Int
11
12
  import std/Float
12
13
  import std/List
13
14
  import std/game/Vec2
15
+ import std/game/Affine
14
16
  import std/game/Color
15
17
  import std/game/gfx
16
- import std/game/scene
17
18
  import std/game/input
19
+ import std/collections/functional/FRoseTree
20
+ import std/game/scene/Place
21
+ import std/game/scene/Actor
22
+ import std/game/scene/Ctx
23
+ import std/game/scene/SceneTree
18
24
  import std/Io
19
25
 
20
26
  Sprites = 5000
@@ -25,108 +31,101 @@ Groups = 50
25
31
  WorldW = 1600.0
26
32
  WorldH = 900.0
27
33
 
34
+ # A sprite of the sheet inside its group, turning about its centre.
28
- struct Dancer(x: Float, y: Float, rotation: Float, srcX: Float)
35
+ struct Dancer(id: Int, x: Float, y: Float, rotation: Float, srcX: Float, sheet: Texture) is Actor[Int] =
36
+ fun key(self) -> Int = self.id
29
37
 
30
- struct Spin(x: Float, y: Float, rotation: Float, dancers: List[Dancer])
38
+ fun place(self) -> Place = place.at(self.x, self.y).rotateTo(self.rotation).pivotAt(8.0, 8.0)
31
39
 
32
- struct Drift(x: Float, y: Float, color: Color)
40
+ fun step(self, ctx: Ctx[Int], dt: Float) -> Dancer =
41
+ r := self.rotation + 0.02
42
+ Dancer(..self, rotation: r, srcX: Float(Int(r * 50.0) / 6 % 4 * 16))
33
43
 
34
- struct Count(x: Float, y: Float, n: Int, text: Str)
44
+ fun paint(self, io: Io, m: Affine, alpha: Float) =
45
+ actor.spritePaint(io, m, alpha, self.sheet, 0.0, 0.0, 16.0, 16.0, self.srcX, 0.0, 16.0, 16.0, Color.White)
35
46
 
47
+ # A group of dancers turning about (75, 85).
36
- struct State(sheet: Texture, spins: List[Spin], rects: List[Drift], circles: List[Drift], counts: List[Count])
48
+ struct Spin(id: Int, x: Float, y: Float, rotation: Float) is Actor[Int] =
49
+ fun key(self) -> Int = self.id
37
50
 
38
- fun hue(i: Int) -> Color =
39
- Color(r: Float(i % 7) / 7.0, g: Float(i % 5) / 5.0, b: 0.4 + Float(i % 3) / 5.0, a: 0.8)
51
+ fun place(self) -> Place = place.at(self.x, self.y).rotateTo(self.rotation).pivotAt(75.0, 85.0)
40
52
 
41
- fun buildFrom[T](i: Int, n: Int, f: fn(Int) -> T) -> List[T] =
42
- if i >= n then Nil else Cons(head: f(i), tail: buildFrom(i + 1, n, f))
53
+ fun step(self, ctx: Ctx[Int], dt: Float) -> Spin = Spin(..self, rotation: self.rotation + 0.004)
43
54
 
44
- # The list f(0), f(1) ... f(n - 1).
45
- fun build[T](n: Int, f: fn(Int) -> T) -> List[T] =
55
+ fun wrap(v: Float, limit: Float) -> Float =
46
- buildFrom(0, n, f)
56
+ if v > limit then v - limit else v
47
57
 
58
+ # A 12 by 8 rect drifting right.
59
+ struct DriftRect(id: Int, x: Float, y: Float, color: Color) is Actor[Int] =
48
- fun newDancer(gi: Int, j: Int) -> Dancer =
60
+ fun key(self) -> Int = self.id
49
- i := gi * {Sprites / Groups} + j
50
- Dancer(x: Float({j * j * 13 + j * 37} % 150), y: Float({j * j * 29 + j * 53} % 170), rotation: Float(i), srcX: Float(i % 4 * 16))
51
61
 
52
- fun newSpin(gi: Int) -> Spin =
62
+ fun place(self) -> Place = place.at(self.x, self.y)
53
- Spin(x: Float(gi % 10 * 160), y: Float(gi / 10 * 180), rotation: 0.0, dancers: build(Sprites / Groups, |j| newDancer(gi, j)))
54
63
 
55
- fun newState(sheet: Texture) -> State =
56
- State(
57
- sheet: sheet,
58
- spins: build(Groups, |gi| newSpin(gi)),
59
- rects: build(Rects, |i| Drift(x: Float(i * 61 % 1600), y: Float(i * 29 % 900), color: hue(i))),
60
- circles: build(Circles, |i| Drift(x: Float(i * 83 % 1600), y: Float(i * 47 % 900), color: hue(i + 3))),
61
- counts: build(Texts, |i| Count(x: Float(i * 30 % 1600), y: Float(i * 17 % 900), n: i, text: "n {i}")))
64
+ fun step(self, ctx: Ctx[Int], dt: Float) -> DriftRect = DriftRect(..self, x: wrap(self.x + 2.0, WorldW))
62
65
 
63
- # --- update: every entity moves by a fixed step per frame ---
66
+ fun paint(self, io: Io, m: Affine, alpha: Float) = actor.boxPaint(io, m, alpha, 12.0, 8.0, self.color)
64
67
 
68
+ # A circle of radius 6 drifting down and right.
69
+ struct DriftCircle(id: Int, x: Float, y: Float, color: Color) is Actor[Int] =
65
- fun stepDancer(d: Dancer) -> Dancer =
70
+ fun key(self) -> Int = self.id
66
- r := d.rotation + 0.02
67
- Dancer(..d, rotation: r, srcX: Float(Int(r * 50.0) / 6 % 4 * 16))
68
71
 
69
- fun stepSpin(s: Spin) -> Spin =
70
- Spin(..s, rotation: s.rotation + 0.004, dancers: s.dancers.map(|d| stepDancer(d)))
72
+ fun place(self) -> Place = place.at(self.x, self.y)
71
73
 
72
- fun wrap(v: Float, limit: Float) -> Float =
74
+ fun step(self, ctx: Ctx[Int], dt: Float) -> DriftCircle =
73
- if v > limit then v - limit else v
74
-
75
- fun stepRect(d: Drift) -> Drift =
76
- Drift(..d, x: wrap(d.x + 2.0, WorldW))
75
+ DriftCircle(..self, x: wrap(self.x + 3.0, WorldW), y: wrap(self.y + 1.0, WorldH))
77
76
 
78
- fun stepCircle(d: Drift) -> Drift =
79
- Drift(..d, x: wrap(d.x + 3.0, WorldW), y: wrap(d.y + 1.0, WorldH))
77
+ fun paint(self, io: Io, m: Affine, alpha: Float) = actor.circlePaint(io, m, alpha, 6.0, 6.0, 6.0, self.color)
80
78
 
79
+ # Shows "n <count>" and counts up each frame.
80
+ struct Count(id: Int, x: Float, y: Float, n: Int, text: Str) is Actor[Int] =
81
- fun stepCount(c: Count) -> Count =
81
+ fun key(self) -> Int = self.id
82
- n := c.n + 1
83
- Count(..c, n: n, text: "n {n}")
84
82
 
85
- fun step(s: State) -> State =
83
+ fun place(self) -> Place = place.at(self.x, self.y)
86
- State(
87
- ..s,
88
- spins: s.spins.map(|g| stepSpin(g)),
89
- rects: s.rects.map(|d| stepRect(d)),
90
- circles: s.circles.map(|d| stepCircle(d)),
91
- counts: s.counts.map(|c| stepCount(c)))
92
84
 
85
+ fun step(self, ctx: Ctx[Int], dt: Float) -> Count =
86
+ n := self.n + 1
93
- # --- view: the whole tree every frame ---
87
+ Count(..self, n: n, text: "n {n}")
94
88
 
95
- fun pivot(x: Float, y: Float, ox: Float, oy: Float, rad: Float) -> Transform =
89
+ fun paint(self, io: Io, m: Affine, alpha: Float) = actor.textPaint(io, m, alpha, self.text, 0.0, 0.0, 14.0, Color.White)
96
- Compose(first: Translate(dx: x + ox, dy: y + oy), then: Compose(first: Rotate(radians: rad), then: Translate(dx: 0.0 - ox, dy: 0.0 - oy)))
97
90
 
98
- fun dancerView(sheet: Texture, d: Dancer) -> SceneNode[Int] =
91
+ fun hue(i: Int) -> Color =
99
- Group(
100
- transform: pivot(d.x, d.y, 8.0, 8.0, d.rotation),
101
- children: [Sprite(tex: sheet, x: 0.0, y: 0.0, w: 16.0, h: 16.0, srcX: d.srcX, srcY: 0.0, srcW: 16.0, srcH: 16.0, tint: Color.White)])
92
+ Color(r: Float(i % 7) / 7.0, g: Float(i % 5) / 5.0, b: 0.4 + Float(i % 3) / 5.0, a: 0.8)
102
93
 
103
- fun spinView(sheet: Texture, g: Spin) -> SceneNode[Int] =
94
+ fun buildFrom(i: Int, n: Int, f: fn(Int) -> FRoseTree[Actor[Int]]) -> List[FRoseTree[Actor[Int]]] =
104
- Group(transform: pivot(g.x, g.y, 75.0, 85.0, g.rotation), children: g.dancers.map(|d| dancerView(sheet, d)))
95
+ if i >= n then Nil else Cons(head: f(i), tail: buildFrom(i + 1, n, f))
105
96
 
106
- fun rectView(d: Drift) -> SceneNode[Int] =
97
+ # The nodes f(0), f(1) ... f(n - 1).
107
- RectShape(x: d.x, y: d.y, w: 12.0, h: 8.0, color: d.color)
98
+ fun build(n: Int, f: fn(Int) -> FRoseTree[Actor[Int]]) -> List[FRoseTree[Actor[Int]]] =
99
+ buildFrom(0, n, f)
108
100
 
109
- fun circleView(d: Drift) -> SceneNode[Int] =
101
+ fun newDancer(sheet: Texture, gi: Int, j: Int) -> FRoseTree[Actor[Int]] =
110
- CircleShape(cx: d.x + 6.0, cy: d.y + 6.0, r: 6.0, color: d.color)
102
+ i := gi * {Sprites / Groups} + j
103
+ FRoseTree.leaf(Dancer(id: 1000 + i, x: Float({j * j * 13 + j * 37} % 150), y: Float({j * j * 29 + j * 53} % 170), rotation: Float(i), srcX: Float(i % 4 * 16), sheet: sheet))
111
104
 
112
- fun countView(c: Count) -> SceneNode[Int] =
105
+ fun newSpin(sheet: Texture, gi: Int) -> FRoseTree[Actor[Int]] =
113
- Text(text: c.text, x: c.x, y: c.y, size: 14.0, color: Color.White)
106
+ FRoseTree.of(Spin(id: 100 + gi, x: Float(gi % 10 * 160), y: Float(gi / 10 * 180), rotation: 0.0), build(Sprites / Groups, |j| newDancer(sheet, gi, j)))
114
107
 
115
- fun view(s: State) -> SceneNode[Int] =
108
+ fun newTree(sheet: Texture) -> SceneTree[Int] =
116
- texts := s.counts.map(|c| countView(c))
109
+ rects := build(Rects, |i| FRoseTree.leaf(DriftRect(id: 10000 + i, x: Float(i * 61 % 1600), y: Float(i * 29 % 900), color: hue(i))))
117
- circles := s.circles.map(|d| circleView(d)).append(texts)
110
+ circles := build(Circles, |i| FRoseTree.leaf(DriftCircle(id: 20000 + i, x: Float(i * 83 % 1600), y: Float(i * 47 % 900), color: hue(i + 3))))
118
- rects := s.rects.map(|d| rectView(d)).append(circles)
111
+ counts := build(Texts, |i| FRoseTree.leaf(Count(id: 30000 + i, x: Float(i * 30 % 1600), y: Float(i * 17 % 900), n: i, text: "n {i}")))
119
- Group(transform: Identity, children: s.spins.map(|g| spinView(s.sheet, g)).append(rects))
112
+ kids := build(Groups, |gi| newSpin(sheet, gi)).append(rects).append(circles).append(counts)
113
+ SceneTree(root: FRoseTree.of(Group(id: 0, x: 0.0, y: 0.0), kids), camX: 0.0, camY: 0.0, camScale: 0.8)
120
114
 
121
- struct World(state: State, input: Input) =
115
+ struct World(tree: SceneTree[Int], input: Input) =
122
116
  fun update(self, io: Io, input: Input, dt: Float) -> World =
123
- World(state: step(self.state), input: input)
117
+ World(tree: self.tree.step(Ctx[Int](), dt), input: input)
124
118
 
125
119
  fun draw(self, io: Io) =
126
120
  gfx.clear(io, Color.rgb(0.05, 0.06, 0.1))
127
- gfx.setCamera(io, 0.0, 0.0, 0.8)
128
- view(self.state).draw(io)
121
+ self.tree.draw(io)
129
- gfx.resetCamera(io)
130
122
 
131
123
  fun main(io: Io) -> World =
132
- World(state: newState(gfx.loadTexture(io, "sprites.png")), input: Input.create())
124
+ World(tree: newTree(gfx.loadTexture(io, "sprites.png")), input: Input.create())
125
+
126
+ test "the tree holds every actor and steps them"
127
+ t := newTree(Texture(id: -1))
128
+ assert t.count() == 1 + 50 + 5000 + 500 + 200 + 50
129
+ s := t.step(Ctx[Int](), 0.016).step(Ctx[Int](), 0.016)
130
+ assert s.findAs[Count](30003).unwrap().text == "n 5"
131
+ assert s.findAs[DriftRect](10000).unwrap().x == 4.0
compiler/game/web-test/fixtures/stress_state_view.plum CHANGED
@@ -1,17 +1,14 @@
1
- # The stress scene of stress_pure_scene.plum written as state and view, now recursive:
1
+ # The stress scene on a scene tree: 5000 sprites in 50 slowly rotating groups, 500 rects
2
- # 5000 sprites in 50 slowly rotating groups, 500 rects and 200 circles (sprites of a
3
- # 1x1 white texture), 50 texts with a changing number, drawn through a 0.8 camera.
2
+ # and 200 circles (sprites of a 1x1 white texture), 50 texts with a changing number,
4
- # `State` is cons `List` lists (each spinner owns the `List` of its 100 dancers);
5
- # `step` is pure, a structural recursion that returns the next state; `view` is pure
6
- # and rebuilds the whole SceneNode tree every frame with recursive functions, which
3
+ # drawn through a 0.8 scale. The scene is a `SceneTree[Int]` of actors that lives from
7
- # `SceneNode.draw` interprets. Nothing is retained between frames but `State`. The
4
+ # frame to frame; each kind changes itself in its own `step` (a spread), and the tree's
8
- # deepest recursion is the 700 drifters; no loops run in step or view.
5
+ # `draw` paints them.
9
6
  #
10
7
  # Entity counts: 5000 sprites (50 groups x 100), 500 rects, 200 circles, 50 texts,
11
8
  # plus 200 animated sprites (Pulsers, pose = Anim.at(anim, clock - start)) and
12
- # 20 ui.button buttons (tagged ids 40000..40019, screen space, outside the camera).
9
+ # 20 ui buttons (ids 40000..40019, screen space, outside the scaled world).
13
- # `State.ui` is a Ui.UiState fed by mouse input: update turns the mouse into a
10
+ # `State.ui` is a ui.UiState fed by mouse input: update turns the mouse into a shared
14
- # shared InputEvent, hit-tests the button layer with SceneNode.hitId, and calls ui.step.
11
+ # InputEvent, hit-tests the tree with `hitId`, calls ui.step and restyles the buttons.
15
12
  module stress_state_view
16
13
  import std/Str
17
14
  import std/Int
@@ -20,12 +17,17 @@ import std/Slice
20
17
  import std/Option
21
18
  import std/List
22
19
  import std/game/Vec2
20
+ import std/game/Affine
23
21
  import std/game/Color
24
22
  import std/game/gfx
25
- import std/game/scene
26
23
  import std/game/Anim
27
24
  import std/game/ui
28
25
  import std/game/input
26
+ import std/collections/functional/FRoseTree
27
+ import std/game/scene/Place
28
+ import std/game/scene/Actor
29
+ import std/game/scene/Ctx
30
+ import std/game/scene/SceneTree
29
31
  import std/Io
30
32
 
31
33
  Sprites = 5000
@@ -37,11 +39,8 @@ Buttons = 20
37
39
  Groups = 50
38
40
  WorldW = 1600
39
41
  WorldH = 900
40
-
41
-
42
- fun mapLink[A, B](xs: List[A], f: fn(A) -> B) -> List[B] = match xs
43
- Nil => Nil
42
+ WorldId = 1
44
- Cons(h, t) => Cons(head: f(h), tail: mapLink(t, f))
43
+ ButtonLayer = 2
45
44
 
46
45
  # The list f(i), f(i + 1) ... f(n - 1).
47
46
  fun rangeLink[T](i: Int, n: Int, f: fn(Int) -> T) -> List[T] =
@@ -51,150 +50,127 @@ fun appendLink[T](xs: List[T], ys: List[T]) -> List[T] = match xs
51
50
  Nil => ys
52
51
  Cons(h, t) => Cons(head: h, tail: appendLink(t, ys))
53
52
 
54
- # The element at `i`, or `dflt` past the end.
53
+ # A sprite of the sheet inside its group, spinning about its centre.
54
+ struct Dancer(id: Int, x: Float, y: Float, rotation: Float, srcX: Float, sheet: Texture) is Actor[Int] =
55
- fun nthOr[T](xs: List[T], i: Int, dflt: T) -> T = match xs
55
+ fun key(self) -> Int = self.id
56
- Nil => dflt
57
- Cons(h, t) => if i <= 0 then h else nthOr(t, i - 1, dflt)
58
56
 
59
- # The nodes f(x) for every x of `xs`, followed by `rest`.
60
- fun toNodes[T](xs: List[T], f: fn(T) -> SceneNode[Int], rest: List[SceneNode[Int]]) -> List[SceneNode[Int]] = match xs
57
+ fun place(self) -> Place = place.at(self.x, self.y).rotateTo(self.rotation).pivotAt(8.0, 8.0)
61
- Nil => rest
62
- Cons(h, t) => Cons(head: f(h), tail: toNodes(t, f, rest))
63
58
 
64
- fun countNodes(ns: List[SceneNode[Int]]) -> Int = match ns
59
+ fun step(self, ctx: Ctx[Int], dt: Float) -> Dancer = Dancer(..self, rotation: self.rotation + 1.2 * dt)
65
- Nil => 0
66
- Cons(_, t) => 1 + countNodes(t)
67
60
 
68
- # A sprite of the sheet inside its group, spinning about its centre.
69
- struct Dancer(id: Int, x: Float, y: Float, rotation: Float, srcX: Float)
61
+ fun paint(self, io: Io, m: Affine, alpha: Float) =
62
+ actor.spritePaint(io, m, alpha, self.sheet, 0.0, 0.0, 16.0, 16.0, self.srcX, 0.0, 16.0, 16.0, Color.White)
70
63
 
71
64
  # A rotating group of dancers: top-left (x, y), pivot (75, 85).
72
- struct Spinner(id: Int, x: Float, y: Float, rotation: Float, dancers: List[Dancer])
65
+ struct Spinner(id: Int, x: Float, y: Float, rotation: Float) is Actor[Int] =
66
+ fun key(self) -> Int = self.id
67
+
68
+ fun place(self) -> Place = place.at(self.x, self.y).rotateTo(self.rotation).pivotAt(75.0, 85.0)
69
+
70
+ fun step(self, ctx: Ctx[Int], dt: Float) -> Spinner = Spinner(..self, rotation: self.rotation + 0.24 * dt)
73
71
 
74
72
  # A square of the white texture that moves by (dx, dy) per frame and wraps.
75
- struct Drifter(id: Int, x: Float, y: Float, w: Float, h: Float, dx: Float, dy: Float, color: Color)
73
+ struct Drifter(id: Int, x: Float, y: Float, w: Float, h: Float, dx: Float, dy: Float, color: Color, white: Texture) is Actor[Int] =
74
+ fun key(self) -> Int = self.id
75
+
76
+ fun place(self) -> Place = place.at(self.x, self.y)
77
+
78
+ fun step(self, ctx: Ctx[Int], dt: Float) -> Drifter =
79
+ movedX := self.x + self.dx
80
+ movedY := self.y + self.dy
81
+ nx := if movedX > Float(WorldW) then movedX - Float(WorldW) else movedX
82
+ ny := if movedY > Float(WorldH) then movedY - Float(WorldH) else movedY
83
+ Drifter(..self, x: nx, y: ny)
84
+
85
+ fun paint(self, io: Io, m: Affine, alpha: Float) =
86
+ actor.spritePaint(io, m, alpha, self.white, 0.0, 0.0, self.w, self.h, 0.0, 0.0, 0.0, 0.0, self.color)
76
87
 
77
88
  # Shows "n <count>" and counts up each frame.
78
- struct Counter(id: Int, x: Float, y: Float, n: Int)
89
+ struct Counter(id: Int, x: Float, y: Float, n: Int) is Actor[Int] =
90
+ fun key(self) -> Int = self.id
79
91
 
80
- # An animated sprite that started its animation at `start` seconds of the clock.
81
- struct Pulser(id: Int, x: Float, y: Float, start: Float, srcX: Float)
92
+ fun place(self) -> Place = place.at(self.x, self.y)
82
93
 
94
+ fun step(self, ctx: Ctx[Int], dt: Float) -> Counter = Counter(..self, n: self.n + 1)
95
+
96
+ fun paint(self, io: Io, m: Affine, alpha: Float) = actor.textPaint(io, m, alpha, "n {self.n}", 0.0, 0.0, 14.0, Color.White)
97
+
98
+ # An animated sprite that started its animation at `start` seconds of its clock: it is
99
+ # where `anim` puts it then.
83
- struct State(sheet: Texture, white: Texture, spinners: List[Spinner], drifters: List[Drifter], counters: List[Counter], pulsers: List[Pulser], anim: Anim, clock: Float, ui: UiState, clicks: Int)
100
+ struct Pulser(id: Int, x: Float, y: Float, start: Float, srcX: Float, clock: Float, anim: Anim, sheet: Texture) is Actor[Int] =
101
+ fun key(self) -> Int = self.id
102
+
103
+ fun place(self) -> Place =
104
+ pose := Anim.at(self.anim, self.clock - self.start)
105
+ place.at(self.x + pose.dx, self.y + pose.dy).rotateTo(pose.rotation).scaleTo(pose.scaleX, pose.scaleY).pivotAt(8.0, 8.0)
106
+
107
+ fun step(self, ctx: Ctx[Int], dt: Float) -> Pulser = Pulser(..self, clock: self.clock + dt)
108
+
109
+ fun paint(self, io: Io, m: Affine, alpha: Float) =
110
+ actor.spritePaint(io, m, alpha, self.sheet, 0.0, 0.0, 16.0, 16.0, self.srcX, 0.0, 16.0, 16.0, Color.White)
111
+
112
+ struct State(tree: SceneTree[Int], clock: Float, ui: UiState, clicks: Int)
84
113
 
85
114
  fun pulseAnim() -> Anim =
86
115
  Forever(anim: Seq(steps: [
87
116
  Par(steps: [MoveBy(dx: 30.0, dy: 0.0, secs: 1.0), RotateBy(radians: 3.14159, secs: 1.0), ScaleTo(sx: 1.5, sy: 1.5, secs: 1.0)]),
88
117
  Par(steps: [MoveBy(dx: 0.0 - 30.0, dy: 0.0, secs: 1.0), ScaleTo(sx: 0.6666, sy: 0.6666, secs: 1.0)])]))
89
118
 
90
- fun newPulser(i: Int) -> Pulser =
119
+ fun newPulser(sheet: Texture, anim: Anim, i: Int) -> FRoseTree[Actor[Int]] =
91
- Pulser(id: 50000 + i, x: Float(i * 97 % 1500), y: Float(i * 53 % 850), start: Float(i % 10) * 0.1, srcX: Float(i % 4 * 16))
120
+ FRoseTree.leaf(Pulser(id: 50000 + i, x: Float(i * 97 % 1500), y: Float(i * 53 % 850), start: Float(i % 10) * 0.1, srcX: Float(i % 4 * 16), clock: 0.0, anim: anim, sheet: sheet))
92
121
 
93
122
  fun hue(i: Int) -> Color =
94
123
  Color(r: Float(i % 7) / 7.0, g: Float(i % 5) / 5.0, b: 0.4 + Float(i % 3) / 5.0, a: 0.8)
95
124
 
96
- fun newDrifter(id: Int, c: Color, x: Float, y: Float, w: Float, h: Float, dx: Float, dy: Float) -> Drifter =
125
+ fun newDrifter(white: Texture, id: Int, c: Color, x: Float, y: Float, w: Float, h: Float, dx: Float, dy: Float) -> FRoseTree[Actor[Int]] =
97
- Drifter(id: id, x: x, y: y, w: w, h: h, dx: dx, dy: dy, color: c)
126
+ FRoseTree.leaf(Drifter(id: id, x: x, y: y, w: w, h: h, dx: dx, dy: dy, color: c, white: white))
98
127
 
99
- fun newDancer(gi: Int, j: Int) -> Dancer =
128
+ fun newDancer(sheet: Texture, gi: Int, j: Int) -> FRoseTree[Actor[Int]] =
100
129
  i := gi * {Sprites / Groups} + j
101
- Dancer(id: 1000 + i, x: Float({j * j * 13 + j * 37} % 150), y: Float({j * j * 29 + j * 53} % 170), rotation: Float(i), srcX: Float(i % 4 * 16))
130
+ FRoseTree.leaf(Dancer(id: 1000 + i, x: Float({j * j * 13 + j * 37} % 150), y: Float({j * j * 29 + j * 53} % 170), rotation: Float(i), srcX: Float(i % 4 * 16), sheet: sheet))
102
-
103
- fun newSpinner(gi: Int) -> Spinner =
104
- Spinner(id: 100 + gi, x: Float(gi % 10 * 160), y: Float(gi / 10 * 180), rotation: 0.0, dancers: rangeLink(0, Sprites / Groups, |j| newDancer(gi, j)))
105
131
 
106
- fun newState(sheet: Texture, white: Texture) -> State =
132
+ fun newSpinner(sheet: Texture, gi: Int) -> FRoseTree[Actor[Int]] =
107
- rects := rangeLink(0, Rects, |i| newDrifter(10000 + i, hue(i), Float(i * 61 % WorldW), Float(i * 29 % WorldH), 12.0, 8.0, 2.0, 0.0))
108
- circles := rangeLink(0, Circles, |i| newDrifter(20000 + i, hue(i + 3), Float(i * 83 % WorldW), Float(i * 47 % WorldH), 12.0, 12.0, 3.0, 1.0))
109
- State(
110
- sheet: sheet, white: white, spinners: rangeLink(0, Groups, |gi| newSpinner(gi)),
111
- drifters: appendLink(rects, circles),
112
- counters: rangeLink(0, Texts, |i| Counter(id: 30000 + i, x: Float(i * 30 % WorldW), y: Float(i * 17 % WorldH), n: i)),
133
+ FRoseTree.of(Spinner(id: 100 + gi, x: Float(gi % 10 * 160), y: Float(gi / 10 * 180), rotation: 0.0), rangeLink(0, Sprites / Groups, |j| newDancer(sheet, gi, j)))
113
- pulsers: rangeLink(0, Pulsers, |i| newPulser(i)), anim: pulseAnim(), clock: 0.0, ui: ui.init(), clicks: 0)
114
134
 
115
- # --- step: pure ---
135
+ fun newButton(i: Int) -> FRoseTree[Actor[Int]] =
136
+ FRoseTree.leaf(Button(id: 40000 + i, x: Float(i % 10 * 70 + 10), y: Float(i / 10 * 30 + 10), w: 64.0, h: 24.0, label: "b{i}", onClick: 40000 + i, look: 0))
116
137
 
117
- fun stepDrifter(d: Drifter) -> Drifter =
138
+ fun newState(sheet: Texture, white: Texture) -> State =
139
+ rects := rangeLink(0, Rects, |i| newDrifter(white, 10000 + i, hue(i), Float(i * 61 % WorldW), Float(i * 29 % WorldH), 12.0, 8.0, 2.0, 0.0))
140
+ circles := rangeLink(0, Circles, |i| newDrifter(white, 20000 + i, hue(i + 3), Float(i * 83 % WorldW), Float(i * 47 % WorldH), 12.0, 12.0, 3.0, 1.0))
141
+ counters: List[FRoseTree[Actor[Int]]] := rangeLink(0, Texts, |i| FRoseTree.leaf(Counter(id: 30000 + i, x: Float(i * 30 % WorldW), y: Float(i * 17 % WorldH), n: i)))
118
- movedX := d.x + d.dx
142
+ anim := pulseAnim()
119
- movedY := d.y + d.dy
143
+ pulsers := rangeLink(0, Pulsers, |i| newPulser(sheet, anim, i))
144
+ worldKids := appendLink(rangeLink(0, Groups, |gi| newSpinner(sheet, gi)), appendLink(pulsers, appendLink(rects, appendLink(circles, counters))))
120
- nx := if movedX > Float(WorldW) then movedX - Float(WorldW) else movedX
145
+ world: FRoseTree[Actor[Int]] := FRoseTree.of(Scaled(id: WorldId, scale: 0.8), worldKids)
121
- ny := if movedY > Float(WorldH) then movedY - Float(WorldH) else movedY
146
+ buttons: FRoseTree[Actor[Int]] := FRoseTree.of(Group(id: ButtonLayer, x: 0.0, y: 0.0), rangeLink(0, Buttons, |i| newButton(i)))
122
- Drifter(id: d.id, x: nx, y: ny, w: d.w, h: d.h, dx: d.dx, dy: d.dy, color: d.color)
147
+ root: FRoseTree[Actor[Int]] := FRoseTree.of(Group(id: 0, x: 0.0, y: 0.0), [world, buttons])
148
+ State(tree: SceneTree(root: root, camX: 0.0, camY: 0.0, camScale: 1.0), clock: 0.0, ui: ui.init(), clicks: 0)
123
149
 
150
+ # The world layer: everything in it scaled by `scale`.
124
- fun stepDancer(d: Dancer, dt: Float) -> Dancer =
151
+ struct Scaled(id: Int, scale: Float) is Actor[Int] =
125
- Dancer(id: d.id, x: d.x, y: d.y, rotation: d.rotation + 1.2 * dt, srcX: d.srcX)
152
+ fun key(self) -> Int = self.id
126
153
 
127
- fun stepSpinner(p: Spinner, dt: Float) -> Spinner =
128
- Spinner(id: p.id, x: p.x, y: p.y, rotation: p.rotation + 0.24 * dt, dancers: mapLink(p.dancers, |d| stepDancer(d, dt)))
154
+ fun place(self) -> Place = place.at(0.0, 0.0).scaleTo(self.scale, self.scale)
129
155
 
130
- fun stepCounter(c: Counter) -> Counter =
156
+ # --- step ---
131
- Counter(id: c.id, x: c.x, y: c.y, n: c.n + 1)
132
157
 
133
158
  fun step(s: State, dt: Float) -> State =
134
- State(
135
- sheet: s.sheet, white: s.white, spinners: mapLink(s.spinners, |p| stepSpinner(p, dt)),
136
- drifters: mapLink(s.drifters, |d| stepDrifter(d)), counters: mapLink(s.counters, |c| stepCounter(c)),
137
- pulsers: s.pulsers, anim: s.anim, clock: s.clock + dt, ui: s.ui, clicks: s.clicks)
159
+ State(..s, tree: s.tree.step(Ctx[Int](), dt), clock: s.clock + dt)
138
160
 
139
161
  fun countClicks(es: List[UiEvent]) -> Int = match es
140
162
  Nil => 0
141
163
  Cons(e, t) => {if e.kind == Click then 1 else 0} + countClicks(t)
142
164
 
143
- # Feeds one pointer input through ui.step against the button layer.
165
+ # Feeds one pointer input through ui.step against the tree.
144
166
  fun stepUi(s: State, input: InputEvent) -> State =
145
167
  po := input.position()
146
168
  if po.isNone()
147
169
  s
148
170
  else
149
171
  pos := po.unwrap()
150
- hit := buttonsView(s.ui).hitId(pos.x, pos.y)
151
- r := ui.step(s.ui, input, hit)
152
- State(
153
- sheet: s.sheet, white: s.white, spinners: s.spinners, drifters: s.drifters, counters: s.counters,
154
- pulsers: s.pulsers, anim: s.anim, clock: s.clock, ui: r.ui, clicks: s.clicks + countClicks(r.events))
155
-
156
- # --- view: pure, the whole tree every frame ---
157
-
158
- fun dancerView(sheet: Texture, d: Dancer) -> SceneNode[Int] =
159
- Group(
160
- transform: Compose(first: Translate(dx: d.x + 8.0, dy: d.y + 8.0), then: Compose(first: Rotate(radians: d.rotation), then: Translate(dx: 0.0 - 8.0, dy: 0.0 - 8.0))),
161
- children: Cons(head: Sprite(
162
- tex: sheet, x: 0.0, y: 0.0, w: 16.0, h: 16.0, srcX: d.srcX, srcY: 0.0, srcW: 16.0, srcH: 16.0,
163
- tint: Color.White), tail: Nil))
164
-
165
- fun spinnerView(sheet: Texture, p: Spinner) -> SceneNode[Int] =
166
- Group(
167
- transform: Compose(first: Translate(dx: p.x + 75.0, dy: p.y + 85.0), then: Compose(first: Rotate(radians: p.rotation), then: Translate(dx: 0.0 - 75.0, dy: 0.0 - 85.0))),
168
- children: toNodes(p.dancers, |d| dancerView(sheet, d), Nil))
169
-
170
- fun drifterView(white: Texture, d: Drifter) -> SceneNode[Int] =
171
- Sprite(
172
- tex: white, x: d.x, y: d.y, w: d.w, h: d.h, srcX: 0.0, srcY: 0.0, srcW: 0.0, srcH: 0.0,
173
- tint: d.color)
174
-
175
- fun counterView(c: Counter) -> SceneNode[Int] =
176
- Text(text: "n {c.n}", x: c.x, y: c.y, size: 14.0, color: Color.White)
177
-
178
- fun pulserView(sheet: Texture, anim: Anim, clock: Float, p: Pulser) -> SceneNode[Int] =
179
- pose := Anim.at(anim, clock - p.start)
180
- Group(
181
- transform: Compose(first: Translate(dx: p.x + pose.dx + 8.0, dy: p.y + pose.dy + 8.0), then: Compose(first: Scale(sx: pose.scaleX, sy: pose.scaleY), then: Compose(first: Rotate(radians: pose.rotation), then: Translate(dx: 0.0 - 8.0, dy: 0.0 - 8.0)))),
182
- children: Cons(head: Sprite(
183
- tex: sheet, x: 0.0, y: 0.0, w: 16.0, h: 16.0, srcX: p.srcX, srcY: 0.0, srcW: 16.0, srcH: 16.0,
184
- tint: Color.White), tail: Nil))
185
-
186
- fun buttonNodes(i: Int, uiState: UiState) -> List[SceneNode[Int]] =
187
- if i >= Buttons then Nil else Cons(head: ui.button(40000 + i, 40000 + i, "b{i}", Float(i % 10 * 70 + 10), Float(i / 10 * 30 + 10), 64.0, 24.0, uiState), tail: buttonNodes(i + 1, uiState))
188
-
189
- fun buttonsView(uiState: UiState) -> SceneNode[Int] =
190
- Group(transform: Identity, children: buttonNodes(0, uiState))
191
-
192
- fun view(s: State) -> SceneNode[Int] =
193
- texts := toNodes(s.counters, |c| counterView(c), Nil)
194
- drifts := toNodes(s.drifters, |d| drifterView(s.white, d), texts)
195
- pulses := toNodes(s.pulsers, |p| pulserView(s.sheet, s.anim, s.clock, p), drifts)
196
- world: SceneNode[Int] := Group(transform: Scale(sx: 0.8, sy: 0.8), children: toNodes(s.spinners, |p| spinnerView(s.sheet, p), pulses))
197
- Group(transform: Identity, children: [world, buttonsView(s.ui)])
172
+ r := ui.step(s.ui, input, s.tree.hitId(pos.x, pos.y))
173
+ State(..s, tree: ui.styled(s.tree, r.ui), ui: r.ui, clicks: s.clicks + countClicks(r.events))
198
174
 
199
175
  fun whiteTexture(io: Io) -> Texture =
200
176
  t := gfx.createTexture(io, 1, 1)
@@ -211,43 +187,31 @@ struct World(state: State, input: Input) =
211
187
 
212
188
  fun draw(self, io: Io) =
213
189
  gfx.clear(io, Color.rgb(0.05, 0.06, 0.1))
214
- view(self.state).draw(io)
190
+ self.state.tree.draw(io)
215
191
 
216
192
  fun main(io: Io) -> World =
217
193
  World(state: newState(gfx.loadTexture(io, "sprites.png"), whiteTexture(io)), input: Input.create())
218
194
 
219
195
  test "ten frames of step run"
220
196
  s := 0.until(10).fold(newState(Texture(id: 0), Texture(id: 0)), |current, _| step(current, 0.016))
221
- assert nthOr(s.counters, 3, Counter(id: 0, x: 0.0, y: 0.0, n: 0)).n == 13
197
+ assert s.tree.findAs[Counter](30003).unwrap().n == 13
222
- assert {nthOr(s.drifters, 0, newDrifter(0, Color.White, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0)).x - 20.0}.abs() < 0.000001
198
+ assert {s.tree.findAs[Drifter](10000).unwrap().x - 20.0}.abs() < 0.000001
223
- first := nthOr(s.spinners, 0, newSpinner(0))
224
- assert {nthOr(first.dancers, 0, newDancer(0, 0)).rotation - 0.192}.abs() < 0.000001
199
+ assert {s.tree.findAs[Dancer](1000).unwrap().rotation - 0.192}.abs() < 0.000001
225
200
 
226
- test "view has one node per actor"
201
+ test "the tree has one actor per entity"
227
202
  s := newState(Texture(id: 0), Texture(id: 0))
228
- v := view(s)
229
- match v
230
- Group(_, top) =>
231
- assert countNodes(top) == 2
203
+ assert s.tree.root.kids().chain().length() == 2
232
- match top.at(0)
233
- Group(_, kids) =>
234
- assert countNodes(kids) == 50 + 500 + 200 + 50 + 200
204
+ assert s.tree.root.kids().kids().chain().length() == 50 + 500 + 200 + 50 + 200
235
- _ =>
236
- assert false
237
- match top.at(1)
238
- Group(_, buttons) =>
239
- assert countNodes(buttons) == 20
205
+ assert s.tree.root.kids().rest().kids().chain().length() == 20
240
- _ =>
241
- assert false
206
+ assert s.tree.count() == 1 + 1 + 50 + 5000 + 500 + 200 + 50 + 200 + 1 + 20
242
- _ =>
243
- assert false
244
207
 
245
208
  test "button click counts and pulsers animate"
246
209
  s := newState(Texture(id: 0), Texture(id: 0))
247
210
  down := stepUi(s, PointerDown(x: 20.0, y: 20.0))
211
+ assert down.tree.findAs[Button[Int]](40000).unwrap().look == 2
248
212
  up := stepUi(down, PointerUp(x: 20.0, y: 20.0))
249
213
  assert up.clicks == 1
250
214
  assert ui.hovered(up.ui, 40000)
251
- p := newPulser(0)
215
+ assert up.tree.findAs[Button[Int]](40000).unwrap().look == 1
252
- a := Anim.at(s.anim, 0.5 - p.start)
216
+ a := Anim.at(pulseAnim(), 0.5 - 0.0)
253
217
  assert a.dx > 14.9 && a.dx < 15.1
compiler/game/web-test/fixtures/stress_state_view_deep.plum DELETED
@@ -1,198 +0,0 @@
1
- # Variant of stress_state_view.plum: all 5000 dancers live in ONE List (each records its
2
- # spinner index), so step recurses 5000 deep. Original header follows.
3
- # The stress scene of stress_pure_scene.plum written as state and view, now recursive:
4
- # 5000 sprites in 50 slowly rotating groups, 500 rects and 200 circles (sprites of a
5
- # 1x1 white texture), 50 texts with a changing number, drawn through a 0.8 camera.
6
- # `State` is cons `List` lists (each spinner owns the `List` of its 100 dancers);
7
- # `step` is pure, a structural recursion that returns the next state; `view` is pure
8
- # and rebuilds the whole SceneNode tree every frame with recursive functions, which
9
- # `SceneNode.draw` interprets. Nothing is retained between frames but `State`. The
10
- # deepest recursion is the 700 drifters; no loops run in step or view.
11
- module stress_state_view
12
- import std/Str
13
- import std/Int
14
- import std/Float
15
- import std/Slice
16
- import std/List
17
- import std/game/Vec2
18
- import std/game/Color
19
- import std/game/gfx
20
- import std/game/scene
21
- import std/Io
22
- import std/game/input
23
-
24
- Sprites = 5000
25
- Rects = 500
26
- Circles = 200
27
- Texts = 50
28
- Groups = 50
29
- WorldW = 1600
30
- WorldH = 900
31
-
32
-
33
- fun mapLink[A, B](xs: List[A], f: fn(A) -> B) -> List[B] = match xs
34
- Nil => Nil
35
- Cons(h, t) => Cons(head: f(h), tail: mapLink(t, f))
36
-
37
- # The list f(i), f(i + 1) ... f(n - 1).
38
- fun rangeLink[T](i: Int, n: Int, f: fn(Int) -> T) -> List[T] =
39
- if i >= n then Nil else Cons(head: f(i), tail: rangeLink(i + 1, n, f))
40
-
41
- fun appendLink[T](xs: List[T], ys: List[T]) -> List[T] = match xs
42
- Nil => ys
43
- Cons(h, t) => Cons(head: h, tail: appendLink(t, ys))
44
-
45
- # The element at `i`, or `dflt` past the end.
46
- fun nthOr[T](xs: List[T], i: Int, dflt: T) -> T = match xs
47
- Nil => dflt
48
- Cons(h, t) => if i <= 0 then h else nthOr(t, i - 1, dflt)
49
-
50
- # The nodes f(x) for every x of `xs`, followed by `rest`.
51
- fun toNodes[T](xs: List[T], f: fn(T) -> SceneNode[Int], rest: List[SceneNode[Int]]) -> List[SceneNode[Int]] = match xs
52
- Nil => rest
53
- Cons(h, t) => Cons(head: f(h), tail: toNodes(t, f, rest))
54
-
55
- fun countNodes(ns: List[SceneNode[Int]]) -> Int = match ns
56
- Nil => 0
57
- Cons(_, t) => 1 + countNodes(t)
58
-
59
- # A sprite of the sheet inside its group, spinning about its centre.
60
- struct Dancer(gi: Int, id: Int, x: Float, y: Float, rotation: Float, srcX: Float)
61
-
62
- # A rotating group of dancers: top-left (x, y), pivot (75, 85).
63
- struct Spinner(id: Int, x: Float, y: Float, rotation: Float)
64
-
65
- # A square of the white texture that moves by (dx, dy) per frame and wraps.
66
- struct Drifter(id: Int, x: Float, y: Float, w: Float, h: Float, dx: Float, dy: Float, color: Color)
67
-
68
- # Shows "n <count>" and counts up each frame.
69
- struct Counter(id: Int, x: Float, y: Float, n: Int)
70
-
71
- struct State(sheet: Texture, white: Texture, spinners: List[Spinner], dancers: List[Dancer], drifters: List[Drifter], counters: List[Counter])
72
-
73
- fun hue(i: Int) -> Color =
74
- Color(r: Float(i % 7) / 7.0, g: Float(i % 5) / 5.0, b: 0.4 + Float(i % 3) / 5.0, a: 0.8)
75
-
76
- fun newDrifter(id: Int, c: Color, x: Float, y: Float, w: Float, h: Float, dx: Float, dy: Float) -> Drifter =
77
- Drifter(id: id, x: x, y: y, w: w, h: h, dx: dx, dy: dy, color: c)
78
-
79
- fun newDancer(gi: Int, j: Int) -> Dancer =
80
- i := gi * {Sprites / Groups} + j
81
- Dancer(gi: gi, id: 1000 + i, x: Float({j * j * 13 + j * 37} % 150), y: Float({j * j * 29 + j * 53} % 170), rotation: Float(i), srcX: Float(i % 4 * 16))
82
-
83
- fun newSpinner(gi: Int) -> Spinner =
84
- Spinner(id: 100 + gi, x: Float(gi % 10 * 160), y: Float(gi / 10 * 180), rotation: 0.0)
85
-
86
- # All dancers, group after group, built by recursion over the spinner index.
87
- fun allDancers(gi: Int) -> List[Dancer] =
88
- if gi >= Groups then Nil else appendLink(rangeLink(0, Sprites / Groups, |j| newDancer(gi, j)), allDancers(gi + 1))
89
-
90
- fun newState(sheet: Texture, white: Texture) -> State =
91
- rects := rangeLink(0, Rects, |i| newDrifter(10000 + i, hue(i), Float(i * 61 % WorldW), Float(i * 29 % WorldH), 12.0, 8.0, 2.0, 0.0))
92
- circles := rangeLink(0, Circles, |i| newDrifter(20000 + i, hue(i + 3), Float(i * 83 % WorldW), Float(i * 47 % WorldH), 12.0, 12.0, 3.0, 1.0))
93
- State(
94
- sheet: sheet, white: white, spinners: rangeLink(0, Groups, |gi| newSpinner(gi)), dancers: allDancers(0),
95
- drifters: appendLink(rects, circles),
96
- counters: rangeLink(0, Texts, |i| Counter(id: 30000 + i, x: Float(i * 30 % WorldW), y: Float(i * 17 % WorldH), n: i)))
97
-
98
- # --- step: pure ---
99
-
100
- fun stepDrifter(d: Drifter) -> Drifter =
101
- movedX := d.x + d.dx
102
- movedY := d.y + d.dy
103
- nx := if movedX > Float(WorldW) then movedX - Float(WorldW) else movedX
104
- ny := if movedY > Float(WorldH) then movedY - Float(WorldH) else movedY
105
- Drifter(id: d.id, x: nx, y: ny, w: d.w, h: d.h, dx: d.dx, dy: d.dy, color: d.color)
106
-
107
- fun stepDancer(d: Dancer, dt: Float) -> Dancer =
108
- Dancer(gi: d.gi, id: d.id, x: d.x, y: d.y, rotation: d.rotation + 1.2 * dt, srcX: d.srcX)
109
-
110
- fun stepSpinner(p: Spinner, dt: Float) -> Spinner =
111
- Spinner(id: p.id, x: p.x, y: p.y, rotation: p.rotation + 0.24 * dt)
112
-
113
- fun stepCounter(c: Counter) -> Counter =
114
- Counter(id: c.id, x: c.x, y: c.y, n: c.n + 1)
115
-
116
- fun step(s: State, dt: Float) -> State =
117
- State(
118
- sheet: s.sheet, white: s.white, spinners: mapLink(s.spinners, |p| stepSpinner(p, dt)), dancers: mapLink(s.dancers, |d| stepDancer(d, dt)),
119
- drifters: mapLink(s.drifters, |d| stepDrifter(d)), counters: mapLink(s.counters, |c| stepCounter(c)))
120
-
121
- # --- view: pure, the whole tree every frame ---
122
-
123
- fun dancerView(sheet: Texture, d: Dancer) -> SceneNode[Int] =
124
- Group(
125
- transform: Compose(first: Translate(dx: d.x + 8.0, dy: d.y + 8.0), then: Compose(first: Rotate(radians: d.rotation), then: Translate(dx: 0.0 - 8.0, dy: 0.0 - 8.0))),
126
- children: Cons(head: Sprite(
127
- tex: sheet, x: 0.0, y: 0.0, w: 16.0, h: 16.0, srcX: d.srcX, srcY: 0.0, srcW: 16.0, srcH: 16.0,
128
- tint: Color.White), tail: Nil))
129
-
130
- # The leading dancers of `ds` that belong to group `gi`, as nodes.
131
- fun groupNodes(sheet: Texture, ds: List[Dancer], gi: Int) -> List[SceneNode[Int]] = match ds
132
- Nil => Nil
133
- Cons(h, t) => if h.gi == gi then Cons(head: dancerView(sheet, h), tail: groupNodes(sheet, t, gi)) else Nil
134
-
135
- # `ds` without its leading dancers of group `gi`.
136
- fun dropGroup(ds: List[Dancer], gi: Int) -> List[Dancer] = match ds
137
- Nil => Nil
138
- Cons(h, t) => if h.gi == gi then dropGroup(t, gi) else ds
139
-
140
- fun spinnerView(sheet: Texture, p: Spinner, ds: List[Dancer]) -> SceneNode[Int] =
141
- Group(
142
- transform: Compose(first: Translate(dx: p.x + 75.0, dy: p.y + 85.0), then: Compose(first: Rotate(radians: p.rotation), then: Translate(dx: 0.0 - 75.0, dy: 0.0 - 85.0))),
143
- children: groupNodes(sheet, ds, p.id - 100))
144
-
145
- # Spinner groups in order, each taking its dancers from the front of the one list.
146
- fun spinnerNodes(sheet: Texture, ps: List[Spinner], ds: List[Dancer], rest: List[SceneNode[Int]]) -> List[SceneNode[Int]] = match ps
147
- Nil => rest
148
- Cons(p, t) => Cons(head: spinnerView(sheet, p, ds), tail: spinnerNodes(sheet, t, dropGroup(ds, p.id - 100), rest))
149
-
150
- fun drifterView(white: Texture, d: Drifter) -> SceneNode[Int] =
151
- Sprite(
152
- tex: white, x: d.x, y: d.y, w: d.w, h: d.h, srcX: 0.0, srcY: 0.0, srcW: 0.0, srcH: 0.0,
153
- tint: d.color)
154
-
155
- fun counterView(c: Counter) -> SceneNode[Int] =
156
- Text(text: "n {c.n}", x: c.x, y: c.y, size: 14.0, color: Color.White)
157
-
158
- fun view(s: State) -> SceneNode[Int] =
159
- texts := toNodes(s.counters, |c| counterView(c), Nil)
160
- drifts := toNodes(s.drifters, |d| drifterView(s.white, d), texts)
161
- Group(transform: Scale(sx: 0.8, sy: 0.8), children: spinnerNodes(s.sheet, s.spinners, s.dancers, drifts))
162
-
163
- fun whiteTexture(io: Io) -> Texture =
164
- t := gfx.createTexture(io, 1, 1)
165
- t.renderTarget(io)
166
- gfx.clear(io, Color.White)
167
- gfx.renderToScreen(io)
168
- t
169
-
170
- struct World(state: State) =
171
- fun update(self, io: Io, input: Input, dt: Float) -> World =
172
- World(state: step(self.state, dt))
173
-
174
- fun draw(self, io: Io) =
175
- gfx.clear(io, Color.rgb(0.05, 0.06, 0.1))
176
- view(self.state).draw(io)
177
-
178
- fun main(io: Io) -> World =
179
- World(state: newState(gfx.loadTexture(io, "sprites.png"), whiteTexture(io)))
180
-
181
- test "ten frames of step run"
182
- s := 0.until(10).fold(newState(Texture(id: 0), Texture(id: 0)), |current, _| step(current, 0.016))
183
- assert nthOr(s.counters, 3, Counter(id: 0, x: 0.0, y: 0.0, n: 0)).n == 13
184
- assert {nthOr(s.drifters, 0, newDrifter(0, Color.White, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0)).x - 20.0}.abs() < 0.000001
185
- assert {nthOr(s.dancers, 0, newDancer(0, 0)).rotation - 0.192}.abs() < 0.000001
186
-
187
- test "view has one node per actor"
188
- s := newState(Texture(id: 0), Texture(id: 0))
189
- v := view(s)
190
- match v
191
- Group(_, kids) =>
192
- assert countNodes(kids) == 50 + 500 + 200 + 50
193
- _ =>
194
- assert false
195
-
196
- test "dancers in one list 5000"
197
- s := newState(Texture(id: 0), Texture(id: 0))
198
- assert countNodes(toNodes(s.dancers, |d| dancerView(Texture(id: 0), d), Nil)) == 5000
compiler/game/web-test/fixtures/stress_world.plum CHANGED
@@ -1,19 +1,26 @@
1
- # A large y-sorted world as state and view: 20000 sprites in one world layer, about 2000
1
+ # A large y-sorted world on a scene tree: 20000 sprites in one world layer, about 2000
2
- # of them in the 1280x720 view. Every frame a few hundred sprites walk, the whole list is
2
+ # of them in the 1280x720 view. Every frame a few hundred sprites walk, the layer's
3
- # sorted by y, and only the sprites in the view become scene nodes. The state is the
3
+ # children are sorted by y, and only the sprites in the view are drawn. The tree is a
4
- # list, the frame number and the camera; `step` returns the next state and `view` builds
4
+ # `SceneTree[Int]` whose root is the camera (a `Group` at minus the camera's position);
5
+ # each sprite is an `Spr` actor that walks in its own `step` and paints itself only when
5
- # the scene from it.
6
+ # it is in the view.
6
7
  module stress_world
7
8
  import std/Str
8
9
  import std/Int
9
10
  import std/Float
11
+ import std/Bool
10
12
  import std/math
11
13
  import std/List
12
14
  import std/Slice
13
15
  import std/game/Vec2
16
+ import std/game/Affine
14
17
  import std/game/Color
15
18
  import std/game/gfx
19
+ import std/collections/functional/FRoseTree
20
+ import std/game/scene/Place
21
+ import std/game/scene/Actor
16
- import std/game/scene
22
+ import std/game/scene/Ctx
23
+ import std/game/scene/SceneTree
17
24
  import std/Io
18
25
  import std/game/input
19
26
 
@@ -24,48 +31,65 @@ Height = 2300
24
31
  ViewW = 1280.0
25
32
  ViewH = 720.0
26
33
 
27
- # `walker` is the index among the walking sprites, or -1 for one that stands still.
34
+ # `walker` is the index among the walking sprites, or -1 for one that stands still;
35
+ # `frame` is the frame it last walked on.
28
- struct Spr(x: Float, y: Float, srcX: Float, walker: Int)
36
+ struct Spr(id: Int, x: Float, y: Float, srcX: Float, walker: Int, frame: Int, sheet: Texture) is Actor[Int] =
37
+ fun key(self) -> Int = self.id
29
38
 
39
+ fun place(self) -> Place = place.at(self.x, self.y)
40
+
41
+ fun step(self, ctx: Ctx[Int], dt: Float) -> Spr =
42
+ if self.walker < 0
43
+ self
44
+ else
45
+ frame := self.frame + 1
46
+ Spr(..self, y: self.y + math.sin(Float(frame) * 0.05 + Float(self.walker)), frame: frame)
47
+
48
+ # Only a sprite in the view is drawn: `m` takes its (0, 0) to the screen.
49
+ fun paint(self, io: Io, m: Affine, alpha: Float) =
50
+ p := m.apply(Vec2(x: 0.0, y: 0.0))
51
+ if p.x + 16.0 >= 0.0 && p.x <= ViewW && p.y + 16.0 >= 0.0 && p.y <= ViewH
52
+ actor.spritePaint(io, m, alpha, self.sheet, 0.0, 0.0, 16.0, 16.0, self.srcX, 0.0, 16.0, 16.0, Color.White)
53
+
30
- struct State(sheet: Texture, sprites: List[Spr], frame: Int, camX: Float, camY: Float)
54
+ struct State(tree: SceneTree[Int], frame: Int, camX: Float, camY: Float)
31
55
 
32
56
  fun walkerOf(i: Int) -> Int =
33
57
  if i % 37 == 0 && i / 37 < Walkers then i / 37 else -1
34
58
 
35
- fun spriteAt(i: Int) -> Spr =
59
+ fun spriteAt(sheet: Texture, i: Int) -> FRoseTree[Actor[Int]] =
36
- Spr(x: Float({i * 7919 + 13} % Width), y: Float({i * i * 31 / 7 + i * 1013} % Height), srcX: Float(i % 4 * 16), walker: walkerOf(i))
60
+ FRoseTree.leaf(Spr(id: 1 + i, x: Float({i * 7919 + 13} % Width), y: Float({i * i * 31 / 7 + i * 1013} % Height), srcX: Float(i % 4 * 16), walker: walkerOf(i), frame: 0, sheet: sheet))
37
61
 
38
- fun spritesFrom(i: Int) -> List[Spr] =
62
+ fun spritesFrom(sheet: Texture, i: Int) -> List[FRoseTree[Actor[Int]]] =
39
- if i >= Sprites then Nil else Cons(head: spriteAt(i), tail: spritesFrom(i + 1))
63
+ if i >= Sprites then Nil else Cons(head: spriteAt(sheet, i), tail: spritesFrom(sheet, i + 1))
40
64
 
41
65
  fun newState(sheet: Texture) -> State =
66
+ root: FRoseTree[Actor[Int]] := FRoseTree.of(Group(id: 0, x: 0.0, y: 0.0), spritesFrom(sheet, 0))
42
- State(sheet: sheet, sprites: spritesFrom(0), frame: 0, camX: 0.0, camY: 0.0)
67
+ State(tree: SceneTree(root: root, camX: 0.0, camY: 0.0, camScale: 1.0), frame: 0, camX: 0.0, camY: 0.0)
68
+
69
+ fun yOf(n: FRoseTree[Actor[Int]]) -> Float = match n
70
+ FRoseNode(a, _, _) => a.place().y
71
+ FRoseEmpty => 0.0
43
72
 
44
- fun walk(frame: Int, s: Spr) -> Spr =
73
+ # The chain of nodes `t` sorted by y.
45
- if s.walker < 0
74
+ fun sortedByY(t: FRoseTree[Actor[Int]]) -> FRoseTree[Actor[Int]] =
46
- s
47
- else
48
- Spr(..s, y: s.y + math.sin(Float(frame) * 0.05 + Float(s.walker)))
75
+ FRoseTree.chainOf(List.fromSlice(t.chain().toSlice().sort(|a, b| yOf(a) < yOf(b))))
49
76
 
50
- # One frame: the camera drifts, some sprites walk, the list is sorted by y.
77
+ # One frame: the camera drifts, the walkers walk, the layer is sorted by y.
51
78
  fun step(s: State) -> State =
52
79
  frame := s.frame + 1
53
80
  t := Float(frame) * 0.01
81
+ camX := 1300.0 + 600.0 * math.sin(t)
54
- moved := s.sprites.map(|k| walk(frame, k))
82
+ camY := 800.0 + 350.0 * math.cos(t * 0.7)
55
- sorted := List.fromSlice(moved.toSlice().sort(|a, b| a.y < b.y))
83
+ stepped := s.tree.step(Ctx[Int](), 1.0 / 60.0)
84
+ sorted := match stepped.root
85
+ FRoseNode(v, k, n) => FRoseNode(value: v, firstChild: sortedByY(k), nextSibling: n)
86
+ FRoseEmpty => stepped.root
87
+ moved := stepped.withRoot(sorted).updateAs[Group[Int]](0, |g| Group(..g, x: 0.0 - camX, y: 0.0 - camY))
56
- State(..s, sprites: sorted, frame: frame, camX: 1300.0 + 600.0 * math.sin(t), camY: 800.0 + 350.0 * math.cos(t * 0.7))
88
+ State(tree: moved, frame: frame, camX: camX, camY: camY)
57
-
89
+
58
- fun inView(s: State, k: Spr) -> Bool =
90
+ fun inView(s: State, a: Actor[Int]) -> Bool =
91
+ p := a.place()
59
- k.x + 16.0 >= s.camX && k.x <= s.camX + ViewW && k.y + 16.0 >= s.camY && k.y <= s.camY + ViewH
92
+ p.x + 16.0 >= s.camX && p.x <= s.camX + ViewW && p.y + 16.0 >= s.camY && p.y <= s.camY + ViewH
60
-
61
- fun visible(s: State) -> List[Spr] =
62
- s.sprites.filter(|k| inView(s, k))
63
-
64
- fun spriteNode(sheet: Texture, k: Spr) -> SceneNode[Int] =
65
- Sprite(tex: sheet, x: k.x, y: k.y, w: 16.0, h: 16.0, srcX: k.srcX, srcY: 0.0, srcW: 16.0, srcH: 16.0, tint: Color.White)
66
-
67
- fun view(s: State) -> SceneNode[Int] =
68
- Group(transform: Translate(dx: 0.0 - s.camX, dy: 0.0 - s.camY), children: visible(s).map(|k| spriteNode(s.sheet, k)))
69
93
 
70
94
  struct Demo(state: State) =
71
95
  fun update(self, io: Io, input: Input, dt: Float) -> Demo =
@@ -73,7 +97,7 @@ struct Demo(state: State) =
73
97
 
74
98
  fun draw(self, io: Io) =
75
99
  gfx.clear(io, Color.rgb(0.05, 0.06, 0.1))
76
- view(self.state).draw(io)
100
+ self.state.tree.draw(io)
77
101
 
78
102
  fun main(io: Io) -> Demo =
79
103
  Demo(state: newState(gfx.loadTexture(io, "sprites.png")))
@@ -82,9 +106,9 @@ fun main(io: Io) -> Demo =
82
106
 
83
107
  test "about 2000 of the 20000 sprites are in view, sorted by y"
84
108
  s := step(newState(Texture(id: -1)))
109
+ kids := s.tree.root.kids().chain().toSlice()
85
- assert s.sprites.length() == 20000
110
+ assert kids.length() == 20000
86
- all := s.sprites.toSlice()
87
111
  for i := range 19999
88
- assert all.at(i).y <= all.at(i + 1).y
112
+ assert yOf(kids.at(i)) <= yOf(kids.at(i + 1))
89
- shown := visible(s).length()
113
+ shown := s.tree.root.kids().fold(0, |n, a| if inView(s, a) then n + 1 else n)
90
114
  assert shown > 1500 && shown < 2600
compiler/lsp/src/main.rs CHANGED
@@ -651,7 +651,7 @@ mod tests {
651
651
  ("gfx", "std/game/gfx"),
652
652
  ("input", "std/game/input"),
653
653
  ("Int", "std/Int"),
654
- ("SceneNode", "std/game/scene"),
654
+ ("SceneTree", "std/game/scene/SceneTree"),
655
655
  ("Io", "std/Io"),
656
656
  ("Key", "std/game/input"),
657
657
  ("Vec2", "std/game/Vec2"),
compiler/wasm-codegen/tests/wasm_codegen/fusion_alloc_test.rs CHANGED
@@ -1,14 +1,9 @@
1
1
  #![allow(non_snake_case)]
2
2
  //! Fusion allocation checks: compile through the real pipeline (checker `typedSource`
3
3
  //! runs the supercompiler stage) and count `struct.new` of cell types per function.
4
- use plum_test_support::repoRoot;
5
4
  use std::collections::HashMap;
6
5
  use std::collections::HashSet;
7
6
 
8
- fn loadFile(path: &std::path::Path) -> plum_core::ast::Source {
9
- plum_core::loadAndMergeDiag(path, &repoRoot()).unwrap_or_else(|e| panic!("load: {e:?}"))
10
- }
11
-
12
7
  fn load(name: &str, src: &str) -> plum_core::ast::Source {
13
8
  plum_test_support::load(name, src).unwrap_or_else(|e| panic!("load: {e:?}"))
14
9
  }
@@ -209,54 +204,6 @@ fn list_pipeline_loop_has_no_cons_alloc() {
209
204
  assert_eq!(a, expected(100));
210
205
  }
211
206
 
212
- /// `s.render().draw(io)` in the functional component game fuses so no
213
- /// SceneNode / Transform / List cell is built per frame: `SceneNode.drawWith` / `drawKids` fuse
214
- /// with `State.render`, its `renderShip` / `renderHud` / `renderOverlay` parts and the
215
- /// `List.map(|o| o.render(..))` children (each `render` resolved by its receiver type).
216
- #[test]
217
- fn state_view_draw_has_no_scenenode_alloc() {
218
- let g = loadFile(&repoRoot().join("examples/games/orb_run.plum"));
219
- let ns = notes(&g);
220
- say(format!("state_view: fusion notes {ns:?}"));
221
- let w = compile(&g, true);
222
- let fns = functions(&w);
223
- // Fused fns: every `drawWith$..` / `drawKids$..` (`drawWith$render$0`, `drawKids$map$c5$0`, ..).
224
- let isFused = |n: &str| n.starts_with("drawWith$") || n.starts_with("drawKids$");
225
- let fused: Vec<&FnInfo> = fns.iter().filter(|f| isFused(&f.name)).collect();
226
- let names: Vec<&str> = fused.iter().map(|f| f.name.as_str()).collect();
227
- say(format!("state_view: fused fns {names:?}"));
228
- assert!(names.contains(&"drawWith$render$0"), "draw(render(s)) did not fuse; notes: {ns:?}");
229
- // Every part of the picture is fused in: no fused fn still calls a part's builder.
230
- let parts = ["State.render", "State.renderShip", "State.renderHud", "State.renderOverlay", "Orb.render", "Mine.render", "Star.render", "Ship.render", "State.lifeIcons", "List[Orb].map", "List[Mine].map", "List[Star].map"];
231
- for f in &fused {
232
- for c in &f.calls {
233
- assert!(
234
- !parts.iter().any(|p| c == p || c.starts_with(&format!("{p}$")) || c.starts_with(&format!("{p}["))),
235
- "fused {} still builds a part of the picture: calls {c}; notes: {ns:?}",
236
- f.name
237
- );
238
- }
239
- }
240
- // struct types are unnamed in the wasm name section, so assert no `struct.new` at all,
241
- // except (a) the game-over panel `renderPanel`, whose button subtree is a genuinely
242
- // shared result (`boundsWith`, then `drawWith`), and (b) the constant Anim trees the ship
243
- // and the title rebuild per frame (`Anim.at` on a just-built Anim is not one match).
244
- let exempt = |f: &FnInfo| f.name.contains("renderPanel") || f.name.contains("renderTitle") || f.calls.iter().any(|c| c == "Anim.at");
245
- let mut exemptAllocs = 0;
246
- for f in &fused {
247
- if exempt(f) {
248
- exemptAllocs += f.news.len();
249
- continue;
250
- }
251
- assert!(f.news.is_empty(), "fused {} allocates scene/list cells {:?}", f.name, f.news);
252
- }
253
- say(format!("state_view: allocations in exempt fused fns: {exemptAllocs}"));
254
- // 18, not 15, since `List(a, b, ..)` became the `[a, b, ..]` literal: its Cons cells
255
- // are now built inline in `renderPanel` / `renderTitle` instead of inside `List.init`.
256
- assert!(exemptAllocs <= 18, "exempt fused fns allocate more than before ({exemptAllocs} > 18)");
257
- assert!(ns.iter().any(|n| n.contains("animAt on a just-built Anim")), "no note for the Anim trees: {ns:?}");
258
- }
259
-
260
207
  #[test]
261
208
  fn million_pipeline_timed() {
262
209
  let n = 1_000_000;
docs/backlog.md CHANGED
@@ -77,9 +77,9 @@ Open work, in the order the user queued it, plus smaller items found during buil
77
77
  - **Fields declared inside `init` can't be `mut`** (`self.camX: Float = 0.0`) — such fields were moved into the record header. (T8)
78
78
  - **Benchmark harness can't pass `--no-fusion`** — `compiler/game/web-test` compiles without flags, so fusion-off numbers can't be taken since the env var was removed. (T11)
79
79
  - **`Orb`/`Mine` copy their shared `Node` per frame** in the pure game, because `Node`'s x/y/rotation stay immutable in std. Decide during FBIP. (T10)
80
- - **A nested spread allocates in a trait step** (actor-trait task 7, 2026-11-09): `Bod(..self, at: self.at.moveTo(x, y))` with `at: Place` allocates a cell per step that FBIP doesn't remove (Ship.step in a probe: one `struct.new` with a nested `Pos` spread), so the scene benchmark's step workload ran 1.7x slower than with `x`/`y` fields and a `place()` that builds the `Place`. Matters for every `Actor` that keeps `at: Place` (orb_run_tree's kinds, task 8's ui widgets).
81
- - **Struct fields have no defaults** (actor-trait task 6): the plan's `struct Place(x, y, scaleX: Float = 1.0, ..)` doesn't parse; std/game_enum_tree/Place has `place.at(x, y)` and `place.turned(x, y, s, r)` instead.
82
- - **A generic call's result pinned only by a later parameter** (actor-trait task 6): `firstOf(Holder.of(Box(id: 5)).same())`, with `firstOf(h: Holder[Int])`, still instantiates `Box[Unit]` and fails codegen ("Box[Unit] has no compiled method 'key' for a call on Thing[Unit]"); an annotated local (`h: Holder[Int] := ..`) works. Likewise `EStage.of(Group(..))` with nothing fixing `M` is an `EStage[Unit]`: annotate it.
80
+ - **A nested spread allocates in a trait step** (actor-trait task 7, 2026-11-09): `Bod(..self, at: self.at.moveTo(x, y))` with `at: Place` allocates a cell per step that FBIP doesn't remove (Ship.step in a probe: one `struct.new` with a nested `Pos` spread), so the scene benchmark's step workload ran 1.7x slower than with `x`/`y` fields and a `place()` that builds the `Place`. So std's actors (`Group`, `Box`, ui's `Button` and `Label`) and the games keep plain `x`/`y` fields (actor-trait task 8); a value `Place` in a unique field is now written into its old box, but the boxed field still costs the step, and removing that needs a layout change.
81
+ - **Struct fields have no defaults** (actor-trait task 6): the plan's `struct Place(x, y, scaleX: Float = 1.0, ..)` doesn't parse; std/game/scene/Place has `place.at(x, y)` and `place.turned(x, y, s, r)` instead.
82
+ - **A generic call's result pinned only by a later parameter** (actor-trait task 6): `firstOf(Holder.of(Box(id: 5)).same())`, with `firstOf(h: Holder[Int])`, still instantiates `Box[Unit]` and fails codegen ("Box[Unit] has no compiled method 'key' for a call on Thing[Unit]"); an annotated local (`h: Holder[Int] := ..`) works. Likewise `SceneTree.of(Group(..))` with nothing fixing `M` is a `SceneTree[Unit]`: annotate it.
83
83
  - **Uniqueness precision** — `adv(Cell(..))` inlined into `main` reports "s used after its spread" although `s.x` is only read inside the spread value (a false "not in place"). (T10)
84
84
  - **Pattern-casing hint for union members** — "did you mean Foo?" doesn't cover a lowercase name that spells a union member (lookup lives in `compiler/core/src/unions.rs`). (T1)
85
85
  - **Constant `Anim` trees rebuilt every frame** in `games/functional/game_state_view.plum` (`renderTitle`, Ship render) — hoist them into `State` or constants. (F-T23-1)
docs/game.md CHANGED
@@ -116,9 +116,18 @@ If the new code has a compile error, the old game keeps running and the error ap
116
116
 
117
117
  ## Scenes
118
118
 
119
- For drawing more than a few shapes, build a picture and draw it. [`std/game/scene.plum`](../std/game/scene.plum) has one scene style: `SceneNode[M]` is a plain value, a tree of `Group`, `Sprite`, `Text`, `RectShape`, `CircleShape`, `LineShape`, `Filter` and `Clickable` nodes. `render(self)` builds a fresh tree from your state every frame, and `draw(io)` draws it. Nothing in the tree is retained or changed in place.
119
+ For more than a few shapes, keep the game in a scene tree and draw it. [`std/game/scene`](../std/game/scene) has one: a `SceneTree[M]` ([`SceneTree.plum`](../std/game/scene/SceneTree.plum)) is a tree of actors that lives from frame to frame, and `M` is the game's own message type. It is a value like the rest of your state: every change returns a new tree, and a kept old tree stays as it was. When nothing holds the old one, the compiler writes the new one into its cells.
120
120
 
121
- A `Clickable` carries a message of type `M`. `hitId(x, y)` tells you which one is under a point, and `msgOf(id)` gives its message, so clicks go through your state like any other event.
121
+ Each kind of actor is its own struct, with only its own fields, that `is Actor[M]` ([`Actor.plum`](../std/game/scene/Actor.plum)). It must say which actor it is (`key`, the id the tree finds it by) and where it is in its parent (`place`, a `Place` with a position, scale, rotation and origin). Everything else has a default that it may override:
122
+
123
+ - `step(self, ctx, dt)` returns its next version, once a tick. `ctx` ([`Ctx.plum`](../std/game/scene/Ctx.plum)) has its parent's world transform and alpha, and takes commands for after the step: `ctx.out.push(Spawn(parent, node))`, `ctx.out.push(Kill(id))` and `ctx.send(msg)`.
124
+ - `paint(self, io, m, alpha)` draws it in its own coordinates seen through `m`. `Actor.plum` has helpers for boxes, circles, lines, sprites and text (`actor.boxPaint(io, m, alpha, w, h, color)`, ...).
125
+ - `hit(self, p)` says whether a point in its own coordinates is on it. Only an actor that says so is found by `tree.hit(x, y)` and `tree.hitId(x, y)`, topmost first.
126
+ - `shown`, `gone` and `opacity`: a hidden actor isn't drawn or hit, a gone one is dropped with its subtree, and opacities multiply down the tree.
127
+
128
+ Keep an actor's position in plain fields (`x: Float, y: Float`) and build its `Place` in `place`, as `place.at(self.x, self.y)`: a `Place` field costs a step about 1.7 times as much. std gives `Group` (a parent that paints nothing) and `Box`; [`std/game/ui.plum`](../std/game/ui.plum) gives `Label` and `Button`, whose `onClick: M` is the message a click sends (`ui.messages`).
129
+
130
+ The tree's `step(ctx, dt)` steps every actor, parents before children, then applies the spawns and kills. `add`, `update`, `kill` and `find` work by id, and `updateAs[T](id, f)` and `findAs[T](id)` act on an actor of the type `T` only. A pattern `Orb as o` on an `Actor[M]` matches an `Orb`.
122
131
 
123
132
  ```plum
124
133
  import std/Int
@@ -128,36 +137,37 @@ import std/Option
128
137
  import std/List
129
138
  import std/Io
130
139
  import std/game/gfx
131
- import std/game/audio
132
140
  import std/game/input
133
141
  import std/game/Color
134
- import std/game/scene
142
+ import std/game/ui
143
+ import std/collections/functional/FRoseTree
144
+ import std/game/scene/Actor
145
+ import std/game/scene/Ctx
146
+ import std/game/scene/SceneTree
135
147
 
136
- struct Counter(clicks: Int) =
148
+ struct Counter(tree: SceneTree[Int], clicks: Int) =
137
149
  fun update(self, io: Io, input: Input, dt: Float) -> Counter =
150
+ t := self.tree.step(Ctx[Int](), dt)
138
- if !input.isMousePressed()
151
+ p := input.mousePos()
152
+ if input.isMousePressed() && t.hitId(p.x, p.y).isSome()
139
- self
153
+ n := self.clicks + 1
154
+ Counter(tree: t.updateAs[Label[Int]](2, |l| l.relabel("clicks {n}")), clicks: n)
140
155
  else
141
- p := input.mousePos()
142
- match self.render().hitId(p.x, p.y)
143
- Some(id) => Counter(clicks: self.clicks + 1)
144
- None => self
145
-
146
- fun render(self) -> SceneNode[Int] =
156
+ Counter(..self, tree: t)
147
- Group(transform: Identity, children: [
148
- Clickable(id: 1, msg: 1, child: RectShape(x: 20.0, y: 20.0, w: 100.0, h: 40.0, color: Color.Red)),
149
- Text(text: "clicks {self.clicks}", x: 20.0, y: 80.0, size: 16.0, color: Color.White)
150
- ])
151
157
 
152
158
  fun draw(self, io: Io) =
153
159
  gfx.clear(io, Color.Black)
154
- self.render().draw(io)
160
+ self.tree.draw(io)
155
161
 
156
162
  fun main(io: Io) -> Counter =
163
+ root: FRoseTree[Actor[Int]] := FRoseTree.of(Group(id: 0, x: 0.0, y: 0.0), [
164
+ FRoseTree.leaf(Box(id: 1, x: 20.0, y: 20.0, w: 100.0, h: 40.0, color: Color.Red)),
165
+ FRoseTree.leaf(Label(id: 2, x: 20.0, y: 80.0, text: "clicks 0", size: 16.0, color: Color.White))
166
+ ])
157
- Counter(clicks: 0)
167
+ Counter(tree: SceneTree(root: root, camX: 0.0, camY: 0.0, camScale: 1.0), clicks: 0)
158
168
  ```
159
169
 
160
- [`std/game/ui.plum`](../std/game/ui.plum) adds buttons on top of this, and [`std/game/Anim.plum`](../std/game/Anim.plum) adds animation by time. A full game written this way is [`orb_run.plum`](../examples/games/orb_run.plum); its header comment explains how it is put together.
170
+ [`std/game/Anim.plum`](../std/game/Anim.plum) adds animation by time. A full game written this way is [`orb_run.plum`](../examples/games/orb_run.plum); its header comment explains how it is put together.
161
171
 
162
172
  ## Testing a game
163
173
 
docs/std.md CHANGED
@@ -121,7 +121,7 @@ Only true tail calls run in constant stack; other recursion overflows at a few t
121
121
  - **`FFenwickTree`:** a prefix-sum tree: a segment tree specialised to `Int` sums, keeping only each node's left-half sum (what prefix queries read). The `i & -i` index trick needs an array, so it isn't used.
122
122
  - **`FQuadtree`, `FKdTree`, `FBvh`:** spatial trees over `Vec2` and `Aabb`. Leaf buckets and query results are cons lists. Balanced builds sort with a merge sort on `List` (`FKdTree`) or pick medians with a quickselect (`FBvh`).
123
123
  - **`FUnionFind`:** a persistent parent map (two `FAvlTree`s: parents and set sizes) with union by size and no path compression. `find`, `union` and `connected` are O(log² n). `union` returns the new forest.
124
- - **`FRoseTree`:** a tree with any number of children per node, in left-child, right-sibling form (`FRoseEmpty`, `FRoseNode(value, firstChild, nextSibling)`). `FRoseTree.leaf(v)` and `FRoseTree.of(v, kids)` build nodes, `FRoseTree.chainOf(ns)` links a `List` of them as siblings. A value is a node with its later siblings; `fold`, `each`, `find`, `toList` and `chain` are tail calls along the siblings, while `map`, `filter`, `append` and `replace` recurse once per sibling. `filter`, `replace` and `update` return untouched subtrees as they were. std/game_enum_tree's stage is an `FRoseTree[Actor[M]]`, a tree of trait objects.
124
+ - **`FRoseTree`:** a tree with any number of children per node, in left-child, right-sibling form (`FRoseEmpty`, `FRoseNode(value, firstChild, nextSibling)`). `FRoseTree.leaf(v)` and `FRoseTree.of(v, kids)` build nodes, `FRoseTree.chainOf(ns)` links a `List` of them as siblings. A value is a node with its later siblings; `fold`, `each`, `find`, `toList` and `chain` are tail calls along the siblings, while `map`, `filter`, `append` and `replace` recurse once per sibling. `filter`, `replace` and `update` return untouched subtrees as they were. std/game/scene's `SceneTree[M]` is an `FRoseTree[Actor[M]]`, a tree of trait objects.
125
125
  - **`FLeftistHeap`, `FPairingHeap`:** priority queues with `fold` in place of an iterator. The pairing heap's two-pass `pop` is tail recursive, so a root with 100,000 children is fine.
126
126
 
127
127
  ## Option and Result
examples/games/kids/balloon_pop.plum CHANGED
@@ -4,28 +4,42 @@
4
4
  # child hears the pop and sees the word. Every 10 pops a "Hooray!" party with
5
5
  # confetti. There is no way to lose and no timer.
6
6
  #
7
- # Functional style, as in ../game_state_view.plum: `State` holds the whole game,
7
+ # The game is a scene tree (std/game/scene): a `SceneTree[Msg]` of actors that lives
8
- # `Msg` is everything that can happen to it, `update(msg)` returns the next `State`
9
- # and `render()` returns a fresh `SceneNode[Msg]` picture every frame. Each balloon
8
+ # from frame to frame, kept in `State` with the pops and a `Random`. Each balloon is a
10
- # is a `Clickable` carrying its own `Pop(id)` message, so a pointer press finds the
9
+ # `Balloon` actor that rises in its own `step` and is the only actor that is ever hit, so
11
- # message under it in the picture (`hitId`, then `msgOf`) and sends it to `update`.
10
+ # a pointer press finds the balloon under it with `hitId` and sends `Pop(id)` to
11
+ # `update`. The sky, the hud and the party are actors too; the hud and the party show
12
+ # the pops `State` gives them. `Msg` is everything that can happen to the state, and
12
- # A press pops at once: small children tap, they do not click.
13
+ # `update(msg)` returns the next `State`. A press pops at once: small children tap, they
14
+ # do not click.
15
+ #
16
+ # 0 root (the camera that fits the arena on screen)
17
+ # ├─ 1 sky
18
+ # ├─ 2 balloons ─ 100..105
19
+ # ├─ 3 hud
20
+ # └─ 4 party (shown while partying)
13
21
  module balloon_pop
14
22
  import std/Str
15
23
  import std/Int
16
24
  import std/Float
25
+ import std/Bool
17
26
  import std/Slice
18
27
  import std/Option
19
28
  import std/List
20
29
  import std/math
21
30
  import std/Random
22
31
  import std/game/Vec2
32
+ import std/game/Affine
23
33
  import std/game/Color
24
34
  import std/game/gfx
25
35
  import std/game/audio
26
- import std/game/scene
27
36
  import std/game/Anim
28
37
  import std/game/input
38
+ import std/collections/functional/FRoseTree
39
+ import std/game/scene/Place
40
+ import std/game/scene/Actor
41
+ import std/game/scene/Ctx
42
+ import std/game/scene/SceneTree
29
43
  import std/Io
30
44
 
31
45
  ArenaW = 800.0
@@ -38,6 +52,11 @@ PopTime = 0.6
38
52
  PartyEvery = 10
39
53
  PartyTime = 2.5
40
54
 
55
+ RootId = 0
56
+ SkyId = 1
57
+ BalloonLayer = 2
58
+ HudId = 3
59
+ PartyId = 4
41
60
  BalloonId = 100
42
61
 
43
62
  # The balloon colours a child can name.
@@ -62,12 +81,9 @@ struct Hue(name: Str, color: Color) =
62
81
 
63
82
  # --- small pure helpers ---
64
83
 
65
- fun nothing() -> SceneNode[Msg] =
66
- Group(transform: Identity, children: Nil)
67
-
68
84
  # Text centred on `cx` (the host font is about 0.6 of its size wide per letter).
69
- fun centred(s: Str, cx: Float, y: Float, size: Float, color: Color) -> SceneNode[Msg] =
85
+ fun centred(io: Io, m: Affine, s: Str, cx: Float, y: Float, size: Float, color: Color) =
70
- Text(text: s, x: cx - size * 0.3 * Float(s.length()), y: y, size: size, color: color)
86
+ actor.textPaint(io, m, 1.0, s, cx - size * 0.3 * Float(s.length()), y, size, color)
71
87
 
72
88
  # Grows in, then pulses gently.
73
89
  fun partyAnim() -> Anim =
@@ -78,78 +94,160 @@ fun partyAnim() -> Anim =
78
94
  ]
79
95
  )
80
96
 
97
+ fun zoomOf(sw: Float, sh: Float) -> Float =
98
+ {sw / ArenaW}.min(sh / ArenaH)
99
+
100
+ # --- the actors ---
101
+
102
+ # The root: the camera that fits the arena on the screen, at (x, y) and scaled by `zoom`.
103
+ struct Camera(id: Int, x: Float, y: Float, zoom: Float) is Actor[Msg] =
104
+ fun key(self) -> Int = self.id
105
+
106
+ fun place(self) -> Place = place.at(self.x, self.y).scaleTo(self.zoom, self.zoom)
107
+
108
+ # Fitting a `sw` by `sh` screen.
109
+ fun fitted(self, sw: Float, sh: Float) -> Camera =
110
+ z := zoomOf(sw, sh)
111
+ Camera(..self, x: {sw - z * ArenaW} / 2.0, y: {sh - z * ArenaH} / 2.0, zoom: z)
112
+
81
- # One balloon. `poppedAt` is the clock time it was popped, or negative while whole.
113
+ # One balloon. `poppedAt` is the clock time it was popped, or negative while whole;
114
+ # `clock` is the game's clock, which it keeps in its own step.
82
- struct Balloon(id: Int, x: Float, y: Float, speed: Float, hue: Int, phase: Float, poppedAt: Float) =
115
+ struct Balloon(id: Int, x: Float, y: Float, speed: Float, hue: Int, phase: Float, poppedAt: Float, clock: Float) is Actor[Msg] =
83
116
 
84
117
  # A fresh balloon below the bottom edge, `depth` further down so they do not
85
- # all arrive together.
118
+ # all arrive together, at the game's `clock`.
86
- fun spawn(id: Int, rng: Random, depth: Float) -> Spawned =
119
+ fun spawn(id: Int, rng: Random, depth: Float, clock: Float) -> Spawned =
87
120
  rx := rng.nextFloat()
88
121
  rs := rx.rng.nextFloat()
89
122
  rh := rs.rng.nextIntBelow(Hue.count())
90
123
  x := 60.0 + rx.value * {ArenaW - 120.0}
91
124
  speed := MinSpeed + rs.value * {MaxSpeed - MinSpeed}
92
- b := Balloon(id: id, x: x, y: ArenaH + Radius + depth, speed: speed, hue: rh.value, phase: rx.value * Float.Tau, poppedAt: -1.0)
125
+ b := Balloon(id: id, x: x, y: ArenaH + Radius + depth, speed: speed, hue: rh.value, phase: rx.value * Float.Tau, poppedAt: -1.0, clock: clock)
93
126
  Spawned(balloon: b, rng: rh.rng)
94
127
 
128
+ fun key(self) -> Int = self.id
129
+
130
+ # It sways side to side as it rises; once popped it stays where it burst.
131
+ fun place(self) -> Place =
132
+ if self.popped() then place.at(self.x, self.y) else place.at(self.swayX(self.clock), self.y)
133
+
134
+ # Rises while whole.
135
+ fun step(self, ctx: Ctx[Msg], dt: Float) -> Balloon =
136
+ if self.popped() then Balloon(..self, clock: self.clock + dt) else Balloon(..self, y: self.y - self.speed * dt, clock: self.clock + dt)
137
+
138
+ fun paint(self, io: Io, m: Affine, alpha: Float) =
139
+ if self.popped() then self.paintBurst(io, m, self.clock - self.poppedAt) else self.paintWhole(io, m)
140
+
141
+ # A whole balloon is hit on its string, its knot or itself.
142
+ fun hit(self, p: Vec2) -> Bool =
143
+ r := Radius
144
+ !self.popped() && {
145
+ actor.lineHit(0.0, r, 6.0 * math.sin(self.clock * 3.0 + self.phase), r * 2.6, 2.0, p)
146
+ || actor.circleHit(0.0, r + 2.0, 6.0, p)
147
+ || actor.circleHit(0.0, 0.0, r, p)
148
+ || actor.circleHit(0.0 - r * 0.35, 0.0 - r * 0.4, r * 0.22, p)}
149
+
95
150
  fun popped(self) -> Bool =
96
151
  self.poppedAt >= 0.0
97
152
 
98
- # Where the balloon is drawn: it sways side to side as it rises.
153
+ # Where the balloon is drawn while whole.
99
154
  fun swayX(self, clock: Float) -> Float =
100
155
  self.x + 14.0 * math.sin(clock * 1.3 + self.phase)
101
156
 
102
- # Rises while whole; once popped it stays where it burst.
157
+ # Popped at `clock`, where it is drawn then.
103
- fun update(self, dt: Float) -> Balloon =
104
- if self.popped() then self else Balloon(..self, y: self.y - self.speed * dt)
158
+ fun poppedAtClock(self, clock: Float) -> Balloon = Balloon(..self, x: self.swayX(clock), poppedAt: clock)
105
159
 
106
160
  # Gone off the top, or popped long enough ago that the burst has faded.
107
161
  fun done(self, clock: Float) -> Bool =
108
162
  self.y < 0.0 - Radius * 3.0 || {self.popped() && clock - self.poppedAt > PopTime}
109
163
 
110
- fun render(self, clock: Float) -> SceneNode[Msg] =
111
- if self.popped() then self.renderBurst(clock - self.poppedAt) else self.renderWhole(clock)
112
-
113
- fun renderWhole(self, clock: Float) -> SceneNode[Msg] =
164
+ fun paintWhole(self, io: Io, m: Affine) =
114
165
  r := Radius
115
166
  c := Hue.of(self.hue).color
116
- Clickable(
117
- id: self.id,
118
- msg: Pop(id: self.id),
119
- child: Group(
120
- transform: Translate(dx: self.swayX(clock), dy: self.y),
121
- children: [
122
- LineShape(x1: 0.0, y1: r, x2: 6.0 * math.sin(clock * 3.0 + self.phase), y2: r * 2.6, thickness: 2.0, color: Color.rgb(0.35, 0.35, 0.35)),
167
+ actor.linePaint(io, m, 1.0, 0.0, r, 6.0 * math.sin(self.clock * 3.0 + self.phase), r * 2.6, 2.0, Color.rgb(0.35, 0.35, 0.35))
123
- CircleShape(cx: 0.0, cy: r + 2.0, r: 6.0, color: c),
168
+ actor.circlePaint(io, m, 1.0, 0.0, r + 2.0, 6.0, c)
124
- CircleShape(cx: 0.0, cy: 0.0, r: r, color: c),
169
+ actor.circlePaint(io, m, 1.0, 0.0, 0.0, r, c)
125
- CircleShape(cx: 0.0 - r * 0.35, cy: 0.0 - r * 0.4, r: r * 0.22, color: Color.White.withAlpha(0.55))
170
+ actor.circlePaint(io, m, 1.0, 0.0 - r * 0.35, 0.0 - r * 0.4, r * 0.22, Color.White.withAlpha(0.55))
126
- ]
127
- )
128
- )
129
171
 
130
172
  # Eight dots fly out and fade, and the colour's name floats up.
131
- fun renderBurst(self, age: Float) -> SceneNode[Msg] =
173
+ fun paintBurst(self, io: Io, m: Affine, age: Float) =
132
174
  t := {age / PopTime}.min(1.0)
133
175
  fade := 1.0 - t
134
176
  hue := Hue.of(self.hue)
135
177
  reach := 20.0 + 70.0 * t
136
- Group(
137
- transform: Translate(dx: self.x, dy: self.y),
138
- children: Cons(
139
- head: centred("{hue.name}!", 0.0, -20.0 - 60.0 * t, 40.0, Color.rgb(0.15, 0.15, 0.3).withAlpha(fade)),
178
+ centred(io, m, "{hue.name}!", 0.0, -20.0 - 60.0 * t, 40.0, Color.rgb(0.15, 0.15, 0.3).withAlpha(fade))
140
- tail: burstDots(0, reach, hue.color.withAlpha(fade))
179
+ c := hue.color.withAlpha(fade)
141
- )
142
- )
143
-
144
- fun burstDots(i: Int, reach: Float, c: Color) -> List[SceneNode[Msg]] =
145
- if i >= 8
180
+ for i := range 8
146
- Nil
147
- else
148
- a := Float(i) * Float.Tau / 8.0
181
+ a := Float(i) * Float.Tau / 8.0
149
- Cons(head: CircleShape(cx: math.cos(a) * reach, cy: math.sin(a) * reach, r: 8.0, color: c), tail: burstDots(i + 1, reach, c))
182
+ actor.circlePaint(io, m, 1.0, math.cos(a) * reach, math.sin(a) * reach, 8.0, c)
150
183
 
151
184
  struct Spawned(balloon: Balloon, rng: Random)
152
185
 
186
+ # Sky, two drifting clouds and the grass. `clock` is the game's clock.
187
+ struct Sky(id: Int, clock: Float) is Actor[Msg] =
188
+ fun key(self) -> Int = self.id
189
+
190
+ fun place(self) -> Place = place.at(0.0, 0.0)
191
+
192
+ fun step(self, ctx: Ctx[Msg], dt: Float) -> Sky = Sky(..self, clock: self.clock + dt)
193
+
194
+ fun paint(self, io: Io, m: Affine, alpha: Float) =
195
+ actor.rectPaint(io, m, 1.0, 0.0, 0.0, ArenaW, ArenaH, Color.rgb(0.55, 0.8, 1.0))
196
+ actor.rectPaint(io, m, 1.0, 0.0, 0.0, ArenaW, 200.0, Color.rgb(0.45, 0.72, 0.98))
197
+ actor.circlePaint(io, m, 1.0, 690.0, 90.0, 46.0, Color.rgb(1.0, 0.9, 0.35))
198
+ paintCloud(io, m, wrapX(120.0 + self.clock * 12.0), 130.0)
199
+ paintCloud(io, m, wrapX(520.0 + self.clock * 8.0), 220.0)
200
+ actor.rectPaint(io, m, 1.0, 0.0, ArenaH - 50.0, ArenaW, 50.0, Color.rgb(0.4, 0.78, 0.35))
201
+
202
+ fun wrapX(x: Float) -> Float =
203
+ span := ArenaW + 200.0
204
+ x - span * Float(Int(x / span)) - 100.0
205
+
206
+ fun paintCloud(io: Io, m: Affine, x: Float, y: Float) =
207
+ white := Color.White.withAlpha(0.9)
208
+ c := m.mul(place.at(x, y).local())
209
+ actor.circlePaint(io, c, 1.0, -30.0, 8.0, 24.0, white)
210
+ actor.circlePaint(io, c, 1.0, 0.0, 0.0, 32.0, white)
211
+ actor.circlePaint(io, c, 1.0, 32.0, 8.0, 24.0, white)
212
+
213
+ # The pop count, top left.
214
+ struct Hud(id: Int, pops: Int) is Actor[Msg] =
215
+ fun key(self) -> Int = self.id
216
+
217
+ fun place(self) -> Place = place.at(0.0, 0.0)
218
+
219
+ fun paint(self, io: Io, m: Affine, alpha: Float) =
220
+ actor.rectPaint(io, m, 1.0, 16.0, 14.0, 170.0, 56.0, Color.White.withAlpha(0.7))
221
+ actor.circlePaint(io, m, 1.0, 46.0, 42.0, 18.0, Hue.of(0).color)
222
+ actor.textPaint(io, m, 1.0, "{self.pops}", 80.0, 20.0, 44.0, Color.rgb(0.15, 0.15, 0.3))
223
+
224
+ # The "Hooray!" party that began at `partyAt` on the game's `clock`: shown for
225
+ # `PartyTime`, with confetti and the pop count.
226
+ struct Party(id: Int, partyAt: Float, clock: Float, pops: Int) is Actor[Msg] =
227
+ fun key(self) -> Int = self.id
228
+
229
+ fun place(self) -> Place = place.at(0.0, 0.0)
230
+
231
+ fun shown(self) -> Bool = self.clock - self.partyAt < PartyTime
232
+
233
+ fun step(self, ctx: Ctx[Msg], dt: Float) -> Party = Party(..self, clock: self.clock + dt)
234
+
235
+ fun paint(self, io: Io, m: Affine, alpha: Float) =
236
+ age := self.clock - self.partyAt
237
+ p := Anim.at(partyAnim(), age)
238
+ paintConfetti(io, m, age)
239
+ c := m.mul(place.at(ArenaW / 2.0, 250.0).scaleTo(p.scaleX, p.scaleY).local())
240
+ centred(io, c, "Hooray!", 0.0, -40.0, 72.0, Color.rgb(0.95, 0.3, 0.5))
241
+ centred(io, c, "{self.pops} balloons!", 0.0, 40.0, 40.0, Color.rgb(0.15, 0.15, 0.3))
242
+
243
+ # 30 confetti squares falling from the top, `age` seconds into the party.
244
+ fun paintConfetti(io: Io, m: Affine, age: Float) =
245
+ for i := range 30
246
+ x := Float({i * 7919} % 800)
247
+ y := Float({i * 104729} % 200) - 200.0 + age * {180.0 + Float(i % 5) * 40.0}
248
+ wob := 10.0 * math.sin(age * 4.0 + Float(i))
249
+ actor.rectPaint(io, m, 1.0, x + wob, y, 12.0, 12.0, Hue.of(i).color)
250
+
153
251
  # What can happen to the game.
154
252
  enum Msg =
155
253
  | Tick(dt: Float)
@@ -157,49 +255,61 @@ enum Msg =
157
255
  | Event(input: InputEvent)
158
256
  | Pop(id: Int)
159
257
 
160
- struct State(balloons: List[Balloon], rng: Random, pops: Int, clock: Float, partyAt: Float, sw: Float, sh: Float) =
258
+ struct State(tree: SceneTree[Msg], rng: Random, pops: Int, clock: Float, partyAt: Float, sw: Float, sh: Float) =
161
259
 
162
260
  fun start(seed: Int, sw: Float, sh: Float) -> State =
261
+ root: FRoseTree[Actor[Msg]] := FRoseTree.of(Camera(id: RootId, x: 0.0, y: 0.0, zoom: 1.0).fitted(sw, sh), [
262
+ FRoseTree.leaf(Sky(id: SkyId, clock: 0.0)),
263
+ FRoseTree.leaf(Group(id: BalloonLayer, x: 0.0, y: 0.0)),
264
+ FRoseTree.leaf(Hud(id: HudId, pops: 0)),
265
+ FRoseTree.leaf(Party(id: PartyId, partyAt: -100.0, clock: 0.0, pops: 0))])
266
+ tree := SceneTree(root: root, camX: 0.0, camY: 0.0, camScale: 1.0)
163
- State(balloons: Nil, rng: Random.seeded(seed), pops: 0, clock: 0.0, partyAt: -100.0, sw: sw, sh: sh).fill(0)
267
+ State(tree: tree, rng: Random.seeded(seed), pops: 0, clock: 0.0, partyAt: -100.0, sw: sw, sh: sh).fill(0)
164
268
 
165
269
  # Balloons `i` and up, spread out below the screen.
166
270
  fun fill(self, i: Int) -> State =
167
271
  if i >= Count
168
272
  self
169
273
  else
170
- sp := Balloon.spawn(BalloonId + i, self.rng, Float(i) * 110.0 - ArenaH * 0.6)
274
+ sp := Balloon.spawn(BalloonId + i, self.rng, Float(i) * 110.0 - ArenaH * 0.6, self.clock)
171
- State(..self, balloons: self.balloons.append([sp.balloon]), rng: sp.rng).fill(i + 1)
275
+ State(..self, tree: self.tree.add(BalloonLayer, FRoseTree.leaf(sp.balloon)), rng: sp.rng).fill(i + 1)
276
+
277
+ # The balloons, in tree order.
278
+ fun balloons(self) -> List[Balloon] =
279
+ self.tree.root.fold(Nil, |acc, a| match a
280
+ Balloon as b => Cons(head: b, tail: acc)
281
+ _ => acc).reverse()
172
282
 
173
283
  fun update(self, msg: Msg) -> State = match msg
174
284
  Tick(dt) => self.tick(dt)
175
- Resize(w, h) => State(..self, sw: w, sh: h)
285
+ Resize(w, h) => State(..self, sw: w, sh: h, tree: self.tree.updateAs[Camera](RootId, |c| c.fitted(w, h)))
176
286
  Event(input) => self.onInput(input)
177
287
  Pop(id) => self.pop(id)
178
288
 
179
289
  fun tick(self, dt: Float) -> State =
180
- moved := State(..self, clock: self.clock + dt, balloons: self.balloons.map(|b| b.update(dt)))
290
+ moved := State(..self, clock: self.clock + dt, tree: self.tree.step(Ctx[Msg](), dt))
181
- moved.balloons.fold(moved, |s, b| s.renew(b))
291
+ moved.balloons().fold(moved, |s, b| s.renew(b))
182
292
 
183
293
  # A balloon that is gone comes back at the bottom with a new colour.
184
294
  fun renew(self, b: Balloon) -> State =
185
295
  if !b.done(self.clock)
186
296
  self
187
297
  else
188
- sp := Balloon.spawn(b.id, self.rng, 0.0)
298
+ sp := Balloon.spawn(b.id, self.rng, 0.0, self.clock)
189
- State(..self, balloons: self.balloons.map(|x| if x.id == b.id then sp.balloon else x), rng: sp.rng)
299
+ State(..self, tree: self.tree.updateAs[Balloon](b.id, |x| sp.balloon), rng: sp.rng)
190
300
 
191
301
  fun pop(self, id: Int) -> State =
192
- hit := self.balloons.fold(false, |found, b| found || {b.id == id && !b.popped()})
302
+ whole := match self.tree.findAs[Balloon](id)
303
+ Some(b) => !b.popped()
304
+ None => false
193
- if !hit
305
+ if !whole
194
306
  self
195
307
  else
196
308
  pops := self.pops + 1
197
- State(
198
- ..self,
199
- pops: pops,
200
- partyAt: if pops % PartyEvery == 0 then self.clock else self.partyAt,
309
+ partyAt := if pops % PartyEvery == 0 then self.clock else self.partyAt
310
+ clock := self.clock
311
+ tree := self.tree.updateAs[Balloon](id, |b| b.poppedAtClock(clock)).updateAs[Hud](HudId, |h| Hud(..h, pops: pops))
201
- balloons: self.balloons.map(|b| if b.id == id then Balloon(..b, x: b.swayX(self.clock), poppedAt: self.clock) else b)
312
+ State(..self, pops: pops, partyAt: partyAt, tree: tree.updateAs[Party](PartyId, |p| Party(..p, partyAt: partyAt, pops: pops)))
202
- )
203
313
 
204
314
  fun partying(self) -> Bool =
205
315
  self.clock - self.partyAt < PartyTime
@@ -210,107 +320,11 @@ struct State(balloons: List[Balloon], rng: Random, pops: Int, clock: Float, part
210
320
  _ => self
211
321
 
212
322
  fun pressAt(self, x: Float, y: Float) -> State =
213
- view := self.render()
214
- if Some(id) := view.hitId(x, y)
323
+ if Some(id) := self.tree.hitId(x, y)
215
- if Some(msg) := view.msgOf(id)
216
- self.update(msg)
324
+ self.update(Pop(id: id))
217
- else
218
- self
219
325
  else
220
326
  self
221
327
 
222
- # --- render ---
223
-
224
- fun zoom(self) -> Float =
225
- {self.sw / ArenaW}.min(self.sh / ArenaH)
226
-
227
- fun offsetX(self) -> Float =
228
- {self.sw - self.zoom() * ArenaW} / 2.0
229
-
230
- fun offsetY(self) -> Float =
231
- {self.sh - self.zoom() * ArenaH} / 2.0
232
-
233
- fun render(self) -> SceneNode[Msg] =
234
- z := self.zoom()
235
- Group(
236
- transform: Compose(first: Translate(dx: self.offsetX(), dy: self.offsetY()), then: Scale(sx: z, sy: z)),
237
- children: [
238
- renderSky(self.clock),
239
- Group(transform: Identity, children: self.balloons.map(|b| b.render(self.clock))),
240
- self.renderHud(),
241
- self.renderParty()
242
- ]
243
- )
244
-
245
- fun renderHud(self) -> SceneNode[Msg] =
246
- Group(
247
- transform: Identity,
248
- children: [
249
- RectShape(x: 16.0, y: 14.0, w: 170.0, h: 56.0, color: Color.White.withAlpha(0.7)),
250
- CircleShape(cx: 46.0, cy: 42.0, r: 18.0, color: Hue.of(0).color),
251
- Text(text: "{self.pops}", x: 80.0, y: 20.0, size: 44.0, color: Color.rgb(0.15, 0.15, 0.3))
252
- ]
253
- )
254
-
255
- fun renderParty(self) -> SceneNode[Msg] =
256
- if !self.partying()
257
- nothing()
258
- else
259
- age := self.clock - self.partyAt
260
- p := Anim.at(partyAnim(), age)
261
- Group(
262
- transform: Identity,
263
- children: [
264
- Group(transform: Identity, children: confetti(0, age)),
265
- Group(
266
- transform: Compose(first: Translate(dx: ArenaW / 2.0, dy: 250.0), then: Scale(sx: p.scaleX, sy: p.scaleY)),
267
- children: [
268
- centred("Hooray!", 0.0, -40.0, 72.0, Color.rgb(0.95, 0.3, 0.5)),
269
- centred("{self.pops} balloons!", 0.0, 40.0, 40.0, Color.rgb(0.15, 0.15, 0.3))
270
- ]
271
- )
272
- ]
273
- )
274
-
275
- # 30 confetti squares falling from the top, `age` seconds into the party.
276
- fun confetti(i: Int, age: Float) -> List[SceneNode[Msg]] =
277
- if i >= 30
278
- Nil
279
- else
280
- x := Float({i * 7919} % 800)
281
- y := Float({i * 104729} % 200) - 200.0 + age * {180.0 + Float(i % 5) * 40.0}
282
- wob := 10.0 * math.sin(age * 4.0 + Float(i))
283
- Cons(head: RectShape(x: x + wob, y: y, w: 12.0, h: 12.0, color: Hue.of(i).color), tail: confetti(i + 1, age))
284
-
285
- # Sky, two drifting clouds and the grass.
286
- fun renderSky(clock: Float) -> SceneNode[Msg] =
287
- Group(
288
- transform: Identity,
289
- children: [
290
- RectShape(x: 0.0, y: 0.0, w: ArenaW, h: ArenaH, color: Color.rgb(0.55, 0.8, 1.0)),
291
- RectShape(x: 0.0, y: 0.0, w: ArenaW, h: 200.0, color: Color.rgb(0.45, 0.72, 0.98)),
292
- CircleShape(cx: 690.0, cy: 90.0, r: 46.0, color: Color.rgb(1.0, 0.9, 0.35)),
293
- cloud(wrapX(120.0 + clock * 12.0), 130.0),
294
- cloud(wrapX(520.0 + clock * 8.0), 220.0),
295
- RectShape(x: 0.0, y: ArenaH - 50.0, w: ArenaW, h: 50.0, color: Color.rgb(0.4, 0.78, 0.35))
296
- ]
297
- )
298
-
299
- fun wrapX(x: Float) -> Float =
300
- span := ArenaW + 200.0
301
- x - span * Float(Int(x / span)) - 100.0
302
-
303
- fun cloud(x: Float, y: Float) -> SceneNode[Msg] =
304
- white := Color.White.withAlpha(0.9)
305
- Group(
306
- transform: Translate(dx: x, dy: y),
307
- children: [
308
- CircleShape(cx: -30.0, cy: 8.0, r: 24.0, color: white),
309
- CircleShape(cx: 0.0, cy: 0.0, r: 32.0, color: white),
310
- CircleShape(cx: 32.0, cy: 8.0, r: 24.0, color: white)
311
- ]
312
- )
313
-
314
328
  # --- the host shell ---
315
329
 
316
330
  struct Balloons(state: State, popSound: Sound, partySound: Sound, musicSound: Sound) =
@@ -329,7 +343,7 @@ struct Balloons(state: State, popSound: Sound, partySound: Sound, musicSound: So
329
343
 
330
344
  fun draw(self, io: Io) =
331
345
  gfx.clear(io, Color.rgb(0.55, 0.8, 1.0))
332
- self.state.render().draw(io)
346
+ self.state.tree.draw(io)
333
347
 
334
348
  fun main(io: Io) -> Balloons =
335
349
  game := Balloons(
@@ -348,22 +362,22 @@ fun newState() -> State =
348
362
 
349
363
  # A state whose first balloon is still and in the middle of the screen.
350
364
  fun withCentred(s: State) -> State =
351
- State(..s, balloons: s.balloons.map(|b| if b.id == BalloonId then Balloon(..b, x: 400.0, y: 300.0, speed: 0.0, phase: 0.0) else b))
365
+ State(..s, tree: s.tree.updateAs[Balloon](BalloonId, |b| Balloon(..b, x: 400.0, y: 300.0, speed: 0.0, phase: 0.0)))
352
366
 
353
367
  fun first(s: State) -> Balloon =
354
- s.balloons.at(0)
368
+ s.balloons().at(0)
355
369
 
356
370
  test "a new game has its balloons below the screen and no pops"
357
371
  s := newState()
358
- assert s.balloons.length() == Count
372
+ assert s.balloons().length() == Count
359
373
  assert s.pops == 0
360
- assert s.balloons.fold(true, |ok, b| ok && b.y > ArenaH * 0.4)
374
+ assert s.balloons().fold(true, |ok, b| ok && b.y > ArenaH * 0.4)
361
375
 
362
376
  test "balloons rise"
363
377
  s := newState()
364
378
  t := s.update(Tick(dt: 1.0))
365
379
  assert first(t).y < first(s).y
366
- assert first(s).y == newState().balloons.at(0).y
380
+ assert first(s).y == newState().balloons().at(0).y
367
381
 
368
382
  test "pressing a balloon pops it and counts"
369
383
  s := withCentred(newState())
@@ -388,11 +402,14 @@ test "every tenth pop starts a party that ends"
388
402
  fresh := newState()
389
403
  s := State(..fresh, pops: 9)
390
404
  assert !s.partying()
405
+ assert !s.tree.find(PartyId).unwrap().shown()
391
406
  t := withCentred(s).update(Pop(id: BalloonId))
392
407
  assert t.pops == 10
393
408
  assert t.partying()
409
+ assert t.tree.find(PartyId).unwrap().shown()
394
410
  u := t.update(Tick(dt: PartyTime + 0.1))
395
411
  assert !u.partying()
412
+ assert !u.tree.find(PartyId).unwrap().shown()
396
413
 
397
414
  test "the press is found through the camera"
398
415
  s := withCentred(newState()).update(Resize(w: 1600.0, h: 600.0))
examples/games/orb_run.plum CHANGED
@@ -1,46 +1,65 @@
1
- # Orb Run as components (`plum run examples/games/orb_run.plum`), written in the
1
+ # Orb Run (`plum run examples/games/orb_run.plum`). Steer the ship with the arrow keys or
2
- # component style of Elm and React but purely functional. Steer the ship
3
- # with the arrow keys or WASD, collect the drifting orbs and avoid the mines. Three
2
+ # WASD, collect the drifting orbs and avoid the mines. Three lives; Enter, R or the
4
- # lives; Enter, R or the "Again" button restarts after the game is over.
3
+ # "Again" button restarts after the game is over.
4
+ #
5
+ # The game lives in a scene tree: a `SceneTree[Msg]` from std/game/scene, a tree of
6
+ # actors that lives from frame to frame. Every kind of body is its own struct (`Ship`,
7
+ # `Orb`, `Mine`, `Star`, `Icon`, ..) with only its own fields, and `is Actor[Msg]`: it
8
+ # says which actor it is (`key`) and where (`place`, made from its plain `x` and `y`), and
9
+ # writes only the behaviour it has: its next version (`step`), its drawing (`paint`), its
10
+ # hit test (`hit`). The backdrop and the dimmer are std's `Box`, the layers std's
11
+ # `Group`, the hud's text std/game/ui's `Label` and the restart button ui's `Button`,
12
+ # whose `onClick` is the message `RestartClicked`. The tree's `step` walks it once a tick
13
+ # and gives every actor its next version; `draw` and `hit` walk it again with the
14
+ # 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 reads actors after the step with `SceneTree.findAs` and
27
+ # changes one kind's own fields with `updateAs` (`tree.updateAs[Ship](ShipId, |s|
28
+ # s.steered(ax, ay))`), and adds and removes them with `add` and `kill`. The tree is a
29
+ # value like the rest of `State`: a kept old state still has its old tree. `Msg` is what
30
+ # can happen to the state (a tick of time, a resize, a restart, a player input, a click);
31
+ # `State.update(msg)` is a short sequence of named steps. A pointer input finds the actor
32
+ # under it with `hitId` and runs `ui.step`; a click on the button sends its message
33
+ # (`ui.messages`), which goes to `State.update` like any other `Msg`.
5
34
  #
6
- # Each kind (`Ship`, `Orb`, `Mine`, `Star`) keeps its data, its behaviour and its
7
- # drawing together: `update(self, ..)` returns the next value of the kind (a spread,
8
- # nothing is changed in place) and `render(self, ..)` returns its `SceneNode` picture.
9
- # `State` is the same for the whole game: the components, the score, a `Random` and the
10
- # screen size. `Msg` is what can happen to it (a tick of time, a resize, a restart, a
11
- # player input, a Ui event); `State.update(msg)` is a short sequence of named steps and
12
- # `State.render()` builds a fresh picture every frame, which `SceneNode.draw` interprets
13
- # (the compiler fuses the two, so the tree is never built). There is no retained
14
- # scene: the restart button is a `ui.button` in the picture. The host polls the
15
- # player's input once a frame and hands each tick its `Input`; `update` sends each
16
- # `InputEvent` to the state as an `Event`: keys update the held keys that steer the ship,
17
- # and a pointer input finds what is under it with `SceneNode.hitId` on the picture the
18
- # player is looking at and runs `ui.step`. A click on a button sends the button's own
19
- # message (`RestartClicked`): `ui.messages` reads it from the picture, and it goes to
20
- # `State.update` like any other `Msg`. The picture is a `SceneNode[Msg]`.
21
- # The game-over title and the ship's hurt flash are `Anim`s of time since they began.
22
35
  # `OrbGame` below is the host shell: `main` returns it, and its
23
36
  # `update(self, io, input, dt)` returns the next one, once per fixed 1/60 s tick. It holds
24
- # the current `State`, turns the tick's input into messages, and plays sounds. All its
37
+ # the current `State`, turns the tick's input into messages (`playTick`), and plays
25
- # randomness is the `Random` in `State`, seeded once in `main`, so one seed and one list
38
+ # sounds. All its randomness is the `Random` in `State`, seeded once in `main`, so one
26
- # of inputs give the same game.
39
+ # seed and one list of inputs give the same game.
27
40
  module orb_run
28
41
  import std/Str
29
42
  import std/Int
30
43
  import std/Float
44
+ import std/Bool
31
45
  import std/Slice
32
46
  import std/Option
33
47
  import std/List
34
48
  import std/math
35
49
  import std/Random
36
50
  import std/game/Vec2
51
+ import std/game/Affine
37
52
  import std/game/Color
38
53
  import std/game/gfx
39
54
  import std/game/audio
40
- import std/game/scene
41
55
  import std/game/Anim
42
56
  import std/game/ui
43
57
  import std/game/input
58
+ import std/collections/functional/FRoseTree
59
+ import std/game/scene/Place
60
+ import std/game/scene/Actor
61
+ import std/game/scene/Ctx
62
+ import std/game/scene/SceneTree
44
63
  import std/Io
45
64
 
46
65
  ArenaW = 800.0
@@ -57,11 +76,28 @@ OrbPoints = 10
57
76
  SheetCell = 16.0
58
77
  SpriteSize = 48.0
59
78
  SpriteHalf = 24.0
60
-
79
+ StarCount = 40
80
+
81
+ # Actor ids: the tree's fixed nodes, then the ranges. Orb `i` is `OrbId + i`, mine `i` is
61
- # Entity ids: orb `i` is `OrbId + i`, mine `i` is `MineId + i`.
82
+ # `MineId + i`, star `i` is `StarId + i` and life icon `i` is `LifeId + i`.
83
+ RootId = 0
84
+ BackId = 1
85
+ StarLayer = 2
86
+ MineLayer = 3
87
+ OrbLayer = 4
88
+ ShipId = 5
89
+ HudId = 6
90
+ PanelId = 7
91
+ ScoreId = 8
92
+ BestId = 9
93
+ TitleId = 11
94
+ PromptId = 12
95
+ DimId = 13
96
+ RestartId = 14
97
+ StarId = 20
62
98
  OrbId = 100
63
99
  MineId = 200
64
- RestartId = 1
100
+ LifeId = 300
65
101
 
66
102
  # A position and velocity: what a spawn returns and what drifters are bounced with.
67
103
  struct Motion(x: Float, y: Float, vx: Float, vy: Float)
@@ -69,29 +105,12 @@ struct Motion(x: Float, y: Float, vx: Float, vy: Float)
69
105
  # A random spot and the generator to continue from.
70
106
  struct Spawned(at: Motion, rng: Random)
71
107
 
72
- # --- small pure helpers ---
108
+ # --- small pure helpers (as in orb_run.plum) ---
73
109
 
74
110
  # Which of `count` animation frames is showing after `clock` seconds at `fps` frames per second.
75
111
  fun frameOf(clock: Float, count: Int, fps: Float) -> Int =
76
112
  Int(clock * fps) % count
77
113
 
78
- fun nothing() -> SceneNode[Msg] =
79
- Group(transform: Identity, children: Nil)
80
-
81
- fun cell(sheet: Texture, x: Float, y: Float, size: Float, col: Int, row: Int) -> SceneNode[Msg] =
82
- Sprite(
83
- tex: sheet,
84
- x: x,
85
- y: y,
86
- w: size,
87
- h: size,
88
- srcX: Float(col) * SheetCell,
89
- srcY: Float(row) * SheetCell,
90
- srcW: SheetCell,
91
- srcH: SheetCell,
92
- tint: Color.White
93
- )
94
-
95
114
  fun overlaps(ax: Float, ay: Float, ra: Float, bx: Float, by: Float, rb: Float) -> Bool =
96
115
  math.hypot(ax - bx, ay - by) < ra + rb
97
116
 
@@ -116,7 +135,7 @@ fun findSpot(rng: Random, ax: Float, ay: Float, gap: Float, tries: Int) -> Spawn
116
135
  else
117
136
  findSpot(dy.rng, ax, ay, gap, tries - 1)
118
137
 
119
- # `b` moved for `dt` seconds and bounced off the arena walls; `b` itself is unchanged.
138
+ # `b` moved for `dt` seconds and bounced off the arena walls.
120
139
  fun driftOf(b: Motion, r: Float, dt: Float) -> Motion =
121
140
  x0 := b.x + b.vx * dt
122
141
  y0 := b.y + b.vy * dt
@@ -147,115 +166,256 @@ fun titleAnim() -> Anim =
147
166
  fun titlePose(t: Float) -> AnimPose =
148
167
  Anim.at(titleAnim(), t)
149
168
 
169
+ # The zoom that fits the arena into a `sw` by `sh` screen, and where its corner lands.
170
+ fun fitZoom(sw: Float, sh: Float) -> Float =
171
+ {sw / ArenaW}.min(sh / ArenaH)
172
+
173
+ fun fitX(sw: Float, sh: Float) -> Float =
174
+ {sw - fitZoom(sw, sh) * ArenaW} / 2.0
175
+
176
+ fun fitY(sw: Float, sh: Float) -> Float =
177
+ {sh - fitZoom(sw, sh) * ArenaH} / 2.0
178
+
179
+ # --- painting: an actor paints in its own coordinates, seen through `m` (std/game/scene/Actor
180
+ # has boxes, circles, lines and text) ---
181
+
182
+ # A `size` square cell (col, row) of the sprite sheet with its top-left at (x, y).
183
+ fun paintCell(io: Io, m: Affine, alpha: Float, sheet: Texture, x: Float, y: Float, size: Float, col: Int, row: Int) =
184
+ sw := size * m.scaleX()
185
+ sh := size * m.scaleY()
186
+ c := m.apply(Vec2(x: x + size / 2.0, y: y + size / 2.0))
187
+ gfx.drawTextureEx(
188
+ io, sheet.id, Float(col) * SheetCell, Float(row) * SheetCell, SheetCell, SheetCell,
189
+ c.x - sw / 2.0, c.y - sh / 2.0, sw, sh, m.rotation(), false, Color.White.withAlpha(alpha))
190
+
150
- # --- the components ---
191
+ # --- the kinds ---
192
+
151
-
193
+ # Each kind of body is its own struct with only its own fields, and `is Actor[Msg]`: the
194
+ # tree asks it for its id (`key`), its place in its parent (`place`), its next version
195
+ # (`step`), its drawing (`paint`, in its own coordinates seen through `m`) and its hit test
196
+ # (`hit`), and whether it is shown and how opaque it is. A kind writes only what differs
197
+ # from the trait's defaults. Orbs, mines and the ship are centred on their (x, y) and turn
152
- # The player.
198
+ # about it. The backdrop and the dimmer are std's `Box`, the layers and the hud std's
199
+ # `Group`, the hud's text ui's `Label` and the restart button ui's `Button`.
200
+
201
+ # The root: the camera that fits the arena on the screen, at (x, y) and scaled by `zoom`.
153
- struct Ship(x: Float, y: Float, vx: Float, vy: Float, rotation: Float, hurt: Float) =
202
+ struct Camera(id: Int, x: Float, y: Float, zoom: Float) is Actor[Msg] =
154
-
155
- fun start() -> Ship =
203
+ fun key(self) -> Int = self.id
156
- Ship(x: ArenaW / 2.0, y: ArenaH / 2.0, vx: 0.0, vy: 0.0, rotation: 0.0, hurt: 0.0)
204
+
157
-
158
- # Accelerates by the input axes, applies drag and keeps the ship in the arena.
159
- fun update(self, ax: Float, ay: Float, dt: Float) -> Ship =
160
- keep := {1.0 - Drag * dt}.max(0.0)
161
- r := ShipRadius
162
- vx0 := {self.vx + ax * Thrust * dt} * keep
163
- vy0 := {self.vy + ay * Thrust * dt} * keep
164
- x0 := self.x + vx0 * dt
165
- y0 := self.y + vy0 * dt
166
- x := x0.max(r).min(ArenaW - r)
167
- y := y0.max(r).min(ArenaH - r)
168
- vx := if x != x0 then 0.0 else vx0
169
- vy := if y != y0 then 0.0 else vy0
170
- Ship(
171
- x: x,
172
- y: y,
173
- vx: vx,
174
- vy: vy,
175
- rotation: if vx * vx + vy * vy > 400.0 then math.atan2(vx, 0.0 - vy) else self.rotation,
176
- hurt: {self.hurt - dt}.max(0.0)
177
- )
178
-
179
- fun touches(self, at: Motion, radius: Float) -> Bool =
180
- overlaps(self.x, self.y, ShipRadius, at.x, at.y, radius)
181
-
182
- # The ship blinks while hurt (`hurtAge` seconds since the hit).
183
- fun render(self, sheet: Texture, clock: Float, hurtAge: Float) -> SceneNode[Msg] =
184
- blink := self.hurt > 0.0 && flashPose(hurtAge).scaleX < 0.7
185
- if blink
186
- nothing()
187
- else
188
- Group(
189
- transform: Compose(first: Translate(dx: self.x, dy: self.y), then: Rotate(radians: self.rotation)),
205
+ fun place(self) -> Place = place.at(self.x, self.y).scaleTo(self.zoom, self.zoom)
190
- children: [
206
+
191
- CircleShape(cx: 0.0, cy: 0.0, r: 17.0, color: Color(r: 0.4, g: 0.8, b: 1.0, a: 0.12)),
207
+ # Fitting a `sw` by `sh` screen.
192
- cell(sheet, 0.0 - SpriteHalf, 0.0 - SpriteHalf, SpriteSize, frameOf(clock, 4, 14.0), 0)
208
+ fun fitted(self, sw: Float, sh: Float) -> Camera = Camera(..self, x: fitX(sw, sh), y: fitY(sw, sh), zoom: fitZoom(sw, sh))
193
- ]
194
- )
195
209
 
196
- # A glowing orb drifting about. `phase` offsets its animation from the other orbs.
210
+ # A twinkling background star at its fixed spot.
197
- struct Orb(id: Int, at: Motion, phase: Float, clock: Float) =
211
+ struct Star(id: Int, i: Int, clock: Float) is Actor[Msg] =
212
+ fun key(self) -> Int = self.id
198
213
 
199
- fun update(self, dt: Float) -> Orb =
200
- Orb(..self, at: driftOf(self.at, OrbRadius, dt), clock: self.clock + dt)
214
+ fun place(self) -> Place = place.at(Float({self.i * 7919} % 800), Float({self.i * 104729} % 600))
201
215
 
202
- fun moved(self, to: Motion) -> Orb =
216
+ fun step(self, ctx: Ctx[Msg], dt: Float) -> Star = Star(..self, clock: self.clock + dt)
203
- Orb(..self, at: to)
204
217
 
218
+ fun paint(self, io: Io, m: Affine, alpha: Float) =
219
+ twinkle := 0.25 + 0.2 * math.sin(self.clock * 2.0 + Float(self.i))
220
+ actor.circlePaint(io, m, alpha, 0.0, 0.0, 1.0 + Float(self.i % 3) * 0.5, Color(r: 0.7, g: 0.8, b: 1.0, a: twinkle))
221
+
222
+ # A glowing orb at (x, y) drifting at (vx, vy). `phase` offsets its animation from the
223
+ # other orbs.
224
+ struct Orb(id: Int, x: Float, y: Float, vx: Float, vy: Float, phase: Float, clock: Float, sheet: Texture) is Actor[Msg] =
205
- fun still(self) -> Orb =
225
+ fun key(self) -> Int = self.id
226
+
206
- p := self.at
227
+ fun place(self) -> Place = place.at(self.x, self.y)
228
+
229
+ fun step(self, ctx: Ctx[Msg], dt: Float) -> Orb =
230
+ m := driftOf(Motion(x: self.x, y: self.y, vx: self.vx, vy: self.vy), OrbRadius, dt)
207
- Orb(..self, at: Motion(..p, vx: 0.0, vy: 0.0))
231
+ Orb(..self, x: m.x, y: m.y, vx: m.vx, vy: m.vy, clock: self.clock + dt)
208
232
 
209
233
  # The glow is drawn additively, then the sprite on top.
210
- fun render(self, sheet: Texture) -> SceneNode[Msg] =
211
- Group(
212
- transform: Translate(dx: self.at.x, dy: self.at.y),
213
- children: [
214
- Filter(
215
- effect: BlendFx(mode: Blend.Add),
216
- child: Group(
217
- transform: Identity,
218
- children: [
219
- CircleShape(cx: 0.0, cy: 0.0, r: 26.0, color: Color(r: 0.35, g: 0.22, b: 0.0, a: 0.5)),
220
- CircleShape(cx: 0.0, cy: 0.0, r: 17.0, color: Color(r: 0.6, g: 0.4, b: 0.05, a: 0.5))
221
- ]
222
- ),
223
- target: Texture(id: 0 - 1)
224
- ),
225
- cell(sheet, 0.0 - SpriteHalf, 0.0 - SpriteHalf, SpriteSize, frameOf(self.clock + self.phase, 4, 8.0), 1)
226
- ]
227
- )
228
-
229
- # A spinning mine drifting about.
230
- struct Mine(id: Int, at: Motion, rotation: Float, spin: Float, clock: Float) =
231
-
232
- fun update(self, dt: Float) -> Mine =
233
- Mine(..self, at: driftOf(self.at, MineRadius, dt), rotation: self.rotation + self.spin * dt, clock: self.clock + dt)
234
-
235
- fun moved(self, to: Motion) -> Mine =
236
- Mine(..self, at: to)
237
-
238
- fun still(self) -> Mine =
239
- p := self.at
240
- Mine(..self, at: Motion(..p, vx: 0.0, vy: 0.0), spin: 0.0)
241
-
242
- fun render(self, sheet: Texture) -> SceneNode[Msg] =
243
- Group(
244
- transform: Compose(first: Translate(dx: self.at.x, dy: self.at.y), then: Rotate(radians: self.rotation)),
245
- children: [cell(sheet, 0.0 - SpriteHalf, 0.0 - SpriteHalf, SpriteSize, frameOf(self.clock, 4, 4.0), 2)]
246
- )
247
-
248
- # A twinkling background star; it never moves.
249
- struct Star(i: Int) =
250
-
251
- # Stars `i` and up to 40.
252
- fun field(i: Int) -> List[Star] =
253
- if i >= 40 then Nil else Cons(head: Star(i: i), tail: Star.field(i + 1))
254
-
255
- fun render(self, clock: Float) -> SceneNode[Msg] =
256
- r := 1.0 + Float(self.i % 3) * 0.5
257
- twinkle := 0.25 + 0.2 * math.sin(clock * 2.0 + Float(self.i))
258
- CircleShape(cx: Float({self.i * 7919} % 800), cy: Float({self.i * 104729} % 600), r: r, color: Color(r: 0.7, g: 0.8, b: 1.0, a: twinkle))
234
+ fun paint(self, io: Io, m: Affine, alpha: Float) =
235
+ gfx.blendMode(io, Blend.Add)
236
+ actor.circlePaint(io, m, alpha, 0.0, 0.0, 26.0, Color(r: 0.35, g: 0.22, b: 0.0, a: 0.5))
237
+ actor.circlePaint(io, m, alpha, 0.0, 0.0, 17.0, Color(r: 0.6, g: 0.4, b: 0.05, a: 0.5))
238
+ gfx.blendMode(io, Blend.Normal)
239
+ paintCell(io, m, alpha, self.sheet, 0.0 - SpriteHalf, 0.0 - SpriteHalf, SpriteSize, frameOf(self.clock + self.phase, 4, 8.0), 1)
240
+
241
+ # Put at `to`, drifting with its velocity.
242
+ fun placed(self, to: Motion) -> Orb = Orb(..self, x: to.x, y: to.y, vx: to.vx, vy: to.vy)
243
+
244
+ # Stopped; it still animates.
245
+ fun still(self) -> Orb = Orb(..self, vx: 0.0, vy: 0.0)
246
+
247
+ # A mine at (x, y) turned by `rotation`, drifting at (vx, vy) and turning at `spin`
248
+ # radians per second.
249
+ struct Mine(id: Int, x: Float, y: Float, rotation: Float, vx: Float, vy: Float, spin: Float, clock: Float, sheet: Texture) is Actor[Msg] =
250
+ fun key(self) -> Int = self.id
251
+
252
+ fun place(self) -> Place = place.at(self.x, self.y).rotateTo(self.rotation)
253
+
254
+ fun step(self, ctx: Ctx[Msg], dt: Float) -> Mine =
255
+ m := driftOf(Motion(x: self.x, y: self.y, vx: self.vx, vy: self.vy), MineRadius, dt)
256
+ Mine(..self, x: m.x, y: m.y, rotation: self.rotation + self.spin * dt, vx: m.vx, vy: m.vy, clock: self.clock + dt)
257
+
258
+ fun paint(self, io: Io, m: Affine, alpha: Float) =
259
+ paintCell(io, m, alpha, self.sheet, 0.0 - SpriteHalf, 0.0 - SpriteHalf, SpriteSize, frameOf(self.clock, 4, 4.0), 2)
260
+
261
+ fun placed(self, to: Motion) -> Mine = Mine(..self, x: to.x, y: to.y, vx: to.vx, vy: to.vy)
262
+
263
+ # Stopped and no longer turning; it still animates.
264
+ fun still(self) -> Mine = Mine(..self, vx: 0.0, vy: 0.0, spin: 0.0)
265
+
266
+ # The player, at (x, y) turned by `rotation`. `ax`, `ay` are the steering axes for its
267
+ # next step, set by the game before it; `hurt` is the time left of its hurt flash and
268
+ # `hurtAge` the time since the hit. Hidden at game over, when it stops.
269
+ struct Ship(
270
+ id: Int, x: Float, y: Float, rotation: Float, vx: Float, vy: Float, ax: Float, ay: Float,
271
+ hurt: Float, hurtAge: Float, clock: Float, sheet: Texture, visible: Bool) is Actor[Msg] =
272
+
273
+ fun key(self) -> Int = self.id
274
+
275
+ fun place(self) -> Place = place.at(self.x, self.y).rotateTo(self.rotation)
276
+
277
+ fun shown(self) -> Bool = self.visible
278
+
279
+ # It accelerates by the axes, drag slows it and the walls stop it.
280
+ fun step(self, ctx: Ctx[Msg], dt: Float) -> Ship =
281
+ if !self.visible
282
+ self
283
+ else
284
+ keep := {1.0 - Drag * dt}.max(0.0)
285
+ r := ShipRadius
286
+ vx0 := {self.vx + self.ax * Thrust * dt} * keep
287
+ vy0 := {self.vy + self.ay * Thrust * dt} * keep
288
+ x0 := self.x + vx0 * dt
289
+ y0 := self.y + vy0 * dt
290
+ x := x0.max(r).min(ArenaW - r)
291
+ y := y0.max(r).min(ArenaH - r)
292
+ nvx := if x != x0 then 0.0 else vx0
293
+ nvy := if y != y0 then 0.0 else vy0
294
+ rot := if nvx * nvx + nvy * nvy > 400.0 then math.atan2(nvx, 0.0 - nvy) else self.rotation
295
+ Ship(
296
+ ..self, x: x, y: y, rotation: rot, vx: nvx, vy: nvy,
297
+ hurt: {self.hurt - dt}.max(0.0), hurtAge: self.hurtAge + dt, clock: self.clock + dt)
298
+
299
+ fun paint(self, io: Io, m: Affine, alpha: Float) =
300
+ if !self.blinking()
301
+ actor.circlePaint(io, m, alpha, 0.0, 0.0, 17.0, Color(r: 0.4, g: 0.8, b: 1.0, a: 0.12))
302
+ paintCell(io, m, alpha, self.sheet, 0.0 - SpriteHalf, 0.0 - SpriteHalf, SpriteSize, frameOf(self.clock, 4, 14.0), 0)
303
+
304
+ # It blinks off while hurt.
305
+ fun blinking(self) -> Bool = self.hurt > 0.0 && flashPose(self.hurtAge).scaleX < 0.7
306
+
307
+ # Steered by the axes for its next step.
308
+ fun steered(self, ax: Float, ay: Float) -> Ship = Ship(..self, ax: ax, ay: ay)
309
+
310
+ # Just hit: hurt for `HurtTime`, its flash from the start.
311
+ fun struck(self) -> Ship = Ship(..self, hurt: HurtTime, hurtAge: 0.0)
312
+
313
+ fun hidden(self) -> Ship = Ship(..self, visible: false)
314
+
315
+ # A `size` square cell (col, row) of the sprite sheet with its top-left at (x, y): a life
316
+ # icon.
317
+ struct Icon(id: Int, x: Float, y: Float, size: Float, col: Int, row: Int, sheet: Texture) is Actor[Msg] =
318
+ fun key(self) -> Int = self.id
319
+
320
+ fun place(self) -> Place = place.at(self.x, self.y)
321
+
322
+ fun paint(self, io: Io, m: Affine, alpha: Float) = paintCell(io, m, alpha, self.sheet, 0.0, 0.0, self.size, self.col, self.row)
323
+
324
+ # The game-over title centred on (x, y): its scale is `titlePose` of its age.
325
+ struct Title(id: Int, x: Float, y: Float, scaleX: Float, scaleY: Float, age: Float, color: Color) is Actor[Msg] =
326
+ fun key(self) -> Int = self.id
327
+
328
+ fun place(self) -> Place = place.at(self.x, self.y).scaleTo(self.scaleX, self.scaleY)
329
+
330
+ fun step(self, ctx: Ctx[Msg], dt: Float) -> Title =
331
+ p := titlePose(self.age + dt)
332
+ Title(..self, scaleX: p.scaleX, scaleY: p.scaleY, age: self.age + dt)
333
+
334
+ fun paint(self, io: Io, m: Affine, alpha: Float) =
335
+ actor.textPaint(io, m, alpha, "Game over", -100.0, -24.0, 48.0, self.color.withAlpha(1.0))
336
+
337
+ # Unscaled, its clock from 0: as it comes up at game over.
338
+ fun revealed(self) -> Title = Title(..self, scaleX: 1.0, scaleY: 1.0, age: 0.0)
339
+
340
+ # The game-over panel, hidden while playing: its opacity fades in over half a second of
341
+ # its age, and so do its children.
342
+ struct Panel(id: Int, age: Float, alpha: Float, visible: Bool) is Actor[Msg] =
343
+ fun key(self) -> Int = self.id
344
+
345
+ fun place(self) -> Place = place.at(0.0, 0.0)
346
+
347
+ fun shown(self) -> Bool = self.visible
348
+
349
+ fun opacity(self) -> Float = self.alpha
350
+
351
+ fun step(self, ctx: Ctx[Msg], dt: Float) -> Panel =
352
+ Panel(..self, alpha: {{self.age + dt} * 2.0}.min(1.0), age: self.age + dt)
353
+
354
+ # Shown, faded out, its clock from 0.
355
+ fun revealed(self) -> Panel = Panel(..self, visible: true, alpha: 0.0, age: 0.0)
356
+
357
+ # An orb or a mine stopped (the others as they are): what game over does to every body.
358
+ fun stilled(a: Actor[Msg]) -> Actor[Msg] = match a
359
+ Orb as o => o.still()
360
+ Mine as m => m.still()
361
+ _ => a
362
+
363
+ # An orb or a mine put at `to` (the others as they are).
364
+ fun placedAt(a: Actor[Msg], to: Motion) -> Actor[Msg] = match a
365
+ Orb as o => o.placed(to)
366
+ Mine as m => m.placed(to)
367
+ _ => a
368
+
369
+ # --- building the tree ---
370
+
371
+ fun group(id: Int, kids: List[FRoseTree[Actor[Msg]]]) -> FRoseTree[Actor[Msg]] =
372
+ FRoseTree.of(Group(id: id, x: 0.0, y: 0.0), kids)
373
+
374
+ fun label(id: Int, text: Str, x: Float, y: Float, size: Float, c: Color) -> FRoseTree[Actor[Msg]] =
375
+ FRoseTree.leaf(Label(id: id, x: x, y: y, text: text, size: size, color: c))
376
+
377
+ # Stars `i` and up to `StarCount`, each at its fixed spot.
378
+ fun starNodes(i: Int) -> List[FRoseTree[Actor[Msg]]] =
379
+ if i >= StarCount
380
+ Nil
381
+ else
382
+ Cons(head: FRoseTree.leaf(Star(id: StarId + i, i: i, clock: 0.0)), tail: starNodes(i + 1))
383
+
384
+ # Life icons `i` and up to `StartLives`, from the right edge going left.
385
+ fun lifeNodes(i: Int, sheet: Texture) -> List[FRoseTree[Actor[Msg]]] =
386
+ if i >= StartLives
387
+ Nil
388
+ else
389
+ icon := Icon(id: LifeId + i, x: ArenaW - 40.0 - Float(i) * 36.0, y: 12.0, size: 32.0, col: 0, row: 0, sheet: sheet)
390
+ Cons(head: FRoseTree.leaf(icon), tail: lifeNodes(i + 1, sheet))
391
+
392
+ fun shipActor(x: Float, y: Float, sheet: Texture) -> Ship =
393
+ Ship(
394
+ id: ShipId, x: x, y: y, rotation: 0.0, vx: 0.0, vy: 0.0, ax: 0.0, ay: 0.0,
395
+ hurt: 0.0, hurtAge: 0.0, clock: 0.0, sheet: sheet, visible: true)
396
+
397
+ # The tree of a fresh run: no orbs or mines yet (`State.start` adds them).
398
+ fun buildTree(sheet: Texture, sw: Float, sh: Float) -> SceneTree[Msg] =
399
+ hud := group(HudId, Cons(
400
+ head: label(ScoreId, "Score 0", 16.0, 12.0, 28.0, Color.White),
401
+ tail: Cons(head: label(BestId, "Best 0", 16.0, 44.0, 20.0, Color.Yellow), tail: lifeNodes(0, sheet))))
402
+ panel: FRoseTree[Actor[Msg]] := FRoseTree.of(Panel(id: PanelId, age: 0.0, alpha: 1.0, visible: false), [
403
+ FRoseTree.leaf(Box(id: DimId, x: 0.0, y: 230.0, w: ArenaW, h: 170.0, color: Color(r: 0.0, g: 0.0, b: 0.0, a: 0.6))),
404
+ FRoseTree.leaf(Title(id: TitleId, x: 400.0, y: 268.0, scaleX: 1.0, scaleY: 1.0, age: 0.0, color: Color.Red)),
405
+ label(PromptId, "Press Enter to play again", 270.0, 300.0, 24.0, Color.White),
406
+ FRoseTree.leaf(Button(id: RestartId, x: 340.0, y: 342.0, w: 120.0, h: 44.0, label: "Again", onClick: RestartClicked, look: 0))])
407
+ camera := Camera(id: RootId, x: 0.0, y: 0.0, zoom: 1.0).fitted(sw, sh)
408
+ root: FRoseTree[Actor[Msg]] := FRoseTree.of(camera, [
409
+ FRoseTree.leaf(Box(id: BackId, x: 0.0, y: 0.0, w: ArenaW, h: ArenaH, color: Color.rgb(0.07, 0.08, 0.16))),
410
+ group(StarLayer, starNodes(0)),
411
+ group(MineLayer, Nil),
412
+ group(OrbLayer, Nil),
413
+ FRoseTree.leaf(shipActor(ArenaW / 2.0, ArenaH / 2.0, sheet)),
414
+ hud,
415
+ panel])
416
+ SceneTree(root: root, camX: 0.0, camY: 0.0, camScale: 1.0)
417
+
418
+ # --- the game ---
259
419
 
260
420
  # What can happen to the state.
261
421
  enum Msg =
@@ -265,146 +425,136 @@ enum Msg =
265
425
  | Event(input: InputEvent)
266
426
  | RestartClicked
267
427
 
268
- # Everything that changes during a run. `sheet` and `target` are resource handles
428
+ # The scene and what is between its actors. `mines` is how many mines are out (the next
269
- # the picture needs: the sprite sheet and the render target of the game-over filter.
429
+ # one's id is `MineId + mines`).
270
430
  struct State(
271
- ship: Ship,
272
- orbs: List[Orb],
431
+ tree: SceneTree[Msg],
273
- mines: List[Mine],
274
- stars: List[Star],
275
432
  rng: Random,
276
433
  score: Int,
277
434
  best: Int,
278
435
  lives: Int,
279
436
  over: Bool,
280
437
  clock: Float,
281
- overClock: Float,
282
- hurtAt: Float,
438
+ mines: Int,
283
- overAt: Float,
284
439
  ui: UiState,
285
440
  held: Held,
286
441
  sw: Float,
287
442
  sh: Float,
288
- sheet: Texture,
443
+ sheet: Texture
289
- target: Texture
290
444
  ) =
291
445
 
292
446
  # A fresh run: the orbs and the mines spread over the arena away from the ship.
293
- fun start(seed: Int, best: Int, sheet: Texture, target: Texture, sw: Float, sh: Float) -> State =
447
+ fun start(seed: Int, best: Int, sheet: Texture, sw: Float, sh: Float) -> State =
294
448
  State(
295
- ship: Ship.start(),
449
+ tree: buildTree(sheet, sw, sh),
296
- orbs: Nil,
297
- mines: Nil,
298
- stars: Star.field(0),
299
450
  rng: Random.seeded(seed),
300
451
  score: 0,
301
452
  best: best,
302
453
  lives: StartLives,
303
454
  over: false,
304
455
  clock: 0.0,
305
- overClock: 0.0,
306
- hurtAt: -1.0,
456
+ mines: 0,
307
- overAt: -1.0,
308
457
  ui: ui.init(),
309
458
  held: Held.none(),
310
459
  sw: sw,
311
460
  sh: sh,
312
- sheet: sheet,
461
+ sheet: sheet
313
- target: target
314
- ).fillOrbs(0).growMines()
462
+ ).fillOrbs(0).growMines().showScore()
315
-
316
- # --- update ---
317
463
 
318
464
  fun update(self, msg: Msg) -> State = match msg
319
465
  Tick(dt, ax, ay) => self.tick(dt, ax, ay)
320
- Resize(w, h) => State(..self, sw: w, sh: h)
466
+ Resize(w, h) => State(..self, sw: w, sh: h, tree: self.tree.updateAs[Camera](RootId, |c| c.fitted(w, h)))
321
467
  Restart(seed) => self.restarted(seed)
322
468
  Event(input) => self.onInput(input)
323
469
  RestartClicked => if self.over then self.restarted(self.rng.nextInt().value) else self
324
470
 
471
+ # One frame: the tree steps every actor (the ship with this frame's axes), then the
325
- # One frame of time. Once the game is over the actors only animate.
472
+ # game looks at what they did. Once the game is over the actors only animate.
326
473
  fun tick(self, dt: Float, ax: Float, ay: Float) -> State =
327
- moved := self.moveAll(dt)
474
+ stepped := self.tree.updateAs[Ship](ShipId, |sh| sh.steered(ax, ay)).step(Ctx[Msg](), dt)
328
- if self.over
329
- State(..moved, overClock: self.overClock + dt)
475
+ moved := State(..self, tree: stepped, clock: self.clock + dt)
330
- else
331
- moved.sail(ax, ay, dt).collect().growMines().hurt().settle()
476
+ if self.over then moved else moved.collect().growMines().hurt().settle()
477
+
478
+ # The actor with this id (every fixed id is always in the tree).
479
+ fun body(self, id: Int) -> Actor[Msg] = self.tree.find(id).unwrap()
332
480
 
333
- fun moveAll(self, dt: Float) -> State =
481
+ fun ship(self) -> Ship = self.tree.findAs[Ship](ShipId).unwrap()
334
- State(..self, clock: self.clock + dt, orbs: self.orbs.map(|o| o.update(dt)), mines: self.mines.map(|k| k.update(dt)))
335
482
 
483
+ # The orbs and the mines, in tree order.
484
+ fun orbs(self) -> List[Orb] =
485
+ self.tree.root.fold(Nil, |acc, a| match a
486
+ Orb as o => Cons(head: o, tail: acc)
487
+ _ => acc).reverse()
488
+
489
+ fun mineList(self) -> List[Mine] =
490
+ self.tree.root.fold(Nil, |acc, a| match a
491
+ Mine as m => Cons(head: m, tail: acc)
492
+ _ => acc).reverse()
493
+
336
- fun sail(self, ax: Float, ay: Float, dt: Float) -> State =
494
+ fun touches(self, x: Float, y: Float, radius: Float) -> Bool =
495
+ sh := self.ship()
337
- State(..self, ship: self.ship.update(ax, ay, dt))
496
+ overlaps(sh.x, sh.y, ShipRadius, x, y, radius)
338
497
 
339
498
  # The ship collects every orb it touches.
340
499
  fun collect(self) -> State =
341
- self.orbs.fold(self, |s, o| s.takeOrb(o))
500
+ self.orbs().fold(self, |s, o| if s.touches(o.x, o.y, OrbRadius) then s.respawnOrb(o.id) else s)
342
501
 
502
+ # Scores the orb `id` and puts it at a new random spot.
343
- fun takeOrb(self, o: Orb) -> State =
503
+ fun respawnOrb(self, id: Int) -> State =
504
+ sh := self.ship()
505
+ sp := spawn(self.rng, sh.x, sh.y, 120.0, 40.0)
344
- if self.ship.touches(o.at, OrbRadius) then self.respawnOrb(o) else self
506
+ State(..self, tree: self.tree.updateAs[Orb](id, |o| o.placed(sp.at)), rng: sp.rng, score: self.score + OrbPoints).showScore()
345
507
 
346
- # Scores `o` and puts it at a new random spot.
508
+ # The hud's labels from the score.
347
- fun respawnOrb(self, o: Orb) -> State =
509
+ fun showScore(self) -> State =
348
- sp := spawn(self.rng, self.ship.x, self.ship.y, 120.0, 40.0)
349
- State(
350
- ..self,
351
- orbs: self.orbs.map(|x| if x.id == o.id then x.moved(sp.at) else x),
352
- rng: sp.rng,
353
- score: self.score + OrbPoints
510
+ score := "Score {self.score}"
354
- )
511
+ best := "Best {self.best.max(self.score)}"
512
+ State(..self, tree: self.tree.updateAs[Label[Msg]](ScoreId, |l| l.relabel(score)).updateAs[Label[Msg]](BestId, |l| l.relabel(best)))
355
513
 
356
514
  # Orbs `i` and up to OrbCount, each at a random spot away from the ship.
357
515
  fun fillOrbs(self, i: Int) -> State =
358
516
  if i >= OrbCount then self else self.addOrb(i).fillOrbs(i + 1)
359
517
 
360
518
  fun addOrb(self, i: Int) -> State =
519
+ sh := self.ship()
361
- sp := spawn(self.rng, self.ship.x, self.ship.y, 120.0, 40.0)
520
+ sp := spawn(self.rng, sh.x, sh.y, 120.0, 40.0)
362
- State(
363
- ..self,
364
- orbs: self.orbs.append([Orb(id: OrbId + i, at: sp.at, phase: Float(i) * 0.1, clock: 0.0)]),
521
+ orb := Orb(id: OrbId + i, x: sp.at.x, y: sp.at.y, vx: sp.at.vx, vy: sp.at.vy, phase: Float(i) * 0.1, clock: 0.0, sheet: self.sheet)
365
- rng: sp.rng
522
+ State(..self, tree: self.tree.add(OrbLayer, FRoseTree.leaf(orb)), rng: sp.rng)
366
- )
367
523
 
368
- # Mines are added (at the end) until there are as many as the score asks for.
524
+ # Mines are added (on top of the others) until there are as many as the score asks for.
369
525
  fun growMines(self) -> State =
370
- if self.mines.length() >= mineCount(self.score) then self else self.addMine().growMines()
526
+ if self.mines >= mineCount(self.score) then self else self.addMine().growMines()
371
527
 
372
528
  fun addMine(self) -> State =
529
+ sh := self.ship()
373
- sp := spawn(self.rng, self.ship.x, self.ship.y, 220.0, 90.0)
530
+ sp := spawn(self.rng, sh.x, sh.y, 220.0, 90.0)
374
- State(
375
- ..self,
376
- mines: self.mines.append([Mine(id: MineId + self.mines.length(), at: sp.at, rotation: 0.0, spin: 2.0, clock: 0.0)]),
531
+ mine := Mine(id: MineId + self.mines, x: sp.at.x, y: sp.at.y, rotation: 0.0, vx: sp.at.vx, vy: sp.at.vy, spin: 2.0, clock: 0.0, sheet: self.sheet)
377
- rng: sp.rng
532
+ State(..self, tree: self.tree.add(MineLayer, FRoseTree.leaf(mine)), rng: sp.rng, mines: self.mines + 1)
378
- )
379
533
 
380
534
  fun touchesMine(self) -> Bool =
381
- self.mines.fold(false, |hit, k| hit || self.ship.touches(k.at, MineRadius))
535
+ self.mineList().fold(false, |hit, m| hit || self.touches(m.x, m.y, MineRadius))
382
536
 
383
- # A mine costs a life, makes the ship flash and, at the last life, ends the game.
537
+ # A mine costs a life (and its icon), makes the ship flash and, at the last life, ends
538
+ # the game: the ship goes and the panel comes up.
384
539
  fun hurt(self) -> State =
385
- if self.ship.hurt <= 0.0 && self.touchesMine() then self.struck() else self
540
+ if self.ship().hurt <= 0.0 && self.touchesMine() then self.struck() else self
386
541
 
387
542
  fun struck(self) -> State =
388
543
  lives := self.lives - 1
389
544
  done := lives <= 0
390
- ship := self.ship
391
- State(
392
- ..self,
393
- lives: lives,
394
- ship: Ship(..ship, hurt: HurtTime),
545
+ hit := self.tree.updateAs[Ship](ShipId, |sh| sh.struck()).kill(LifeId + lives)
395
- hurtAt: self.clock,
396
- over: done,
397
- overAt: if done then self.clock else self.overAt,
546
+ tree := if done then gameOver(hit) else hit
398
- best: if done then self.best.max(self.score) else self.best
547
+ State(..self, tree: tree, lives: lives, over: done, best: if done then self.best.max(self.score) else self.best)
399
- )
400
548
 
401
549
  # After game over the orbs and mines stop: they only animate.
402
550
  fun settle(self) -> State =
403
- if self.over then State(..self, orbs: self.orbs.map(|o| o.still()), mines: self.mines.map(|k| k.still())) else self
551
+ if self.over then State(..self, tree: self.tree.withRoot(self.tree.root.map(stilled))) else self
404
552
 
553
+ # A fresh run that keeps the best score, the Ui and the held keys; the button shows the
554
+ # Ui's state.
405
555
  fun restarted(self, seed: Int) -> State =
406
- fresh := State.start(seed, self.best.max(self.score), self.sheet, self.target, self.sw, self.sh)
556
+ fresh := State.start(seed, self.best.max(self.score), self.sheet, self.sw, self.sh)
407
- State(..fresh, ui: self.ui, held: self.held)
557
+ State(..fresh, ui: self.ui, held: self.held, tree: ui.styled(fresh.tree, self.ui))
408
558
 
409
559
  # A player input: keys update the held keys (Enter or R restarts a finished game),
410
560
  # a pointer input goes through the Ui.
@@ -424,105 +574,40 @@ struct State(
424
574
  fun axisY(self) -> Float =
425
575
  axis(self.held.isDown(Key.Up) || self.held.isDown(Key.KeyW), self.held.isDown(Key.Down) || self.held.isDown(Key.KeyS))
426
576
 
427
-
428
- # One pointer input: finds what is under it in the current picture, runs the Ui,
577
+ # One pointer input: the tree finds the actor under it (through the root's camera),
429
- # and sends the messages of the buttons it clicked to `update`.
578
+ # the Ui turns that into press, hover and click, the button shows the result, and a
579
+ # click on it restarts.
430
580
  fun feed(self, input: InputEvent) -> State =
431
581
  po := input.position()
432
582
  if po.isNone()
433
583
  self
434
584
  else
435
585
  pos := po.unwrap()
436
- view := self.render()
437
- r := ui.step(self.ui, input, view.hitId(pos.x, pos.y))
586
+ r := ui.step(self.ui, input, self.tree.hitId(pos.x, pos.y))
587
+ s := State(..self, ui: r.ui, tree: ui.styled(self.tree, r.ui))
438
- ui.messages(view, r.events).fold(State(..self, ui: r.ui), |s, m| s.update(m))
588
+ ui.messages(s.tree, r.events).fold(s, |t, msg| t.update(msg))
439
-
440
- # --- render ---
589
+
441
-
442
- # The zoom that fits the arena into the screen, and where the arena's corner lands.
443
- fun zoom(self) -> Float =
444
- {self.sw / ArenaW}.min(self.sh / ArenaH)
445
-
446
- fun offsetX(self) -> Float =
447
- {self.sw - self.zoom() * ArenaW} / 2.0
448
-
449
- fun offsetY(self) -> Float =
450
- {self.sh - self.zoom() * ArenaH} / 2.0
451
-
452
- # The whole picture, in drawing order, under the camera that fits the arena on screen.
453
- fun render(self) -> SceneNode[Msg] =
454
- z := self.zoom()
455
- Group(
456
- transform: Compose(first: Translate(dx: self.offsetX(), dy: self.offsetY()), then: Scale(sx: z, sy: z)),
457
- children: [
458
- RectShape(x: 0.0, y: 0.0, w: ArenaW, h: ArenaH, color: Color.rgb(0.07, 0.08, 0.16)),
459
- Group(transform: Identity, children: self.stars.map(|st| st.render(self.clock))),
460
- Group(transform: Identity, children: self.mines.map(|k| k.render(self.sheet))),
461
- Group(transform: Identity, children: self.orbs.map(|o| o.render(self.sheet))),
462
- self.renderShip(),
463
- self.renderHud(),
464
- self.renderOverlay()
465
- ]
466
- )
467
-
468
- # The ship is gone once the game is over (an empty group keeps the slots).
469
- fun renderShip(self) -> SceneNode[Msg] =
470
- if self.over then nothing() else self.ship.render(self.sheet, self.clock, self.clock - self.hurtAt)
471
-
472
- # One life icon per remaining life, from the right edge going left.
473
- fun lifeIcons(self, i: Int) -> List[SceneNode[Msg]] =
474
- if i >= self.lives
475
- Nil
476
- else
477
- Cons(head: cell(self.sheet, ArenaW - 40.0 - Float(i) * 36.0, 12.0, 32.0, 0, 0), tail: self.lifeIcons(i + 1))
478
-
479
- # `Cons` (not `List(..).append(..)`) so the life icons fuse into the draw walk too.
480
- fun renderHud(self) -> SceneNode[Msg] =
481
- Group(
482
- transform: Identity,
483
- children: Cons(
484
- head: Text(text: "Score {self.score}", x: 16.0, y: 12.0, size: 28.0, color: Color.White),
485
- tail: Cons(head: Text(text: "Best {self.best.max(self.score)}", x: 16.0, y: 44.0, size: 20.0, color: Color.Yellow), tail: self.lifeIcons(0))
486
- )
487
- )
488
-
489
- fun renderTitle(self) -> SceneNode[Msg] =
490
- p := titlePose(self.clock - self.overAt)
491
- Group(
492
- transform: Compose(first: Translate(dx: 400.0 + p.dx, dy: 268.0 + p.dy), then: Scale(sx: p.scaleX, sy: p.scaleY)),
493
- children: [Text(text: "Game over", x: -100.0, y: -24.0, size: 48.0, color: Color.Red)]
494
- )
495
-
496
- # The game-over panel is empty while playing, so nothing in it can be hit.
497
- fun renderOverlay(self) -> SceneNode[Msg] =
498
- if self.over then self.renderPanel() else nothing()
499
-
500
- # The panel with the restart button, faded in through a render-target filter.
501
- fun renderPanel(self) -> SceneNode[Msg] =
502
- btn := ui.button(RestartId, RestartClicked, "Again", 340.0, 342.0, 120.0, 44.0, self.ui)
503
- Filter(
504
- effect: Alpha(alpha: {self.overClock * 2.0}.min(1.0)),
505
- child: Group(
506
- transform: Identity,
507
- children: [
508
- RectShape(x: 0.0, y: 230.0, w: ArenaW, h: 170.0, color: Color(r: 0.0, g: 0.0, b: 0.0, a: 0.6)),
509
- self.renderTitle(),
510
- Text(text: "Press Enter to play again", x: 270.0, y: 300.0, size: 24.0, color: Color.White),
511
- btn
512
- ]
513
- ),
514
- target: self.target
515
- )
516
-
517
- # True when (x, y) in screen pixels is on the restart button of the picture `render` builds.
590
+ # True when (x, y) in screen pixels is on the restart button.
518
591
  fun onRestart(self, x: Float, y: Float) -> Bool =
519
- self.render().hitId(x, y).unwrapOr(-1) == RestartId
592
+ self.tree.hitId(x, y).unwrapOr(-1) == RestartId
593
+
594
+ # The tree at game over: the ship hidden, the panel and its title coming up.
595
+ fun gameOver(s: SceneTree[Msg]) -> SceneTree[Msg] =
596
+ s.updateAs[Ship](ShipId, |sh| sh.hidden()).updateAs[Panel](PanelId, |p| p.revealed()).updateAs[Title](TitleId, |t| t.revealed())
520
597
 
521
598
  # Enter or R going down.
522
599
  fun isRestartKey(e: InputEvent) -> Bool = match e
523
600
  KeyDown(k) => k == Key.Enter || k == Key.KeyR
524
601
  _ => false
525
602
 
603
+ fun axis(negative: Bool, positive: Bool) -> Float =
604
+ if negative && !positive
605
+ -1.0
606
+ else if positive && !negative
607
+ 1.0
608
+ else
609
+ 0.0
610
+
526
611
  # --- the host shell ---
527
612
 
528
613
  struct OrbGame(state: State, pickupSound: Sound, hitSound: Sound, overSound: Sound, musicSound: Sound) =
@@ -552,7 +637,7 @@ struct OrbGame(state: State, pickupSound: Sound, hitSound: Sound, overSound: Sou
552
637
 
553
638
  fun draw(self, io: Io) =
554
639
  gfx.clear(io, Color.rgb(0.04, 0.05, 0.1))
555
- self.state.render().draw(io)
640
+ self.state.tree.draw(io)
556
641
 
557
642
  # The rules of one tick, with no host calls: sends the tick's input events to the state,
558
643
  # then, unless they restarted a finished game, one tick of time steered by the held keys.
@@ -568,7 +653,7 @@ fun musicVolume() -> Float =
568
653
  0.3
569
654
 
570
655
  fun main(io: Io) -> OrbGame =
571
- s := State.start(io.randomSeed(), 0, gfx.loadTexture(io, "sprites.png"), gfx.createTexture(io, 1600, 1200), ArenaW, ArenaH)
656
+ s := State.start(io.randomSeed(), 0, gfx.loadTexture(io, "sprites.png"), ArenaW, ArenaH)
572
657
  game := OrbGame(
573
658
  state: s,
574
659
  pickupSound: audio.loadSound(io, "pickup.wav"),
@@ -579,14 +664,6 @@ fun main(io: Io) -> OrbGame =
579
664
  game.startMusic(io)
580
665
  game
581
666
 
582
- fun axis(negative: Bool, positive: Bool) -> Float =
583
- if negative && !positive
584
- -1.0
585
- else if positive && !negative
586
- 1.0
587
- else
588
- 0.0
589
-
590
667
  # --- tests ---
591
668
 
592
669
  # Tick `i` of a scripted run: Right held over ticks 10..59 and Up over 30..89, with a
@@ -613,9 +690,9 @@ fun scriptedRun(seed: Int) -> State =
613
690
  0.until(120).fold(newState(seed), |s, i| playTick(s, scriptedInput(i), 1.0 / 60.0))
614
691
 
615
692
  fun sameRun(a: State, b: State) -> Bool =
616
- orbsA := a.orbs.map(|o| o.at.x + o.at.y * 1000.0).fold(0.0, |t, v| t + v)
693
+ orbsA := a.orbs().map(|o| o.x + o.y * 1000.0).fold(0.0, |t, v| t + v)
617
- orbsB := b.orbs.map(|o| o.at.x + o.at.y * 1000.0).fold(0.0, |t, v| t + v)
694
+ orbsB := b.orbs().map(|o| o.x + o.y * 1000.0).fold(0.0, |t, v| t + v)
618
- a.rng.seed == b.rng.seed && a.score == b.score && a.lives == b.lives && a.ship.x == b.ship.x && a.ship.y == b.ship.y && orbsA == orbsB && a.clock == b.clock
695
+ a.rng.seed == b.rng.seed && a.score == b.score && a.lives == b.lives && a.ship().x == b.ship().x && a.ship().y == b.ship().y && orbsA == orbsB && a.clock == b.clock
619
696
 
620
697
  fun near(a: Float, b: Float) -> Bool =
621
698
  {a - b}.abs() < 0.01
@@ -634,134 +711,141 @@ fun away() -> Motion =
634
711
  Motion(x: 5000.0, y: 0.0, vx: 0.0, vy: 0.0)
635
712
 
636
713
  fun newState(seed: Int) -> State =
637
- State.start(seed, 0, Texture(id: -1), Texture(id: -1), ArenaW, ArenaH)
714
+ State.start(seed, 0, Texture(id: -1), ArenaW, ArenaH)
638
715
 
639
- fun withOrb(s: State, i: Int, m: Motion) -> State =
640
- State(..s, orbs: s.orbs.map(|o| if o.id == OrbId + i then Orb(id: o.id, at: m, phase: Float(i) * 0.1, clock: 0.0) else o))
641
-
642
- fun withMine(s: State, i: Int, m: Motion) -> State =
716
+ fun moveBody(s: State, id: Int, m: Motion) -> State =
643
- State(..s, mines: s.mines.map(|k| if k.id == MineId + i then Mine(id: k.id, at: m, rotation: 0.0, spin: 2.0, clock: 0.0) else k))
717
+ State(..s, tree: s.tree.update(id, |a| placedAt(a, m)))
644
718
 
645
719
  # A state with the orbs and mines moved out of the way.
646
720
  fun emptyState() -> State =
647
721
  s := newState(7)
648
- State(..s, orbs: s.orbs.map(|o| o.moved(away())), mines: s.mines.map(|k| k.moved(away())))
722
+ State(..s, tree: s.tree.withRoot(s.tree.root.map(|a| placedAt(a, away()))))
649
723
 
650
724
  fun onShip(s: State) -> Motion =
651
- Motion(x: s.ship.x, y: s.ship.y, vx: 0.0, vy: 0.0)
725
+ Motion(x: s.ship().x, y: s.ship().y, vx: 0.0, vy: 0.0)
652
726
 
653
727
  fun forceOver(s: State) -> State =
654
- State(..s, lives: 0, over: true, overAt: s.clock, best: s.best.max(s.score))
728
+ State(..s, tree: gameOver(s.tree), lives: 0, over: true, best: s.best.max(s.score))
729
+
730
+ fun lone(sh: Ship) -> SceneTree[Msg] = SceneTree.of(sh)
731
+
732
+ fun shipAt(x: Float, y: Float) -> Ship = shipActor(x, y, Texture(id: -1))
733
+
734
+ fun shipOf(s: SceneTree[Msg]) -> Ship = s.findAs[Ship](ShipId).unwrap()
655
735
 
656
- fun countNodes(n: SceneNode[Msg]) -> Int = match n
736
+ fun steer(s: SceneTree[Msg], ax: Float, ay: Float) -> SceneTree[Msg] = s.updateAs[Ship](ShipId, |sh| sh.steered(ax, ay))
657
- Group(_, kids) => 1 + countKids(kids)
658
- Filter(_, child, _) => 1 + countNodes(child)
659
- _ => 1
660
737
 
738
+ fun labelText(s: State, id: Int) -> Str = s.tree.findAs[Label[Msg]](id).unwrap().text
739
+
740
+ fun buttonLookOf(s: State) -> Int = s.tree.findAs[Button[Msg]](RestartId).unwrap().look
741
+
661
- fun countKids(ks: List[SceneNode[Msg]]) -> Int = match ks
742
+ fun mineAt(s: State, id: Int) -> Mine = s.tree.findAs[Mine](id).unwrap()
743
+
744
+ fun orbAt(s: State, id: Int) -> Orb = s.tree.findAs[Orb](id).unwrap()
745
+
746
+ test "the scene starts as a tree of 63 actors, 58 of them drawn"
662
- Nil => 0
747
+ s := newState(7)
748
+ assert s.tree.count() == 63
663
- Cons(h, t) => countNodes(h) + countKids(t)
749
+ assert s.tree.flatten().length() == 58
750
+ over := forceOver(s)
751
+ assert over.tree.flatten().length() == 58 - 1 + 5
664
752
 
665
753
  test "steering accelerates and drag slows the ship"
666
- s := Ship.start().update(1.0, 0.0, 0.1)
754
+ s := steer(lone(shipAt(ArenaW / 2.0, ArenaH / 2.0)), 1.0, 0.0).step(Ctx[Msg](), 0.1)
667
- assert s.vx > 0.0
755
+ sh := shipOf(s)
668
- assert s.x > ArenaW / 2.0
756
+ assert sh.x > ArenaW / 2.0
669
- fast := s.vx
757
+ assert sh.vx > 0.0
758
+ coast := steer(s, 0.0, 0.0)
670
- t := 0.until(30).fold(s, |current, _| current.update(0.0, 0.0, 0.1))
759
+ t := 0.until(30).fold(coast, |cur, _| cur.step(Ctx[Msg](), 0.1))
671
- assert t.vx < fast / 4.0
760
+ assert shipOf(t).vx < sh.vx / 4.0
761
+ assert shipOf(t).x - sh.x < 50.0
672
762
 
673
763
  test "the ship stops at the arena walls"
674
- start := Ship(x: 20.0, y: 20.0, vx: 0.0, vy: 0.0, rotation: 0.0, hurt: 0.0)
764
+ start := steer(lone(shipAt(20.0, 20.0)), -1.0, -1.0)
675
- s := 0.until(20).fold(start, |current, _| current.update(-1.0, -1.0, 0.1))
765
+ s := 0.until(20).fold(start, |cur, _| cur.step(Ctx[Msg](), 0.1))
766
+ sh := shipOf(s)
676
- assert s.x == ShipRadius
767
+ assert sh.x == ShipRadius
677
- assert s.y == ShipRadius
768
+ assert sh.y == ShipRadius
678
- assert s.vx == 0.0
769
+ assert sh.vx == 0.0
679
-
680
- test "shipStep leaves its input unchanged"
770
+
681
- s := Ship.start()
682
- _ := s.update(1.0, 1.0, 0.1)
683
- assert s.vx == 0.0
684
- assert s.x == ArenaW / 2.0
685
-
686
- test "drifters bounce off the walls"
771
+ test "orbs bounce off the walls and mines spin as they drift"
687
- b := driftOf(Motion(x: 795.0, y: 300.0, vx: 100.0, vy: 0.0), OrbRadius, 0.1)
688
- assert b.vx == -100.0
689
- assert b.x == ArenaW - 10.0
690
- orb := Orb(id: OrbId, at: Motion(x: 795.0, y: 300.0, vx: 100.0, vy: 0.0), phase: 0.0, clock: 0.0).update(0.1)
772
+ orb := Orb(id: OrbId, x: 795.0, y: 300.0, vx: 100.0, vy: 0.0, phase: 0.0, clock: 0.0, sheet: Texture(id: -1))
773
+ o := orb.step(Ctx[Msg](), 0.1)
691
- assert near(orb.at.x, ArenaW - 10.0)
774
+ assert near(o.x, ArenaW - 10.0)
692
-
693
- test "a mine spins as it drifts"
694
- mine := Mine(id: MineId, at: Motion(x: 400.0, y: 300.0, vx: 10.0, vy: 0.0), rotation: 0.0, spin: 2.0, clock: 0.0)
775
+ mine := Mine(id: MineId, x: 400.0, y: 300.0, rotation: 0.0, vx: 10.0, vy: 0.0, spin: 2.0, clock: 0.0, sheet: Texture(id: -1))
695
- next := mine.update(0.5)
776
+ k := mine.step(Ctx[Msg](), 0.5)
696
- assert near(next.rotation, 1.0)
777
+ assert near(k.rotation, 1.0)
697
- assert near(next.at.x, 405.0)
778
+ assert near(k.x, 405.0)
698
779
  assert near(mine.rotation, 0.0)
699
780
 
700
- test "collecting an orb scores and respawns it elsewhere"
781
+ test "collecting an orb scores, respawns it elsewhere and updates the hud"
782
+ e := emptyState()
701
- s := withOrb(emptyState(), 0, onShip(emptyState()))
783
+ s := moveBody(e, OrbId, onShip(e))
702
784
  t := tickOf(s, 0.0, 0.0, 0.016)
703
- orb := t.orbs.at(0)
785
+ orb := orbAt(t, OrbId)
704
786
  assert t.score == OrbPoints
705
- assert math.hypot(orb.at.x - t.ship.x, orb.at.y - t.ship.y) >= 120.0
787
+ assert math.hypot(orb.x - t.ship().x, orb.y - t.ship().y) >= 120.0
706
- assert orb.at.x < 5000.0
788
+ assert orb.x < 5000.0
707
- assert t.orbs.length() == OrbCount
789
+ assert t.orbs().length() == OrbCount
790
+ assert labelText(t, ScoreId) == "Score 10"
791
+ assert labelText(s, ScoreId) == "Score 0"
708
792
 
709
- test "a mine costs one life and makes the ship flash"
793
+ test "a mine costs one life and its icon, and makes the ship flash"
710
794
  e := emptyState()
711
- s := withMine(e, 0, onShip(e))
795
+ s := moveBody(e, MineId, onShip(e))
712
796
  hit := tickOf(s, 0.0, 0.0, 0.016)
713
797
  assert hit.lives == StartLives - 1
714
- assert hit.ship.hurt > 0.0
798
+ assert hit.ship().hurt > 0.0
799
+ assert hit.tree.find(LifeId + 2).isNone()
800
+ assert hit.tree.find(LifeId + 1).isSome()
715
- start := Blinks(state: withMine(hit, 0, away()), hidden: 0, shown: 0)
801
+ start := Blinks(state: moveBody(hit, MineId, away()), hidden: 0, shown: 0)
716
802
  blinks := 0.until(100).fold(start, |b, _|
717
803
  next := tickOf(b.state, 0.0, 0.0, 0.016)
718
- if countNodes(next.renderShip()) == 1
804
+ if next.ship().blinking()
719
805
  Blinks(state: next, hidden: b.hidden + 1, shown: b.shown)
720
806
  else
721
807
  Blinks(state: next, hidden: b.hidden, shown: b.shown + 1)
722
808
  )
723
- t := blinks.state
724
809
  assert blinks.hidden > 0
725
810
  assert blinks.shown > 0
726
- assert t.ship.hurt == 0.0
811
+ assert blinks.state.ship().hurt == 0.0
727
- assert countNodes(t.renderShip()) == 3
812
+ assert !blinks.state.ship().blinking()
728
- assert t.lives == StartLives - 1
813
+ assert blinks.state.lives == StartLives - 1
729
814
 
730
815
  test "the ship is briefly safe after a hit"
731
816
  e := emptyState()
732
- hit := tickOf(withMine(e, 0, onShip(e)), 0.0, 0.0, 0.016)
817
+ hit := tickOf(moveBody(e, MineId, onShip(e)), 0.0, 0.0, 0.016)
733
- t := tickOf(hit, 0.0, 0.0, 0.016)
734
- assert t.lives == StartLives - 1
818
+ assert tickOf(hit, 0.0, 0.0, 0.016).lives == StartLives - 1
735
819
 
736
- test "the game ends at zero lives and then ignores steps"
820
+ test "the game ends at zero lives: the ship goes, the panel comes up, steps are ignored"
737
821
  e := emptyState()
738
822
  s := State(..e, lives: 1, score: 40)
739
- t := tickOf(withMine(s, 0, onShip(s)), 0.0, 0.0, 0.016)
823
+ t := tickOf(moveBody(s, MineId, onShip(s)), 0.0, 0.0, 0.016)
740
824
  assert t.over
741
825
  assert t.lives == 0
742
826
  assert t.best == 40
827
+ assert !t.ship().shown()
743
- assert countNodes(t.renderShip()) == 1
828
+ assert t.body(PanelId).shown()
744
- x := t.ship.x
829
+ x := t.ship().x
745
- u := tickOf(t, 1.0, 0.0, 0.5)
830
+ assert tickOf(t, 1.0, 0.0, 0.5).ship().x == x
746
- assert u.ship.x == x
747
831
 
748
832
  test "after game over nothing moves but the animations keep running"
749
833
  e := emptyState()
750
834
  s := State(..e, lives: 1)
751
- ended := tickOf(withMine(s, 0, Motion(x: s.ship.x, y: s.ship.y, vx: 10.0, vy: 0.0)), 0.0, 0.0, 0.016)
835
+ 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)
752
836
  assert ended.over
753
- mine := ended.mines.at(0)
837
+ mine := mineAt(ended, MineId)
754
838
  t := ticksOf(ended, 10, 1.0, 0.0, 0.1)
755
- after := t.mines.at(0)
839
+ after := mineAt(t, MineId)
756
- assert after.at.x == mine.at.x
840
+ assert after.x == mine.x
757
841
  assert after.rotation == mine.rotation
758
- assert t.ship.x == ArenaW / 2.0
842
+ assert t.ship().x == ArenaW / 2.0
759
843
  assert after.clock > mine.clock + 0.9
760
- assert t.orbs.at(0).clock > 0.9
844
+ assert orbAt(t, OrbId).clock > 0.9
761
845
  assert t.clock > 0.9
762
846
  assert t.score == 0
763
847
 
764
- test "restart resets the run and keeps the best score"
848
+ test "restart builds a fresh tree and keeps the best score"
765
849
  e := emptyState()
766
850
  s := forceOver(State(..e, score: 90))
767
851
  r := s.update(Restart(seed: 5))
@@ -769,144 +853,86 @@ test "restart resets the run and keeps the best score"
769
853
  assert r.score == 0
770
854
  assert r.best == 90
771
855
  assert r.lives == StartLives
772
- assert r.ship.x == ArenaW / 2.0
856
+ assert r.ship().x == ArenaW / 2.0
857
+ assert r.ship().shown()
858
+ assert !r.body(PanelId).shown()
773
- assert r.mines.length() == mineCount(0)
859
+ assert r.mineList().length() == mineCount(0)
774
- assert countNodes(r.renderShip()) == 3
775
- assert countNodes(r.renderOverlay()) == 1
860
+ assert labelText(r, BestId) == "Best 90"
776
861
 
777
- test "more mines appear as the score grows and restart removes them"
862
+ test "more mines are added to the tree as the score grows"
778
863
  assert mineCount(0) == 3
779
864
  assert mineCount(100) == 5
780
865
  assert mineCount(10000) == 8
781
866
  e := emptyState()
782
- s := State(..e, score: 100)
783
- t := tickOf(s, 0.0, 0.0, 0.016)
867
+ t := tickOf(State(..e, score: 100), 0.0, 0.0, 0.016)
784
- assert t.mines.length() == 5
868
+ assert t.mineList().length() == 5
869
+ assert t.tree.find(MineId + 4).isSome()
785
- r := t.update(Restart(seed: 3))
870
+ assert t.update(Restart(seed: 3)).mineList().length() == 3
786
- assert r.mines.length() == 3
787
871
 
788
872
  test "the same seed plays out the same way"
789
873
  a := ticksOf(newState(11), 120, 1.0, -1.0, 0.016)
790
874
  b := ticksOf(newState(11), 120, 1.0, -1.0, 0.016)
791
- assert a.ship.x == b.ship.x
875
+ assert a.ship().x == b.ship().x
792
876
  assert a.score == b.score
793
- assert a.mines.at(0).at.x == b.mines.at(0).at.x
877
+ assert mineAt(a, MineId).x == mineAt(b, MineId).x
794
- other := newState(12)
795
- assert other.orbs.at(0).at.x != a.orbs.at(0).at.x
878
+ assert orbAt(newState(12), OrbId).x != orbAt(a, OrbId).x
796
-
797
- test "fit centres the arena on the screen"
798
- s := emptyState().update(Resize(w: 1600.0, h: 600.0))
799
- assert near(s.zoom(), 1.0)
800
- assert near(s.offsetX(), 400.0)
801
- assert near(s.offsetY(), 0.0)
802
-
803
- test "animation frames cycle"
804
- assert frameOf(0.0, 4, 8.0) == 0
805
- assert frameOf(0.13, 4, 8.0) == 1
806
- assert frameOf(0.5, 4, 8.0) == 0
807
- assert axis(true, false) == -1.0
808
- assert axis(true, true) == 0.0
809
-
810
- test "restart_button_hidden_while_playing"
811
- s := emptyState()
812
- assert !s.onRestart(400.0, 364.0)
813
-
814
- test "restart_button_click_restarts"
815
- s := forceOver(emptyState())
816
- assert s.onRestart(400.0, 364.0)
817
- assert !s.onRestart(100.0, 100.0)
818
- assert !s.onRestart(400.0, 260.0)
819
- r := s.update(Restart(seed: 9))
820
- assert !r.over
821
- assert !r.onRestart(400.0, 364.0)
822
-
823
- test "the restart button is found through the camera"
824
- s := forceOver(emptyState()).update(Resize(w: 1600.0, h: 600.0))
825
- assert s.onRestart(800.0, 364.0)
826
- assert !s.onRestart(400.0, 364.0)
827
879
 
828
- test "update_is_pure"
880
+ test "a kept old state still has its old tree"
829
881
  s := emptyState()
830
- x := s.ship.x
882
+ x := s.ship().x
831
883
  t := tickOf(s, 1.0, 0.0, 0.1)
832
- assert t.ship.x > x
884
+ assert t.ship().x > x
833
- assert s.ship.x == x
885
+ assert s.ship().x == x
834
-
835
- test "freezing at game over keeps the orb and mine animation clocks"
836
- running := ticksOf(emptyState(), 5, 0.0, 0.0, 0.1)
837
- orbClock := running.orbs.at(0).clock
838
- mineClock := running.mines.at(0).clock
839
- assert orbClock > 0.4
840
- lastLife := State(..running, lives: 1)
841
- t := tickOf(withMine(lastLife, 1, onShip(lastLife)), 0.0, 0.0, 0.1)
842
- assert t.over
843
- assert t.orbs.at(0).clock > orbClock
844
- assert t.mines.at(0).clock > mineClock
845
886
 
846
- test "view_is_pure"
887
+ test "the root fits the arena on the screen"
847
- s := emptyState()
848
- a := countNodes(s.render())
888
+ s := emptyState().update(Resize(w: 1600.0, h: 600.0))
849
- b := countNodes(s.render())
850
- assert a == b
851
- ba := s.render().bounds()
889
+ root := s.body(RootId).place().local()
852
- bb := s.render().bounds()
853
- assert ba.x == bb.x
890
+ assert near(root.a, 1.0)
854
- assert ba.w == bb.w
891
+ assert near(root.e, 400.0)
855
- assert s.clock == 0.0
892
+ assert near(root.f, 0.0)
856
-
857
- test "view_node_count"
858
- s := newState(7)
859
- assert countNodes(s.render()) == 79
860
- over := forceOver(s)
861
- assert countNodes(over.renderOverlay()) > 5
862
- assert countNodes(over.render()) > countNodes(s.render()) - 3
863
893
 
894
+ test "the restart button is hidden while playing and found through the root's camera"
895
+ s := emptyState()
896
+ assert !s.onRestart(400.0, 364.0)
897
+ o := forceOver(s)
898
+ assert o.onRestart(400.0, 364.0)
899
+ assert !o.onRestart(100.0, 100.0)
900
+ assert !o.onRestart(400.0, 260.0)
901
+ wide := o.update(Resize(w: 1600.0, h: 600.0))
902
+ assert wide.onRestart(800.0, 364.0)
903
+ assert !wide.onRestart(400.0, 364.0)
904
+
864
- test "restart_click_through_ui"
905
+ test "a click on the button restarts through the ui"
865
906
  e := emptyState()
866
907
  s := forceOver(State(..e, score: 90))
867
908
  down := s.feed(PointerDown(x: 400.0, y: 364.0))
868
909
  assert down.over
869
910
  assert ui.pressed(down.ui, RestartId)
911
+ assert buttonLookOf(down) == 2
870
912
  up := down.feed(PointerUp(x: 400.0, y: 364.0))
871
913
  assert !up.over
872
914
  assert up.score == 0
873
915
  assert up.best == 90
874
916
  assert up.lives == StartLives
875
- off := s.feed(PointerDown(x: 400.0, y: 364.0)).feed(PointerUp(x: 100.0, y: 100.0))
917
+ assert s.feed(PointerDown(x: 400.0, y: 364.0)).feed(PointerUp(x: 100.0, y: 100.0)).over
876
- assert off.over
877
- miss := s.feed(PointerDown(x: 100.0, y: 100.0)).feed(PointerUp(x: 100.0, y: 100.0))
918
+ assert s.feed(PointerDown(x: 100.0, y: 100.0)).feed(PointerUp(x: 100.0, y: 100.0)).over
878
- assert miss.over
879
919
 
880
- test "hit_flash_pose_at_fixed_times"
881
- assert near(flashPose(0.0).scaleX, 1.0)
882
- assert near(flashPose(0.05).scaleX, 0.4)
883
- assert near(flashPose(0.075).scaleX, 0.7)
884
- assert near(flashPose(0.1).scaleX, 1.0)
885
- assert near(flashPose(1.05).scaleX, 0.4)
886
-
887
- test "title_anim_pose_at_fixed_times"
920
+ test "the title pulses and the panel fades in by their own clocks"
921
+ t := ticksOf(forceOver(emptyState()), 15, 0.0, 0.0, 0.02)
888
- assert near(titlePose(0.0).scaleX, 1.0)
922
+ assert near(t.body(PanelId).opacity(), 0.6)
889
- assert near(titlePose(0.15).scaleX, 1.15)
890
- assert near(titlePose(0.3).scaleX, 1.3)
923
+ assert near(t.body(TitleId).place().local().a, 1.3)
891
924
  assert near(titlePose(0.8).scaleX, 1.17)
892
- assert near(titlePose(1.3).scaleX, 1.3)
925
+ assert near(flashPose(0.05).scaleX, 0.4)
893
- assert near(titlePose(1.8).scaleY, 1.17)
894
926
 
895
- test "held keys from input events steer the ship"
927
+ test "held keys steer, and enter restarts a finished game and nothing else"
896
928
  s := emptyState().update(Event(input: KeyDown(key: Key.Left))).update(Event(input: KeyDown(key: Key.KeyS)))
897
929
  assert s.axisX() == -1.0
898
930
  assert s.axisY() == 1.0
899
- t := s.update(Event(input: KeyUp(key: Key.Left)))
931
+ assert s.update(Event(input: KeyUp(key: Key.Left))).axisX() == 0.0
900
- assert t.axisX() == 0.0
901
- assert t.axisY() == 1.0
902
-
903
- test "enter restarts a finished game and nothing else"
904
932
  playing := emptyState().update(Event(input: KeyDown(key: Key.Enter)))
905
- assert playing.score == 0
906
933
  assert !playing.over
907
934
  e := emptyState()
908
- s := forceOver(State(..e, score: 40))
909
- r := s.update(Event(input: KeyDown(key: Key.Enter)))
935
+ r := forceOver(State(..e, score: 40)).update(Event(input: KeyDown(key: Key.Enter)))
910
936
  assert !r.over
911
937
  assert r.best == 40
912
938
  assert r.held.isDown(Key.Enter)
@@ -915,5 +941,5 @@ test "same_seed_same_game: one seed and one input list give the same run"
915
941
  a := scriptedRun(42)
916
942
  b := scriptedRun(42)
917
943
  assert sameRun(a, b)
918
- assert a.ship.x != newState(42).ship.x
944
+ assert a.ship().x != newState(42).ship().x
919
945
  assert !sameRun(a, scriptedRun(43))
examples/games/orb_run_tree.plum DELETED
@@ -1,946 +0,0 @@
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[Msg]` from std/game_enum_tree, a tree of actors that lives from frame to frame.
9
- # Every kind of body is its own struct (`Ship`, `Orb`, `Mine`, `Star`, `Label`, the
10
- # `Button`, ..) with only its own fields, and `is Actor[Msg]`: it says which actor it is
11
- # (`key`) and where (`place`), and writes only the behaviour it has: its next version
12
- # (`step`), its drawing (`paint`), its hit test (`hit`). The backdrop and the dimmer are
13
- # std's `Box`, and the root and the layers std's `Group`. The stage's `step` walks the
14
- # tree once a tick and gives every actor its next version; `draw` and `hit` walk it again
15
- # with the parents' transforms and alphas multiplied down.
16
- #
17
- # 0 root (the camera that fits the arena on screen)
18
- # ├─ 1 backdrop
19
- # ├─ 2 stars ─ 20..59
20
- # ├─ 3 mines ─ 200..
21
- # ├─ 4 orbs ─ 100..102
22
- # ├─ 5 ship
23
- # ├─ 6 hud ─ 8 score, 9 best, 300..302 lives
24
- # └─ 7 panel (hidden while playing) ─ 13 dim, 11 title, 12 prompt, 14 "Again"
25
- #
26
- # What is between bodies (an orb is touched, a mine hits the ship, the score and the
27
- # lives) stays in `State`, which reads actors after the step with `EStage.findAs` and
28
- # changes one kind's own fields with `updateAs` (`stage.updateAs[Ship](ShipId, |s|
29
- # s.steered(ax, ay))`), and adds and removes them with `add` and `kill`. The stage is a
30
- # value like the rest of `State`: a kept old state still has its old tree.
31
- #
32
- # Differences from orb_run.plum: the game-over panel fades by multiplying its opacity
33
- # into each of its children instead of drawing through a render-target filter (so
34
- # overlapping children are each translucent), and the ship's hurt flash, the title's
35
- # pulse and the panel's fade keep their own clocks in their own structs.
36
- module orb_run_tree
37
- import std/Str
38
- import std/Int
39
- import std/Float
40
- import std/Bool
41
- import std/Slice
42
- import std/Option
43
- import std/List
44
- import std/math
45
- import std/Random
46
- import std/game/Vec2
47
- import std/game/Affine
48
- import std/game/Color
49
- import std/game/gfx
50
- import std/game/audio
51
- import std/game/Anim
52
- import std/game/ui
53
- import std/game/input
54
- import std/collections/functional/FRoseTree
55
- import std/game_enum_tree/Place
56
- import std/game_enum_tree/Actor
57
- import std/game_enum_tree/ECtx
58
- import std/game_enum_tree/EStage
59
- import std/Io
60
-
61
- ArenaW = 800.0
62
- ArenaH = 600.0
63
- ShipRadius = 10.0
64
- OrbRadius = 10.0
65
- MineRadius = 11.0
66
- Thrust = 900.0
67
- Drag = 2.2
68
- OrbCount = 3
69
- StartLives = 3
70
- HurtTime = 1.5
71
- OrbPoints = 10
72
- SheetCell = 16.0
73
- SpriteSize = 48.0
74
- SpriteHalf = 24.0
75
- StarCount = 40
76
-
77
- # Actor ids: the tree's fixed nodes, then the ranges. Orb `i` is `OrbId + i`, mine `i` is
78
- # `MineId + i`, star `i` is `StarId + i` and life icon `i` is `LifeId + i`.
79
- RootId = 0
80
- BackId = 1
81
- StarLayer = 2
82
- MineLayer = 3
83
- OrbLayer = 4
84
- ShipId = 5
85
- HudId = 6
86
- PanelId = 7
87
- ScoreId = 8
88
- BestId = 9
89
- TitleId = 11
90
- PromptId = 12
91
- DimId = 13
92
- RestartId = 14
93
- StarId = 20
94
- OrbId = 100
95
- MineId = 200
96
- LifeId = 300
97
-
98
- # A position and velocity: what a spawn returns and what drifters are bounced with.
99
- struct Motion(x: Float, y: Float, vx: Float, vy: Float)
100
-
101
- # A random spot and the generator to continue from.
102
- struct Spawned(at: Motion, rng: Random)
103
-
104
- # --- small pure helpers (as in orb_run.plum) ---
105
-
106
- # Which of `count` animation frames is showing after `clock` seconds at `fps` frames per second.
107
- fun frameOf(clock: Float, count: Int, fps: Float) -> Int =
108
- Int(clock * fps) % count
109
-
110
- fun overlaps(ax: Float, ay: Float, ra: Float, bx: Float, by: Float, rb: Float) -> Bool =
111
- math.hypot(ax - bx, ay - by) < ra + rb
112
-
113
- # A random spot at least `gap` away from (ax, ay), drifting at up to `speed`.
114
- fun spawn(rng: Random, ax: Float, ay: Float, gap: Float, speed: Float) -> Spawned =
115
- spot := findSpot(rng, ax, ay, gap, 20)
116
- dh := spot.rng.nextFloat()
117
- dp := dh.rng.nextFloat()
118
- heading := dh.value * Float.Tau
119
- pace := speed * {0.4 + 0.6 * dp.value}
120
- Spawned(at: Motion(x: spot.at.x, y: spot.at.y, vx: math.cos(heading) * pace, vy: math.sin(heading) * pace), rng: dp.rng)
121
-
122
- # A random spot at least `gap` away from (ax, ay); after `tries` draws the last one stands.
123
- fun findSpot(rng: Random, ax: Float, ay: Float, gap: Float, tries: Int) -> Spawned =
124
- margin := 30.0
125
- dx := rng.nextFloat()
126
- dy := dx.rng.nextFloat()
127
- x := margin + dx.value * {ArenaW - 2.0 * margin}
128
- y := margin + dy.value * {ArenaH - 2.0 * margin}
129
- if tries <= 1 || math.hypot(x - ax, y - ay) >= gap
130
- Spawned(at: Motion(x: x, y: y, vx: 0.0, vy: 0.0), rng: dy.rng)
131
- else
132
- findSpot(dy.rng, ax, ay, gap, tries - 1)
133
-
134
- # `b` moved for `dt` seconds and bounced off the arena walls.
135
- fun driftOf(b: Motion, r: Float, dt: Float) -> Motion =
136
- x0 := b.x + b.vx * dt
137
- y0 := b.y + b.vy * dt
138
- x := x0.max(r).min(ArenaW - r)
139
- y := y0.max(r).min(ArenaH - r)
140
- 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)
141
-
142
- # How many mines are out: more as the score grows.
143
- fun mineCount(score: Int) -> Int =
144
- {3 + score / 50}.min(8)
145
-
146
- # The hurt flash: the ship shrinks and recovers every 0.1 s (the scale returns to 1 each lap).
147
- fun hitFlash() -> Anim =
148
- Forever(anim: Seq(steps: [ScaleTo(sx: 0.4, sy: 0.4, secs: 0.05), ScaleTo(sx: 2.5, sy: 2.5, secs: 0.05)]))
149
-
150
- fun flashPose(t: Float) -> AnimPose =
151
- Anim.at(hitFlash(), t)
152
-
153
- # The game-over title: grows to 1.3x, then pulses between 1.17x and 1.3x.
154
- fun titleAnim() -> Anim =
155
- Seq(
156
- steps: [
157
- ScaleTo(sx: 1.3, sy: 1.3, secs: 0.3),
158
- 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)]))
159
- ]
160
- )
161
-
162
- fun titlePose(t: Float) -> AnimPose =
163
- Anim.at(titleAnim(), t)
164
-
165
- # The zoom that fits the arena into a `sw` by `sh` screen, and where its corner lands.
166
- fun fitZoom(sw: Float, sh: Float) -> Float =
167
- {sw / ArenaW}.min(sh / ArenaH)
168
-
169
- fun fitX(sw: Float, sh: Float) -> Float =
170
- {sw - fitZoom(sw, sh) * ArenaW} / 2.0
171
-
172
- fun fitY(sw: Float, sh: Float) -> Float =
173
- {sh - fitZoom(sw, sh) * ArenaH} / 2.0
174
-
175
- # --- painting helpers: an actor paints in its own coordinates, seen through `m` ---
176
-
177
- # A `size` square cell (col, row) of the sprite sheet with its top-left at (x, y).
178
- fun paintCell(io: Io, m: Affine, alpha: Float, sheet: Texture, x: Float, y: Float, size: Float, col: Int, row: Int) =
179
- sw := size * m.scaleX()
180
- sh := size * m.scaleY()
181
- c := m.apply(Vec2(x: x + size / 2.0, y: y + size / 2.0))
182
- gfx.drawTextureEx(
183
- io, sheet.id, Float(col) * SheetCell, Float(row) * SheetCell, SheetCell, SheetCell,
184
- c.x - sw / 2.0, c.y - sh / 2.0, sw, sh, m.rotation(), false, Color.White.withAlpha(alpha))
185
-
186
- fun paintCircle(io: Io, m: Affine, x: Float, y: Float, r: Float, c: Color) =
187
- p := m.apply(Vec2(x: x, y: y))
188
- gfx.drawCircle(io, p.x, p.y, r * m.scaleX(), c)
189
-
190
- fun paintText(io: Io, m: Affine, text: Str, x: Float, y: Float, size: Float, c: Color) =
191
- p := m.apply(Vec2(x: x, y: y))
192
- gfx.drawText(io, text, p.x, p.y, size * m.scaleY(), c)
193
-
194
- # --- the kinds ---
195
-
196
- # Each kind of body is its own struct with only its own fields, and `is Actor[Msg]`: the
197
- # stage asks it for its id (`key`), its place in its parent (`place`), its next version
198
- # (`step`), its drawing (`paint`, in its own coordinates seen through `m`) and its hit test
199
- # (`hit`), and whether it is shown and how opaque it is. A kind writes only what differs
200
- # from the trait's defaults. Orbs, mines and the ship are centred on their place's (x, y)
201
- # and turn about it. The backdrop and the dimmer are std's `Box`, and the root, the layers
202
- # and the hud are std's `Group`.
203
-
204
- # A twinkling background star at its fixed spot.
205
- struct Star(id: Int, i: Int, clock: Float) is Actor[Msg] =
206
- fun key(self) -> Int = self.id
207
-
208
- fun place(self) -> Place = place.at(Float({self.i * 7919} % 800), Float({self.i * 104729} % 600))
209
-
210
- fun step(self, ctx: ECtx[Msg], dt: Float) -> Star = Star(..self, clock: self.clock + dt)
211
-
212
- fun paint(self, io: Io, m: Affine, alpha: Float) =
213
- twinkle := 0.25 + 0.2 * math.sin(self.clock * 2.0 + Float(self.i))
214
- paintCircle(io, m, 0.0, 0.0, 1.0 + Float(self.i % 3) * 0.5, Color(r: 0.7, g: 0.8, b: 1.0, a: twinkle * alpha))
215
-
216
- # A glowing orb drifting at (vx, vy). `phase` offsets its animation from the other orbs.
217
- struct Orb(id: Int, at: Place, vx: Float, vy: Float, phase: Float, clock: Float, sheet: Texture) is Actor[Msg] =
218
- fun key(self) -> Int = self.id
219
-
220
- fun place(self) -> Place = self.at
221
-
222
- fun step(self, ctx: ECtx[Msg], dt: Float) -> Orb =
223
- m := driftOf(Motion(x: self.at.x, y: self.at.y, vx: self.vx, vy: self.vy), OrbRadius, dt)
224
- Orb(..self, at: self.at.moveTo(m.x, m.y), vx: m.vx, vy: m.vy, clock: self.clock + dt)
225
-
226
- # The glow is drawn additively, then the sprite on top.
227
- fun paint(self, io: Io, m: Affine, alpha: Float) =
228
- gfx.blendMode(io, Blend.Add)
229
- paintCircle(io, m, 0.0, 0.0, 26.0, Color(r: 0.35, g: 0.22, b: 0.0, a: 0.5 * alpha))
230
- paintCircle(io, m, 0.0, 0.0, 17.0, Color(r: 0.6, g: 0.4, b: 0.05, a: 0.5 * alpha))
231
- gfx.blendMode(io, Blend.Normal)
232
- paintCell(io, m, alpha, self.sheet, 0.0 - SpriteHalf, 0.0 - SpriteHalf, SpriteSize, frameOf(self.clock + self.phase, 4, 8.0), 1)
233
-
234
- # Put at `to`, drifting with its velocity.
235
- fun placed(self, to: Motion) -> Orb = Orb(..self, at: self.at.moveTo(to.x, to.y), vx: to.vx, vy: to.vy)
236
-
237
- # Stopped; it still animates.
238
- fun still(self) -> Orb = Orb(..self, vx: 0.0, vy: 0.0)
239
-
240
- # A mine drifting at (vx, vy) and turning at `spin` radians per second.
241
- struct Mine(id: Int, at: Place, vx: Float, vy: Float, spin: Float, clock: Float, sheet: Texture) is Actor[Msg] =
242
- fun key(self) -> Int = self.id
243
-
244
- fun place(self) -> Place = self.at
245
-
246
- fun step(self, ctx: ECtx[Msg], dt: Float) -> Mine =
247
- m := driftOf(Motion(x: self.at.x, y: self.at.y, vx: self.vx, vy: self.vy), MineRadius, dt)
248
- at := Place(..self.at, x: m.x, y: m.y, rotation: self.at.rotation + self.spin * dt)
249
- Mine(..self, at: at, vx: m.vx, vy: m.vy, clock: self.clock + dt)
250
-
251
- fun paint(self, io: Io, m: Affine, alpha: Float) =
252
- paintCell(io, m, alpha, self.sheet, 0.0 - SpriteHalf, 0.0 - SpriteHalf, SpriteSize, frameOf(self.clock, 4, 4.0), 2)
253
-
254
- fun placed(self, to: Motion) -> Mine = Mine(..self, at: self.at.moveTo(to.x, to.y), vx: to.vx, vy: to.vy)
255
-
256
- # Stopped and no longer turning; it still animates.
257
- fun still(self) -> Mine = Mine(..self, vx: 0.0, vy: 0.0, spin: 0.0)
258
-
259
- # The player. `ax`, `ay` are the steering axes for its next step, set by the game before
260
- # it; `hurt` is the time left of its hurt flash and `hurtAge` the time since the hit.
261
- # Hidden at game over, when it stops.
262
- struct Ship(
263
- id: Int, at: Place, vx: Float, vy: Float, ax: Float, ay: Float,
264
- hurt: Float, hurtAge: Float, clock: Float, sheet: Texture, visible: Bool) is Actor[Msg] =
265
-
266
- fun key(self) -> Int = self.id
267
-
268
- fun place(self) -> Place = self.at
269
-
270
- fun shown(self) -> Bool = self.visible
271
-
272
- # It accelerates by the axes, drag slows it and the walls stop it.
273
- fun step(self, ctx: ECtx[Msg], dt: Float) -> Ship =
274
- if !self.visible
275
- self
276
- else
277
- keep := {1.0 - Drag * dt}.max(0.0)
278
- r := ShipRadius
279
- vx0 := {self.vx + self.ax * Thrust * dt} * keep
280
- vy0 := {self.vy + self.ay * Thrust * dt} * keep
281
- x0 := self.at.x + vx0 * dt
282
- y0 := self.at.y + vy0 * dt
283
- x := x0.max(r).min(ArenaW - r)
284
- y := y0.max(r).min(ArenaH - r)
285
- nvx := if x != x0 then 0.0 else vx0
286
- nvy := if y != y0 then 0.0 else vy0
287
- rot := if nvx * nvx + nvy * nvy > 400.0 then math.atan2(nvx, 0.0 - nvy) else self.at.rotation
288
- Ship(
289
- ..self, at: Place(..self.at, x: x, y: y, rotation: rot), vx: nvx, vy: nvy,
290
- hurt: {self.hurt - dt}.max(0.0), hurtAge: self.hurtAge + dt, clock: self.clock + dt)
291
-
292
- fun paint(self, io: Io, m: Affine, alpha: Float) =
293
- if !self.blinking()
294
- paintCircle(io, m, 0.0, 0.0, 17.0, Color(r: 0.4, g: 0.8, b: 1.0, a: 0.12 * alpha))
295
- paintCell(io, m, alpha, self.sheet, 0.0 - SpriteHalf, 0.0 - SpriteHalf, SpriteSize, frameOf(self.clock, 4, 14.0), 0)
296
-
297
- # It blinks off while hurt.
298
- fun blinking(self) -> Bool = self.hurt > 0.0 && flashPose(self.hurtAge).scaleX < 0.7
299
-
300
- # Steered by the axes for its next step.
301
- fun steered(self, ax: Float, ay: Float) -> Ship = Ship(..self, ax: ax, ay: ay)
302
-
303
- # Just hit: hurt for `HurtTime`, its flash from the start.
304
- fun struck(self) -> Ship = Ship(..self, hurt: HurtTime, hurtAge: 0.0)
305
-
306
- fun hidden(self) -> Ship = Ship(..self, visible: false)
307
-
308
- # A `size` square cell (col, row) of the sprite sheet: a life icon.
309
- struct Icon(id: Int, at: Place, size: Float, col: Int, row: Int, sheet: Texture) is Actor[Msg] =
310
- fun key(self) -> Int = self.id
311
-
312
- fun place(self) -> Place = self.at
313
-
314
- fun paint(self, io: Io, m: Affine, alpha: Float) = paintCell(io, m, alpha, self.sheet, 0.0, 0.0, self.size, self.col, self.row)
315
-
316
- # A line of text in `color`, whose alpha is its opacity.
317
- struct Label(id: Int, at: Place, text: Str, size: Float, color: Color) is Actor[Msg] =
318
- fun key(self) -> Int = self.id
319
-
320
- fun place(self) -> Place = self.at
321
-
322
- fun opacity(self) -> Float = self.color.a
323
-
324
- fun paint(self, io: Io, m: Affine, alpha: Float) =
325
- paintText(io, m, self.text, 0.0, 0.0, self.size, self.color.withAlpha(alpha))
326
-
327
- fun relabel(self, t: Str) -> Label = Label(..self, text: t)
328
-
329
- # The game-over title: its scale is `titlePose` of its age.
330
- struct Title(id: Int, at: Place, age: Float, color: Color) is Actor[Msg] =
331
- fun key(self) -> Int = self.id
332
-
333
- fun place(self) -> Place = self.at
334
-
335
- fun step(self, ctx: ECtx[Msg], dt: Float) -> Title =
336
- p := titlePose(self.age + dt)
337
- Title(..self, at: self.at.scaleTo(p.scaleX, p.scaleY), age: self.age + dt)
338
-
339
- fun paint(self, io: Io, m: Affine, alpha: Float) =
340
- paintText(io, m, "Game over", -100.0, -24.0, 48.0, self.color.withAlpha(alpha))
341
-
342
- # Unscaled, its clock from 0: as it comes up at game over.
343
- fun revealed(self) -> Title = Title(..self, at: self.at.scaleTo(1.0, 1.0), age: 0.0)
344
-
345
- # The game-over panel, hidden while playing: its opacity fades in over half a second of
346
- # its age, and so do its children.
347
- struct Panel(id: Int, at: Place, age: Float, alpha: Float, visible: Bool) is Actor[Msg] =
348
- fun key(self) -> Int = self.id
349
-
350
- fun place(self) -> Place = self.at
351
-
352
- fun shown(self) -> Bool = self.visible
353
-
354
- fun opacity(self) -> Float = self.alpha
355
-
356
- fun step(self, ctx: ECtx[Msg], dt: Float) -> Panel =
357
- Panel(..self, alpha: {{self.age + dt} * 2.0}.min(1.0), age: self.age + dt)
358
-
359
- # Shown, faded out, its clock from 0.
360
- fun revealed(self) -> Panel = Panel(..self, visible: true, alpha: 0.0, age: 0.0)
361
-
362
- # The "Again" button, `w` by `h`. `look` is 0 idle, 1 hovered, 2 pressed (from the
363
- # `UiState`).
364
- struct Button(id: Int, at: Place, w: Float, h: Float, label: Str, look: Int) is Actor[Msg] =
365
- fun key(self) -> Int = self.id
366
-
367
- fun place(self) -> Place = self.at
368
-
369
- fun paint(self, io: Io, m: Affine, alpha: Float) =
370
- actor.boxPaint(io, m, alpha, self.w, self.h, buttonColor(self.look))
371
- paintText(io, m, self.label, 4.0, 4.0, self.h * 0.5, Color.White.withAlpha(alpha))
372
-
373
- # The only body that can be clicked.
374
- fun hit(self, p: Vec2) -> Bool = actor.boxHit(self.w, self.h, p)
375
-
376
- fun looked(self, k: Int) -> Button = Button(..self, look: k)
377
-
378
- # An orb or a mine stopped (the others as they are): what game over does to every body.
379
- fun stilled(a: Actor[Msg]) -> Actor[Msg] = match a
380
- Orb as o => o.still()
381
- Mine as m => m.still()
382
- _ => a
383
-
384
- # An orb or a mine put at `to` (the others as they are).
385
- fun placedAt(a: Actor[Msg], to: Motion) -> Actor[Msg] = match a
386
- Orb as o => o.placed(to)
387
- Mine as m => m.placed(to)
388
- _ => a
389
-
390
- fun buttonColor(look: Int) -> Color =
391
- if look == 2
392
- ui.uiPressedColor()
393
- else if look == 1
394
- ui.uiHoverColor()
395
- else
396
- ui.uiIdleColor()
397
-
398
- fun buttonLook(u: UiState) -> Int =
399
- if ui.pressed(u, RestartId)
400
- 2
401
- else if ui.hovered(u, RestartId)
402
- 1
403
- else
404
- 0
405
-
406
- # The root's place as the camera for a `sw` by `sh` screen.
407
- fun fitted(sw: Float, sh: Float) -> Place =
408
- z := fitZoom(sw, sh)
409
- place.at(fitX(sw, sh), fitY(sw, sh)).scaleTo(z, z)
410
-
411
- # --- building the tree ---
412
-
413
- fun group(id: Int, kids: List[FRoseTree[Actor[Msg]]]) -> FRoseTree[Actor[Msg]] =
414
- FRoseTree.of(Group(id: id, at: place.at(0.0, 0.0)), kids)
415
-
416
- fun label(id: Int, text: Str, x: Float, y: Float, size: Float, c: Color) -> FRoseTree[Actor[Msg]] =
417
- FRoseTree.leaf(Label(id: id, at: place.at(x, y), text: text, size: size, color: c))
418
-
419
- # Stars `i` and up to `StarCount`, each at its fixed spot.
420
- fun starNodes(i: Int) -> List[FRoseTree[Actor[Msg]]] =
421
- if i >= StarCount
422
- Nil
423
- else
424
- Cons(head: FRoseTree.leaf(Star(id: StarId + i, i: i, clock: 0.0)), tail: starNodes(i + 1))
425
-
426
- # Life icons `i` and up to `StartLives`, from the right edge going left.
427
- fun lifeNodes(i: Int, sheet: Texture) -> List[FRoseTree[Actor[Msg]]] =
428
- if i >= StartLives
429
- Nil
430
- else
431
- icon := Icon(id: LifeId + i, at: place.at(ArenaW - 40.0 - Float(i) * 36.0, 12.0), size: 32.0, col: 0, row: 0, sheet: sheet)
432
- Cons(head: FRoseTree.leaf(icon), tail: lifeNodes(i + 1, sheet))
433
-
434
- fun shipActor(x: Float, y: Float, sheet: Texture) -> Ship =
435
- Ship(
436
- id: ShipId, at: place.at(x, y), vx: 0.0, vy: 0.0, ax: 0.0, ay: 0.0,
437
- hurt: 0.0, hurtAge: 0.0, clock: 0.0, sheet: sheet, visible: true)
438
-
439
- # The stage of a fresh run: no orbs or mines yet (`State.start` adds them).
440
- fun buildStage(sheet: Texture, sw: Float, sh: Float) -> EStage[Msg] =
441
- hud := group(HudId, Cons(
442
- head: label(ScoreId, "Score 0", 16.0, 12.0, 28.0, Color.White),
443
- tail: Cons(head: label(BestId, "Best 0", 16.0, 44.0, 20.0, Color.Yellow), tail: lifeNodes(0, sheet))))
444
- panel: FRoseTree[Actor[Msg]] := FRoseTree.of(Panel(id: PanelId, at: place.at(0.0, 0.0), age: 0.0, alpha: 1.0, visible: false), [
445
- FRoseTree.leaf(Box(id: DimId, at: place.at(0.0, 230.0), w: ArenaW, h: 170.0, color: Color(r: 0.0, g: 0.0, b: 0.0, a: 0.6))),
446
- FRoseTree.leaf(Title(id: TitleId, at: place.at(400.0, 268.0), age: 0.0, color: Color.Red)),
447
- label(PromptId, "Press Enter to play again", 270.0, 300.0, 24.0, Color.White),
448
- FRoseTree.leaf(Button(id: RestartId, at: place.at(340.0, 342.0), w: 120.0, h: 44.0, label: "Again", look: 0))])
449
- root: FRoseTree[Actor[Msg]] := FRoseTree.of(Group(id: RootId, at: fitted(sw, sh)), [
450
- FRoseTree.leaf(Box(id: BackId, at: place.at(0.0, 0.0), w: ArenaW, h: ArenaH, color: Color.rgb(0.07, 0.08, 0.16))),
451
- group(StarLayer, starNodes(0)),
452
- group(MineLayer, Nil),
453
- group(OrbLayer, Nil),
454
- FRoseTree.leaf(shipActor(ArenaW / 2.0, ArenaH / 2.0, sheet)),
455
- hud,
456
- panel])
457
- EStage(root: root, camX: 0.0, camY: 0.0, camScale: 1.0)
458
-
459
- # --- the game ---
460
-
461
- # What can happen to the state.
462
- enum Msg =
463
- | Tick(dt: Float, ax: Float, ay: Float)
464
- | Resize(w: Float, h: Float)
465
- | Restart(seed: Int)
466
- | Event(input: InputEvent)
467
- | RestartClicked
468
-
469
- # The scene and what is between its actors. `mines` is how many mines are out (the next
470
- # one's id is `MineId + mines`).
471
- struct State(
472
- stage: EStage[Msg],
473
- rng: Random,
474
- score: Int,
475
- best: Int,
476
- lives: Int,
477
- over: Bool,
478
- clock: Float,
479
- mines: Int,
480
- ui: UiState,
481
- held: Held,
482
- sw: Float,
483
- sh: Float,
484
- sheet: Texture
485
- ) =
486
-
487
- # A fresh run: the orbs and the mines spread over the arena away from the ship.
488
- fun start(seed: Int, best: Int, sheet: Texture, sw: Float, sh: Float) -> State =
489
- State(
490
- stage: buildStage(sheet, sw, sh),
491
- rng: Random.seeded(seed),
492
- score: 0,
493
- best: best,
494
- lives: StartLives,
495
- over: false,
496
- clock: 0.0,
497
- mines: 0,
498
- ui: ui.init(),
499
- held: Held.none(),
500
- sw: sw,
501
- sh: sh,
502
- sheet: sheet
503
- ).fillOrbs(0).growMines().showScore()
504
-
505
- fun update(self, msg: Msg) -> State = match msg
506
- Tick(dt, ax, ay) => self.tick(dt, ax, ay)
507
- Resize(w, h) => State(..self, sw: w, sh: h, stage: self.stage.updateAs[Group[Msg]](RootId, |g| Group(..g, at: fitted(w, h))))
508
- Restart(seed) => self.restarted(seed)
509
- Event(input) => self.onInput(input)
510
- RestartClicked => if self.over then self.restarted(self.rng.nextInt().value) else self
511
-
512
- # One frame: the stage steps every actor (the ship with this frame's axes), then the
513
- # game looks at what they did. Once the game is over the actors only animate.
514
- fun tick(self, dt: Float, ax: Float, ay: Float) -> State =
515
- stepped := self.stage.updateAs[Ship](ShipId, |sh| sh.steered(ax, ay)).step(ECtx[Msg](), dt)
516
- moved := State(..self, stage: stepped, clock: self.clock + dt)
517
- if self.over then moved else moved.collect().growMines().hurt().settle()
518
-
519
- # The actor with this id (every fixed id is always on the stage).
520
- fun body(self, id: Int) -> Actor[Msg] = self.stage.find(id).unwrap()
521
-
522
- fun ship(self) -> Ship = self.stage.findAs[Ship](ShipId).unwrap()
523
-
524
- # The orbs and the mines, in tree order.
525
- fun orbs(self) -> List[Orb] =
526
- self.stage.root.fold(Nil, |acc, a| match a
527
- Orb as o => Cons(head: o, tail: acc)
528
- _ => acc).reverse()
529
-
530
- fun mineList(self) -> List[Mine] =
531
- self.stage.root.fold(Nil, |acc, a| match a
532
- Mine as m => Cons(head: m, tail: acc)
533
- _ => acc).reverse()
534
-
535
- fun touches(self, at: Place, radius: Float) -> Bool =
536
- sh := self.ship()
537
- overlaps(sh.at.x, sh.at.y, ShipRadius, at.x, at.y, radius)
538
-
539
- # The ship collects every orb it touches.
540
- fun collect(self) -> State =
541
- self.orbs().fold(self, |s, o| if s.touches(o.at, OrbRadius) then s.respawnOrb(o.id) else s)
542
-
543
- # Scores the orb `id` and puts it at a new random spot.
544
- fun respawnOrb(self, id: Int) -> State =
545
- sh := self.ship()
546
- sp := spawn(self.rng, sh.at.x, sh.at.y, 120.0, 40.0)
547
- State(..self, stage: self.stage.updateAs[Orb](id, |o| o.placed(sp.at)), rng: sp.rng, score: self.score + OrbPoints).showScore()
548
-
549
- # The hud's labels from the score.
550
- fun showScore(self) -> State =
551
- score := "Score {self.score}"
552
- best := "Best {self.best.max(self.score)}"
553
- State(..self, stage: self.stage.updateAs[Label](ScoreId, |l| l.relabel(score)).updateAs[Label](BestId, |l| l.relabel(best)))
554
-
555
- # Orbs `i` and up to OrbCount, each at a random spot away from the ship.
556
- fun fillOrbs(self, i: Int) -> State =
557
- if i >= OrbCount then self else self.addOrb(i).fillOrbs(i + 1)
558
-
559
- fun addOrb(self, i: Int) -> State =
560
- sh := self.ship()
561
- sp := spawn(self.rng, sh.at.x, sh.at.y, 120.0, 40.0)
562
- orb := Orb(id: OrbId + i, at: place.at(sp.at.x, sp.at.y), vx: sp.at.vx, vy: sp.at.vy, phase: Float(i) * 0.1, clock: 0.0, sheet: self.sheet)
563
- State(..self, stage: self.stage.add(OrbLayer, FRoseTree.leaf(orb)), rng: sp.rng)
564
-
565
- # Mines are added (on top of the others) until there are as many as the score asks for.
566
- fun growMines(self) -> State =
567
- if self.mines >= mineCount(self.score) then self else self.addMine().growMines()
568
-
569
- fun addMine(self) -> State =
570
- sh := self.ship()
571
- sp := spawn(self.rng, sh.at.x, sh.at.y, 220.0, 90.0)
572
- mine := Mine(id: MineId + self.mines, at: place.at(sp.at.x, sp.at.y), vx: sp.at.vx, vy: sp.at.vy, spin: 2.0, clock: 0.0, sheet: self.sheet)
573
- State(..self, stage: self.stage.add(MineLayer, FRoseTree.leaf(mine)), rng: sp.rng, mines: self.mines + 1)
574
-
575
- fun touchesMine(self) -> Bool =
576
- self.mineList().fold(false, |hit, m| hit || self.touches(m.at, MineRadius))
577
-
578
- # A mine costs a life (and its icon), makes the ship flash and, at the last life, ends
579
- # the game: the ship goes and the panel comes up.
580
- fun hurt(self) -> State =
581
- if self.ship().hurt <= 0.0 && self.touchesMine() then self.struck() else self
582
-
583
- fun struck(self) -> State =
584
- lives := self.lives - 1
585
- done := lives <= 0
586
- hit := self.stage.updateAs[Ship](ShipId, |sh| sh.struck()).kill(LifeId + lives)
587
- stage := if done then gameOver(hit) else hit
588
- State(..self, stage: stage, lives: lives, over: done, best: if done then self.best.max(self.score) else self.best)
589
-
590
- # After game over the orbs and mines stop: they only animate.
591
- fun settle(self) -> State =
592
- if self.over then State(..self, stage: self.stage.withRoot(self.stage.root.map(stilled))) else self
593
-
594
- # A fresh run that keeps the best score, the Ui and the held keys; the button shows the
595
- # Ui's state.
596
- fun restarted(self, seed: Int) -> State =
597
- fresh := State.start(seed, self.best.max(self.score), self.sheet, self.sw, self.sh)
598
- look := buttonLook(self.ui)
599
- State(..fresh, ui: self.ui, held: self.held, stage: fresh.stage.updateAs[Button](RestartId, |b| b.looked(look)))
600
-
601
- # A player input: keys update the held keys (Enter or R restarts a finished game),
602
- # a pointer input goes through the Ui.
603
- fun onInput(self, e: InputEvent) -> State =
604
- s := State(..self, held: self.held.after(e))
605
- if e.isPointer()
606
- s.feed(e)
607
- else if s.over && isRestartKey(e)
608
- s.restarted(s.rng.nextInt().value)
609
- else
610
- s
611
-
612
- # The steering axes from the held arrow or WASD keys.
613
- fun axisX(self) -> Float =
614
- axis(self.held.isDown(Key.Left) || self.held.isDown(Key.KeyA), self.held.isDown(Key.Right) || self.held.isDown(Key.KeyD))
615
-
616
- fun axisY(self) -> Float =
617
- axis(self.held.isDown(Key.Up) || self.held.isDown(Key.KeyW), self.held.isDown(Key.Down) || self.held.isDown(Key.KeyS))
618
-
619
- # One pointer input: the stage finds the actor under it (through the root's camera),
620
- # the Ui turns that into press, hover and click, the button shows the result, and a
621
- # click on it restarts.
622
- fun feed(self, input: InputEvent) -> State =
623
- po := input.position()
624
- if po.isNone()
625
- self
626
- else
627
- pos := po.unwrap()
628
- r := ui.step(self.ui, input, self.stage.hitId(pos.x, pos.y))
629
- look := buttonLook(r.ui)
630
- s := State(..self, ui: r.ui, stage: self.stage.updateAs[Button](RestartId, |b| b.looked(look)))
631
- clicked := r.events.fold(false, |c, e| c || {e.kind == Click && e.id == RestartId})
632
- if clicked then s.update(RestartClicked) else s
633
-
634
- # True when (x, y) in screen pixels is on the restart button.
635
- fun onRestart(self, x: Float, y: Float) -> Bool =
636
- self.stage.hitId(x, y).unwrapOr(-1) == RestartId
637
-
638
- # The stage at game over: the ship hidden, the panel and its title coming up.
639
- fun gameOver(s: EStage[Msg]) -> EStage[Msg] =
640
- s.updateAs[Ship](ShipId, |sh| sh.hidden()).updateAs[Panel](PanelId, |p| p.revealed()).updateAs[Title](TitleId, |t| t.revealed())
641
-
642
- # Enter or R going down.
643
- fun isRestartKey(e: InputEvent) -> Bool = match e
644
- KeyDown(k) => k == Key.Enter || k == Key.KeyR
645
- _ => false
646
-
647
- fun axis(negative: Bool, positive: Bool) -> Float =
648
- if negative && !positive
649
- -1.0
650
- else if positive && !negative
651
- 1.0
652
- else
653
- 0.0
654
-
655
- # --- the host shell ---
656
-
657
- struct OrbGame(state: State, input: Input, pickupSound: Sound, hitSound: Sound, overSound: Sound, musicSound: Sound) =
658
-
659
- # Restarts the music loop from the top.
660
- fun startMusic(self, io: Io) =
661
- self.musicSound.stop(io)
662
- self.musicSound.loop(io, 0.3)
663
-
664
- # Sends the tick's input events to the state, then one tick steered by the held keys;
665
- # plays sounds for what changed. Returns the game with the next state.
666
- fun update(self, io: Io, input: Input, dt: Float) -> OrbGame =
667
- polled := input
668
- s := self.state.update(Resize(w: gfx.screenWidth(io), h: gfx.screenHeight(io)))
669
- inputs := polled.events
670
- clicked := 0.until(inputs.length()).fold(s, |current, i| current.update(Event(input: inputs.at(i))))
671
- if s.over && !clicked.over
672
- self.startMusic(io)
673
- OrbGame(..self, state: clicked, input: polled)
674
- else
675
- t := clicked.update(Tick(dt: dt, ax: clicked.axisX(), ay: clicked.axisY()))
676
- if t.score > clicked.score
677
- self.pickupSound.play(io, 0.8)
678
- if t.lives < clicked.lives
679
- if t.over
680
- self.musicSound.stop(io)
681
- self.overSound.play(io, 1.0)
682
- else
683
- self.hitSound.play(io, 1.0)
684
- OrbGame(..self, state: t, input: polled)
685
-
686
- fun draw(self, io: Io) =
687
- gfx.clear(io, Color.rgb(0.04, 0.05, 0.1))
688
- self.state.stage.draw(io)
689
-
690
- fun main(io: Io) -> OrbGame =
691
- s := State.start(io.randomSeed(), 0, gfx.loadTexture(io, "sprites.png"), ArenaW, ArenaH)
692
- game := OrbGame(
693
- state: s,
694
- input: Input.create(),
695
- pickupSound: audio.loadSound(io, "pickup.wav"),
696
- hitSound: audio.loadSound(io, "hit.wav"),
697
- overSound: audio.loadSound(io, "gameover.wav"),
698
- musicSound: audio.loadSound(io, "music.wav")
699
- )
700
- game.startMusic(io)
701
- game
702
-
703
- # --- tests ---
704
-
705
- fun near(a: Float, b: Float) -> Bool =
706
- {a - b}.abs() < 0.01
707
-
708
- fun tickOf(s: State, ax: Float, ay: Float, dt: Float) -> State =
709
- s.update(Tick(dt: dt, ax: ax, ay: ay))
710
-
711
- # `n` ticks in a row with the same steering.
712
- fun ticksOf(s: State, n: Int, ax: Float, ay: Float, dt: Float) -> State =
713
- 0.until(n).fold(s, |current, _| tickOf(current, ax, ay, dt))
714
-
715
- # How many frames the ship was hidden and shown while ticking `state`.
716
- struct Blinks(state: State, hidden: Int, shown: Int)
717
-
718
- fun away() -> Motion =
719
- Motion(x: 5000.0, y: 0.0, vx: 0.0, vy: 0.0)
720
-
721
- fun newState(seed: Int) -> State =
722
- State.start(seed, 0, Texture(id: -1), ArenaW, ArenaH)
723
-
724
- fun moveBody(s: State, id: Int, m: Motion) -> State =
725
- State(..s, stage: s.stage.update(id, |a| placedAt(a, m)))
726
-
727
- # A state with the orbs and mines moved out of the way.
728
- fun emptyState() -> State =
729
- s := newState(7)
730
- State(..s, stage: s.stage.withRoot(s.stage.root.map(|a| placedAt(a, away()))))
731
-
732
- fun onShip(s: State) -> Motion =
733
- Motion(x: s.ship().at.x, y: s.ship().at.y, vx: 0.0, vy: 0.0)
734
-
735
- fun forceOver(s: State) -> State =
736
- State(..s, stage: gameOver(s.stage), lives: 0, over: true, best: s.best.max(s.score))
737
-
738
- fun lone(sh: Ship) -> EStage[Msg] = EStage.of(sh)
739
-
740
- fun shipAt(x: Float, y: Float) -> Ship = shipActor(x, y, Texture(id: -1))
741
-
742
- fun shipOf(s: EStage[Msg]) -> Ship = s.findAs[Ship](ShipId).unwrap()
743
-
744
- fun steer(s: EStage[Msg], ax: Float, ay: Float) -> EStage[Msg] = s.updateAs[Ship](ShipId, |sh| sh.steered(ax, ay))
745
-
746
- fun labelText(s: State, id: Int) -> Str = s.stage.findAs[Label](id).unwrap().text
747
-
748
- fun buttonLookOf(s: State) -> Int = s.stage.findAs[Button](RestartId).unwrap().look
749
-
750
- fun mineAt(s: State, id: Int) -> Mine = s.stage.findAs[Mine](id).unwrap()
751
-
752
- fun orbAt(s: State, id: Int) -> Orb = s.stage.findAs[Orb](id).unwrap()
753
-
754
- test "the scene starts as a tree of 63 actors, 58 of them drawn"
755
- s := newState(7)
756
- assert s.stage.count() == 63
757
- assert s.stage.flatten().length() == 58
758
- over := forceOver(s)
759
- assert over.stage.flatten().length() == 58 - 1 + 5
760
-
761
- test "steering accelerates and drag slows the ship"
762
- s := steer(lone(shipAt(ArenaW / 2.0, ArenaH / 2.0)), 1.0, 0.0).step(ECtx[Msg](), 0.1)
763
- sh := shipOf(s)
764
- assert sh.at.x > ArenaW / 2.0
765
- assert sh.vx > 0.0
766
- coast := steer(s, 0.0, 0.0)
767
- t := 0.until(30).fold(coast, |cur, _| cur.step(ECtx[Msg](), 0.1))
768
- assert shipOf(t).vx < sh.vx / 4.0
769
- assert shipOf(t).at.x - sh.at.x < 50.0
770
-
771
- test "the ship stops at the arena walls"
772
- start := steer(lone(shipAt(20.0, 20.0)), -1.0, -1.0)
773
- s := 0.until(20).fold(start, |cur, _| cur.step(ECtx[Msg](), 0.1))
774
- sh := shipOf(s)
775
- assert sh.at.x == ShipRadius
776
- assert sh.at.y == ShipRadius
777
- assert sh.vx == 0.0
778
-
779
- test "orbs bounce off the walls and mines spin as they drift"
780
- orb := Orb(id: OrbId, at: place.at(795.0, 300.0), vx: 100.0, vy: 0.0, phase: 0.0, clock: 0.0, sheet: Texture(id: -1))
781
- o := orb.step(ECtx[Msg](), 0.1)
782
- assert near(o.at.x, ArenaW - 10.0)
783
- mine := Mine(id: MineId, at: place.at(400.0, 300.0), vx: 10.0, vy: 0.0, spin: 2.0, clock: 0.0, sheet: Texture(id: -1))
784
- k := mine.step(ECtx[Msg](), 0.5)
785
- assert near(k.at.rotation, 1.0)
786
- assert near(k.at.x, 405.0)
787
- assert near(mine.at.rotation, 0.0)
788
-
789
- test "collecting an orb scores, respawns it elsewhere and updates the hud"
790
- e := emptyState()
791
- s := moveBody(e, OrbId, onShip(e))
792
- t := tickOf(s, 0.0, 0.0, 0.016)
793
- orb := orbAt(t, OrbId)
794
- assert t.score == OrbPoints
795
- assert math.hypot(orb.at.x - t.ship().at.x, orb.at.y - t.ship().at.y) >= 120.0
796
- assert orb.at.x < 5000.0
797
- assert t.orbs().length() == OrbCount
798
- assert labelText(t, ScoreId) == "Score 10"
799
- assert labelText(s, ScoreId) == "Score 0"
800
-
801
- test "a mine costs one life and its icon, and makes the ship flash"
802
- e := emptyState()
803
- s := moveBody(e, MineId, onShip(e))
804
- hit := tickOf(s, 0.0, 0.0, 0.016)
805
- assert hit.lives == StartLives - 1
806
- assert hit.ship().hurt > 0.0
807
- assert hit.stage.find(LifeId + 2).isNone()
808
- assert hit.stage.find(LifeId + 1).isSome()
809
- start := Blinks(state: moveBody(hit, MineId, away()), hidden: 0, shown: 0)
810
- blinks := 0.until(100).fold(start, |b, _|
811
- next := tickOf(b.state, 0.0, 0.0, 0.016)
812
- if next.ship().blinking()
813
- Blinks(state: next, hidden: b.hidden + 1, shown: b.shown)
814
- else
815
- Blinks(state: next, hidden: b.hidden, shown: b.shown + 1)
816
- )
817
- assert blinks.hidden > 0
818
- assert blinks.shown > 0
819
- assert blinks.state.ship().hurt == 0.0
820
- assert !blinks.state.ship().blinking()
821
- assert blinks.state.lives == StartLives - 1
822
-
823
- test "the ship is briefly safe after a hit"
824
- e := emptyState()
825
- hit := tickOf(moveBody(e, MineId, onShip(e)), 0.0, 0.0, 0.016)
826
- assert tickOf(hit, 0.0, 0.0, 0.016).lives == StartLives - 1
827
-
828
- test "the game ends at zero lives: the ship goes, the panel comes up, steps are ignored"
829
- e := emptyState()
830
- s := State(..e, lives: 1, score: 40)
831
- t := tickOf(moveBody(s, MineId, onShip(s)), 0.0, 0.0, 0.016)
832
- assert t.over
833
- assert t.lives == 0
834
- assert t.best == 40
835
- assert !t.ship().shown()
836
- assert t.body(PanelId).shown()
837
- x := t.ship().at.x
838
- assert tickOf(t, 1.0, 0.0, 0.5).ship().at.x == x
839
-
840
- test "after game over nothing moves but the animations keep running"
841
- e := emptyState()
842
- s := State(..e, lives: 1)
843
- ended := tickOf(moveBody(s, MineId, Motion(x: s.ship().at.x, y: s.ship().at.y, vx: 10.0, vy: 0.0)), 0.0, 0.0, 0.016)
844
- assert ended.over
845
- mine := mineAt(ended, MineId)
846
- t := ticksOf(ended, 10, 1.0, 0.0, 0.1)
847
- after := mineAt(t, MineId)
848
- assert after.at.x == mine.at.x
849
- assert after.at.rotation == mine.at.rotation
850
- assert t.ship().at.x == ArenaW / 2.0
851
- assert after.clock > mine.clock + 0.9
852
- assert orbAt(t, OrbId).clock > 0.9
853
- assert t.clock > 0.9
854
- assert t.score == 0
855
-
856
- test "restart builds a fresh tree and keeps the best score"
857
- e := emptyState()
858
- s := forceOver(State(..e, score: 90))
859
- r := s.update(Restart(seed: 5))
860
- assert !r.over
861
- assert r.score == 0
862
- assert r.best == 90
863
- assert r.lives == StartLives
864
- assert r.ship().at.x == ArenaW / 2.0
865
- assert r.ship().shown()
866
- assert !r.body(PanelId).shown()
867
- assert r.mineList().length() == mineCount(0)
868
- assert labelText(r, BestId) == "Best 90"
869
-
870
- test "more mines are added to the tree as the score grows"
871
- assert mineCount(0) == 3
872
- assert mineCount(100) == 5
873
- assert mineCount(10000) == 8
874
- e := emptyState()
875
- t := tickOf(State(..e, score: 100), 0.0, 0.0, 0.016)
876
- assert t.mineList().length() == 5
877
- assert t.stage.find(MineId + 4).isSome()
878
- assert t.update(Restart(seed: 3)).mineList().length() == 3
879
-
880
- test "the same seed plays out the same way"
881
- a := ticksOf(newState(11), 120, 1.0, -1.0, 0.016)
882
- b := ticksOf(newState(11), 120, 1.0, -1.0, 0.016)
883
- assert a.ship().at.x == b.ship().at.x
884
- assert a.score == b.score
885
- assert mineAt(a, MineId).at.x == mineAt(b, MineId).at.x
886
- assert orbAt(newState(12), OrbId).at.x != orbAt(a, OrbId).at.x
887
-
888
- test "a kept old state still has its old tree"
889
- s := emptyState()
890
- x := s.ship().at.x
891
- t := tickOf(s, 1.0, 0.0, 0.1)
892
- assert t.ship().at.x > x
893
- assert s.ship().at.x == x
894
-
895
- test "the root fits the arena on the screen"
896
- s := emptyState().update(Resize(w: 1600.0, h: 600.0))
897
- root := s.body(RootId).place().local()
898
- assert near(root.a, 1.0)
899
- assert near(root.e, 400.0)
900
- assert near(root.f, 0.0)
901
-
902
- test "the restart button is hidden while playing and found through the root's camera"
903
- s := emptyState()
904
- assert !s.onRestart(400.0, 364.0)
905
- o := forceOver(s)
906
- assert o.onRestart(400.0, 364.0)
907
- assert !o.onRestart(100.0, 100.0)
908
- assert !o.onRestart(400.0, 260.0)
909
- wide := o.update(Resize(w: 1600.0, h: 600.0))
910
- assert wide.onRestart(800.0, 364.0)
911
- assert !wide.onRestart(400.0, 364.0)
912
-
913
- test "a click on the button restarts through the ui"
914
- e := emptyState()
915
- s := forceOver(State(..e, score: 90))
916
- down := s.feed(PointerDown(x: 400.0, y: 364.0))
917
- assert down.over
918
- assert ui.pressed(down.ui, RestartId)
919
- assert buttonLookOf(down) == 2
920
- up := down.feed(PointerUp(x: 400.0, y: 364.0))
921
- assert !up.over
922
- assert up.score == 0
923
- assert up.best == 90
924
- assert up.lives == StartLives
925
- assert s.feed(PointerDown(x: 400.0, y: 364.0)).feed(PointerUp(x: 100.0, y: 100.0)).over
926
- assert s.feed(PointerDown(x: 100.0, y: 100.0)).feed(PointerUp(x: 100.0, y: 100.0)).over
927
-
928
- test "the title pulses and the panel fades in by their own clocks"
929
- t := ticksOf(forceOver(emptyState()), 15, 0.0, 0.0, 0.02)
930
- assert near(t.body(PanelId).opacity(), 0.6)
931
- assert near(t.body(TitleId).place().local().a, 1.3)
932
- assert near(titlePose(0.8).scaleX, 1.17)
933
- assert near(flashPose(0.05).scaleX, 0.4)
934
-
935
- test "held keys steer, and enter restarts a finished game and nothing else"
936
- s := emptyState().update(Event(input: KeyDown(key: Key.Left))).update(Event(input: KeyDown(key: Key.KeyS)))
937
- assert s.axisX() == -1.0
938
- assert s.axisY() == 1.0
939
- assert s.update(Event(input: KeyUp(key: Key.Left))).axisX() == 0.0
940
- playing := emptyState().update(Event(input: KeyDown(key: Key.Enter)))
941
- assert !playing.over
942
- e := emptyState()
943
- r := forceOver(State(..e, score: 40)).update(Event(input: KeyDown(key: Key.Enter)))
944
- assert !r.over
945
- assert r.best == 40
946
- assert r.held.isDown(Key.Enter)
std/collections/functional/FRoseTree.plum CHANGED
@@ -30,12 +30,12 @@ import std/List
30
30
  # of thousands of nodes); `fold`, `each`, `find`, `toList` and `chain` are tail calls on
31
31
  # the siblings and run in constant stack along a chain.
32
32
  #
33
- # Siblings are kept in order: the first child comes first in every walk (std/game_enum_tree
33
+ # Siblings are kept in order: the first child comes first in every walk (std/game/scene's
34
- # draws it first and hits it last). Appending a child copies the link nodes of its earlier
34
+ # SceneTree draws it first and hits it last). Appending a child copies the link nodes of its earlier
35
35
  # siblings (their values and subtrees are shared), O(children); `appendAll` adds a batch
36
36
  # for the cost of one.
37
37
  #
38
- # Nodes are referred to by what is in them (std/game_enum_tree's actors have a `key()`), not
38
+ # Nodes are referred to by what is in them (std/game/scene's actors have a `key()`), not
39
39
  # by the node itself: after an update the old node is a different, older value.
40
40
  enum FRoseTree[T] =
41
41
  | FRoseEmpty
std/game/scene.plum DELETED
@@ -1,387 +0,0 @@
1
- module std
2
-
3
- import std/Int
4
- import std/Float
5
- import std/Str
6
- import std/Slice
7
- import std/List
8
- import std/math
9
- import std/game/Vec2
10
- import std/game/Color
11
- import std/game/Affine
12
- import std/game/gfx
13
- import std/Io
14
- import std/Option
15
-
16
- # The functional scene: a `SceneNode[M]` is plain data (shapes, sprites, text, groups
17
- # with a transform, filters, clickable areas), rebuilt every frame and never mutated.
18
- # `M` is the game's own message type: a `Clickable(id, msg, child)` carries the
19
- # message a click on it sends (see `ui.messages`), so games match on their messages
20
- # instead of comparing ids; the id identifies the element for hover and press state. Its methods draw
21
- # it, measure it and hit-test it by structural recursion, passing the parent matrix
22
- # and alpha down as arguments. Children are a `List[SceneNode[M]]`; the static
23
- # `SceneNode` helpers over such a list (`drawKids`, `boundsKids`, ..) do the same walk
24
- # for each child. `Compose(first, then)` applies `then` first, then `first` (`first`
25
- # is the outermost).
26
-
27
- enum Transform =
28
- | Identity
29
- | Translate(dx: Float, dy: Float)
30
- | Rotate(radians: Float)
31
- | Scale(sx: Float, sy: Float)
32
- | Compose(first: Transform, then: Transform)
33
-
34
- fun matrix(self) -> Affine = match self
35
- Identity => Affine.Identity
36
- Translate(dx, dy) => Affine(a: 1.0, b: 0.0, c: 0.0, d: 1.0, e: dx, f: dy)
37
- Rotate(rad) => Affine(a: math.cos(rad), b: math.sin(rad), c: 0.0 - math.sin(rad), d: math.cos(rad), e: 0.0, f: 0.0)
38
- Scale(sx, sy) => Affine(a: sx, b: 0.0, c: 0.0, d: sy, e: 0.0, f: 0.0)
39
- Compose(first, then) => first.matrix().mul(then.matrix())
40
-
41
- # `mode` is a `Blend` constant from std/game/gfx.
42
- enum Effect =
43
- | Tint(color: Color)
44
- | Alpha(alpha: Float)
45
- | BlendFx(mode: Int)
46
-
47
- # The color a filtered texture is composited with.
48
- fun tint(self, alpha: Float) -> Color = match self
49
- Tint(color) => color.withAlpha(color.a * alpha)
50
- Alpha(a) => Color.White.withAlpha(a * alpha)
51
- _ => Color.White.withAlpha(alpha)
52
-
53
- struct Rect(x: Float, y: Float, w: Float, h: Float) =
54
- # The bounding box, in the outer space, of the box (x, y, w, h) seen through `m`.
55
- fun through(x: Float, y: Float, w: Float, h: Float, m: Affine) -> Rect =
56
- p1 := m.apply(Vec2(x: x, y: y))
57
- p2 := m.apply(Vec2(x: x + w, y: y))
58
- p3 := m.apply(Vec2(x: x, y: y + h))
59
- p4 := m.apply(Vec2(x: x + w, y: y + h))
60
- x0 := p1.x.min(p2.x).min(p3.x.min(p4.x))
61
- x1 := p1.x.max(p2.x).max(p3.x.max(p4.x))
62
- y0 := p1.y.min(p2.y).min(p3.y.min(p4.y))
63
- y1 := p1.y.max(p2.y).max(p3.y.max(p4.y))
64
- Rect(x: x0, y: y0, w: x1 - x0, h: y1 - y0)
65
-
66
- # The bounding box of a line `thickness` wide seen through `m`.
67
- fun throughLine(x1: Float, y1: Float, x2: Float, y2: Float, thickness: Float, m: Affine) -> Rect =
68
- lx := x1.min(x2) - thickness / 2.0
69
- ly := y1.min(y2) - thickness / 2.0
70
- Rect.through(lx, ly, {x1 - x2}.abs() + thickness, {y1 - y2}.abs() + thickness, m)
71
-
72
- # The smallest box holding `a` (when there is one) and `b`.
73
- fun union(a: Option[Rect], b: Rect) -> Rect =
74
- match a
75
- Some(ra) =>
76
- x0 := ra.x.min(b.x)
77
- y0 := ra.y.min(b.y)
78
- x1 := {ra.x + ra.w}.max(b.x + b.w)
79
- y1 := {ra.y + ra.h}.max(b.y + b.h)
80
- Rect(x: x0, y: y0, w: x1 - x0, h: y1 - y0)
81
- None => b
82
-
83
- fun contains(self, px: Float, py: Float) -> Bool =
84
- px >= self.x && px <= self.x + self.w && py >= self.y && py <= self.y + self.h
85
-
86
- # A Sprite is a texture region `w` by `h` with its top-left at (x, y).
87
- # A Filter draws its child into `target`, then composites it with the effect.
88
- # `target` is a texture the game creates ONCE at load with `Texture.create`; draw
89
- # creates nothing, so a view does not leak a texture per frame. The size of
90
- # `target` bounds what the filter can show: child pixels beyond it are cut off.
91
- # A negative target draws nothing.
92
- enum SceneNode[M] =
93
- | Group(transform: Transform, children: List[SceneNode[M]])
94
- | Filter(effect: Effect, child: SceneNode[M], target: Texture)
95
- | Sprite(tex: Texture, x: Float, y: Float, w: Float, h: Float, srcX: Float, srcY: Float, srcW: Float, srcH: Float, tint: Color)
96
- | Text(text: Str, x: Float, y: Float, size: Float, color: Color)
97
- | RectShape(x: Float, y: Float, w: Float, h: Float, color: Color)
98
- | CircleShape(cx: Float, cy: Float, r: Float, color: Color)
99
- | LineShape(x1: Float, y1: Float, x2: Float, y2: Float, thickness: Float, color: Color)
100
- | Clickable(id: Int, msg: M, child: SceneNode[M])
101
-
102
- # Draws the scene to the current target.
103
- fun draw(self, io: Io) =
104
- self.drawWith(io, Affine.Identity, 1.0, Texture(id: 0 - 1))
105
-
106
- # The bounding box of the scene in its own space (all zero when empty).
107
- fun bounds(self) -> Rect =
108
- match self.boundsWith(Affine.Identity)
109
- Some(r) => r
110
- None => Rect(x: 0.0, y: 0.0, w: 0.0, h: 0.0)
111
-
112
- # Child indices from the root down to the topmost hit leaf; empty on a miss.
113
- fun hitPath(self, x: Float, y: Float) -> Slice[Int] =
114
- match self.hitWith(x, y)
115
- Some(p) => p
116
- None => Slice[Int]()
117
-
118
- # The id of the innermost Clickable node under (x, y), or None. Later siblings win.
119
- fun hitId(self, x: Float, y: Float) -> Option[Int] =
120
- self.hitIdWith(None, x, y)
121
-
122
- # The message of the first Clickable with `id`, depth first, or None.
123
- fun msgOf(self, id: Int) -> Option[M] = match self
124
- Clickable(cid, msg, child) => if cid == id then Some(msg) else child.msgOf(id)
125
- Group(_, kids) => SceneNode.msgOfKids(kids, id)
126
- Filter(_, child, _) => child.msgOf(id)
127
- _ => None
128
-
129
- fun msgOfKids(kids: List[SceneNode[M]], id: Int) -> Option[M] = match kids
130
- Nil => None
131
- Cons(head, tail) =>
132
- if Some(m) := head.msgOf(id)
133
- Some(m)
134
- else
135
- SceneNode.msgOfKids(tail, id)
136
-
137
- # --- drawing ---
138
-
139
- # Draws under the parent matrix `m` and alpha into `target` (negative: the screen).
140
- fun drawWith(self, io: Io, m: Affine, alpha: Float, target: Texture) = match self
141
- RectShape(x, y, w, h, color) =>
142
- sx := w * m.scaleX()
143
- sy := h * m.scaleY()
144
- c := m.apply(Vec2(x: x + w / 2.0, y: y + h / 2.0))
145
- gfx.drawRect(io, c.x - sx / 2.0, c.y - sy / 2.0, sx, sy, color.withAlpha(color.a * alpha))
146
- CircleShape(cx, cy, r, ccolor) =>
147
- cc := m.apply(Vec2(x: cx, y: cy))
148
- gfx.drawCircle(io, cc.x, cc.y, r * m.scaleX(), ccolor.withAlpha(ccolor.a * alpha))
149
- LineShape(x1, y1, x2, y2, th, lcolor) =>
150
- p := m.apply(Vec2(x: x1, y: y1))
151
- q := m.apply(Vec2(x: x2, y: y2))
152
- gfx.drawLine(io, p.x, p.y, q.x, q.y, th * m.scaleX(), lcolor.withAlpha(lcolor.a * alpha))
153
- Sprite(tex, sx0, sy0, sw0, sh0, srcX, srcY, srcW, srcH, tint) =>
154
- sw := sw0 * m.scaleX()
155
- sh := sh0 * m.scaleY()
156
- sc := m.apply(Vec2(x: sx0 + sw0 / 2.0, y: sy0 + sh0 / 2.0))
157
- gfx.drawTextureEx(io, tex.id, srcX, srcY, srcW, srcH, sc.x - sw / 2.0, sc.y - sh / 2.0, sw, sh, m.rotation(), false, tint.withAlpha(tint.a * alpha))
158
- Text(txt, tx, ty, size, tcolor) =>
159
- tp := m.apply(Vec2(x: tx, y: ty))
160
- gfx.drawText(io, txt, tp.x, tp.y, size * m.scaleY(), tcolor.withAlpha(tcolor.a * alpha))
161
- Group(tr, kids) => SceneNode.drawKids(io, kids, m.mul(tr.matrix()), alpha, target)
162
- Filter(effect, child, tex) => SceneNode.drawFiltered(io, effect, child, tex, m, alpha, target)
163
- Clickable(_, _, child) => child.drawWith(io, m, alpha, target)
164
-
165
- fun drawKids(io: Io, kids: List[SceneNode[M]], m: Affine, alpha: Float, target: Texture) = match kids
166
- Nil => 0
167
- Cons(head, tail) =>
168
- head.drawWith(io, m, alpha, target)
169
- SceneNode.drawKids(io, tail, m, alpha, target)
170
-
171
- fun drawFiltered(io: Io, effect: Effect, child: SceneNode[M], tex: Texture, m: Affine, alpha: Float, target: Texture) = match effect
172
- BlendFx(mode) =>
173
- gfx.blendMode(io, mode)
174
- child.drawWith(io, m, alpha, target)
175
- gfx.blendMode(io, Blend.Normal)
176
- _ =>
177
- if Some(b) := child.boundsWith(m)
178
- if tex.id >= 0
179
- w := {Int(b.w) + 1}.min(gfx.textureWidth(io, tex.id))
180
- h := {Int(b.h) + 1}.min(gfx.textureHeight(io, tex.id))
181
- gfx.renderTarget(io, tex.id)
182
- gfx.clear(io, Color.Transparent)
183
- shift := Affine(a: 1.0, b: 0.0, c: 0.0, d: 1.0, e: 0.0 - b.x, f: 0.0 - b.y)
184
- child.drawWith(io, shift.mul(m), 1.0, tex)
185
- gfx.renderTarget(io, target.id)
186
- gfx.drawTextureEx(io, tex.id, 0.0, 0.0, Float(w), Float(h), b.x, b.y, Float(w), Float(h), 0.0, false, effect.tint(alpha))
187
-
188
- # --- bounds ---
189
-
190
- # The bounds of the node drawn under `m`, or None when it has no extent.
191
- fun boundsWith(self, m: Affine) -> Option[Rect] = match self
192
- RectShape(x, y, w, h, _) => Some(Rect.through(x, y, w, h, m))
193
- CircleShape(cx, cy, r, _) => Some(Rect.through(cx - r, cy - r, r * 2.0, r * 2.0, m))
194
- LineShape(x1, y1, x2, y2, th, _) => Some(Rect.throughLine(x1, y1, x2, y2, th, m))
195
- Sprite(_, sx, sy, sw, sh, _, _, _, _, _) => Some(Rect.through(sx, sy, sw, sh, m))
196
- Text(txt, tx, ty, size, _) => Some(Rect.through(tx, ty, size * 0.6 * Float(txt.length()), size, m))
197
- Group(tr, kids) => SceneNode.boundsKids(kids, m.mul(tr.matrix()), None)
198
- Filter(_, child, _) => child.boundsWith(m)
199
- Clickable(_, _, child) => child.boundsWith(m)
200
-
201
- fun boundsKids(kids: List[SceneNode[M]], m: Affine, acc: Option[Rect]) -> Option[Rect] = match kids
202
- Nil => acc
203
- Cons(head, tail) =>
204
- if Some(cr) := head.boundsWith(m)
205
- SceneNode.boundsKids(tail, m, Some(Rect.union(acc, cr)))
206
- else
207
- SceneNode.boundsKids(tail, m, acc)
208
-
209
- # --- hit testing ---
210
-
211
- # The child indices from the node down to the hit leaf, or None on a miss. A leaf
212
- # that is hit is an empty path. (px, py) is in the node's own space.
213
- fun hitWith(self, px: Float, py: Float) -> Option[Slice[Int]] = match self
214
- RectShape(x, y, w, h, _) => hitLeaf(Rect(x: x, y: y, w: w, h: h).contains(px, py))
215
- CircleShape(cx, cy, r, _) => hitLeaf(math.hypot(px - cx, py - cy) <= r)
216
- LineShape(x1, y1, x2, y2, th, _) => hitLeaf(nearLine(x1, y1, x2, y2, th, px, py))
217
- Sprite(_, sx, sy, sw, sh, _, _, _, _, _) => hitLeaf(Rect(x: sx, y: sy, w: sw, h: sh).contains(px, py))
218
- Text(txt, tx, ty, size, _) => hitLeaf(Rect(x: tx, y: ty, w: size * 0.6 * Float(txt.length()), h: size).contains(px, py))
219
- Group(tr, kids) =>
220
- if Some(gi) := tr.matrix().invert()
221
- lp := gi.apply(Vec2(x: px, y: py))
222
- SceneNode.hitKids(kids, 0, lp.x, lp.y)
223
- else
224
- None
225
- Filter(_, child, _) =>
226
- if Some(fp) := child.hitWith(px, py)
227
- Some(hitPrepend(0, fp))
228
- else
229
- None
230
- Clickable(_, _, child) =>
231
- if Some(tp) := child.hitWith(px, py)
232
- Some(hitPrepend(0, tp))
233
- else
234
- None
235
-
236
- # Tries the later children first (they are drawn on top); `i` is the index of
237
- # `kids`' head. The first hit found from the back wins.
238
- fun hitKids(kids: List[SceneNode[M]], i: Int, px: Float, py: Float) -> Option[Slice[Int]] = match kids
239
- Nil => None
240
- Cons(head, tail) =>
241
- if Some(later) := SceneNode.hitKids(tail, i + 1, px, py)
242
- Some(later)
243
- else
244
- if Some(sub) := head.hitWith(px, py)
245
- Some(hitPrepend(i, sub))
246
- else
247
- None
248
-
249
- # The id of the innermost Clickable node whose subtree is hit at (px, py), or None.
250
- # `outer` is the id of the nearest enclosing tag (None at the root).
251
- fun hitIdWith(self, outer: Option[Int], px: Float, py: Float) -> Option[Int] = match self
252
- Group(tr, kids) =>
253
- if Some(gi) := tr.matrix().invert()
254
- lp := gi.apply(Vec2(x: px, y: py))
255
- SceneNode.hitIdKids(kids, outer, lp.x, lp.y)
256
- else
257
- None
258
- Filter(_, child, _) => child.hitIdWith(outer, px, py)
259
- Clickable(id, _, child) => child.hitIdWith(Some(id), px, py)
260
- _ =>
261
- if self.hitWith(px, py).isSome()
262
- outer
263
- else
264
- None
265
-
266
- # Later siblings are drawn on top, so they are tried first.
267
- fun hitIdKids(kids: List[SceneNode[M]], outer: Option[Int], px: Float, py: Float) -> Option[Int] = match kids
268
- Nil => None
269
- Cons(head, tail) =>
270
- if Some(later) := SceneNode.hitIdKids(tail, outer, px, py)
271
- Some(later)
272
- else
273
- head.hitIdWith(outer, px, py)
274
-
275
- # Hit-test helpers that do not mention `M`. They are not static methods of
276
- # `SceneNode[M]` because a call like `SceneNode.leaf(..)` could not tell which `M`.
277
-
278
- fun hitLeaf(hit: Bool) -> Option[Slice[Int]] =
279
- if hit
280
- Some(Slice[Int]())
281
- else
282
- None
283
-
284
- # `i` followed by the path `sub`.
285
- fun hitPrepend(i: Int, sub: Slice[Int]) -> Slice[Int] =
286
- path := [i].toSlice()
287
- for j := range sub.length()
288
- path.push(sub.at(j))
289
- path
290
-
291
- fun nearLine(x1: Float, y1: Float, x2: Float, y2: Float, thickness: Float, px: Float, py: Float) -> Bool =
292
- dx := x2 - x1
293
- dy := y2 - y1
294
- len2 := dx * dx + dy * dy
295
- t := if len2 == 0.0 then 0.0 else {{px - x1} * dx + {py - y1} * dy} / len2
296
- tc := t.max(0.0).min(1.0)
297
- qx := x1 + dx * tc
298
- qy := y1 + dy * tc
299
- math.hypot(px - qx, py - qy) <= thickness.max(1.0) / 2.0
300
-
301
- fun picNear(a: Float, b: Float) -> Bool =
302
- {a - b}.abs() < 1e-6
303
-
304
- fun picRect(x: Float, y: Float, w: Float, h: Float, c: Color) -> SceneNode[Int] =
305
- RectShape(x: x, y: y, w: w, h: h, color: c)
306
-
307
- test "bounds_translate_scale"
308
- g := Group(transform: Compose(first: Translate(dx: 5.0, dy: 5.0), then: Scale(sx: 2.0, sy: 2.0)), children: Cons(head: picRect(0.0, 0.0, 10.0, 10.0, Color.Red), tail: Nil))
309
- r := g.bounds()
310
- assert picNear(r.x, 5.0)
311
- assert picNear(r.y, 5.0)
312
- assert picNear(r.w, 20.0)
313
- assert picNear(r.h, 20.0)
314
-
315
- test "bounds_rotate_quarter"
316
- g := Group(transform: Rotate(radians: 1.5707963267948966), children: Cons(head: picRect(0.0, 0.0, 10.0, 4.0, Color.Red), tail: Nil))
317
- r := g.bounds()
318
- assert picNear(r.x, 0.0 - 4.0)
319
- assert picNear(r.y, 0.0)
320
- assert picNear(r.w, 4.0)
321
- assert picNear(r.h, 10.0)
322
-
323
- test "hit_path_nested"
324
- inner := Group(transform: Translate(dx: 10.0, dy: 0.0), children: Cons(head: picRect(0.0, 0.0, 10.0, 10.0, Color.Blue), tail: Nil))
325
- g := Group(transform: Identity, children: Cons(head: picRect(0.0, 0.0, 10.0, 10.0, Color.Red), tail: Cons(head: inner, tail: Nil)))
326
- p := g.hitPath(15.0, 5.0)
327
- assert p.length() == 2
328
- assert p.at(0) == 1
329
- assert p.at(1) == 0
330
- q := g.hitPath(5.0, 5.0)
331
- assert q.length() == 1
332
- assert q.at(0) == 0
333
-
334
- test "hit_path_last_child_wins"
335
- g := Group(transform: Identity, children: Cons(head: picRect(0.0, 0.0, 10.0, 10.0, Color.Red), tail: Cons(head: picRect(0.0, 0.0, 10.0, 10.0, Color.Blue), tail: Nil)))
336
- p := g.hitPath(5.0, 5.0)
337
- assert p.length() == 1
338
- assert p.at(0) == 1
339
-
340
- test "hit_miss_empty"
341
- g := Group(transform: Identity, children: Cons(head: picRect(0.0, 0.0, 10.0, 10.0, Color.Red), tail: Nil))
342
- assert g.hitPath(50.0, 50.0).length() == 0
343
-
344
- test "filter_bounds_is_child_bounds"
345
- g := Filter(effect: Alpha(alpha: 0.5), child: picRect(1.0, 2.0, 10.0, 4.0, Color.Red), target: Texture(id: 0 - 1))
346
- r := g.bounds()
347
- assert picNear(r.x, 1.0)
348
- assert picNear(r.y, 2.0)
349
- assert picNear(r.w, 10.0)
350
- assert picNear(r.h, 4.0)
351
-
352
- test "tagged_bounds_and_path"
353
- g := Group(transform: Identity, children: Cons(head: Clickable(id: 7, msg: 7 * 10, child: picRect(1.0, 2.0, 10.0, 4.0, Color.Red)), tail: Nil))
354
- r := g.bounds()
355
- assert picNear(r.x, 1.0)
356
- assert picNear(r.w, 10.0)
357
- p := g.hitPath(5.0, 3.0)
358
- assert p.length() == 2
359
- assert p.at(0) == 0
360
- assert p.at(1) == 0
361
-
362
- test "hit_id_innermost_and_topmost"
363
- inner := Clickable(id: 2, msg: 2 * 10, child: picRect(0.0, 0.0, 10.0, 10.0, Color.Blue))
364
- outer := Clickable(id: 1, msg: 1 * 10, child: Group(transform: Identity, children: Cons(head: picRect(0.0, 0.0, 20.0, 20.0, Color.Red), tail: Cons(head: inner, tail: Nil))))
365
- top := Clickable(id: 3, msg: 3 * 10, child: picRect(15.0, 15.0, 10.0, 10.0, Color.Red))
366
- g := Group(transform: Translate(dx: 1.0, dy: 0.0), children: Cons(head: outer, tail: Cons(head: top, tail: Nil)))
367
- a := g.hitId(6.0, 5.0)
368
- if Some(va) := a
369
- assert va == 2
370
- else
371
- assert false
372
- b := g.hitId(19.0, 5.0)
373
- if Some(vb) := b
374
- assert vb == 1
375
- else
376
- assert false
377
- c := g.hitId(17.0, 17.0)
378
- if Some(vc) := c
379
- assert vc == 3
380
- else
381
- assert false
382
- assert g.hitId(100.0, 100.0).isNone()
383
-
384
- test "msg_of_finds_the_clickable_message"
385
- g := Group(transform: Identity, children: [picRect(0.0, 0.0, 1.0, 1.0, Color.Red), Clickable(id: 4, msg: 40, child: picRect(0.0, 0.0, 1.0, 1.0, Color.Red))])
386
- assert g.msgOf(4).unwrapOr(-1) == 40
387
- assert g.msgOf(5).isNone()
std/game/scene/Actor.plum ADDED
@@ -0,0 +1,157 @@
1
+ module std
2
+
3
+ import std/Int
4
+ import std/Float
5
+ import std/Bool
6
+ import std/Str
7
+ import std/math
8
+ import std/Io
9
+ import std/game/Vec2
10
+ import std/game/Affine
11
+ import std/game/Color
12
+ import std/game/gfx
13
+ import std/game/scene/Place
14
+ import std/game/scene/Ctx
15
+
16
+ # One actor of a scene tree (`FRoseTree[Actor[M]]` in a `SceneTree[M]`). Each kind of
17
+ # actor is its own type, with only its own fields, that `is Actor[M]`; `M` is the game's
18
+ # message type (what `ctx.send` takes). A kind must say which actor it is (`key`, the id
19
+ # the tree finds it by) and where it is in its parent (`place`); everything else has a
20
+ # default:
21
+ #
22
+ # step the next version of it, once a tick (`ctx` is its parent's context)
23
+ # paint draws it, seen through `m` (its own coordinates to the tree's) at `alpha`
24
+ # (the accumulated alpha, its own `opacity` included)
25
+ # hit whether `p`, in its own coordinates, is on it
26
+ # shown false: it and its subtree are not drawn or hit (but still stepped)
27
+ # gone true: it is dropped with its subtree (returned from `step`, in the same step)
28
+ # opacity its own alpha, multiplied down the tree
29
+ #
30
+ # struct Walker(id: Int, x: Float, y: Float, speed: Float) is Actor[Msg] =
31
+ # fun key(self) -> Int = self.id
32
+ # fun place(self) -> Place = place.at(self.x, self.y)
33
+ # fun step(self, ctx: Ctx[Msg], dt: Float) -> Walker =
34
+ # Walker(..self, x: self.x + self.speed * dt)
35
+ #
36
+ # An actor is a value: a step returns the next one, usually a spread (`Walker(..self,
37
+ # ..)`), which the compiler writes in place when nothing else holds the old one. Keep the
38
+ # position in plain fields and make the `Place` in `place`, as above: a `Place` field
39
+ # moved by a nested spread (`at: self.at.moveTo(..)`) costs a step about 1.7 times as
40
+ # much. The std kinds below, `Group` and `Box` (and std/game/ui's `Button` and `Label`),
41
+ # are generic in `M` so any game's tree takes them.
42
+ trait Actor[M] =
43
+ fun key(self) -> Int
44
+
45
+ fun place(self) -> Place
46
+
47
+ fun step(self, ctx: Ctx[M], dt: Float) -> Self = self
48
+
49
+ fun paint(self, io: Io, m: Affine, alpha: Float) = Unit
50
+
51
+ fun hit(self, p: Vec2) -> Bool = false
52
+
53
+ fun shown(self) -> Bool = true
54
+
55
+ fun gone(self) -> Bool = false
56
+
57
+ fun opacity(self) -> Float = 1.0
58
+
59
+ # An actor that paints nothing and is never hit: a parent for others (a layer).
60
+ struct Group[M](id: Int, x: Float, y: Float) is Actor[M] =
61
+ fun key(self) -> Int = self.id
62
+
63
+ fun place(self) -> Place = place.at(self.x, self.y)
64
+
65
+ # A filled `w` by `h` box in `color`, with its top-left at (x, y); hit inside it. Its
66
+ # opacity is its colour's alpha.
67
+ struct Box[M](id: Int, x: Float, y: Float, w: Float, h: Float, color: Color) is Actor[M] =
68
+ fun key(self) -> Int = self.id
69
+
70
+ fun place(self) -> Place = place.at(self.x, self.y)
71
+
72
+ fun opacity(self) -> Float = self.color.a
73
+
74
+ fun paint(self, io: Io, m: Affine, alpha: Float) =
75
+ boxPaint(io, m, alpha, self.w, self.h, self.color.withAlpha(1.0))
76
+
77
+ fun hit(self, p: Vec2) -> Bool = boxHit(self.w, self.h, p)
78
+
79
+ # Painting and hit testing for kinds: each draws in the actor's own coordinates seen
80
+ # through `m`, in `c` at `c.a * alpha`.
81
+
82
+ # Whether `p` is inside a `w` by `h` box at (0, 0); a box with no size is never hit.
83
+ fun boxHit(w: Float, h: Float, p: Vec2) -> Bool =
84
+ w > 0.0 && h > 0.0 && p.x >= 0.0 && p.x <= w && p.y >= 0.0 && p.y <= h
85
+
86
+ # A `w` by `h` box at (0, 0).
87
+ fun boxPaint(io: Io, m: Affine, alpha: Float, w: Float, h: Float, c: Color) =
88
+ rectPaint(io, m, alpha, 0.0, 0.0, w, h, c)
89
+
90
+ # A `w` by `h` box with its top-left at (x, y).
91
+ fun rectPaint(io: Io, m: Affine, alpha: Float, x: Float, y: Float, w: Float, h: Float, c: Color) =
92
+ sx := w * m.scaleX()
93
+ sy := h * m.scaleY()
94
+ p := m.apply(Vec2(x: x + w / 2.0, y: y + h / 2.0))
95
+ gfx.drawRect(io, p.x - sx / 2.0, p.y - sy / 2.0, sx, sy, c.withAlpha(c.a * alpha))
96
+
97
+ # Whether `p` is within `r` of (cx, cy).
98
+ fun circleHit(cx: Float, cy: Float, r: Float, p: Vec2) -> Bool =
99
+ math.hypot(p.x - cx, p.y - cy) <= r
100
+
101
+ # A circle of radius `r` about (cx, cy).
102
+ fun circlePaint(io: Io, m: Affine, alpha: Float, cx: Float, cy: Float, r: Float, c: Color) =
103
+ p := m.apply(Vec2(x: cx, y: cy))
104
+ gfx.drawCircle(io, p.x, p.y, r * m.scaleX(), c.withAlpha(c.a * alpha))
105
+
106
+ # Whether `p` is on the line from (x1, y1) to (x2, y2), `thickness` wide (at least 1).
107
+ fun lineHit(x1: Float, y1: Float, x2: Float, y2: Float, thickness: Float, p: Vec2) -> Bool =
108
+ dx := x2 - x1
109
+ dy := y2 - y1
110
+ len2 := dx * dx + dy * dy
111
+ t := if len2 == 0.0 then 0.0 else {{p.x - x1} * dx + {p.y - y1} * dy} / len2
112
+ tc := t.max(0.0).min(1.0)
113
+ math.hypot(p.x - {x1 + dx * tc}, p.y - {y1 + dy * tc}) <= thickness.max(1.0) / 2.0
114
+
115
+ # A line from (x1, y1) to (x2, y2), `thickness` wide.
116
+ fun linePaint(io: Io, m: Affine, alpha: Float, x1: Float, y1: Float, x2: Float, y2: Float, thickness: Float, c: Color) =
117
+ p := m.apply(Vec2(x: x1, y: y1))
118
+ q := m.apply(Vec2(x: x2, y: y2))
119
+ gfx.drawLine(io, p.x, p.y, q.x, q.y, thickness * m.scaleX(), c.withAlpha(c.a * alpha))
120
+
121
+ # The region (srcX, srcY, srcW, srcH) of `tex` as a `w` by `h` sprite with its top-left at
122
+ # (x, y), tinted `tint`.
123
+ fun spritePaint(io: Io, m: Affine, alpha: Float, tex: Texture, x: Float, y: Float, w: Float, h: Float, srcX: Float, srcY: Float, srcW: Float, srcH: Float, tint: Color) =
124
+ sw := w * m.scaleX()
125
+ sh := h * m.scaleY()
126
+ c := m.apply(Vec2(x: x + w / 2.0, y: y + h / 2.0))
127
+ gfx.drawTextureEx(io, tex.id, srcX, srcY, srcW, srcH, c.x - sw / 2.0, c.y - sh / 2.0, sw, sh, m.rotation(), false, tint.withAlpha(tint.a * alpha))
128
+
129
+ # `text` with its top-left at (x, y), `size` high.
130
+ fun textPaint(io: Io, m: Affine, alpha: Float, text: Str, x: Float, y: Float, size: Float, c: Color) =
131
+ p := m.apply(Vec2(x: x, y: y))
132
+ gfx.drawText(io, text, p.x, p.y, size * m.scaleY(), c.withAlpha(c.a * alpha))
133
+
134
+ test "a box is hit inside its size, a group never"
135
+ b: Actor[Int] := Box(id: 7, x: 1.0, y: 2.0, w: 4.0, h: 3.0, color: Color.Red.withAlpha(0.25))
136
+ assert b.key() == 7
137
+ assert b.place().x == 1.0
138
+ assert b.hit(Vec2(x: 2.0, y: 1.0))
139
+ assert !b.hit(Vec2(x: 5.0, y: 1.0))
140
+ assert b.opacity() == 0.25
141
+ assert b.shown() && !b.gone()
142
+ g: Actor[Int] := Group(id: 1, x: 0.0, y: 0.0)
143
+ assert !g.hit(Vec2(x: 0.0, y: 0.0))
144
+ assert g.opacity() == 1.0
145
+ assert !boxHit(0.0, 3.0, Vec2(x: 0.0, y: 0.0))
146
+
147
+ test "circles and lines are hit within their size"
148
+ assert circleHit(1.0, 1.0, 2.0, Vec2(x: 2.0, y: 2.0))
149
+ assert !circleHit(1.0, 1.0, 1.0, Vec2(x: 2.0, y: 2.0))
150
+ assert lineHit(0.0, 0.0, 10.0, 0.0, 2.0, Vec2(x: 5.0, y: 0.9))
151
+ assert !lineHit(0.0, 0.0, 10.0, 0.0, 2.0, Vec2(x: 5.0, y: 1.1))
152
+ assert !lineHit(0.0, 0.0, 10.0, 0.0, 2.0, Vec2(x: 11.5, y: 0.0))
153
+
154
+ test "the default step returns the actor as it was"
155
+ b: Actor[Int] := Box(id: 3, x: 1.0, y: 1.0, w: 4.0, h: 2.0, color: Color.Blue)
156
+ assert b.step(Ctx[Int](), 1.0) == b
157
+ assert b.step(Ctx[Int](), 1.0).place().x == 1.0
std/game/scene/Ctx.plum ADDED
@@ -0,0 +1,101 @@
1
+ module std
2
+
3
+ import std/Int
4
+ import std/Float
5
+ import std/Str
6
+ import std/List
7
+ import std/Slice
8
+ import std/game/Affine
9
+ import std/collections/functional/FRoseTree
10
+ import std/game/scene/Actor
11
+
12
+ # What a step changes besides the actors. `Spawn` and `Kill` are applied once the step's
13
+ # walk is over (`SceneTree.apply`): a new node under the actor `parent` (by id), on top
14
+ # of its children, or the end of the actor `id` and its subtree. `Send` is a message of
15
+ # the game's type `M` for the game: the tree leaves it in `ctx.out`, in order, for the
16
+ # game to take (`ctx.takeSends()`).
17
+ enum Cmd[M] =
18
+ | Spawn(parent: Int, node: FRoseTree[Actor[M]])
19
+ | Kill(id: Int)
20
+ | Send(msg: M)
21
+
22
+ fun isSend(self) -> Bool = match self
23
+ Send(_) => true
24
+ _ => false
25
+
26
+ # What the step hands each actor in place of a parent link: the context of the actor's
27
+ # parent. `up` is the parent's world transform and `alpha` its accumulated opacity, so an
28
+ # actor's own world transform is `ctx.worldOf(self.place().local())` and its alpha
29
+ # `ctx.alphaOf(self.opacity())`, computed only when it asks. `out` takes the commands an
30
+ # actor pushes for after the walk (`ctx.out.push(Spawn(..))`, `ctx.out.push(Kill(..))`,
31
+ # `ctx.send(msg)`).
32
+ #
33
+ # fun step(self, ctx: Ctx[Msg], dt: Float) -> Gun =
34
+ # ctx.out.push(Spawn(parent: 0, node: FRoseTree.leaf(Bullet(id: self.next, x: self.x, y: self.y))))
35
+ # Gun(..self, next: self.next + 1)
36
+ #
37
+ # A context is a value. The walk makes one for each parent with children (`under`), with
38
+ # one multiply, and hands it to every child.
39
+ struct Ctx[M](up: Affine, alpha: Float, out: Slice[Cmd[M]]) =
40
+
41
+ # The context above a tree's root: the identity transform, full opacity, no commands.
42
+ fun init() -> Ctx[M] =
43
+ Ctx(up: Affine.Identity, alpha: 1.0, out: Slice[Cmd[M]]())
44
+
45
+ # The world transform of a child whose own transform is `local`.
46
+ fun worldOf(self, local: Affine) -> Affine = self.up.mul(local)
47
+
48
+ # The accumulated alpha of a child whose own is `a`.
49
+ fun alphaOf(self, a: Float) -> Float = self.alpha * a
50
+
51
+ # The context for the children of a child with the transform `local` and opacity `a`:
52
+ # the same commands, the child's world transform above them.
53
+ fun under(self, local: Affine, a: Float) -> Ctx[M] =
54
+ Ctx(up: self.up.mul(local), alpha: self.alpha * a, out: self.out)
55
+
56
+ # Sends `msg` to the game after the step.
57
+ fun send(self, msg: M) = self.out.push(Send(msg: msg))
58
+
59
+ # The messages sent so far, oldest first, taken out of `out` (its other commands stay,
60
+ # in order).
61
+ fun takeSends(self) -> List[M] =
62
+ if self.out.length() == 0
63
+ Nil
64
+ else
65
+ msgs := Slice[M]()
66
+ for c := range self.out
67
+ if Send(m) := c
68
+ msgs.push(m)
69
+ self.keepOnly(false)
70
+ List.fromSlice(msgs)
71
+
72
+ # Keeps in `out` only its sends (`sends` true) or only its other commands, in order.
73
+ fun keepOnly(self, sends: Bool) =
74
+ kept := Slice[Cmd[M]]()
75
+ for c := range self.out
76
+ if c.isSend() == sends
77
+ kept.push(c)
78
+ self.out.clear()
79
+ self.out.add(kept)
80
+
81
+ test "under multiplies the child's transform into the parent's"
82
+ c := Ctx[Int]()
83
+ m := Affine(a: 2.0, b: 0.0, c: 0.0, d: 2.0, e: 1.0, f: 0.0)
84
+ u := c.under(m, 0.5).under(m, 0.5)
85
+ assert u.up.a == 4.0 && u.up.e == 3.0
86
+ assert u.alpha == 0.25
87
+ assert u.worldOf(m).e == 7.0
88
+ u.out.push(Kill(id: 3))
89
+ assert c.out.length() == 1
90
+
91
+ test "sends are taken out in order and the other commands stay"
92
+ c := Ctx[Str]()
93
+ c.send("a")
94
+ c.out.push(Kill(id: 3))
95
+ c.under(Affine.Identity, 1.0).send("b")
96
+ c.out.push(Kill(id: 4))
97
+ msgs := c.takeSends()
98
+ assert msgs.length() == 2 && msgs.get(0).unwrap() == "a" && msgs.get(1).unwrap() == "b"
99
+ assert c.out.length() == 2
100
+ assert c.takeSends().isEmpty()
101
+ assert c.out.length() == 2
std/{game_enum_tree → game/scene}/Place.plum RENAMED
File without changes
std/{game_enum_tree/EStage.plum → game/scene/SceneTree.plum} RENAMED
@@ -17,30 +17,29 @@ import std/game/Affine
17
17
  import std/game/Color
18
18
  import std/game/gfx
19
19
  import std/collections/functional/FRoseTree
20
- import std/game_enum_tree/Actor
20
+ import std/game/scene/Actor
21
- import std/game_enum_tree/Place
21
+ import std/game/scene/Place
22
- import std/game_enum_tree/ECtx
22
+ import std/game/scene/Ctx
23
-
23
+
24
- # A persistent scene tree: master's std/game_enum_tree `EStage`, over actors of any kind
24
+ # The game's scene: a persistent tree of actors of any kind that `is Actor[M]` (see
25
- # that `is Actor[M]` (see std/game_enum_tree/Actor), `M` being the game's message type.
25
+ # std/game/scene/Actor), `M` being the game's message type. The root is an
26
- # The root is an `FRoseTree[Actor[M]]`, a left-child, right-sibling tree of actors, and a
26
+ # `FRoseTree[Actor[M]]`, a left-child, right-sibling tree of actors, and a scene tree is a
27
- # stage is a value: every change returns a new stage. While something holds the old stage
27
+ # value: every change returns a new tree. While something holds the old tree it stays as
28
- # it stays as it was, a snapshot; when nothing does, the compiler reuses its cells for the
28
+ # it was, a snapshot; when nothing does, the compiler reuses its cells for the new one.
29
- # new one.
30
29
  #
31
- # s := EStage.of(Group(id: 0, at: place.at(0.0, 0.0))) # a root group, id 0
30
+ # s: SceneTree[Msg] := SceneTree.of(Group(id: 0, x: 0.0, y: 0.0)) # a root group, id 0
32
- # s2 := s.add(0, FRoseTree.leaf(Box(id: 1, at: place.at(10.0, 5.0), w: 40.0, h: 20.0, color: Color.Red)))
31
+ # s2 := s.add(0, FRoseTree.leaf(Box(id: 1, x: 10.0, y: 5.0, w: 40.0, h: 20.0, color: Color.Red)))
33
- # ctx := ECtx[Msg]()
32
+ # ctx := Ctx[Msg]()
34
33
  # s3 := s2.step(ctx, dt) # every actor's next version, then the commands in ctx.out
35
34
  # s3.draw(io)
36
35
  #
37
- # The stage uses only what the trait gives: it finds actors by `key()` (`add(parent, n)`,
36
+ # The tree uses only what the trait gives: it finds actors by `key()` (`add(parent, n)`,
38
- # `update(id, f)`, `find(id)`, `kill(id)`, `ESpawn(parent, n)`, `EKill(id)`, each by a
37
+ # `update(id, f)`, `find(id)`, `kill(id)`, `Spawn(parent, n)`, `Kill(id)`, each by a
39
38
  # search down from the root, O(n); `step` applies all of a tick's commands in its own
40
39
  # walk), drops a `gone()` actor with its subtree, skips one that is not `shown()` (or is
41
40
  # gone) with its subtree when it draws and hit tests, and multiplies the transforms
42
41
  # (`place().local()`) and alphas (`opacity()`) down the tree. Each actor's own type gives
43
- # the behaviour: `step`, `paint` and `hit`. The stage never needs an actor's own type;
42
+ # the behaviour: `step`, `paint` and `hit`. The tree never needs an actor's own type;
44
43
  # game code that does uses `updateAs[T]` and `findAs[T]`, which act only on an actor of
45
44
  # the type `T`.
46
45
  #
@@ -48,23 +47,23 @@ import std/game_enum_tree/ECtx
48
47
  # first to last. Hit testing goes the other way, topmost first: children before their
49
48
  # parent, later siblings before earlier ones.
50
49
  #
51
- # Unlike master's, the walks (`step`, `apply`) rebuild every link node they pass instead
50
+ # The walks (`step`, `apply`) rebuild every link node they pass instead of returning an
52
- # of returning an unchanged chain as it was: sharing needs the old node after the match,
51
+ # unchanged chain as it was: sharing needs the old node after the match, and that use
53
- # and that use would stop the compiler from writing the new node into the old one's cell.
52
+ # would stop the compiler from writing the new node into the old one's cell. A step over
54
- # A step over a stage nothing else holds therefore allocates no link nodes at all, and
53
+ # a tree nothing else holds therefore allocates no link nodes at all, and one over a kept
55
- # one over a kept stage copies all of them.
54
+ # tree copies all of them.
56
- struct EStage[M](root: FRoseTree[Actor[M]], camX: Float, camY: Float, camScale: Float) =
55
+ struct SceneTree[M](root: FRoseTree[Actor[M]], camX: Float, camY: Float, camScale: Float) =
57
56
 
58
- # A stage whose root is the actor `top`.
57
+ # A tree whose root is the actor `top`.
59
- fun of(top: Actor[M]) -> EStage[M] =
58
+ fun of(top: Actor[M]) -> SceneTree[M] =
60
- EStage(root: FRoseTree.leaf(top), camX: 0.0, camY: 0.0, camScale: 1.0)
59
+ SceneTree(root: FRoseTree.leaf(top), camX: 0.0, camY: 0.0, camScale: 1.0)
61
60
 
62
61
  # The same camera over another tree.
63
- fun withRoot(self, r: FRoseTree[Actor[M]]) -> EStage[M] = EStage(..self, root: r)
62
+ fun withRoot(self, r: FRoseTree[Actor[M]]) -> SceneTree[M] = SceneTree(..self, root: r)
64
63
 
65
- fun pan(self, x: Float, y: Float) -> EStage[M] = EStage(..self, camX: x, camY: y)
64
+ fun pan(self, x: Float, y: Float) -> SceneTree[M] = SceneTree(..self, camX: x, camY: y)
66
65
 
67
- fun zoom(self, s: Float) -> EStage[M] = EStage(..self, camScale: s)
66
+ fun zoom(self, s: Float) -> SceneTree[M] = SceneTree(..self, camScale: s)
68
67
 
69
68
  # The number of actors.
70
69
  fun count(self) -> Int = self.root.count()
@@ -73,94 +72,94 @@ struct EStage[M](root: FRoseTree[Actor[M]], camX: Float, camY: Float, camScale:
73
72
  fun find(self, id: Int) -> Option[Actor[M]] = self.root.find(|a| a.key() == id)
74
73
 
75
74
  # The actor with this id as its own type `T`, if there is one and it is a `T`:
76
- # `stage.findAs[Ship](ShipId)`.
75
+ # `tree.findAs[Ship](ShipId)`.
77
76
  fun findAs[T](self, id: Int) -> Option[T] = match self.find(id)
78
77
  Some(T as t) => Some(t)
79
78
  _ => None
80
79
 
81
- # The stage with `n` added as the last child of the actor `parent`; unchanged if there
80
+ # The tree with `n` added as the last child of the actor `parent`; unchanged if there
82
81
  # is no such actor.
83
- fun add(self, parent: Int, n: FRoseTree[Actor[M]]) -> EStage[M] =
82
+ fun add(self, parent: Int, n: FRoseTree[Actor[M]]) -> SceneTree[M] =
84
83
  self.withRoot(self.root.replace(|a| a.key() == parent, |p| p.addChild(n)))
85
84
 
86
- # The stage with the actor `id` replaced by `f(actor)`; everything off its path is
85
+ # The tree with the actor `id` replaced by `f(actor)`; everything off its path is
87
86
  # shared.
88
- fun update(self, id: Int, f: fn(Actor[M]) -> Actor[M]) -> EStage[M] =
87
+ fun update(self, id: Int, f: fn(Actor[M]) -> Actor[M]) -> SceneTree[M] =
89
88
  self.withRoot(self.root.update(|a| a.key() == id, f))
90
89
 
91
- # The stage with the actor `id` replaced by `f(actor)` if it is a `T`, and unchanged if
90
+ # The tree with the actor `id` replaced by `f(actor)` if it is a `T`, and unchanged if
92
- # it is not: `stage.updateAs[Orb](id, |o| Orb(..o, vx: 0.0))`.
91
+ # it is not: `tree.updateAs[Orb](id, |o| Orb(..o, vx: 0.0))`.
93
- fun updateAs[T](self, id: Int, f: fn(T) -> T) -> EStage[M] =
92
+ fun updateAs[T](self, id: Int, f: fn(T) -> T) -> SceneTree[M] =
94
93
  self.withRoot(self.root.update(|a| a.key() == id, |a| match a
95
94
  T as t =>
96
95
  b: Actor[M] := f(t)
97
96
  b
98
97
  _ => a))
99
98
 
100
- # The stage without the actor `id` and its subtree.
99
+ # The tree without the actor `id` and its subtree.
101
- fun kill(self, id: Int) -> EStage[M] = self.withRoot(self.root.filter(|a| a.key() != id))
100
+ fun kill(self, id: Int) -> SceneTree[M] = self.withRoot(self.root.filter(|a| a.key() != id))
102
101
 
103
102
  # The next tick: every live actor's `step`, parents before children, siblings in
104
103
  # order, each given its parent's context under `ctx` (the context above the root). An
105
- # actor whose step returns it gone is dropped with its subtree. Every `ESpawn` and
104
+ # actor whose step returns it gone is dropped with its subtree. Every `Spawn` and
106
- # `EKill` in `ctx.out` takes effect after the step, as `apply` would apply it. Those
105
+ # `Kill` in `ctx.out` takes effect after the step, as `apply` would apply it. Those
107
106
  # pushed before the step are applied in its own walk: an actor killed this way is
108
107
  # dropped without its step, and a spawned node goes on top of its parent's children
109
108
  # unstepped. Those pushed during the step (by the actors) are applied by `apply` once
110
109
  # the walk is over, as a second batch. Hidden actors are stepped too. `ctx.out` is left
111
- # with only the `ESend`s, those pushed before the step first, in order, for the game to
110
+ # with only the `Send`s, those pushed before the step first, in order, for the game to
112
111
  # take (`ctx.takeSends()`).
113
- fun step(self, ctx: ECtx[M], dt: Float) -> EStage[M] =
112
+ fun step(self, ctx: Ctx[M], dt: Float) -> SceneTree[M] =
114
- w := EWalk.of(ctx.out)
113
+ w := TreeWalk.of(ctx.out)
115
- ectx.ecmdKeepOnly(ctx.out, true)
114
+ ctx.keepOnly(true)
116
115
  empty: FRoseTree[Actor[M]] := FRoseEmpty
117
- r := estep(self.root, ctx, dt, w, empty)
116
+ r := stepChain(self.root, ctx, dt, w, empty)
118
- s := EStage(..self, root: r).apply(ctx.out)
117
+ s := SceneTree(..self, root: r).apply(ctx.out)
119
- ectx.ecmdKeepOnly(ctx.out, true)
118
+ ctx.keepOnly(true)
120
119
  s
121
120
 
122
- # The stage with the commands applied, in one pass over the tree: every `EKill` actor
121
+ # The tree with the commands applied, in one pass over the tree: every `Kill` actor
123
- # goes with its subtree, and every `ESpawn` node goes on top of its parent's children,
122
+ # goes with its subtree, and every `Spawn` node goes on top of its parent's children,
124
- # in the order pushed. A spawn whose parent is not on the stage, or is killed by the
123
+ # in the order pushed. A spawn whose parent is not on the tree, or is killed by the
125
- # same batch, is dropped. `ESend`s are not the stage's, and are skipped.
124
+ # same batch, is dropped. `Send`s are not the tree's, and are skipped.
126
- fun apply(self, cmds: Slice[ECmd[M]]) -> EStage[M] =
125
+ fun apply(self, cmds: Slice[Cmd[M]]) -> SceneTree[M] =
127
126
  if cmds.length() == 0
128
127
  self
129
128
  else
130
- w := EWalk.of(cmds)
129
+ w := TreeWalk.of(cmds)
131
130
  if !w.hasKills && !w.hasSpawns
132
131
  self
133
132
  else
134
133
  empty: FRoseTree[Actor[M]] := FRoseEmpty
135
- EStage(..self, root: eapply(self.root, w, empty))
134
+ SceneTree(..self, root: applyChain(self.root, w, empty))
136
135
 
137
- # What `draw` would draw, in order: each shown actor with its stage transform and alpha,
136
+ # What `draw` would draw, in order: each shown actor with its tree transform and alpha,
138
137
  # a parent before its children, siblings first to last.
139
- fun flatten(self) -> Slice[EDrawn[M]] =
138
+ fun flatten(self) -> Slice[Drawn[M]] =
140
- out := Slice[EDrawn[M]]()
139
+ out := Slice[Drawn[M]]()
141
- ecollect(self.root, Affine.Identity, 1.0, out)
140
+ collectChain(self.root, Affine.Identity, 1.0, out)
142
141
  out
143
142
 
144
- # The topmost shown actor at a stage point that says it is hit there (`hit(p)`, with
143
+ # The topmost shown actor at a tree point that says it is hit there (`hit(p)`, with
145
144
  # `p` in the actor's own coordinates).
146
- fun hit(self, x: Float, y: Float) -> Option[Actor[M]] = ehit(self.root, Vec2(x: x, y: y))
145
+ fun hit(self, x: Float, y: Float) -> Option[Actor[M]] = hitChain(self.root, Vec2(x: x, y: y))
147
146
 
148
147
  # The id of that actor, if any.
149
148
  fun hitId(self, x: Float, y: Float) -> Option[Int] = self.hit(x, y).map(|a| a.key())
150
149
 
151
150
  fun draw(self, io: Io) =
152
151
  gfx.setCamera(io, self.camX, self.camY, self.camScale)
153
- edraw(self.root, io, Affine.Identity, 1.0)
152
+ drawChain(self.root, io, Affine.Identity, 1.0)
154
153
  gfx.resetCamera(io)
155
154
 
156
- # One entry of the draw list: a shown actor, its stage transform and its alpha.
155
+ # One entry of the draw list: a shown actor, its tree transform and its alpha.
157
- struct EDrawn[M](actor: Actor[M], m: Affine, alpha: Float)
156
+ struct Drawn[M](actor: Actor[M], m: Affine, alpha: Float)
158
157
 
159
158
  # The largest id range the bitsets cover is [0, 2^22).
160
159
  BitsCap = 4194304
161
160
 
162
161
  # The largest id seen in a batch, and whether all of them fit the bitsets.
163
- struct EScan(mut top: Int, mut ok: Bool) =
162
+ struct TreeScan(mut top: Int, mut ok: Bool) =
164
163
  fun see(self, id: Int) =
165
164
  if id < 0 || id >= BitsCap
166
165
  self.ok = false
@@ -172,22 +171,22 @@ struct EScan(mut top: Int, mut ok: Bool) =
172
171
  # and the map it keeps a bitset of each (one bit per id up to the batch's largest): most
173
172
  # answers are a shift and a mask, and only an actor with spawns does a hash lookup. Ids
174
173
  # below 0 or from 2^22 up make that batch use the set and the map alone.
175
- struct EWalk[M](
174
+ struct TreeWalk[M](
176
175
  kills: Set[Int], spawns: Map[Int, Slice[FRoseTree[Actor[M]]]],
177
176
  hasKills: Bool, hasSpawns: Bool,
178
177
  bitsOk: Bool, killBits: Array[Int], spawnBits: Array[Int]) =
179
178
 
180
- fun of(cmds: Slice[ECmd[M]]) -> EWalk[M] =
179
+ fun of(cmds: Slice[Cmd[M]]) -> TreeWalk[M] =
181
180
  kills := Set[Int]()
182
181
  spawns: Map[Int, Slice[FRoseTree[Actor[M]]]] := Map.empty()
183
- scan := EScan(top: 0, ok: true)
182
+ scan := TreeScan(top: 0, ok: true)
184
183
  for c := range cmds
185
184
  match c
186
- EKill(id) =>
185
+ Kill(id) =>
187
186
  kills.add(id)
188
187
  scan.see(id)
189
- ESend(_) => Unit
188
+ Send(_) => Unit
190
- ESpawn(parent, node) =>
189
+ Spawn(parent, node) =>
191
190
  scan.see(parent)
192
191
  if Some(xs) := spawns.get(parent)
193
192
  xs.push(node)
@@ -201,10 +200,10 @@ struct EWalk[M](
201
200
  if words > 0
202
201
  for c := range cmds
203
202
  match c
204
- EKill(id) => ewalkSet(killBits, id)
203
+ Kill(id) => bitSet(killBits, id)
205
- ESpawn(parent, _) => ewalkSet(spawnBits, parent)
204
+ Spawn(parent, _) => bitSet(spawnBits, parent)
206
- ESend(_) => Unit
205
+ Send(_) => Unit
207
- EWalk(
206
+ TreeWalk(
208
207
  kills: kills, spawns: spawns,
209
208
  hasKills: kills.length() > 0, hasSpawns: spawns.length() > 0,
210
209
  bitsOk: scan.ok, killBits: killBits, spawnBits: spawnBits)
@@ -214,34 +213,34 @@ struct EWalk[M](
214
213
  if !self.hasKills
215
214
  false
216
215
  else if self.bitsOk
217
- ewalkHas(self.killBits, id)
216
+ bitHas(self.killBits, id)
218
217
  else
219
218
  self.kills.has(id)
220
219
 
221
220
  # The nodes to add under the actor `id`, as a chain in the order pushed (empty if none).
222
221
  fun spawnsUnder(self, id: Int) -> FRoseTree[Actor[M]] =
223
- if !self.hasSpawns || {self.bitsOk && !ewalkHas(self.spawnBits, id)}
222
+ if !self.hasSpawns || {self.bitsOk && !bitHas(self.spawnBits, id)}
224
223
  FRoseEmpty
225
224
  else
226
225
  match self.spawns.get(id)
227
- Some(xs) => echainFrom(xs, 0)
226
+ Some(xs) => chainFrom(xs, 0)
228
227
  None => FRoseEmpty
229
228
 
230
229
  # The nodes of `ns` from index `i` on (each with its subtree, not its siblings), linked
231
230
  # into one chain, in order: `FRoseTree.chainOf` for a `Slice`.
232
- fun echainFrom[T](ns: Slice[FRoseTree[T]], i: Int) -> FRoseTree[T] =
231
+ fun chainFrom[T](ns: Slice[FRoseTree[T]], i: Int) -> FRoseTree[T] =
233
232
  if i >= ns.length()
234
233
  FRoseEmpty
235
234
  else
236
235
  match ns.at(i)
237
- FRoseEmpty => echainFrom(ns, i + 1)
236
+ FRoseEmpty => chainFrom(ns, i + 1)
238
- FRoseNode(v, k, _) => FRoseNode(value: v, firstChild: k, nextSibling: echainFrom(ns, i + 1))
237
+ FRoseNode(v, k, _) => FRoseNode(value: v, firstChild: k, nextSibling: chainFrom(ns, i + 1))
239
238
 
240
- fun ewalkSet(bits: Array[Int], id: Int) =
239
+ fun bitSet(bits: Array[Int], id: Int) =
241
240
  w := id / 64
242
241
  bits.set(w, bits.get(w) | {1 << {id % 64}})
243
242
 
244
- fun ewalkHas(bits: Array[Int], id: Int) -> Bool =
243
+ fun bitHas(bits: Array[Int], id: Int) -> Bool =
245
244
  w := id / 64
246
245
  if id < 0 || w >= bits.length() then false else {{bits.get(w) >> {id % 64}} & 1} == 1
247
246
 
@@ -249,67 +248,67 @@ fun ewalkHas(bits: Array[Int], id: Int) -> Bool =
249
248
  # actors `w` kills, and followed by `extra` (the parent's spawns, unstepped). An actor with
250
249
  # children (or spawns) gets one context for them, made from its place before its step.
251
250
  # Every kept node is rebuilt: in place when nothing else holds `t`.
252
- fun estep[M](t: FRoseTree[Actor[M]], ctx: ECtx[M], dt: Float, w: EWalk[M], extra: FRoseTree[Actor[M]]) -> FRoseTree[Actor[M]] = match t
251
+ fun stepChain[M](t: FRoseTree[Actor[M]], ctx: Ctx[M], dt: Float, w: TreeWalk[M], extra: FRoseTree[Actor[M]]) -> FRoseTree[Actor[M]] = match t
253
252
  FRoseEmpty => extra
254
253
  FRoseNode(a, k, n) =>
255
254
  if a.gone() || {w.hasKills && w.killed(a.key())}
256
- estep(n, ctx, dt, w, extra)
255
+ stepChain(n, ctx, dt, w, extra)
257
256
  else
258
257
  xs := if w.hasSpawns then w.spawnsUnder(a.key()) else FRoseEmpty
259
258
  walkKids := !k.isEmpty() || !xs.isEmpty()
260
259
  cc := if walkKids then ctx.under(a.place().local(), a.opacity()) else ctx
261
260
  na := a.step(ctx, dt)
262
261
  if na.gone()
263
- estep(n, ctx, dt, w, extra)
262
+ stepChain(n, ctx, dt, w, extra)
264
263
  else
265
- k2 := if walkKids then estep(k, cc, dt, w, xs) else k
264
+ k2 := if walkKids then stepChain(k, cc, dt, w, xs) else k
266
- FRoseNode(value: na, firstChild: k2, nextSibling: estep(n, ctx, dt, w, extra))
265
+ FRoseNode(value: na, firstChild: k2, nextSibling: stepChain(n, ctx, dt, w, extra))
267
266
 
268
267
  # The chain `t` without the actors `w` kills and followed by `extra`, with the same done
269
268
  # in every subtree: `apply`'s walk.
270
- fun eapply[M](t: FRoseTree[Actor[M]], w: EWalk[M], extra: FRoseTree[Actor[M]]) -> FRoseTree[Actor[M]] = match t
269
+ fun applyChain[M](t: FRoseTree[Actor[M]], w: TreeWalk[M], extra: FRoseTree[Actor[M]]) -> FRoseTree[Actor[M]] = match t
271
270
  FRoseEmpty => extra
272
271
  FRoseNode(a, k, n) =>
273
272
  id := a.key()
274
273
  if w.killed(id)
275
- eapply(n, w, extra)
274
+ applyChain(n, w, extra)
276
275
  else
277
276
  xs := w.spawnsUnder(id)
278
- k2 := if k.isEmpty() && xs.isEmpty() then k else eapply(k, w, xs)
277
+ k2 := if k.isEmpty() && xs.isEmpty() then k else applyChain(k, w, xs)
279
- FRoseNode(value: a, firstChild: k2, nextSibling: eapply(n, w, extra))
278
+ FRoseNode(value: a, firstChild: k2, nextSibling: applyChain(n, w, extra))
280
279
 
281
280
  # Whether the walks that draw and hit test go into `a`: shown, and not gone.
282
- fun eshown[M](a: Actor[M]) -> Bool = a.shown() && !a.gone()
281
+ fun isShown[M](a: Actor[M]) -> Bool = a.shown() && !a.gone()
283
282
 
284
- fun ecollect[M](t: FRoseTree[Actor[M]], parent: Affine, alpha: Float, out: Slice[EDrawn[M]]) =
283
+ fun collectChain[M](t: FRoseTree[Actor[M]], parent: Affine, alpha: Float, out: Slice[Drawn[M]]) =
285
284
  if FRoseNode(a, k, n) := t
286
- if eshown(a)
285
+ if isShown(a)
287
286
  m := parent.mul(a.place().local())
288
287
  al := alpha * a.opacity()
289
- out.push(EDrawn(actor: a, m: m, alpha: al))
288
+ out.push(Drawn(actor: a, m: m, alpha: al))
290
- ecollect(k, m, al, out)
289
+ collectChain(k, m, al, out)
291
- ecollect(n, parent, alpha, out)
290
+ collectChain(n, parent, alpha, out)
292
291
 
293
- fun edraw[M](t: FRoseTree[Actor[M]], io: Io, parent: Affine, alpha: Float) =
292
+ fun drawChain[M](t: FRoseTree[Actor[M]], io: Io, parent: Affine, alpha: Float) =
294
293
  if FRoseNode(a, k, n) := t
295
- if eshown(a)
294
+ if isShown(a)
296
295
  m := parent.mul(a.place().local())
297
296
  al := alpha * a.opacity()
298
297
  a.paint(io, m, al)
299
- edraw(k, io, m, al)
298
+ drawChain(k, io, m, al)
300
- edraw(n, io, parent, alpha)
299
+ drawChain(n, io, parent, alpha)
301
300
 
302
301
  # The topmost shown actor under `p` (a point in the chain's parent's coordinates) that
303
302
  # says it is hit: later siblings first, and in each, its children before itself.
304
- fun ehit[M](t: FRoseTree[Actor[M]], p: Vec2) -> Option[Actor[M]] = match t
303
+ fun hitChain[M](t: FRoseTree[Actor[M]], p: Vec2) -> Option[Actor[M]] = match t
305
304
  FRoseEmpty => None
306
305
  FRoseNode(a, k, n) =>
307
- match ehit(n, p)
306
+ match hitChain(n, p)
308
307
  Some(found) => Some(found)
309
308
  None =>
310
- if eshown(a)
309
+ if isShown(a)
311
310
  q := a.place().local().inverse().apply(p)
312
- match ehit(k, q)
311
+ match hitChain(k, q)
313
312
  Some(found) => Some(found)
314
313
  None => if a.hit(q) then Some(a) else None
315
314
  else
@@ -337,7 +336,7 @@ struct TDrifter(id: Int, at: Place, vx: Float, ttl: Int, visible: Bool, dead: Bo
337
336
  fun shown(self) -> Bool = self.visible
338
337
  fun gone(self) -> Bool = self.dead
339
338
  fun hit(self, p: Vec2) -> Bool = actor.boxHit(10.0, 10.0, p)
340
- fun step(self, ctx: ECtx[Int], dt: Float) -> TDrifter =
339
+ fun step(self, ctx: Ctx[Int], dt: Float) -> TDrifter =
341
340
  if self.ttl == 0
342
341
  TDrifter(..self, dead: true)
343
342
  else
@@ -348,8 +347,8 @@ struct TDrifter(id: Int, at: Place, vx: Float, ttl: Int, visible: Bool, dead: Bo
348
347
  struct TSpawner(id: Int, next: Int) is Actor[Int] =
349
348
  fun key(self) -> Int = self.id
350
349
  fun place(self) -> Place = place.at(0.0, 0.0)
351
- fun step(self, ctx: ECtx[Int], dt: Float) -> TSpawner =
350
+ fun step(self, ctx: Ctx[Int], dt: Float) -> TSpawner =
352
- ctx.out.push(ESpawn(parent: 0, node: tdrifter(self.next, 0.0, 0.0, -1)))
351
+ ctx.out.push(Spawn(parent: 0, node: tdrifter(self.next, 0.0, 0.0, -1)))
353
352
  ctx.send(self.next)
354
353
  TSpawner(..self, next: self.next + 1)
355
354
 
@@ -358,15 +357,15 @@ struct TProbe(id: Int, at: Place, seen: Affine, seenA: Float) is Actor[Int] =
358
357
  fun key(self) -> Int = self.id
359
358
  fun place(self) -> Place = self.at
360
359
  fun opacity(self) -> Float = 0.5
361
- fun step(self, ctx: ECtx[Int], dt: Float) -> TProbe =
360
+ fun step(self, ctx: Ctx[Int], dt: Float) -> TProbe =
362
361
  TProbe(..self, seen: ctx.worldOf(self.at.local()), seenA: ctx.alphaOf(self.opacity()))
363
362
 
364
- # Pushes `EKill(target)` in each step.
363
+ # Pushes `Kill(target)` in each step.
365
364
  struct TKiller(id: Int, target: Int) is Actor[Int] =
366
365
  fun key(self) -> Int = self.id
367
366
  fun place(self) -> Place = place.at(0.0, 0.0)
368
- fun step(self, ctx: ECtx[Int], dt: Float) -> TKiller =
367
+ fun step(self, ctx: Ctx[Int], dt: Float) -> TKiller =
369
- ctx.out.push(EKill(id: self.target))
368
+ ctx.out.push(Kill(id: self.target))
370
369
  self
371
370
 
372
371
  fun tbody(id: Int, x: Float, y: Float, w: Float) -> TBody =
@@ -391,28 +390,28 @@ fun tturned(id: Int, x: Float, y: Float, s: Float, r: Float) -> TBody =
391
390
  fun tgroup(id: Int, x: Float, y: Float, s: Float, r: Float, kids: List[FRoseTree[Actor[Int]]]) -> FRoseTree[Actor[Int]] =
392
391
  FRoseTree.of(tturned(id, x, y, s, r), kids)
393
392
 
394
- fun tstage() -> EStage[Int] = EStage.of(tbody(0, 0.0, 0.0, 0.0))
393
+ fun ttree() -> SceneTree[Int] = SceneTree.of(tbody(0, 0.0, 0.0, 0.0))
395
394
 
396
- fun tids(s: EStage[Int]) -> Str = s.root.fold("", |acc, a| if acc == "" then "{a.key()}" else "{acc},{a.key()}")
395
+ fun tids(s: SceneTree[Int]) -> Str = s.root.fold("", |acc, a| if acc == "" then "{a.key()}" else "{acc},{a.key()}")
397
396
 
398
- fun tx(s: EStage[Int], id: Int) -> Float = s.find(id).unwrap().place().x
397
+ fun tx(s: SceneTree[Int], id: Int) -> Float = s.find(id).unwrap().place().x
399
398
 
400
399
  fun tnear(a: Float, b: Float) -> Bool = {a - b}.abs() < 0.0001
401
400
 
402
401
  fun tsameM(a: Affine, b: Affine) -> Bool =
403
402
  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)
404
403
 
405
- fun tseen(s: EStage[Int], id: Int) -> Affine = s.findAs[TProbe](id).unwrap().seen
404
+ fun tseen(s: SceneTree[Int], id: Int) -> Affine = s.findAs[TProbe](id).unwrap().seen
406
405
 
407
- fun tseenA(s: EStage[Int], id: Int) -> Float = s.findAs[TProbe](id).unwrap().seenA
406
+ fun tseenA(s: SceneTree[Int], id: Int) -> Float = s.findAs[TProbe](id).unwrap().seenA
408
407
 
409
- fun tfade(s: EStage[Int], id: Int, a: Float) -> EStage[Int] = s.updateAs[TBody](id, |b| TBody(..b, alpha: a))
408
+ fun tfade(s: SceneTree[Int], id: Int, a: Float) -> SceneTree[Int] = s.updateAs[TBody](id, |b| TBody(..b, alpha: a))
410
409
 
411
- fun thide(s: EStage[Int], id: Int) -> EStage[Int] = s.updateAs[TBody](id, |b| TBody(..b, visible: false))
410
+ fun thide(s: SceneTree[Int], id: Int) -> SceneTree[Int] = s.updateAs[TBody](id, |b| TBody(..b, visible: false))
412
411
 
413
- test "step returns a new stage and leaves a kept one as it was"
412
+ test "step returns a new tree and leaves a kept one as it was"
414
- s0 := tstage().add(0, tdrifter(1, 0.0, 10.0, -1)).add(0, tdrifter(2, 5.0, -10.0, -1))
413
+ s0 := ttree().add(0, tdrifter(1, 0.0, 10.0, -1)).add(0, tdrifter(2, 5.0, -10.0, -1))
415
- ctx := ECtx[Int]()
414
+ ctx := Ctx[Int]()
416
415
  s1 := s0.step(ctx, 0.5)
417
416
  s2 := s1.step(ctx, 0.5)
418
417
  assert tx(s0, 1) == 0.0
@@ -423,15 +422,15 @@ test "step returns a new stage and leaves a kept one as it was"
423
422
  assert tids(s2) == "0,1,2"
424
423
 
425
424
  test "a step that changes nothing keeps every actor"
426
- 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)]))
425
+ s0 := ttree().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)]))
427
- s1 := s0.step(ECtx[Int](), 1.0)
426
+ s1 := s0.step(Ctx[Int](), 1.0)
428
427
  assert tids(s1) == "0,1,2,3"
429
428
  assert s1.find(3).unwrap() == s0.find(3).unwrap()
430
429
 
431
430
  test "an actor whose step returns it gone is dropped with its subtree in the same step"
432
- 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))
431
+ s := ttree().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))
433
432
  assert tids(s) == "0,1,3,2"
434
- ctx := ECtx[Int]()
433
+ ctx := Ctx[Int]()
435
434
  s1 := s.step(ctx, 1.0)
436
435
  assert tids(s1) == "0,1,3,2"
437
436
  s2 := s1.step(ctx, 1.0)
@@ -439,20 +438,20 @@ test "an actor whose step returns it gone is dropped with its subtree in the sam
439
438
  assert s2.find(3).isNone()
440
439
 
441
440
  test "a gone or hidden actor: gone ones go with their subtree, hidden ones still step"
442
- 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))
441
+ s := ttree().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))
443
442
  hidden := s.updateAs[TDrifter](1, |d| TDrifter(..d, visible: false))
444
- h1 := hidden.step(ECtx[Int](), 1.0)
443
+ h1 := hidden.step(Ctx[Int](), 1.0)
445
444
  assert tx(h1, 1) == 1.0
446
445
  assert h1.flatten().length() == 2
447
446
  assert h1.hit(1.0, 1.0).unwrap().key() == 3
448
447
  gone := s.updateAs[TDrifter](1, |d| TDrifter(..d, dead: true))
449
448
  # not drawn or hit before the step drops it
450
449
  assert gone.flatten().length() == 2
451
- assert tids(gone.step(ECtx[Int](), 1.0)) == "0,3"
450
+ assert tids(gone.step(Ctx[Int](), 1.0)) == "0,3"
452
451
 
453
452
  test "spawns pushed to ctx.out are added after the step, on top, and sends stay for the game"
454
- s := tstage().add(0, tspawner(1, 10))
453
+ s := ttree().add(0, tspawner(1, 10))
455
- ctx := ECtx[Int]()
454
+ ctx := Ctx[Int]()
456
455
  ctx.send(99)
457
456
  s1 := s.step(ctx, 1.0)
458
457
  assert tids(s1) == "0,1,10"
@@ -465,24 +464,24 @@ test "spawns pushed to ctx.out are added after the step, on top, and sends stay
465
464
  assert ctx.out.length() == 0
466
465
 
467
466
  test "apply kills and spawns in one pass, in order, and skips sends"
468
- 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))
467
+ s := ttree().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))
469
- cmds := Slice[ECmd[Int]]()
468
+ cmds := Slice[Cmd[Int]]()
470
- cmds.push(EKill(id: 2))
469
+ cmds.push(Kill(id: 2))
471
- cmds.push(ESpawn(parent: 1, node: trect(5, 0.0, 0.0, 1.0)))
470
+ cmds.push(Spawn(parent: 1, node: trect(5, 0.0, 0.0, 1.0)))
472
- cmds.push(ESend(msg: 7))
471
+ cmds.push(Send(msg: 7))
473
- cmds.push(ESpawn(parent: 0, node: trect(6, 0.0, 0.0, 1.0)))
472
+ cmds.push(Spawn(parent: 0, node: trect(6, 0.0, 0.0, 1.0)))
474
- cmds.push(ESpawn(parent: 1, node: trect(7, 0.0, 0.0, 1.0)))
473
+ cmds.push(Spawn(parent: 1, node: trect(7, 0.0, 0.0, 1.0)))
475
- cmds.push(ESpawn(parent: 99, node: trect(8, 0.0, 0.0, 1.0)))
474
+ cmds.push(Spawn(parent: 99, node: trect(8, 0.0, 0.0, 1.0)))
476
475
  s2 := s.apply(cmds)
477
476
  assert tids(s2) == "0,1,3,5,7,4,6"
478
477
  assert tids(s) == "0,1,2,3,4"
479
478
  assert s.kill(1).count() == 2
480
- sends := Slice[ECmd[Int]]()
479
+ sends := Slice[Cmd[Int]]()
481
- sends.push(ESend(msg: 1))
480
+ sends.push(Send(msg: 1))
482
481
  assert tids(s.apply(sends)) == "0,1,2,3,4"
483
482
 
484
483
  test "update by id changes one actor and shares its untouched siblings"
485
- 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
+ s := ttree().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)]))
486
485
  s1 := s.add(0, tgroup(4, 0.0, 0.0, 1.0, 0.0, [trect(5, 0.0, 0.0, 1.0)]))
487
486
  u := s1.updateAs[TBody](2, |b| TBody(..b, at: b.at.moveTo(9.0, 9.0), w: 3.0))
488
487
  assert tx(u, 2) == 9.0
@@ -490,11 +489,11 @@ test "update by id changes one actor and shares its untouched siblings"
490
489
  # 2's later sibling (3) and 1's later sibling (the group 4) are the same nodes
491
490
  assert u.root.kids().kids().rest() == s1.root.kids().kids().rest()
492
491
  assert u.root.kids().rest() == s1.root.kids().rest()
493
- k := s1.update(5, |a| TDrifter(id: a.key(), at: a.place(), vx: 2.0, ttl: -1, visible: true, dead: false)).step(ECtx[Int](), 1.0)
492
+ k := s1.update(5, |a| TDrifter(id: a.key(), at: a.place(), vx: 2.0, ttl: -1, visible: true, dead: false)).step(Ctx[Int](), 1.0)
494
493
  assert tx(k, 5) == 2.0
495
494
 
496
495
  test "updateAs and findAs act only on an actor of that type"
497
- s := tstage().add(0, tdrifter(1, 0.0, 1.0, -1)).add(0, trect(2, 3.0, 0.0, 1.0))
496
+ s := ttree().add(0, tdrifter(1, 0.0, 1.0, -1)).add(0, trect(2, 3.0, 0.0, 1.0))
498
497
  assert s.findAs[TDrifter](1).unwrap().vx == 1.0
499
498
  assert s.findAs[TBody](1).isNone()
500
499
  assert s.findAs[TBody](2).unwrap().w == 1.0
@@ -502,18 +501,18 @@ test "updateAs and findAs act only on an actor of that type"
502
501
  same := s.updateAs[TBody](1, |b| TBody(..b, w: 50.0))
503
502
  assert same.find(1).unwrap() == s.find(1).unwrap()
504
503
  assert same.find(2).unwrap() == s.find(2).unwrap()
505
- t := s.updateAs[TDrifter](1, |d| TDrifter(..d, vx: 5.0)).step(ECtx[Int](), 1.0)
504
+ t := s.updateAs[TDrifter](1, |d| TDrifter(..d, vx: 5.0)).step(Ctx[Int](), 1.0)
506
505
  assert tx(t, 1) == 5.0
507
506
  assert tx(t, 2) == 3.0
508
507
  # std's own kinds
509
- g: EStage[Int] := EStage.of(Group(id: 0, at: place.at(0.0, 0.0))).add(0, FRoseTree.leaf(Box(id: 1, at: place.at(1.0, 0.0), w: 2.0, h: 2.0, color: Color.Red)))
508
+ g: SceneTree[Int] := SceneTree.of(Group(id: 0, x: 0.0, y: 0.0)).add(0, FRoseTree.leaf(Box(id: 1, x: 1.0, y: 0.0, w: 2.0, h: 2.0, color: Color.Red)))
510
- moved := g.updateAs[Box[Int]](1, |b| Box(..b, at: b.at.moveBy(1.0, 0.0)))
509
+ moved := g.updateAs[Box[Int]](1, |b| Box(..b, x: b.x + 1.0))
511
- assert moved.findAs[Box[Int]](1).unwrap().at.x == 2.0
510
+ assert moved.findAs[Box[Int]](1).unwrap().x == 2.0
512
511
  assert moved.findAs[Group[Int]](0).unwrap().id == 0
513
512
 
514
- test "flatten gives each shown actor its stage transform, parents first"
513
+ test "flatten gives each shown actor its tree transform, parents first"
515
514
  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)])
516
- s := tstage().add(0, g).add(0, trect(4, 5.0, 5.0, 1.0))
515
+ s := ttree().add(0, g).add(0, trect(4, 5.0, 5.0, 1.0))
517
516
  d := s.flatten()
518
517
  assert d.length() == 5
519
518
  ids := Slice[Int]()
@@ -531,11 +530,11 @@ test "flatten gives each shown actor its stage transform, parents first"
531
530
 
532
531
  test "hit finds the topmost actor: later siblings and children first"
533
532
  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)])
534
- s := tstage().add(0, g)
533
+ s := ttree().add(0, g)
535
534
  assert s.hit(90.0, 30.0).unwrap().key() == 3
536
535
  assert s.hit(70.0, 10.0).unwrap().key() == 2
537
536
  assert s.hit(10.0, 10.0).isNone()
538
- 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))
537
+ t := ttree().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))
539
538
  assert t.hit(10.0, 10.0).unwrap().key() == 5
540
539
  assert t.hit(30.0, 5.0).unwrap().key() == 7
541
540
  assert t.hitId(40.0, 10.0).unwrap() == 6
@@ -546,8 +545,8 @@ test "an actor's world transform is computed when it asks, and matches the eager
546
545
  hb := TBody(..tturned(2, -20.0, 5.0, 1.5, -1.1), at: place.turned(-20.0, 5.0, 1.5, -1.1).pivotAt(3.0, 4.0))
547
546
  p := tprobe(3, 7.0, -2.0, 2.5)
548
547
  q := tprobe(4, 1.0, 1.0, 0.0)
549
- s := tstage().add(0, FRoseTree.of(gb, [FRoseTree.of(hb, [FRoseTree.leaf(p), FRoseTree.leaf(q)])]))
548
+ s := ttree().add(0, FRoseTree.of(gb, [FRoseTree.of(hb, [FRoseTree.leaf(p), FRoseTree.leaf(q)])]))
550
- s1 := s.step(ECtx[Int](), 1.0)
549
+ s1 := s.step(Ctx[Int](), 1.0)
551
550
  assert tsameM(tseen(s1, 3), gb.at.local().mul(hb.at.local()).mul(p.at.local()))
552
551
  assert tnear(tseenA(s1, 3), 0.5)
553
552
  # the sibling got its own transform from the same context
@@ -558,33 +557,33 @@ test "siblings with children each give their children their own world transform"
558
557
  g2 := tturned(2, -40.0, 5.0, 0.5, -1.2)
559
558
  p1 := tprobe(3, 7.0, -2.0, 2.5)
560
559
  p2 := tprobe(4, 1.0, 9.0, 0.3)
561
- s := tstage().add(0, FRoseTree.of(g1, [FRoseTree.leaf(p1)])).add(0, FRoseTree.of(g2, [FRoseTree.leaf(p2)]))
560
+ s := ttree().add(0, FRoseTree.of(g1, [FRoseTree.leaf(p1)])).add(0, FRoseTree.of(g2, [FRoseTree.leaf(p2)]))
562
- s1 := s.step(ECtx[Int](), 1.0)
561
+ s1 := s.step(Ctx[Int](), 1.0)
563
562
  assert tsameM(tseen(s1, 3), g1.at.local().mul(p1.at.local()))
564
563
  assert tsameM(tseen(s1, 4), g2.at.local().mul(p2.at.local()))
565
564
 
566
565
  test "a kill pushed before the step drops the actor in the step's own walk, unstepped"
567
- 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)]))
566
+ s := ttree().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)]))
568
- ctx := ECtx[Int]()
567
+ ctx := Ctx[Int]()
569
- ctx.out.push(EKill(id: 1))
568
+ ctx.out.push(Kill(id: 1))
570
569
  s2 := s.step(ctx, 1.0)
571
570
  # the spawner was not stepped, so it spawned nothing
572
571
  assert tids(s2) == "0,2,3"
573
572
  assert ctx.out.length() == 0
574
573
  # ids outside the bitsets' range take the set: the same answers
575
- ctx.out.push(EKill(id: -7))
574
+ ctx.out.push(Kill(id: -7))
576
- ctx.out.push(EKill(id: 3))
575
+ ctx.out.push(Kill(id: 3))
577
- ctx.out.push(EKill(id: 5000000))
576
+ ctx.out.push(Kill(id: 5000000))
578
577
  assert tids(s2.step(ctx, 1.0)) == "0,2"
579
578
 
580
579
  test "spawns pushed before the step go on top of their parents, in order, unstepped"
581
- 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)]))
580
+ s := ttree().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)]))
582
581
  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)]))
583
- ctx := ECtx[Int]()
582
+ ctx := Ctx[Int]()
584
- ctx.out.push(ESpawn(parent: 1, node: tdrifter(5, 0.0, 10.0, -1)))
583
+ ctx.out.push(Spawn(parent: 1, node: tdrifter(5, 0.0, 10.0, -1)))
585
- ctx.out.push(ESpawn(parent: 4, node: trect(6, 0.0, 0.0, 1.0)))
584
+ ctx.out.push(Spawn(parent: 4, node: trect(6, 0.0, 0.0, 1.0)))
586
- ctx.out.push(ESpawn(parent: 1, node: trect(7, 0.0, 0.0, 1.0)))
585
+ ctx.out.push(Spawn(parent: 1, node: trect(7, 0.0, 0.0, 1.0)))
587
- ctx.out.push(ESpawn(parent: 99, node: trect(8, 0.0, 0.0, 1.0)))
586
+ ctx.out.push(Spawn(parent: 99, node: trect(8, 0.0, 0.0, 1.0)))
588
587
  s2 := s1.step(ctx, 1.0)
589
588
  assert tids(s2) == "0,1,2,3,5,7,4,6,9,10"
590
589
  # the drifter was added after the step: it hasn't moved yet
@@ -592,7 +591,7 @@ test "spawns pushed before the step go on top of their parents, in order, unstep
592
591
  assert tx(s2.step(ctx, 1.0), 5) == 10.0
593
592
  # many spawns into one parent keep their order
594
593
  for i := range 50
595
- ctx.out.push(ESpawn(parent: 4, node: trect(100 + i, 0.0, 0.0, 1.0)))
594
+ ctx.out.push(Spawn(parent: 4, node: trect(100 + i, 0.0, 0.0, 1.0)))
596
595
  s3 := s2.step(ctx, 1.0)
597
596
  ids := s3.root.kids().rest().kids().fold(Slice[Int](), |acc, a|
598
597
  acc.push(a.key())
@@ -601,53 +600,53 @@ test "spawns pushed before the step go on top of their parents, in order, unstep
601
600
  assert ids.length() == 51 && ids.at(0) == 6 && ids.at(1) == 100 && ids.at(50) == 149
602
601
 
603
602
  test "a kill and a spawn of the same id before the step: the old actor goes, the new one stays"
604
- 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)]))
603
+ s := ttree().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)]))
605
- ctx := ECtx[Int]()
604
+ ctx := Ctx[Int]()
606
- ctx.out.push(EKill(id: 2))
605
+ ctx.out.push(Kill(id: 2))
607
- ctx.out.push(ESpawn(parent: 1, node: trect(2, 7.0, 0.0, 1.0)))
606
+ ctx.out.push(Spawn(parent: 1, node: trect(2, 7.0, 0.0, 1.0)))
608
607
  s2 := s.step(ctx, 1.0)
609
608
  assert tids(s2) == "0,1,3,2"
610
609
  assert tx(s2, 2) == 7.0
611
- # the old stage is as it was
610
+ # the old tree is as it was
612
611
  assert tids(s) == "0,1,2,3"
613
612
  assert tx(s, 2) == 0.0
614
613
  # a reused id is killed again by the next batch
615
- ctx.out.push(EKill(id: 2))
614
+ ctx.out.push(Kill(id: 2))
616
615
  assert tids(s2.step(ctx, 1.0)) == "0,1,3"
617
616
 
618
617
  test "commands pushed during the step apply after those pushed before it"
619
- s := tstage().add(0, tkiller(1, 5)).add(0, tgroup(2, 0.0, 0.0, 1.0, 0.0, []))
618
+ s := ttree().add(0, tkiller(1, 5)).add(0, tgroup(2, 0.0, 0.0, 1.0, 0.0, []))
620
- ctx := ECtx[Int]()
619
+ ctx := Ctx[Int]()
621
620
  # spawned by the batch before the step, then killed by an actor during it
622
- ctx.out.push(ESpawn(parent: 2, node: trect(5, 0.0, 0.0, 1.0)))
621
+ ctx.out.push(Spawn(parent: 2, node: trect(5, 0.0, 0.0, 1.0)))
623
622
  s2 := s.step(ctx, 1.0)
624
623
  assert tids(s2) == "0,1,2"
625
624
  assert ctx.out.length() == 0
626
625
 
627
626
  test "the bitsets cover ids up to 2^22 - 1, and the set and map take the ids past it"
628
627
  big := 4194303
629
- s := tstage().add(0, tgroup(big, 0.0, 0.0, 1.0, 0.0, [trect(big - 1, 0.0, 0.0, 1.0)]))
628
+ s := ttree().add(0, tgroup(big, 0.0, 0.0, 1.0, 0.0, [trect(big - 1, 0.0, 0.0, 1.0)]))
630
629
  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)]))
631
- ctx := ECtx[Int]()
630
+ ctx := Ctx[Int]()
632
631
  # in the bitsets' range: the last bit of the last word, and a word boundary
633
- ctx.out.push(EKill(id: big - 1))
632
+ ctx.out.push(Kill(id: big - 1))
634
- ctx.out.push(EKill(id: 64))
633
+ ctx.out.push(Kill(id: 64))
635
- ctx.out.push(ESpawn(parent: big, node: trect(0 - 3, 0.0, 0.0, 1.0)))
634
+ ctx.out.push(Spawn(parent: big, node: trect(0 - 3, 0.0, 0.0, 1.0)))
636
635
  s2 := s1.step(ctx, 1.0)
637
636
  assert tids(s2) == "0,{big},-3,{big + 1},63"
638
637
  # one id past the range: the whole batch uses the set and the map
639
- ctx.out.push(ESpawn(parent: big + 1, node: trect(9, 0.0, 0.0, 1.0)))
638
+ ctx.out.push(Spawn(parent: big + 1, node: trect(9, 0.0, 0.0, 1.0)))
640
- ctx.out.push(EKill(id: 0 - 3))
639
+ ctx.out.push(Kill(id: 0 - 3))
641
- ctx.out.push(EKill(id: 63))
640
+ ctx.out.push(Kill(id: 63))
642
641
  s3 := s2.step(ctx, 1.0)
643
642
  assert tids(s3) == "0,{big},{big + 1},9"
644
643
  # a kill of an id the tree doesn't have, past the bitsets: nothing changes
645
- ctx.out.push(EKill(id: big + 100))
644
+ ctx.out.push(Kill(id: big + 100))
646
645
  assert tids(s3.step(ctx, 1.0)) == "0,{big},{big + 1},9"
647
646
 
648
- test "a plain stage of std's Group and Box: add, step, draw list"
647
+ test "a plain tree of std's Group and Box: add, step, draw list"
649
- s: EStage[Int] := EStage.of(Group(id: 0, at: place.at(0.0, 0.0))).add(0, FRoseTree.leaf(Box(id: 1, at: place.at(10.0, 5.0), w: 40.0, h: 20.0, color: Color.Red)))
648
+ s: SceneTree[Int] := SceneTree.of(Group(id: 0, x: 0.0, y: 0.0)).add(0, FRoseTree.leaf(Box(id: 1, x: 10.0, y: 5.0, w: 40.0, h: 20.0, color: Color.Red)))
650
- s1 := s.step(ECtx[Int](), 1.0)
649
+ s1 := s.step(Ctx[Int](), 1.0)
651
650
  assert s1.count() == 2
652
651
  assert s1.flatten().at(1).m.e == 10.0
653
652
  assert s1.hit(20.0, 10.0).unwrap().key() == 1
std/game/ui.plum CHANGED
@@ -6,17 +6,23 @@ import std/Str
6
6
  import std/Slice
7
7
  import std/List
8
8
  import std/Option
9
+ import std/Io
10
+ import std/game/Vec2
11
+ import std/game/Affine
9
12
  import std/game/Color
10
- import std/game/scene
11
13
  import std/game/input
14
+ import std/collections/functional/FRoseTree
15
+ import std/game/scene/Place
16
+ import std/game/scene/Actor
17
+ import std/game/scene/SceneTree
12
18
 
19
+ # Widgets for a scene tree, and the pointer rules that drive them. `Button[M]` and
13
- # A pure UI layer for the functional scene style. `step` takes the previous
20
+ # `Label[M]` are actors (`is Actor[M]`), so any game's `SceneTree[M]` takes them. `step`
14
- # UiState, one pointer input and the id under the pointer (from SceneNode.hitId on
21
+ # takes the previous UiState, one pointer input and the id under the pointer (from
15
- # the current view) and returns the new state plus the UiEvents it raised.
22
+ # `tree.hitId(x, y)`) and returns the new state plus the UiEvents it raised; `messages`
16
- # `messages` turns the Clicks among them into the game's own messages, read from
23
+ # turns the Clicks among them into the game's own messages, each button's `onClick`, and
17
- # the `Clickable` nodes of that view. Same
18
- # button rules as the old pure scene: Down captures the pressed id; while captured only
24
+ # `styled` gives every button the look of the state. Down captures the pressed id; while
19
- # that id gets Enter/Exit; Up releases (Click only when still over it).
25
+ # captured only that id gets Enter/Exit; Up releases (Click only when still over it).
20
26
 
21
27
  struct UiState(x: Float, y: Float, down: Bool, hot: Option[Int], captured: Option[Int])
22
28
 
@@ -92,30 +98,72 @@ fun hovered(ui: UiState, id: Int) -> Bool =
92
98
  Some(h) => h == id
93
99
  None => false
94
100
 
95
- # A tagged, translated rectangle with a label whose colour follows the state.
101
+ # A button `w` by `h` with its top-left at (x, y) that sends `onClick` when clicked
102
+ # (`messages`). `look` is how it shows the pointer: 0 idle, 1 hovered, 2 pressed (`styled`).
103
+ struct Button[M](id: Int, x: Float, y: Float, w: Float, h: Float, label: Str, onClick: M, look: Int) is Actor[M] =
104
+ fun key(self) -> Int = self.id
105
+
106
+ fun place(self) -> Place = place.at(self.x, self.y)
107
+
108
+ fun paint(self, io: Io, m: Affine, alpha: Float) =
109
+ actor.boxPaint(io, m, alpha, self.w, self.h, lookColor(self.look))
110
+ actor.textPaint(io, m, alpha, self.label, 4.0, 4.0, self.h * 0.5, Color.White)
111
+
112
+ fun hit(self, p: Vec2) -> Bool = actor.boxHit(self.w, self.h, p)
113
+
114
+ # Showing `ui` (idle, hovered or pressed).
115
+ fun styled(self, ui: UiState) -> Button[M] = Button(..self, look: lookOf(ui, self.id))
116
+
117
+ # A line of text in `color` with its top-left at (x, y), `size` high. Its opacity is its
118
+ # colour's alpha.
119
+ struct Label[M](id: Int, x: Float, y: Float, text: Str, size: Float, color: Color) is Actor[M] =
120
+ fun key(self) -> Int = self.id
121
+
122
+ fun place(self) -> Place = place.at(self.x, self.y)
123
+
124
+ fun opacity(self) -> Float = self.color.a
125
+
126
+ fun paint(self, io: Io, m: Affine, alpha: Float) =
127
+ actor.textPaint(io, m, alpha, self.text, 0.0, 0.0, self.size, self.color.withAlpha(1.0))
128
+
129
+ fun relabel(self, t: Str) -> Label[M] = Label(..self, text: t)
130
+
131
+ # The look of the button `id` in `ui`: 2 pressed, 1 hovered, 0 idle.
132
+ fun lookOf(ui: UiState, id: Int) -> Int =
133
+ if pressed(ui, id)
134
+ 2
135
+ else if hovered(ui, id)
136
+ 1
137
+ else
138
+ 0
139
+
140
+ fun lookColor(look: Int) -> Color =
141
+ if look == 2
142
+ uiPressedColor()
143
+ else if look == 1
144
+ uiHoverColor()
145
+ else
146
+ uiIdleColor()
147
+
96
- # The messages of the Clickables that `events` clicked, in order, read from `view`.
148
+ # The messages of the buttons that `events` clicked, in order, read from `tree`.
97
- fun messages[M](view: SceneNode[M], events: List[UiEvent]) -> List[M] = match events
149
+ fun messages[M](tree: SceneTree[M], events: List[UiEvent]) -> List[M] = match events
98
150
  Nil => Nil
99
151
  Cons(e, rest) =>
100
- later := messages(view, rest)
152
+ later := messages(tree, rest)
101
153
  if e.kind != Click
102
154
  later
103
155
  else
104
- match view.msgOf(e.id)
156
+ match tree.findAs[Button[M]](e.id)
105
- Some(m) => Cons(head: m, tail: later)
157
+ Some(b) => Cons(head: b.onClick, tail: later)
106
158
  None => later
107
159
 
108
- # A button that sends `msg` when clicked; `id` identifies it for hover and press.
160
+ # `tree` with every button showing `ui`.
109
- fun button[M](id: Int, msg: M, label: Str, x: Float, y: Float, w: Float, h: Float, ui: UiState) -> SceneNode[M] =
161
+ fun styled[M](tree: SceneTree[M], ui: UiState) -> SceneTree[M] =
162
+ tree.withRoot(tree.root.map(|a| match a
163
+ Button as b =>
110
- color := if pressed(ui, id)
164
+ c: Actor[M] := b.styled(ui)
111
- uiPressedColor()
112
- else if hovered(ui, id)
113
- uiHoverColor()
114
- else
165
+ c
115
- uiIdleColor()
166
+ _ => a))
116
- Clickable(id: id, msg: msg, child: Group(transform: Translate(dx: x, dy: y), children: [
117
- RectShape(x: 0.0, y: 0.0, w: w, h: h, color: color),
118
- Text(text: label, x: 4.0, y: 4.0, size: h * 0.5, color: Color.White)]))
119
167
 
120
168
  fun uiIdleColor() -> Color = Color.rgb(0.2, 0.2, 0.3)
121
169
 
@@ -136,11 +184,14 @@ fun uiCount(s: UiStep, k: UiKind) -> Int =
136
184
 
137
185
  fun uiIs(e: UiEvent, id: Int, kind: UiKind) -> Bool = e.id == id && e.kind == kind
138
186
 
187
+ fun uiButton(id: Int, msg: Int, label: Str, x: Float, y: Float) -> FRoseTree[Actor[Int]] =
188
+ FRoseTree.leaf(Button(id: id, x: x, y: y, w: 10.0, h: 10.0, label: label, onClick: msg, look: 0))
189
+
139
- fun uiButtonColor(n: SceneNode[Int]) -> Color = match n
190
+ fun uiTree() -> SceneTree[Int] =
191
+ root: FRoseTree[Actor[Int]] := FRoseTree.of(Group(id: 0, x: 0.0, y: 0.0), [uiButton(3, 30, "Go", 0.0, 0.0), uiButton(4, 40, "Stop", 20.0, 0.0)])
140
- Clickable(_, _, child) => uiButtonColor(child)
192
+ SceneTree(root: root, camX: 0.0, camY: 0.0, camScale: 1.0)
193
+
141
- Group(_, children) => uiButtonColor(children.at(0))
194
+ fun uiLook(t: SceneTree[Int], id: Int) -> Int = t.findAs[Button[Int]](id).unwrap().look
142
- RectShape(_, _, _, _, c) => c
143
- _ => Color.Black
144
195
 
145
196
  test "press_sets_capture"
146
197
  s1 := step(init(), uiDown(1.0), Some(5))
@@ -195,22 +246,27 @@ test "hover_without_press_routes_move"
195
246
  assert uiIs(s3.events.at(0), 5, Exit)
196
247
  assert !hovered(s3.ui, 5)
197
248
 
198
- test "button_visual_reflects_state"
249
+ test "buttons show the pointer and are hit in their box"
199
- idle := button(3, 30, "Go", 10.0, 20.0, 100.0, 40.0, init())
250
+ t := uiTree()
200
- hov := button(3, 30, "Go", 10.0, 20.0, 100.0, 40.0, step(init(), uiMove(1.0), Some(3)).ui)
251
+ hov := styled(t, step(init(), uiMove(1.0), Some(3)).ui)
201
- prs := button(3, 30, "Go", 10.0, 20.0, 100.0, 40.0, step(init(), uiDown(1.0), Some(3)).ui)
252
+ prs := styled(t, step(init(), uiDown(1.0), Some(3)).ui)
202
- assert uiButtonColor(idle).eq(uiIdleColor())
203
- assert uiButtonColor(hov).eq(uiHoverColor())
204
- assert uiButtonColor(prs).eq(uiPressedColor())
205
- if Some(hid) := idle.hitId(20.0, 30.0)
206
- assert hid == 3
253
+ assert uiLook(t, 3) == 0
207
- else
254
+ assert uiLook(hov, 3) == 1 && uiLook(hov, 4) == 0
208
- assert false
255
+ assert uiLook(prs, 3) == 2
256
+ assert lookColor(2).eq(uiPressedColor()) && lookColor(1).eq(uiHoverColor()) && lookColor(0).eq(uiIdleColor())
257
+ assert t.hitId(5.0, 5.0).unwrapOr(-1) == 3
258
+ assert t.hitId(25.0, 5.0).unwrapOr(-1) == 4
259
+ assert t.hitId(15.0, 5.0).isNone()
209
260
 
210
261
  test "messages_are_the_clicked_buttons_messages"
211
- view := Group(transform: Identity, children: [button(3, 30, "Go", 0.0, 0.0, 10.0, 10.0, init()), button(4, 40, "Stop", 20.0, 0.0, 10.0, 10.0, init())])
212
262
  evs := [UiEvent(id: 4, kind: Press), UiEvent(id: 4, kind: Click), UiEvent(id: 9, kind: Click), UiEvent(id: 3, kind: Click)]
213
- ms := messages(view, evs)
263
+ ms := messages(uiTree(), evs)
214
264
  assert ms.length() == 2
215
265
  assert ms.get(0).unwrapOr(-1) == 40
216
266
  assert ms.get(1).unwrapOr(-1) == 30
267
+
268
+ test "a label relabels and its alpha is its opacity"
269
+ l: Label[Int] := Label(id: 1, x: 0.0, y: 0.0, text: "a", size: 10.0, color: Color.White.withAlpha(0.5))
270
+ assert l.relabel("b").text == "b"
271
+ a: Actor[Int] := l
272
+ assert a.opacity() == 0.5
std/game_enum_tree/Actor.plum DELETED
@@ -1,101 +0,0 @@
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/gfx
11
- import std/game_enum_tree/Place
12
- import std/game_enum_tree/ECtx
13
-
14
- # One body of a persistent scene tree (`FRoseTree[Actor[M]]` in an `EStage[M]`). Each
15
- # kind of body is its own type, with only its own fields, that `is Actor[M]`; `M` is the
16
- # game's message type (what `ctx.send` takes). A kind must say which actor it is (`key`,
17
- # the id the stage finds it by) and where it is in its parent (`place`); everything else
18
- # has a default:
19
- #
20
- # step the next version of it, once a tick (`ctx` is its parent's context)
21
- # paint draws it, seen through `m` (its own coordinates to the stage's) at `alpha`
22
- # (the accumulated alpha, its own `opacity` included)
23
- # hit whether `p`, in its own coordinates, is on it
24
- # shown false: it and its subtree are not drawn or hit (but still stepped)
25
- # gone true: it is dropped with its subtree (returned from `step`, in the same step)
26
- # opacity its own alpha, multiplied down the tree
27
- #
28
- # struct Walker(id: Int, at: Place, speed: Float) is Actor[Msg] =
29
- # fun key(self) -> Int = self.id
30
- # fun place(self) -> Place = self.at
31
- # fun step(self, ctx: ECtx[Msg], dt: Float) -> Walker =
32
- # Walker(..self, at: self.at.moveBy(self.speed * dt, 0.0))
33
- #
34
- # An actor is a value: a step returns the next one, usually a spread (`Walker(..self,
35
- # ..)`), which the compiler writes in place when nothing else holds the old one. The two
36
- # std kinds below, `Group` and `Box`, are generic in `M` so any game's tree takes them.
37
- trait Actor[M] =
38
- fun key(self) -> Int
39
-
40
- fun place(self) -> Place
41
-
42
- fun step(self, ctx: ECtx[M], dt: Float) -> Self = self
43
-
44
- fun paint(self, io: Io, m: Affine, alpha: Float) = Unit
45
-
46
- fun hit(self, p: Vec2) -> Bool = false
47
-
48
- fun shown(self) -> Bool = true
49
-
50
- fun gone(self) -> Bool = false
51
-
52
- fun opacity(self) -> Float = 1.0
53
-
54
- # An actor that paints nothing and is never hit: a parent for others (a layer, a camera).
55
- struct Group[M](id: Int, at: Place) is Actor[M] =
56
- fun key(self) -> Int = self.id
57
-
58
- fun place(self) -> Place = self.at
59
-
60
- # A filled `w` by `h` box in `color`, with its top-left at its place's (0, 0); hit inside
61
- # it. Its opacity is its colour's alpha.
62
- struct Box[M](id: Int, at: Place, w: Float, h: Float, color: Color) is Actor[M] =
63
- fun key(self) -> Int = self.id
64
-
65
- fun place(self) -> Place = self.at
66
-
67
- fun opacity(self) -> Float = self.color.a
68
-
69
- fun paint(self, io: Io, m: Affine, alpha: Float) =
70
- boxPaint(io, m, alpha, self.w, self.h, self.color.withAlpha(1.0))
71
-
72
- fun hit(self, p: Vec2) -> Bool = boxHit(self.w, self.h, p)
73
-
74
- # Whether `p` is inside a `w` by `h` box at (0, 0); a box with no size is never hit.
75
- fun boxHit(w: Float, h: Float, p: Vec2) -> Bool =
76
- w > 0.0 && h > 0.0 && p.x >= 0.0 && p.x <= w && p.y >= 0.0 && p.y <= h
77
-
78
- # A `w` by `h` box at (0, 0) seen through `m`, filled with `c` at `c.a * alpha`.
79
- fun boxPaint(io: Io, m: Affine, alpha: Float, w: Float, h: Float, c: Color) =
80
- sx := w * m.scaleX()
81
- sy := h * m.scaleY()
82
- p := m.apply(Vec2(x: w / 2.0, y: h / 2.0))
83
- gfx.drawRect(io, p.x - sx / 2.0, p.y - sy / 2.0, sx, sy, c.withAlpha(c.a * alpha))
84
-
85
- test "a box is hit inside its size, a group never"
86
- b: Actor[Int] := Box(id: 7, at: place.at(1.0, 2.0), w: 4.0, h: 3.0, color: Color.Red.withAlpha(0.25))
87
- assert b.key() == 7
88
- assert b.place().x == 1.0
89
- assert b.hit(Vec2(x: 2.0, y: 1.0))
90
- assert !b.hit(Vec2(x: 5.0, y: 1.0))
91
- assert b.opacity() == 0.25
92
- assert b.shown() && !b.gone()
93
- g: Actor[Int] := Group(id: 1, at: place.at(0.0, 0.0))
94
- assert !g.hit(Vec2(x: 0.0, y: 0.0))
95
- assert g.opacity() == 1.0
96
- assert !boxHit(0.0, 3.0, Vec2(x: 0.0, y: 0.0))
97
-
98
- test "the default step returns the actor as it was"
99
- b: Actor[Int] := Box(id: 3, at: place.at(1.0, 1.0), w: 4.0, h: 2.0, color: Color.Blue)
100
- assert b.step(ECtx[Int](), 1.0) == b
101
- assert b.step(ECtx[Int](), 1.0).place().x == 1.0
std/game_enum_tree/ECtx.plum DELETED
@@ -1,108 +0,0 @@
1
- module std
2
-
3
- import std/Int
4
- import std/Float
5
- import std/Str
6
- import std/List
7
- import std/Slice
8
- import std/game/Affine
9
- import std/collections/functional/FRoseTree
10
- import std/game_enum_tree/Actor
11
-
12
- # What a step changes besides the actors. `ESpawn` and `EKill` are applied once the
13
- # step's walk is over (`EStage.apply`): a new node under the actor `parent` (by id), on
14
- # top of its children, or the end of the actor `id` and its subtree. `ESend` is a message
15
- # of the game's type `M` for the game's store: the stage leaves it in `ctx.out`, in order,
16
- # for the game to take (`ctx.takeSends()`).
17
- enum ECmd[M] =
18
- | ESpawn(parent: Int, node: FRoseTree[Actor[M]])
19
- | EKill(id: Int)
20
- | ESend(msg: M)
21
-
22
- # What the step hands each actor in place of a parent link: the context of the actor's
23
- # parent. `up` is the parent's world transform and `alpha` its accumulated opacity, so an
24
- # actor's own world transform is `ctx.worldOf(self.place().local())` and its alpha
25
- # `ctx.alphaOf(self.opacity())`, computed only when it asks. `out` takes the commands an
26
- # actor pushes for after the walk (`ctx.out.push(ESpawn(..))`, `ctx.out.push(EKill(..))`,
27
- # `ctx.send(msg)`).
28
- #
29
- # fun step(self, ctx: ECtx[Msg], dt: Float) -> Gun =
30
- # ctx.out.push(ESpawn(parent: 0, node: FRoseTree.leaf(Bullet(id: self.next, at: self.at))))
31
- # Gun(..self, next: self.next + 1)
32
- #
33
- # A context is a value. The walk makes one for each parent with children (`under`), with
34
- # one multiply, and hands it to every child: the lazy world transform of master's `ECtx`
35
- # without the cached field and the `retarget` that master needs to reuse one context.
36
- struct ECtx[M](up: Affine, alpha: Float, out: Slice[ECmd[M]]) =
37
-
38
- # The context above a stage's root: the identity transform, full opacity, no commands.
39
- fun init() -> ECtx[M] =
40
- ECtx(up: Affine.Identity, alpha: 1.0, out: Slice[ECmd[M]]())
41
-
42
- # The world transform of a child whose own transform is `local`.
43
- fun worldOf(self, local: Affine) -> Affine = self.up.mul(local)
44
-
45
- # The accumulated alpha of a child whose own is `a`.
46
- fun alphaOf(self, a: Float) -> Float = self.alpha * a
47
-
48
- # The context for the children of a child with the transform `local` and opacity `a`:
49
- # the same commands, the child's world transform above them.
50
- fun under(self, local: Affine, a: Float) -> ECtx[M] =
51
- ECtx(up: self.up.mul(local), alpha: self.alpha * a, out: self.out)
52
-
53
- # Sends `msg` to the game's store after the step.
54
- fun send(self, msg: M) = self.out.push(ESend(msg: msg))
55
-
56
- # The messages sent so far, oldest first, taken out of `out` (its other commands stay,
57
- # in order).
58
- fun takeSends(self) -> List[M] =
59
- if self.out.length() == 0
60
- Nil
61
- else
62
- msgs := ecmdSends(self.out, self.out.length() - 1, Nil)
63
- ecmdKeepOnly(self.out, false)
64
- msgs
65
-
66
- # The messages of `cmds` up to index `i`, oldest first, in front of `acc`.
67
- fun ecmdSends[M](cmds: Slice[ECmd[M]], i: Int, acc: List[M]) -> List[M] =
68
- if i < 0
69
- acc
70
- else
71
- match cmds.at(i)
72
- ESend(m) => ecmdSends(cmds, i - 1, Cons(m, acc))
73
- _ => ecmdSends(cmds, i - 1, acc)
74
-
75
- # Keeps in `cmds` only its sends (`sends` true) or only its other commands, in order.
76
- fun ecmdKeepOnly[M](cmds: Slice[ECmd[M]], sends: Bool) =
77
- kept := Slice[ECmd[M]]()
78
- for c := range cmds
79
- if ecmdIsSend(c) == sends
80
- kept.push(c)
81
- cmds.clear()
82
- cmds.add(kept)
83
-
84
- fun ecmdIsSend[M](c: ECmd[M]) -> Bool = match c
85
- ESend(_) => true
86
- _ => false
87
-
88
- test "under multiplies the child's transform into the parent's"
89
- c := ECtx[Int]()
90
- m := Affine(a: 2.0, b: 0.0, c: 0.0, d: 2.0, e: 1.0, f: 0.0)
91
- u := c.under(m, 0.5).under(m, 0.5)
92
- assert u.up.a == 4.0 && u.up.e == 3.0
93
- assert u.alpha == 0.25
94
- assert u.worldOf(m).e == 7.0
95
- u.out.push(EKill(id: 3))
96
- assert c.out.length() == 1
97
-
98
- test "sends are taken out in order and the other commands stay"
99
- c := ECtx[Str]()
100
- c.send("a")
101
- c.out.push(EKill(id: 3))
102
- c.under(Affine.Identity, 1.0).send("b")
103
- c.out.push(EKill(id: 4))
104
- msgs := c.takeSends()
105
- assert msgs.length() == 2 && msgs.get(0).unwrap() == "a" && msgs.get(1).unwrap() == "b"
106
- assert c.out.length() == 2
107
- assert c.takeSends().isEmpty()
108
- assert c.out.length() == 2