plum

#treesitter#compiler#wasm

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

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


8461d00 — Peter John 2026-11-10T11:07:21+05:30
game std: pointer routing finds the hit first, cheaper idle ticks, allAs/kidsAs, FRoseTree walks in constant stack
docs/game.md CHANGED
@@ -258,7 +258,7 @@ Each kind of actor is its own struct, with only its own fields, that `is Actor[M
258
258
 
259
259
  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. An actor that doesn't change should return `self` from `step` and `input` (the defaults do), not a copy: an `input` that returns the actor as it was leaves the tree as it was (`ref.same`, see [std](std.md#utilities)), and a screen's `react` that returns its tree as it was (the default) leaves the game's tree as it was. std gives `Group` (a parent that paints nothing) and `Box`; [`std/game/ui.plum`](../std/game/ui.plum) gives `Label` and `Button` (`ui.button(id, x, y, w, h, label, onClick)`). A button shows the pointer over it and a press on it, and a press and a release on it send its `onClick` message.
260
260
 
261
- The tree's `step(ctx, dt)` steps every actor, parents before children, then applies the spawns and kills; `input(ctx, e)` routes one pointer event. `Game` calls both. `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, which is how a screen's `rules` and `react` read and change one kind's own fields in its subtree. `subtree(id)` is an actor with its subtree as a tree of its own, and `withTop(a)` a tree with its root actor replaced. A pattern `Orb as o` on an `Actor[M]` matches an `Orb`.
261
+ The tree's `step(ctx, dt)` steps every actor, parents before children, then applies the spawns and kills; `input(ctx, e)` routes one pointer event. `Game` calls both. `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, which is how a screen's `rules` and `react` read and change one kind's own fields in its subtree. `allAs[T]()` is every actor of the type `T`, in tree order, and `kidsAs[T](parent)` the `T`s among one actor's children (a layer: `t.kidsAs[Balloon](BalloonLayer)`), which is how `rules` reads one kind's actors. `subtree(id)` is an actor with its subtree as a tree of its own, and `withTop(a)` a tree with its root actor replaced. A pattern `Orb as o` on an `Actor[M]` matches an `Orb`.
262
262
 
263
263
  [`std/game/Anim.plum`](../std/game/Anim.plum) adds animation by time.
264
264
 
docs/std.md CHANGED
@@ -127,7 +127,7 @@ Only true tail calls run in constant stack; other recursion overflows at a few t
127
127
  - **`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.
128
128
  - **`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`).
129
129
  - **`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.
130
- - **`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.
130
+ - **`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; every walk runs in constant stack along the siblings (a node with 200,000 children is fine), and only the tree's depth takes stack. `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.
131
131
  - **`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.
132
132
 
133
133
  ## Option and Result
examples/games/kids/balloon_pop.plum CHANGED
@@ -92,13 +92,12 @@ fun centred(io: Io, m: Affine, s: Str, cx: Float, y: Float, size: Float, color:
92
92
  actor.textPaint(io, m, 1.0, s, cx - size * 0.3 * Float(s.length()), y, size, color)
93
93
 
94
94
  # Grows in, then pulses gently.
95
- fun partyAnim() -> Anim =
95
+ PartyAnim = Seq(
96
- Seq(
97
- steps: [
96
+ steps: [
98
- ScaleTo(sx: 1.4, sy: 1.4, secs: 0.25),
97
+ ScaleTo(sx: 1.4, sy: 1.4, secs: 0.25),
99
- Forever(anim: Seq(steps: [ScaleTo(sx: 0.85, sy: 0.85, secs: 0.4), ScaleTo(sx: 1.0 / 0.85, sy: 1.0 / 0.85, secs: 0.4)]))
98
+ Forever(anim: Seq(steps: [ScaleTo(sx: 0.85, sy: 0.85, secs: 0.4), ScaleTo(sx: 1.0 / 0.85, sy: 1.0 / 0.85, secs: 0.4)]))
100
- ]
99
+ ]
101
- )
100
+ )
102
101
 
103
102
  fun zoomOf(sw: Float, sh: Float) -> Float =
104
103
  {sw / ArenaW}.min(sh / ArenaH)
@@ -253,7 +252,7 @@ struct Party(id: Int, partyAt: Float, clock: Float, pops: Int) is Actor[Msg] =
253
252
 
254
253
  fun paint(self, io: Io, m: Affine, alpha: Float) =
255
254
  age := self.clock - self.partyAt
256
- p := Anim.at(partyAnim(), age)
255
+ p := Anim.at(PartyAnim, age)
257
256
  paintConfetti(io, m, age)
258
257
  c := m.mul(place.at(ArenaW / 2.0, 250.0).scaleTo(p.scaleX, p.scaleY).local())
259
258
  centred(io, c, "Hooray!", 0.0, -40.0, 72.0, Color.rgb(0.95, 0.3, 0.5))
@@ -351,11 +350,14 @@ struct SkyScreen(id: Int) is Screen[State, Msg] =
351
350
  gfx.clear(io, Color.rgb(0.55, 0.8, 1.0))
352
351
  shown.draw(io)
353
352
 
354
- # The balloons of `t`, in tree order.
353
+ # The balloons of `t`, in tree order: the children of their layer.
354
+ fun balloonsOf(t: SceneTree[Msg]) -> List[Balloon] = t.kidsAs[Balloon](BalloonLayer)
355
+
355
- fun balloonsOf(t: SceneTree[Msg]) -> List[Balloon] =
356
+ fun firstBalloon(t: SceneTree[Msg]) -> Balloon =
357
+ # Bound to an annotated local first: `t.kidsAs[Balloon](..).at(0)` straight on fails in
358
+ # codegen with fusion on (`unknown function 'get$kidsAs$0'`).
356
- t.root.fold(Nil, |acc, a| match a
359
+ bs: List[Balloon] := balloonsOf(t)
357
- Balloon as b => Cons(head: b, tail: acc)
358
- _ => acc).reverse()
360
+ bs.at(0)
359
361
 
360
362
  # A new game's tree and state.
361
363
  struct Play(tree: SceneTree[Msg], state: State)
@@ -375,7 +377,7 @@ fun newGame() -> Game[State, Msg] =
375
377
  Game.start(play.tree, play.state)
376
378
 
377
379
  fun first(g: Game[State, Msg]) -> Balloon =
378
- balloonsOf(g.screenTree()).at(0)
380
+ firstBalloon(g.screenTree())
379
381
 
380
382
  # A tick of `dt` with `events` on a `view` screen.
381
383
  fun tickOn(io: Io, g: Game[State, Msg], events: List[InputEvent], dt: Float, view: Vec2) -> Game[State, Msg] =
@@ -455,5 +457,5 @@ test "the press is found through the camera"
455
457
  test "the same seed gives the same balloons"
456
458
  a := SkyScreen.start(State.start(9, Sound.Silent, Sound.Silent))
457
459
  b := SkyScreen.start(State.start(9, Sound.Silent, Sound.Silent))
458
- assert balloonsOf(a.tree).at(0).x == balloonsOf(b.tree).at(0).x
460
+ assert firstBalloon(a.tree).x == firstBalloon(b.tree).x
459
- assert balloonsOf(a.tree).at(0).hue == balloonsOf(b.tree).at(0).hue
461
+ assert firstBalloon(a.tree).hue == firstBalloon(b.tree).hue
examples/games/orb_run.plum CHANGED
@@ -163,23 +163,22 @@ fun mineCount(score: Int) -> Int =
163
163
  {3 + score / 50}.min(8)
164
164
 
165
165
  # The hurt flash: the ship shrinks and recovers every 0.1 s (the scale returns to 1 each lap).
166
- fun hitFlash() -> Anim =
166
+ # A constant, built once, not on every frame that asks for a pose.
167
- Forever(anim: Seq(steps: [ScaleTo(sx: 0.4, sy: 0.4, secs: 0.05), ScaleTo(sx: 2.5, sy: 2.5, secs: 0.05)]))
167
+ HitFlash = Forever(anim: Seq(steps: [ScaleTo(sx: 0.4, sy: 0.4, secs: 0.05), ScaleTo(sx: 2.5, sy: 2.5, secs: 0.05)]))
168
168
 
169
169
  fun flashPose(t: Float) -> AnimPose =
170
- Anim.at(hitFlash(), t)
170
+ Anim.at(HitFlash, t)
171
171
 
172
172
  # The game-over title: grows to 1.3x, then pulses between 1.17x and 1.3x.
173
- fun titleAnim() -> Anim =
173
+ TitleAnim = Seq(
174
- Seq(
175
- steps: [
174
+ steps: [
176
- ScaleTo(sx: 1.3, sy: 1.3, secs: 0.3),
175
+ ScaleTo(sx: 1.3, sy: 1.3, secs: 0.3),
177
- 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)]))
176
+ 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)]))
178
- ]
177
+ ]
179
- )
178
+ )
180
179
 
181
180
  fun titlePose(t: Float) -> AnimPose =
182
- Anim.at(titleAnim(), t)
181
+ Anim.at(TitleAnim, t)
183
182
 
184
183
  # The zoom that fits the arena into a `sw` by `sh` screen, and where its corner lands.
185
184
  fun fitZoom(sw: Float, sh: Float) -> Float =
@@ -613,12 +612,13 @@ struct PlayScreen(id: Int) is Screen[State, Msg] =
613
612
  # After every actor stepped: the orbs the ship touches, the mines to grow, a mine that
614
613
  # hits the ship (unless it is still flashing from the last).
615
614
  fun rules(self, t: SceneTree[Msg], ctx: Ctx[Msg], state: State, dt: Float) -> SceneTree[Msg] =
615
+ b := bodiesOf(t)
616
- sh := t.findAs[Ship](ShipId).unwrap()
616
+ sh := b.ship.unwrap()
617
- for o := range orbsOf(t)
617
+ for o := range b.orbs
618
618
  if overlaps(sh.x, sh.y, ShipRadius, o.x, o.y, OrbRadius)
619
619
  ctx.send(Collected(id: o.id, x: sh.x, y: sh.y))
620
620
  ctx.send(Grow(x: sh.x, y: sh.y))
621
- if sh.hurt <= 0.0 && minesOf(t).find(|m| overlaps(sh.x, sh.y, ShipRadius, m.x, m.y, MineRadius)).isSome()
621
+ if sh.hurt <= 0.0 && b.mines.find(|m| overlaps(sh.x, sh.y, ShipRadius, m.x, m.y, MineRadius)).isSome()
622
622
  ctx.send(Hurt)
623
623
  t
624
624
 
@@ -635,16 +635,30 @@ struct PlayScreen(id: Int) is Screen[State, Msg] =
635
635
  # How long the play screen takes to fade in over the title, in seconds.
636
636
  TitleFade = 0.5
637
637
 
638
+ # What the play screen's rules read: the ship, the orbs and the mines.
639
+ struct Bodies(ship: Option[Ship], orbs: List[Orb], mines: List[Mine])
640
+
641
+ # The bodies of the play screen's tree `t`, read in one walk along the screen's children
638
- # The orbs and the mines of `t`, in tree order.
642
+ # (the ship, and the orb and mine layers), so the stars are never visited.
639
- fun orbsOf(t: SceneTree[Msg]) -> List[Orb] =
640
- t.root.fold(Nil, |acc, a| match a
641
- Orb as o => Cons(head: o, tail: acc)
642
- _ => acc).reverse()
643
-
644
- fun minesOf(t: SceneTree[Msg]) -> List[Mine] =
643
+ fun bodiesOf(t: SceneTree[Msg]) -> Bodies =
644
+ none: Option[Ship] := None
645
+ orbs: List[Orb] := Nil
646
+ mines: List[Mine] := Nil
647
+ layersFrom(t.root.kids(), Bodies(ship: none, orbs: orbs, mines: mines))
648
+
649
+ fun layersFrom(c: FRoseTree[Actor[Msg]], b: Bodies) -> Bodies = match c
650
+ FRoseEmpty => b
645
- t.root.fold(Nil, |acc, a| match a
651
+ FRoseNode(a, k, n) =>
652
+ id := a.key()
653
+ next := if id == OrbLayer
654
+ Bodies(..b, orbs: scenetree.chainAs[Orb, Msg](k))
655
+ else if id == MineLayer
656
+ Bodies(..b, mines: scenetree.chainAs[Mine, Msg](k))
657
+ else
658
+ match a
646
- Mine as m => Cons(head: m, tail: acc)
659
+ Ship as sh => Bodies(..b, ship: Some(sh))
647
- _ => acc).reverse()
660
+ _ => b
661
+ layersFrom(n, next)
648
662
 
649
663
  # The hud's labels from the score.
650
664
  fun showScore(t: SceneTree[Msg], state: State) -> SceneTree[Msg] =
std/collections/functional/FRoseTree.plum CHANGED
@@ -5,6 +5,7 @@ import std/Bool
5
5
  import std/Str
6
6
  import std/Option
7
7
  import std/List
8
+ import std/ref
8
9
 
9
10
  # A rose tree written functionally (see std/collections/functional/FAvlTree for the
10
11
  # rules of the folder): a persistent tree in which a node has any number of children,
@@ -25,10 +26,11 @@ import std/List
25
26
  # preorder; `t.append(n)` puts `n` at the end of the chain. `addChild` works on the node
26
27
  # itself (the first of the chain), and keeps its siblings.
27
28
  #
28
- # Every walk is a recursion over the chain. Walks that rebuild a chain (`map`, `filter`,
29
+ # Every walk is a recursion over the chain, and runs in constant stack along it: `fold`,
30
+ # `each`, `find`, `toList` and `chain` are tail calls on the siblings, `map`, `concat` and
29
- # `append`) recurse once per sibling, so a chain's length is bounded by the stack (tens
31
+ # `append` build the chain front to back (tail modulo cons), and `chainOf`, `filter` and
30
- # of thousands of nodes); `fold`, `each`, `find`, `toList` and `chain` are tail calls on
32
+ # `replace` (`update`) keep the nodes they passed in a list, last on top, and link them
31
- # the siblings and run in constant stack along a chain.
33
+ # back with tail calls. Only the depth of the tree takes stack.
32
34
  #
33
35
  # Siblings are kept in order: the first child comes first in every walk (std/game/scene's
34
36
  # SceneTree draws it first and hits it last). Appending a child copies the link nodes of its earlier
@@ -52,12 +54,18 @@ enum FRoseTree[T] =
52
54
  FRoseNode(value: v, firstChild: FRoseTree.chainOf(kids), nextSibling: empty)
53
55
 
54
56
  # The nodes of `ns` (each with its subtree, not its siblings) linked into one chain, in
55
- # order.
57
+ # order. Linked from the last one back, a tail call per node: constant stack.
56
- fun chainOf(ns: List[FRoseTree[T]]) -> FRoseTree[T] = match ns
58
+ fun chainOf(ns: List[FRoseTree[T]]) -> FRoseTree[T] =
59
+ empty: FRoseTree[T] := FRoseEmpty
60
+ FRoseTree.linkOnto(ns.reverse(), empty)
61
+
62
+ # The nodes of `rev` (each without its siblings), linked in front of `acc` one by one, so
63
+ # that the last of `rev` comes first.
64
+ fun linkOnto(rev: List[FRoseTree[T]], acc: FRoseTree[T]) -> FRoseTree[T] = match rev
57
- Nil => FRoseEmpty
65
+ Nil => acc
58
66
  Cons(h, t) => match h
59
- FRoseEmpty => FRoseTree.chainOf(t)
67
+ FRoseEmpty => FRoseTree.linkOnto(t, acc)
60
- FRoseNode(v, k, _) => FRoseNode(value: v, firstChild: k, nextSibling: FRoseTree.chainOf(t))
68
+ FRoseNode(v, k, _) => FRoseTree.linkOnto(t, FRoseNode(value: v, firstChild: k, nextSibling: acc))
61
69
 
62
70
  fun isEmpty(self) -> Bool = match self
63
71
  FRoseEmpty => true
@@ -118,16 +126,34 @@ enum FRoseTree[T] =
118
126
 
119
127
  # The tree without the nodes whose value fails `keep`; a dropped node takes its subtree
120
128
  # with it. A chain in which nothing was dropped, at any depth, is returned as it was (the
121
- # same value), so untouched subtrees are shared.
129
+ # same value), so untouched subtrees are shared. One tail call per sibling (recursion
130
+ # only into children): a chain of any length runs in constant stack.
122
- fun filter(self, keep: fn(T) -> Bool) -> FRoseTree[T] = match self
131
+ fun filter(self, keep: fn(T) -> Bool) -> FRoseTree[T] =
132
+ nil: List[FRoseTree[T]] := Nil
133
+ self.filterFrom(self, keep, nil, nil, self, false)
134
+
135
+ # `filter`'s walk along the chain. `done` holds the nodes up to the last change, last on
136
+ # top, each with its children filtered; `run` the unchanged nodes since then, which
137
+ # `runStart` (the chain from the first of them) still links, so a chain's unchanged end
138
+ # is shared. `changed` is whether anything was dropped; `whole` is the chain the walk
139
+ # started from, returned when nothing was.
140
+ fun filterFrom(self, whole: FRoseTree[T], keep: fn(T) -> Bool, done: List[FRoseTree[T]], run: List[FRoseTree[T]], runStart: FRoseTree[T], changed: Bool) -> FRoseTree[T] = match self
123
- FRoseEmpty => self
141
+ FRoseEmpty =>
142
+ if changed
143
+ FRoseTree.linkOnto(done, if run.isEmpty() then self else runStart)
144
+ else
145
+ whole
124
146
  FRoseNode(v, k, n) =>
147
+ nil: List[FRoseTree[T]] := Nil
125
148
  if keep(v)
126
149
  k2 := k.filter(keep)
127
- n2 := n.filter(keep)
150
+ if k2 == k
151
+ n.filterFrom(whole, keep, done, Cons(head: self, tail: run), if run.isEmpty() then self else runStart, changed)
152
+ else
128
- if k2 == k && n2 == n then self else FRoseNode(value: v, firstChild: k2, nextSibling: n2)
153
+ node := FRoseNode(value: v, firstChild: k2, nextSibling: n)
154
+ n.filterFrom(whole, keep, Cons(head: node, tail: run.append(done)), nil, n, true)
129
155
  else
130
- n.filter(keep)
156
+ n.filterFrom(whole, keep, run.append(done), nil, n, true)
131
157
 
132
158
  # The chain with the node `n` (and its subtree, not its siblings) added at the end.
133
159
  fun append(self, n: FRoseTree[T]) -> FRoseTree[T] = self.concat(n.alone())
@@ -170,20 +196,27 @@ enum FRoseTree[T] =
170
196
  # to that node is shared: the node's later siblings, the subtrees of its earlier ones
171
197
  # (only their link nodes are copied) and of its ancestors' siblings alike. With no
172
198
  # match, the tree itself is returned.
199
+ # One tail call per sibling (recursion only into children): constant stack along a chain.
173
- fun replace(self, pick: fn(T) -> Bool, f: fn(FRoseTree[T]) -> FRoseTree[T]) -> FRoseTree[T] = match self
200
+ fun replace(self, pick: fn(T) -> Bool, f: fn(FRoseTree[T]) -> FRoseTree[T]) -> FRoseTree[T] =
201
+ nil: List[FRoseTree[T]] := Nil
202
+ self.replaceFrom(self, pick, f, nil)
203
+
204
+ # `replace`'s walk along the chain: `passed` holds the nodes before this one, last on
205
+ # top, relinked in front of the changed node once it is found. `whole` is the chain the
206
+ # walk started from, returned when nothing matches.
207
+ fun replaceFrom(self, whole: FRoseTree[T], pick: fn(T) -> Bool, f: fn(FRoseTree[T]) -> FRoseTree[T], passed: List[FRoseTree[T]]) -> FRoseTree[T] = match self
174
- FRoseEmpty => self
208
+ FRoseEmpty => whole
175
209
  FRoseNode(v, k, n) =>
176
210
  if pick(v)
177
211
  match f(self.alone())
178
- FRoseEmpty => n
212
+ FRoseEmpty => FRoseTree.linkOnto(passed, n)
179
- FRoseNode(v2, k2, _) => FRoseNode(value: v2, firstChild: k2, nextSibling: n)
213
+ FRoseNode(v2, k2, _) => FRoseTree.linkOnto(passed, FRoseNode(value: v2, firstChild: k2, nextSibling: n))
180
214
  else
181
215
  k2 := k.replace(pick, f)
182
216
  if k2 != k
183
- FRoseNode(value: v, firstChild: k2, nextSibling: n)
217
+ FRoseTree.linkOnto(passed, FRoseNode(value: v, firstChild: k2, nextSibling: n))
184
218
  else
185
- n2 := n.replace(pick, f)
186
- if n2 == n then self else FRoseNode(value: v, firstChild: k, nextSibling: n2)
219
+ n.replaceFrom(whole, pick, f, Cons(head: self, tail: passed))
187
220
 
188
221
  # The tree with the value of the first node, in preorder, that passes `pick` replaced by
189
222
  # `f(value)`. As `replace`, it shares everything off the path.
@@ -308,3 +341,20 @@ test "a sibling chain of 10,000 nodes"
308
341
  u := t.update(|v| v == 9999, |v| 0)
309
342
  assert u.fold(0, |a, v| a + v) == 49995000 - 1 - 9999
310
343
  assert t.filter(|v| v < 0 || v % 2 == 0).count() == 5001
344
+
345
+ test "200000 children: of, chainOf, filter, replace, update, addChild and map run in constant stack"
346
+ kids := fRoseLeaves(200000, Nil)
347
+ t := FRoseTree.of(-1, kids)
348
+ assert t.count() == 200001
349
+ assert FRoseTree.chainOf(kids).count() == 200000
350
+ assert t.filter(|v| v != 199999).count() == 200000
351
+ assert t.filter(|v| v < 0 || v % 2 == 0).count() == 100001
352
+ assert ref.same(t.filter(|v| v != 0).kids(), t.kids().rest())
353
+ assert ref.same(t.filter(|v| v != -5), t)
354
+ u := t.update(|v| v == 199999, |v| 7)
355
+ assert u.count() == 200001 && u.kids().fold(0, |a, v| a + v) == t.kids().fold(0, |a, v| a + v) - 199999 + 7
356
+ assert ref.same(t.update(|v| v == -5, |v| 7), t)
357
+ assert t.replace(|v| v == 100000, |n| FRoseEmpty).count() == 200000
358
+ assert t.addChild(FRoseTree.leaf(7)).count() == 200002
359
+ assert t.map(|v| v + 1).fold(0, |a, v| a + v) == t.fold(0, |a, v| a + v) + 200001
360
+ assert t.kids().toList().length() == 200000
std/game/Game.plum CHANGED
@@ -162,13 +162,14 @@ struct ShiftFrame[M](id: Int, x: Float, y: Float, alpha: Float) is Actor[M] =
162
162
  ShiftFrameId = -1000001
163
163
 
164
164
  # A running game: the tree (the root and its screens), the store, the name of the current
165
- # screen, a name the state asks for that no screen has ("" if none), the transition in
165
+ # screen and its actor's key, a name the state asks for that no screen has ("" if none), the transition in
166
166
  # progress, the first tree and state (for `Restart`), whether it has exited, the ticks it
167
167
  # has run, where the last pointer event was, and the size of the screen at the last tick.
168
168
  struct Game[S: Reducer[M], M](
169
169
  tree: SceneTree[M],
170
170
  store: Store[S, M],
171
171
  current: Str,
172
+ screenKey: Int,
172
173
  unknown: Str,
173
174
  shift: Option[Shift],
174
175
  first: SceneTree[M],
@@ -189,11 +190,11 @@ struct Game[S: Reducer[M], M](
189
190
  crash e
190
191
  none: Option[Shift] := None
191
192
  Game(
192
- tree: tree, store: Store.of(state), current: name, unknown: "", shift: none, first: tree, initial: state,
193
+ tree: tree, store: Store.of(state), current: name, screenKey: keyOf[S, M](tree, name), unknown: "", shift: none, first: tree, initial: state,
193
194
  exited: false, ticks: 0, pointer: NoPointer, view: Vec2(x: 0.0, y: 0.0))
194
195
 
195
- # The key of the current screen's actor.
196
+ # The key of the current screen's actor (kept with its name, so a tick doesn't look it up).
196
- fun currentKey(self) -> Int = keyOf[S, M](self.tree, self.current)
197
+ fun currentKey(self) -> Int = self.screenKey
197
198
 
198
199
  # The state now.
199
200
  fun state(self) -> S = self.store.state
@@ -263,12 +264,14 @@ struct Game[S: Reducer[M], M](
263
264
  pointer := lastPointer(input.events, self.pointer)
264
265
  if turn.restart && !turn.exit
265
266
  none: Option[Shift] := None
267
+ again := chosen[S, M](self.first, self.initial.screen())
266
268
  Game(
267
- ..self, tree: self.first, store: Store.of(self.initial), current: chosen[S, M](self.first, self.initial.screen()), unknown: "", shift: none,
269
+ ..self, tree: self.first, store: Store.of(self.initial), current: again, screenKey: keyOf[S, M](self.first, again), unknown: "", shift: none,
268
270
  ticks: self.ticks + 1, pointer: pointer, view: view)
269
271
  else
270
272
  ran := Game(..self, tree: turn.tree, store: flushed, shift: advanced(self.shift, dt), exited: turn.exit, ticks: self.ticks + 1, pointer: pointer, view: view)
273
+ # Only a message changes the state, so a tick that sent none names the same screen.
271
- ran.switched(io)
274
+ if ref.same(turn.store, self.store) then ran else ran.switched(io)
272
275
 
273
276
  # The game with the screen `state.screen()` names current, if it is another one: it
274
277
  # `enter`s, and comes in by its `transition`. A name no screen has keeps the current
@@ -293,7 +296,7 @@ struct Game[S: Reducer[M], M](
293
296
  entered := onScreen[S, M](self.tree, key, |s, t| s.enter(t, st, whole))
294
297
  how := transitionTo[S, M](entered, key, self.current)
295
298
  shift: Option[Shift] := if how.secs() > 0.0 then Some(Shift(from: self.current, how: how, t: 0.0)) else None
296
- Game(..self, tree: entered, current: to, unknown: "", shift: shift)
299
+ Game(..self, tree: entered, current: to, screenKey: key, unknown: "", shift: shift)
297
300
 
298
301
  # Draws a frame: the current screen's `draw` (by default the tree's) of what is shown.
299
302
  fun draw(self, io: Io) =
std/game/Store.plum CHANGED
@@ -47,10 +47,13 @@ struct Store[S: Reducer[M], M](state: S, queue: List[M]) =
47
47
  fun pending(self) -> List[M] = self.queue.reverse()
48
48
 
49
49
  # Runs `handle` on the state for each queued message, oldest first, and empties the queue.
50
+ # A store with nothing queued is returned as it is.
50
- fun flush(self, io: Io) -> Store[S, M] =
51
+ fun flush(self, io: Io) -> Store[S, M] = match self.queue
52
+ Nil => self
53
+ Cons(_, _) =>
51
- st := self.state
54
+ st := self.state
52
- self.pending().each(|m| st.handle(io, m))
55
+ self.pending().each(|m| st.handle(io, m))
53
- Store(state: st, queue: Nil)
56
+ Store(state: st, queue: Nil)
54
57
 
55
58
  # The state after each of `msgs` in order, with no effects: what a recorded run of
56
59
  # messages leads to.
std/game/scene/SceneTree.plum CHANGED
@@ -100,6 +100,18 @@ struct SceneTree[M](root: FRoseTree[Actor[M]], camX: Float, camY: Float, camScal
100
100
  Some(T as t) => Some(t)
101
101
  _ => None
102
102
 
103
+ # Every actor of the type `T`, in tree order (a parent before its children, siblings
104
+ # in order): `tree.allAs[Orb]()`.
105
+ fun allAs[T](self) -> List[T] =
106
+ nil: List[T] := Nil
107
+ self.root.fold(nil, |acc, a| match a
108
+ T as t => Cons(head: t, tail: acc)
109
+ _ => acc).reverse()
110
+
111
+ # The children of the actor `parent` that are `T`s, in order: one layer, not their
112
+ # subtrees (`tree.kidsAs[Balloon](BalloonLayer)`). Empty if there is no such actor.
113
+ fun kidsAs[T](self, parent: Int) -> List[T] = chainAs[T, M](nodeOf(self.root, parent).kids())
114
+
103
115
  # The tree with `n` added as the last child of the actor `parent`; unchanged if there
104
116
  # is no such actor.
105
117
  fun add(self, parent: Int, n: FRoseTree[Actor[M]]) -> SceneTree[M] =
@@ -132,39 +144,49 @@ struct SceneTree[M](root: FRoseTree[Actor[M]], camX: Float, camY: Float, camScal
132
144
  # the walk is over, as a second batch. Hidden actors are stepped too. `ctx.out` is left
133
145
  # with only the game's commands (`Send`, `Restart`, `Exit`), those pushed before the
134
146
  # step first, in order, for the game to take (`ctx.takeSends()`).
147
+ # A tick whose commands are all the game's (most ticks) walks with no batch at all, and
148
+ # one whose actors push no `Spawn` or `Kill` applies nothing after it.
135
149
  fun step(self, ctx: Ctx[M], dt: Float) -> SceneTree[M] =
150
+ r := if gameOnly(ctx.out, 0)
151
+ stepPlain(self.root, ctx, dt)
152
+ else
136
- w := TreeWalk.of(ctx.out)
153
+ w: TreeWalk[M] := TreeWalk.ofTree(ctx.out)
137
- ctx.keepOnly(true)
154
+ ctx.keepOnly(true)
138
- empty: FRoseTree[Actor[M]] := FRoseEmpty
155
+ empty: FRoseTree[Actor[M]] := FRoseEmpty
139
- r := stepChain(self.root, ctx, dt, w, empty)
156
+ stepChain(self.root, ctx, dt, w, empty)
140
- s := self.withRoot(r).apply(ctx.out)
157
+ s := self.withRoot(r)
158
+ if gameOnly(ctx.out, 0)
159
+ s
160
+ else
161
+ s2 := s.apply(ctx.out)
141
- ctx.keepOnly(true)
162
+ ctx.keepOnly(true)
142
- s
163
+ s2
143
164
 
144
165
  # The tree with the commands applied, in one pass over the tree: every `Kill` actor
145
166
  # goes with its subtree, and every `Spawn` node goes on top of its parent's children,
146
167
  # in the order pushed. A spawn whose parent is not on the tree, or is killed by the
147
168
  # same batch, is dropped. The game's commands (`Send`, `Restart`, `Exit`) are skipped.
148
169
  fun apply(self, cmds: Slice[Cmd[M]]) -> SceneTree[M] =
149
- if cmds.length() == 0
170
+ if gameOnly(cmds, 0)
150
171
  self
151
172
  else
152
- w := TreeWalk.of(cmds)
173
+ w: TreeWalk[M] := TreeWalk.ofTree(cmds)
153
- if !w.hasKills && !w.hasSpawns
154
- self
155
- else
156
- empty: FRoseTree[Actor[M]] := FRoseEmpty
174
+ empty: FRoseTree[Actor[M]] := FRoseEmpty
157
- self.withRoot(applyChain(self.root, w, empty))
175
+ self.withRoot(applyChain(self.root, w, empty))
158
176
 
159
177
  # The tree after the pointer event `e` (in tree coordinates; a key event changes
160
178
  # nothing): the topmost shown actor under it that says it is hit (as `hit` finds it)
161
179
  # gets it through `input`, then each of its parents up to the root. Each gets `e` in its
162
180
  # own coordinates (as `hit` gets its point) and its parent's context under `ctx` (as
163
181
  # `step` gives it). With no actor under the pointer the tree is returned as it was.
182
+ # The hit actor is found first, with no context built (`hitPath`); then only the nodes
183
+ # on its path are walked again, each child's context made from its parent's.
164
184
  fun input(self, ctx: Ctx[M], e: InputEvent) -> SceneTree[M] = match e.position()
165
185
  None => self
166
- Some(p) => match inputChain(self.root, ctx, p, e)
186
+ Some(p) => match hitPath(self.root, p, 0)
167
- Some(r) => self.withRoot(r)
187
+ Some(path) => match path
188
+ Cons(i, rest) => self.withRoot(routeChain(self.root, ctx, p, e, i, rest))
189
+ Nil => self
168
190
  None => self
169
191
 
170
192
  # What `draw` would draw, in order: each shown actor with its tree transform and alpha,
@@ -205,6 +227,17 @@ fun nodeOf[M](t: FRoseTree[Actor[M]], id: Int) -> FRoseTree[Actor[M]] = match t
205
227
  below := nodeOf(k, id)
206
228
  if below.isEmpty() then nodeOf(n, id) else below
207
229
 
230
+ # The actors of the chain `c` (not their subtrees) that are `T`s, in order.
231
+ fun chainAs[T, M](c: FRoseTree[Actor[M]]) -> List[T] =
232
+ nil: List[T] := Nil
233
+ chainAsOnto[T, M](c, nil).reverse()
234
+
235
+ fun chainAsOnto[T, M](c: FRoseTree[Actor[M]], acc: List[T]) -> List[T] = match c
236
+ FRoseEmpty => acc
237
+ FRoseNode(a, _, n) => chainAsOnto[T, M](n, match a
238
+ T as t => Cons(head: t, tail: acc)
239
+ _ => acc)
240
+
208
241
  # One entry of the draw list: a shown actor, its tree transform and its alpha.
209
242
  struct Drawn[M](actor: Actor[M], m: Affine, alpha: Float)
210
243
 
@@ -319,6 +352,22 @@ fun bitHas(bits: Array[Int], id: Int) -> Bool =
319
352
  w := id / 64
320
353
  if id < 0 || w >= bits.length() then false else {{bits.get(w) >> {id % 64}} & 1} == 1
321
354
 
355
+ # `stepChain` for a tick with no `Kill` and no `Spawn` before the step: no batch to ask.
356
+ fun stepPlain[M](t: FRoseTree[Actor[M]], ctx: Ctx[M], dt: Float) -> FRoseTree[Actor[M]] = match t
357
+ FRoseEmpty => t
358
+ FRoseNode(a, k, n) =>
359
+ if a.gone()
360
+ stepPlain(n, ctx, dt)
361
+ else
362
+ walkKids := !k.isEmpty()
363
+ cc := if walkKids then ctx.under(a.place().local(), a.opacity()) else ctx
364
+ na := a.step(ctx, dt)
365
+ if na.gone()
366
+ stepPlain(n, ctx, dt)
367
+ else
368
+ k2 := if walkKids then stepPlain(k, cc, dt) else k
369
+ FRoseNode(value: na, firstChild: k2, nextSibling: stepPlain(n, ctx, dt))
370
+
322
371
  # The chain `t` one step on, under `ctx` (the context of the chain's parent), without the
323
372
  # actors `w` kills, and followed by `extra` (the parent's spawns, unstepped). An actor with
324
373
  # children (or spawns) gets one context for them, made from its place before its step.
@@ -373,31 +422,55 @@ fun drawChain[M](t: FRoseTree[Actor[M]], io: Io, parent: Affine, alpha: Float) =
373
422
  drawChain(k, io, m, al)
374
423
  drawChain(n, io, parent, alpha)
375
424
 
425
+ # `p` (a point in the parent's coordinates of an actor at `pl`) in the actor's own
426
+ # coordinates: `pl.local().inverse().apply(p)`, or for an unscaled, unturned place about
427
+ # (0, 0) (most of them) the subtraction that gives.
428
+ fun toLocal(pl: Place, p: Vec2) -> Vec2 =
429
+ if pl.rotation == 0.0 && pl.scaleX == 1.0 && pl.scaleY == 1.0 && pl.originX == 0.0 && pl.originY == 0.0
430
+ Vec2(x: p.x - pl.x, y: p.y - pl.y)
431
+ else
432
+ pl.local().inverse().apply(p)
433
+
376
- # The chain `t` after the pointer event `e` at `p` (in the chain's parent's coordinates),
434
+ # Where the actor `hitChain` finds under `p` is in the chain `t` (whose first node is the
377
- # found as `hitChain` finds it: the hit actor's `input`, then its parents' on the way
435
+ # `i`-th of its siblings): its index among its siblings at each depth, from the chain down.
378
- # back up. None if no actor of the chain is hit (the chain is then unchanged), so one walk
379
- # both finds the actor and routes the event, and a miss builds nothing.
380
- fun inputChain[M](t: FRoseTree[Actor[M]], ctx: Ctx[M], p: Vec2, e: InputEvent) -> Option[FRoseTree[Actor[M]]] = match t
436
+ fun hitPath[M](t: FRoseTree[Actor[M]], p: Vec2, i: Int) -> Option[List[Int]] = match t
381
437
  FRoseEmpty => None
382
- FRoseNode(a, k, n) => match inputChain(n, ctx, p, e)
438
+ FRoseNode(a, k, n) => match hitPath(n, p, i + 1)
383
- Some(n2) => Some(if ref.same(n2, n) then t else FRoseNode(value: a, firstChild: k, nextSibling: n2))
439
+ Some(path) => Some(path)
384
440
  None =>
385
441
  if !isShown(a)
386
442
  None
387
443
  else
388
- local := a.place().local()
389
- q := local.inverse().apply(p)
444
+ q := toLocal(a.place(), p)
390
- rk := if k.isEmpty() then None else inputChain(k, ctx.under(local, a.opacity()), q, e)
445
+ below := if k.isEmpty() then None else hitPath(k, q, 0)
391
- match rk
446
+ match below
392
- Some(k2) =>
393
- na := a.input(ctx, InputEvent.pointerAt(e, q))
447
+ Some(path) => Some(Cons(head: i, tail: path))
394
- Some(if ref.same(na, a) && ref.same(k2, k) then t else FRoseNode(value: na, firstChild: k2, nextSibling: n))
395
448
  None =>
449
+ nil: List[Int] := Nil
450
+ if a.hit(q) then Some(Cons(head: i, tail: nil)) else None
451
+
452
+ # The chain `t` after the pointer event `e` at `p` (in the chain's parent's coordinates)
453
+ # went to the actor at `i`, then `path` below it (as `hitPath` found it): that actor's
454
+ # `input`, then its parents' on the way back up, each under its parent's context (`ctx`
455
+ # for this chain). A node whose actor and children come back as they were is kept, and so
456
+ # is every node off the path.
457
+ fun routeChain[M](t: FRoseTree[Actor[M]], ctx: Ctx[M], p: Vec2, e: InputEvent, i: Int, path: List[Int]) -> FRoseTree[Actor[M]] = match t
458
+ FRoseEmpty => t
459
+ FRoseNode(a, k, n) =>
396
- if a.hit(q)
460
+ if i > 0
461
+ n2 := routeChain(n, ctx, p, e, i - 1, path)
462
+ if ref.same(n2, n) then t else FRoseNode(value: a, firstChild: k, nextSibling: n2)
463
+ else
464
+ pl := a.place()
465
+ q := toLocal(pl, p)
466
+ match path
467
+ Cons(j, rest) =>
468
+ k2 := routeChain(k, ctx.under(pl.local(), a.opacity()), q, e, j, rest)
397
- na := a.input(ctx, InputEvent.pointerAt(e, q))
469
+ na := a.input(ctx, InputEvent.pointerAt(e, q))
470
+ if ref.same(na, a) && ref.same(k2, k) then t else FRoseNode(value: na, firstChild: k2, nextSibling: n)
471
+ Nil =>
472
+ na := a.input(ctx, InputEvent.pointerAt(e, q))
398
- Some(if ref.same(na, a) then t else FRoseNode(value: na, firstChild: k, nextSibling: n))
473
+ if ref.same(na, a) then t else FRoseNode(value: na, firstChild: k, nextSibling: n)
399
- else
400
- None
401
474
 
402
475
  # The topmost shown actor under `p` (a point in the chain's parent's coordinates) that
403
476
  # says it is hit: later siblings first, and in each, its children before itself.
@@ -408,7 +481,7 @@ fun hitChain[M](t: FRoseTree[Actor[M]], p: Vec2) -> Option[Actor[M]] = match t
408
481
  Some(found) => Some(found)
409
482
  None =>
410
483
  if isShown(a)
411
- q := a.place().local().inverse().apply(p)
484
+ q := toLocal(a.place(), p)
412
485
  match hitChain(k, q)
413
486
  Some(found) => Some(found)
414
487
  None => if a.hit(q) then Some(a) else None
@@ -789,3 +862,26 @@ test "a plain tree of std's Group and Box: add, step, draw list"
789
862
  assert s1.count() == 2
790
863
  assert s1.flatten().at(1).m.e == 10.0
791
864
  assert s1.hit(20.0, 10.0).unwrap().key() == 1
865
+
866
+ test "allAs gives every actor of a type in tree order, kidsAs one layer of it"
867
+ s := ttree().add(0, tgroup(10, 0.0, 0.0, 1.0, 0.0, [trect(11, 0.0, 0.0, 1.0), tclicker(12, 0.0), trect(13, 0.0, 0.0, 1.0)])).add(0, trect(14, 0.0, 0.0, 1.0)).add(11, trect(15, 0.0, 0.0, 1.0))
868
+ bodies := s.allAs[TBody]()
869
+ assert bodies.map(|b| b.id).toStr() == "[0,10,11,15,13,14]"
870
+ assert s.allAs[TClicker]().map(|c| c.id).toStr() == "[12]"
871
+ assert s.allAs[TKiller]().isEmpty()
872
+ assert s.kidsAs[TBody](10).map(|b| b.id).toStr() == "[11,13]"
873
+ assert s.kidsAs[TClicker](10).map(|c| c.id).toStr() == "[12]"
874
+ assert s.kidsAs[TBody](0).map(|b| b.id).toStr() == "[10,14]"
875
+ assert s.kidsAs[TBody](99).isEmpty() && s.kidsAs[TBody](15).isEmpty()
876
+
877
+ test "a kill among 200000 siblings runs in constant stack and keeps the others"
878
+ kids := 0.until(200000).fold(Slice[FRoseTree[Actor[Int]]](), |acc, i|
879
+ acc.push(trect(i + 1, 0.0, 0.0, 1.0))
880
+ acc
881
+ )
882
+ wide := SceneTree.of(tbody(0, 0.0, 0.0, 0.0)).withRoot(FRoseTree.of(tbody(0, 0.0, 0.0, 0.0), List.fromSlice(kids)))
883
+ assert wide.count() == 200001
884
+ k := wide.kill(100000)
885
+ assert k.count() == 200000 && k.find(100000).isNone() && k.find(100001).isSome()
886
+ assert wide.kill(-7).count() == 200001
887
+ assert wide.kidsAs[TBody](0).length() == 200000