plum

#treesitter#compiler#wasm

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

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


c5839be — Peter John 2026-11-09T22:25:05+05:30
Scene tree: keep unchanged nodes in input and the game's tick; mostly-still benchmark workloads
benchmarks/scene_trees/run.py CHANGED
@@ -2,7 +2,7 @@
2
2
  """Times the persistent scene tree on this branch against master's three scene trees.
3
3
 
4
4
  usage: python3 benchmarks/scene_trees/run.py --master DIR [--runs 5] [--sizes 100,1000,10000]
5
- [--workloads 1,...,9] [--out target/scene_trees]
5
+ [--workloads 1,...,11] [--out target/scene_trees]
6
6
  [--plum target/debug/plum] [--master-plum DIR/target/debug/plum]
7
7
 
8
8
  Run from the repository root of this branch, after `cargo build -p plum-cli`. `--master` is
@@ -29,7 +29,9 @@ wasmtime). Then every (workload, N, version) runs once per round, in a rotated o
29
29
  arguments and time with the microsecond clock; the branch's program reads them from
30
30
  `scene_trees.args` in its working folder and times with the branch's whole-ms clock. The
31
31
  table gives the median ms with the range, and fails if two runs that should agree print
32
- different checksums. Workloads 8 and 9 (snapshots kept) only run on the persistent trees.
32
+ different checksums. Workloads 8 and 9 (snapshots kept) only run on the persistent trees,
33
+ and 10 and 11 (mostly still: 1% of the leaves move, spread over the groups or all in one)
34
+ only on the branch: master's programs have no still leaves.
33
35
  """
34
36
  import argparse
35
37
  import os
@@ -40,7 +42,7 @@ import sys
40
42
 
41
43
  WORKLOADS = {1: "step", 2: "churn", 3: "draw", 4: "hit",
42
44
  5: "step, no transforms", 6: "step, eager transforms", 7: "churn, apply after",
43
- 8: "step, 60 kept", 9: "churn, 60 kept"}
45
+ 8: "step, 60 kept", 9: "churn, 60 kept", 10: "mostly still", 11: "mostly still, one group"}
44
46
  MASTER = ["game", "game_tree", "enum_tree"]
45
47
  BRANCH = [("branch", []), ("branch --no-fbip", ["--no-fbip"]), ("branch --no-fusion", ["--no-fusion"])]
46
48
  HERE = os.path.dirname(os.path.abspath(__file__))
@@ -63,7 +65,7 @@ def main():
63
65
  ap.add_argument("--master", required=True, help="a built checkout of master")
64
66
  ap.add_argument("--runs", type=int, default=5)
65
67
  ap.add_argument("--sizes", default="100,1000,10000")
66
- ap.add_argument("--workloads", default="1,2,3,4,5,6,7,8,9")
68
+ ap.add_argument("--workloads", default="1,2,3,4,5,6,7,8,9,10,11")
67
69
  ap.add_argument("--out", default="target/scene_trees")
68
70
  ap.add_argument("--plum", default="target/debug/plum", help="this branch's compiler")
69
71
  ap.add_argument("--master-plum", help="master's compiler (default: DIR/target/debug/plum)")
@@ -89,7 +91,7 @@ def main():
89
91
  times, sums = {}, {}
90
92
  for r in range(args.runs):
91
93
  for w, n in cells:
92
- vs = [v for v in versions if w < 8 or v not in ("game", "game_tree")]
94
+ vs = [v for v in versions if (w < 8 or v not in ("game", "game_tree")) and (w < 10 or v not in MASTER)]
93
95
  k = r % len(vs)
94
96
  for v in vs[k:] + vs[:k]:
95
97
  if v in MASTER:
@@ -114,7 +116,7 @@ def main():
114
116
  row += " - |"
115
117
  continue
116
118
  row += f" {fmt(statistics.median(ts))} ({fmt(min(ts))}-{fmt(max(ts))}) |"
117
- e = statistics.median(times[(w, n, "enum_tree")])
119
+ e = statistics.median(times[(w, n, "enum_tree")]) if (w, n, "enum_tree") in times else 0
118
120
  b = statistics.median(times[(w, n, "branch")])
119
121
  row += f" {b / e:.2f}x |" if e > 0 else " - |"
120
122
  row += f" {', '.join(sorted(sums[(w, n)]))} |"
benchmarks/scene_trees/scene_tree.plum CHANGED
@@ -43,6 +43,11 @@ import std/game/scene/SceneTree
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.
46
+ # 10 mostly still: 1 with only 1% of the leaves moving (every 101st, so spread over all
47
+ # the groups); the others are `Still`s, whose step returns them as they are.
48
+ # 11 mostly still, one group: 10 with the moving 1% all in the first group (every 10th of
49
+ # its leaves), the other nine groups still: a HUD or a menu beside the action.
50
+ # Workloads 10 and 11 are the branch's own: master's programs have no still leaves.
46
51
 
47
52
  struct Rng(mut s: Int) =
48
53
  fun next(self, k: Int) -> Int =
@@ -74,6 +79,17 @@ struct Bod(id: Int, x: Float, y: Float, vx: Float, vy: Float) is Actor[Int] =
74
79
  vy := if ny < 0.0 || ny > 200.0 then 0.0 - self.vy else self.vy
75
80
  Bod(..self, x: nx, y: ny, vx: vx, vy: vy)
76
81
 
82
+ # A leaf that never moves: `Bod` without a velocity, whose step is `Actor`'s default (it
83
+ # returns the leaf as it is).
84
+ struct Still(id: Int, x: Float, y: Float) is Actor[Int] =
85
+ fun key(self) -> Int = self.id
86
+
87
+ fun place(self) -> Place = place.at(self.x, self.y)
88
+
89
+ fun paint(self, io: Io, m: Affine, alpha: Float) = actor.boxPaint(io, m, alpha, 20.0, 20.0, Color.Red)
90
+
91
+ fun hit(self, p: Vec2) -> Bool = actor.boxHit(20.0, 20.0, p)
92
+
77
93
  # A group at (x, y), scaled by `s` and turned by `r` radians: it paints nothing.
78
94
  struct Turned(id: Int, x: Float, y: Float, s: Float, r: Float) is Actor[Int] =
79
95
  fun key(self) -> Int = self.id
@@ -83,12 +99,25 @@ struct Turned(id: Int, x: Float, y: Float, s: Float, r: Float) is Actor[Int] =
83
99
  fun group(id: Int, x: Float, y: Float, s: Float, r: Float) -> Actor[Int] =
84
100
  Turned(id: id, x: x, y: y, s: s, r: r)
85
101
 
102
+ fun newLeaf(rng: Rng, id: Int) -> FRoseTree[Actor[Int]] = leafOf(rng, id, true)
103
+
104
+ # `newLeaf`, a `Still` at the same place unless `moves` (the same random numbers either way).
86
- fun newLeaf(rng: Rng, id: Int) -> FRoseTree[Actor[Int]] =
105
+ fun leafOf(rng: Rng, id: Int, moves: Bool) -> FRoseTree[Actor[Int]] =
87
106
  x := rng.float(200)
88
107
  y := rng.float(200)
89
108
  vx := rng.float(100) - 50.0
90
109
  vy := rng.float(100) - 50.0
91
- FRoseTree.leaf(Bod(id: id, x: x, y: y, vx: vx, vy: vy))
110
+ a: Actor[Int] := if moves then Bod(id: id, x: x, y: y, vx: vx, vy: vy) else Still(id: id, x: x, y: y)
111
+ FRoseTree.leaf(a)
112
+
113
+ # Whether leaf `i` (from 0) moves in workload `w`: all of them but in 10 and 11.
114
+ fun moving(w: Int, i: Int) -> Bool =
115
+ if w == 10
116
+ i % 101 == 0
117
+ else if w == 11
118
+ i % 10 == 0 && {i / 10} % 10 == 0
119
+ else
120
+ true
92
121
 
93
122
  # What the workloads change besides the stage: the live ids, the random numbers, the next
94
123
  # id to give out.
@@ -98,12 +127,12 @@ fun bench(n: Int) -> Bench = Bench(live: Slice[Int](), rng: Rng(s: 12345), nextI
98
127
 
99
128
  # The scene, built bottom up as master builds it: each group's children first, then the
100
129
  # groups under the root. Ids: the root 0, the groups 1 to 10, the leaves from 11.
101
- fun build(n: Int, sc: Bench) -> SceneTree[Int] =
130
+ fun build(n: Int, sc: Bench, w: Int) -> SceneTree[Int] =
102
131
  kids := Slice[Slice[FRoseTree[Actor[Int]]]]()
103
132
  for g := range 10
104
133
  kids.push(Slice[FRoseTree[Actor[Int]]]())
105
134
  for i := range n - 11
106
- kids.at(i % 10).push(newLeaf(sc.rng, 11 + i))
135
+ kids.at(i % 10).push(leafOf(sc.rng, 11 + i, moving(w, i)))
107
136
  sc.live.push(11 + i)
108
137
  groups := Slice[FRoseTree[Actor[Int]]]()
109
138
  for g := range 10
@@ -246,7 +275,7 @@ fun work(stage: SceneTree[Int], sc: Bench, w: Int, n: Int) -> Int =
246
275
  dt := 1.0 / 60.0
247
276
  ctx := Ctx[Int]()
248
277
  k := {{n - 11} / 100}.max(1)
249
- if w == 1
278
+ if w == 1 || w == 10 || w == 11
250
279
  hashTree(steps(stage, ctx, dt, 1000).root, 0)
251
280
  else if w == 2 || w == 7
252
281
  hashTree(churns(stage, sc, ctx, dt, k, 1000, w == 7).root, 0) + sc.live.length()
@@ -264,7 +293,7 @@ fun work(stage: SceneTree[Int], sc: Bench, w: Int, n: Int) -> Int =
264
293
  # Builds the scene, then times the workload alone with the wall clock.
265
294
  fun run(io: Io, w: Int, n: Int) -> Int =
266
295
  sc := bench(n)
267
- stage := build(n, sc)
296
+ stage := build(n, sc, w)
268
297
  t0 := io.rawNowMillis()
269
298
  sum := work(stage, sc, w, n)
270
299
  ms := io.rawNowMillis() - t0
@@ -281,7 +310,7 @@ fun main(io: Io) =
281
310
 
282
311
  fun check(w: Int) -> Int =
283
312
  sc := bench(100)
284
- work(build(100, sc), sc, w, 100)
313
+ work(build(100, sc, w), sc, w, 100)
285
314
 
286
315
  # The same checksums as master's three versions.
287
316
  test "the nine workloads at N = 100 give master's checksums"
@@ -294,3 +323,19 @@ test "the nine workloads at N = 100 give master's checksums"
294
323
  assert check(7) == 998134459
295
324
  assert check(8) == 809683012
296
325
  assert check(9) == 998134459
326
+
327
+ test "mostly still: the still leaves stay where they are, the moving ones move"
328
+ sc := bench(1000)
329
+ stage := build(1000, sc, 10)
330
+ ctx := Ctx[Int]()
331
+ later := steps(stage, ctx, 1.0 / 60.0, 30)
332
+ assert later.count() == stage.count()
333
+ moved := stage.root.fold(0, |acc, a|
334
+ match later.find(a.key())
335
+ Some(b) => if a.place().x != b.place().x || a.place().y != b.place().y then acc + 1 else acc
336
+ None => acc)
337
+ # Leaves 0, 101, .. 909 of 989: 10 move (a bounce never brings one back exactly).
338
+ assert moved == 10
339
+ sc2 := bench(1000)
340
+ still := build(1000, sc2, 11)
341
+ assert hashTree(steps(still, ctx, 1.0 / 60.0, 30).root, 0) != hashTree(still.root, 0)
docs/backlog.md CHANGED
@@ -30,7 +30,7 @@ Open work, in the order the user queued it, plus smaller items found during buil
30
30
  - **Generics in `<>`, traits in `[]`** (user 2026-11-09, later): `struct Ship<M>[Actor<M>, Clickable](x: Float, y: Float)`, `fun map<B>(..) -> Option<B>`, `Slice<Jv>()`, `stage.updateAs<Orb>(id, f)`; replaces `[]` generics and the `is` clause. In expressions `<` is also less-than: parse `name<...>` as type arguments only when the matching `>` is directly followed by `(`, `.` or `)` (C#/Kotlin rule; `a < B > (c)` would compare a Bool), and split `>>` in nested types. Mechanical but touches every generic in std, examples, tests, docs, the parser, tree-sitter and type-printing snapshots; do it as one task. An intermediate option discussed: `struct Ship(Actor, Clickable)(x: Float, y: Float)` with `[]` generics kept.
31
31
  - **Optional or automatic actor keys** (user 2026-11-09, after the actor-trait plan). Store does not replace `key`: the Store holds game state, while `key` names one actor in the tree for `Kill(id)`, `updateAs[T](id, f)`, `findAs[T](id)` and messages like `Collected(id)`. Most actors don't need one: self-removal uses `gone`, messages can carry data (`Collected(points: 10)`), and singletons can be found by type (`findAs[Player]()`). Options: (a) make `key` a default method `fun key(self) -> Option[Int] = None`, overridden only by actors a rule must pick out; (b) have the tree hand out ids itself: a counter in `SceneTree`, the id stored in the tree node next to the actor (not in the actor), given on `Spawn`, and returned by queries such as `findAll[Orb]() -> List[Pair[Int, Orb]]`. Use a counter, not a random id: it is unique, needs no `Random` and keeps replays deterministic. Not an index or path in the tree, which changes after a kill. Open: how a spawner learns its child's id (maybe `Spawn(actor, onId: fn(Int) -> M)`).
32
32
  - **Faster SceneTree step, staying functional** (user 2026-11-09: backlog it; bring it up only if the master vs simpler-language benchmark is really bad). No mutation in the language: better data structures, caching and FBIP. Today `stepChain` (std/game/scene/SceneTree.plum) rebuilds an `FRoseNode` per live actor per step, recurses down `nextSibling` (10k-deep for 10k siblings), and makes 3–5 trait dispatches per actor (`gone` before and after `step`, `key`, `place`, `opacity`). In order:
33
- 1. **Keep unchanged nodes:** after `step`, if the actor is the same reference (`ref.eq`, default `step` returns `self`) and its children are unchanged, keep the old node and allocate nothing. Optionally a cached per-node "subtree can change" flag, so still subtrees (menus, HUD) are skipped whole, like Flutter `const` or React `memo`. Helps real games; not the all-actors-move benchmark, so add a "mostly static" workload.
33
+ 1. **Keep unchanged nodes:** tried 2026-11-09; the mechanism landed, the step walk kept its rebuild. std's `ref.same(a, b)` (std/ref.plum: one `ref.eq`; the checker allows heap types only; a variable passed to it is never updated in place, `plum_core::uniqueness`) now keeps unchanged nodes in `inputChain`, `withRoot` and Game's `liveAt`, `shown`, `spliced`, `replaceKid` and `onScreen` (a `react` that returns its tree, as for every `Tick`, leaves the game's tree as it was). In `stepChain` and `applyChain` it was slower, also on the new "mostly still" workloads 10 and 11 of benchmarks/scene_trees (10,000 actors, 1% moving: 148 ms rebuilding vs 240 ms sharing): keeping a node needs its later siblings' result before it is built, so the walk recurses along each sibling chain, and that loses the compiler's tail-modulo-cons loop, which builds a chain front to back without recursion. In a left-child right-sibling chain only a suffix after the last changed sibling could be kept anyway. Sharing in the step needs item 3 first (a chunked children vector, where a still chunk is kept whole), or a codegen loop that defers the copy of an unchanged run of siblings and links the old run at the end. The cached per-node "subtree can change" flag (skip still subtrees whole, like Flutter `const` or React `memo`) is not done: a node needs a field `FRoseTree` doesn't have, an actor needs a way to say its `step` is the default (returning `self` is not enough, `step` may push commands), and a `Spawn`/`Kill` batch into a still subtree must still walk it.
34
34
  2. **Fewer dispatches:** drop the pre-step `gone()` check (`apply` filters actors spawned gone); later maybe `key`/`place` as fields.
35
35
  3. **Chunked persistent vector for children** (32-way trie, wasm-gc array leaves, Clojure/Scala style) instead of the cons chain: about 32 times fewer spine allocations on a full map, a loop instead of deep recursion, log₃₂ n path copy for `updateAs`.
36
36
  4. **FBIP into the tree:** a binder taken out of a uniquely owned value by a consuming match is unique too (Koka Perceus-style reuse, done at compile time), so `stepChain` rebuilds nodes and actors in place; kept snapshots still copy.
docs/game.md CHANGED
@@ -256,7 +256,7 @@ Each kind of actor is its own struct, with only its own fields, that `is Actor[M
256
256
  - `hit(self, p)` says whether a point in its own coordinates is on it. Only an actor that says so gets pointer events, and is found by `tree.hit(x, y)` and `tree.hitId(x, y)`, topmost first.
257
257
  - `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.
258
258
 
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. 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.
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
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`.
262
262
 
std/game/Game.plum CHANGED
@@ -8,6 +8,7 @@ import std/Option
8
8
  import std/List
9
9
  import std/Slice
10
10
  import std/Io
11
+ import std/ref
11
12
  import std/game/Vec2
12
13
  import std/game/Affine
13
14
  import std/game/Color
@@ -206,15 +207,18 @@ struct Game[S: Reducer[M], M](
206
207
  fun shown(self) -> SceneTree[M] =
207
208
  match self.tree.root
208
209
  FRoseEmpty => self.tree
209
- FRoseNode(r, k, _) =>
210
+ FRoseNode(r, k, n) =>
210
211
  now := screenNode(k, self.currentKey())
211
212
  kids := match self.shift
212
213
  Some(s) =>
213
214
  out := framed(screenNode(k, keyOf[S, M](self.tree, s.from)), s.frame(false, self.view))
214
215
  out.concat(framed(now, s.frame(true, self.view)))
215
216
  None => now
217
+ if ref.same(kids, k) && n.isEmpty()
218
+ self.tree
219
+ else
216
- node: FRoseTree[Actor[M]] := FRoseNode(value: r, firstChild: kids, nextSibling: FRoseEmpty)
220
+ node: FRoseTree[Actor[M]] := FRoseNode(value: r, firstChild: kids, nextSibling: FRoseEmpty)
217
- self.tree.withRoot(node)
221
+ self.tree.withRoot(node)
218
222
 
219
223
  # The root over the screen that is stepped and gets input: the current one, under its
220
224
  # `ShiftFrame` during a transition.
@@ -224,13 +228,16 @@ struct Game[S: Reducer[M], M](
224
228
  fun liveAt(self, key: Int) -> SceneTree[M] =
225
229
  match self.tree.root
226
230
  FRoseEmpty => self.tree
227
- FRoseNode(r, k, _) =>
231
+ FRoseNode(r, k, n) =>
228
232
  now := screenNode(k, key)
229
233
  kids := match self.shift
230
234
  Some(s) => framed(now, s.frame(true, self.view))
231
235
  None => now
236
+ if ref.same(kids, k) && n.isEmpty()
237
+ self.tree
238
+ else
232
- node: FRoseTree[Actor[M]] := FRoseNode(value: r, firstChild: kids, nextSibling: FRoseEmpty)
239
+ node: FRoseTree[Actor[M]] := FRoseNode(value: r, firstChild: kids, nextSibling: FRoseEmpty)
233
- self.tree.withRoot(node)
240
+ self.tree.withRoot(node)
234
241
 
235
242
  # One tick of `dt` seconds with `input` on the host's screen: what the host runs.
236
243
  fun update(self, io: Io, input: Input, dt: Float) -> Game[S, M] =
@@ -371,10 +378,9 @@ fun screensError[S, M](tree: SceneTree[M], name: Str) -> Option[Str] =
371
378
  # siblings); empty if there is none.
372
379
  fun screenNode[M](kids: FRoseTree[Actor[M]], key: Int) -> FRoseTree[Actor[M]] = match kids
373
380
  FRoseEmpty => kids
374
- FRoseNode(a, k, n) =>
381
+ FRoseNode(a, _, n) =>
375
382
  if a.key() == key
376
- empty: FRoseTree[Actor[M]] := FRoseEmpty
383
+ kids.alone()
377
- FRoseNode(value: a, firstChild: k, nextSibling: empty)
378
384
  else
379
385
  screenNode(n, key)
380
386
 
@@ -394,12 +400,17 @@ fun framed[M](n: FRoseTree[Actor[M]], f: ShiftFrame[M]) -> FRoseTree[Actor[M]] =
394
400
  fun spliced[M](whole: FRoseTree[Actor[M]], live: FRoseTree[Actor[M]], key: Int) -> FRoseTree[Actor[M]] =
395
401
  match whole
396
402
  FRoseEmpty => whole
397
- FRoseNode(_, k, _) => match live
403
+ FRoseNode(r0, k, n0) => match live
398
404
  FRoseEmpty => live
399
405
  FRoseNode(r, lk, _) =>
406
+ put := replaceKid(k, key, liveScreen(lk, key))
407
+ extras := liveExtras(lk, key)
408
+ kids := if extras.isEmpty() then put else put.concat(extras)
409
+ if ref.same(r, r0) && ref.same(kids, k) && n0.isEmpty()
410
+ whole
411
+ else
400
- empty: FRoseTree[Actor[M]] := FRoseEmpty
412
+ empty: FRoseTree[Actor[M]] := FRoseEmpty
401
- kids := replaceKid(k, key, liveScreen(lk, key)).concat(liveExtras(lk, key))
402
- FRoseNode(value: r, firstChild: kids, nextSibling: empty)
413
+ FRoseNode(value: r, firstChild: kids, nextSibling: empty)
403
414
 
404
415
  # The screen `key` in the live root's children `lk`: there, or the child of its frame.
405
416
  fun liveScreen[M](lk: FRoseTree[Actor[M]], key: Int) -> FRoseTree[Actor[M]] = match lk
@@ -408,8 +419,7 @@ fun liveScreen[M](lk: FRoseTree[Actor[M]], key: Int) -> FRoseTree[Actor[M]] = ma
408
419
  if a.key() == ShiftFrameId
409
420
  screenNode(k, key)
410
421
  else if a.key() == key
411
- empty: FRoseTree[Actor[M]] := FRoseEmpty
412
- FRoseNode(value: a, firstChild: k, nextSibling: empty)
422
+ lk.alone()
413
423
  else
414
424
  liveScreen(n, key)
415
425
 
@@ -430,9 +440,10 @@ fun replaceKid[M](kids: FRoseTree[Actor[M]], key: Int, by: FRoseTree[Actor[M]])
430
440
  if a.key() == key
431
441
  match by
432
442
  FRoseEmpty => n
433
- FRoseNode(b, bk, _) => FRoseNode(value: b, firstChild: bk, nextSibling: n)
443
+ FRoseNode(b, bk, _) => if ref.same(b, a) && ref.same(bk, k) then kids else FRoseNode(value: b, firstChild: bk, nextSibling: n)
434
444
  else
445
+ n2 := replaceKid(n, key, by)
435
- FRoseNode(value: a, firstChild: k, nextSibling: replaceKid(n, key, by))
446
+ if ref.same(n2, n) then kids else FRoseNode(value: a, firstChild: k, nextSibling: n2)
436
447
 
437
448
  # The tree with the screen `key` (a child of the root) through `f` with its own subtree,
438
449
  # if it is a `Screen[S, M]`; unchanged otherwise.
@@ -449,7 +460,7 @@ fun onScreen[S, M](tree: SceneTree[M], key: Int, f: fn(Screen[S, M], SceneTree[M
449
460
  Some(x) => x.key() == ShiftFrameId
450
461
  None => false
451
462
  kids := if framedNow then framedAgain(k, sub.root) else replaceKid(k, key, sub.root)
452
- tree.withRoot(FRoseNode(value: r, firstChild: kids, nextSibling: n))
463
+ if ref.same(kids, k) then tree else tree.withRoot(FRoseNode(value: r, firstChild: kids, nextSibling: n))
453
464
  _ => tree
454
465
  None => tree
455
466
 
std/game/scene/SceneTree.plum CHANGED
@@ -12,6 +12,7 @@ import std/Map
12
12
  import std/Set
13
13
  import std/math
14
14
  import std/Io
15
+ import std/ref
15
16
  import std/game/Vec2
16
17
  import std/game/Affine
17
18
  import std/game/Color
@@ -48,19 +49,25 @@ import std/game/scene/Ctx
48
49
  # first to last. Hit testing goes the other way, topmost first: children before their
49
50
  # parent, later siblings before earlier ones.
50
51
  #
51
- # The walks (`step`, `apply`) rebuild every link node they pass instead of returning an
52
+ # The walks `step` and `apply` rebuild every link node they pass: each is one loop along a
52
- # unchanged chain as it was: sharing needs the old node after the match, and that use
53
- # would stop the compiler from writing the new node into the old one's cell. A step over
53
+ # sibling chain (the compiler builds the chain front to back, tail modulo cons), with
54
+ # recursion only into children. Keeping an unchanged node instead (`ref.same` on its actor,
55
+ # children and later siblings) needs the siblings' result before the node is built, so the
54
- # a tree nothing else holds therefore allocates no link nodes at all, and one over a kept
56
+ # walk recurses along the chain; that costs more than the nodes it saves, even when 99% of
57
+ # the actors stand still (benchmarks/scene_trees, workloads 10 and 11). `input`, which
58
+ # recurses anyway, keeps every node off the hit actor's path, and the hit node itself when
59
+ # the actor's `input` returns it as it was (`Actor`'s default); a value compared by
60
+ # `ref.same` is never updated in place (std/ref.plum), so a changed actor is always another
61
+ # object. `withRoot`, `apply` with nothing to do and `input` that hits nothing return the
55
- # tree copies all of them.
62
+ # tree itself.
56
63
  struct SceneTree[M](root: FRoseTree[Actor[M]], camX: Float, camY: Float, camScale: Float) =
57
64
 
58
65
  # A tree whose root is the actor `top`.
59
66
  fun of(top: Actor[M]) -> SceneTree[M] =
60
67
  SceneTree(root: FRoseTree.leaf(top), camX: 0.0, camY: 0.0, camScale: 1.0)
61
68
 
62
- # The same camera over another tree.
69
+ # The same camera over another tree; this very tree when `r` is its own root.
63
- fun withRoot(self, r: FRoseTree[Actor[M]]) -> SceneTree[M] = SceneTree(..self, root: r)
70
+ fun withRoot(self, r: FRoseTree[Actor[M]]) -> SceneTree[M] = if ref.same(r, self.root) then self else SceneTree(..self, root: r)
64
71
 
65
72
  # A game's tree (std/game/Game): a root group (id `ScreensRootId`) whose children are the
66
73
  # screens, in order.
@@ -130,7 +137,7 @@ struct SceneTree[M](root: FRoseTree[Actor[M]], camX: Float, camY: Float, camScal
130
137
  ctx.keepOnly(true)
131
138
  empty: FRoseTree[Actor[M]] := FRoseEmpty
132
139
  r := stepChain(self.root, ctx, dt, w, empty)
133
- s := SceneTree(..self, root: r).apply(ctx.out)
140
+ s := self.withRoot(r).apply(ctx.out)
134
141
  ctx.keepOnly(true)
135
142
  s
136
143
 
@@ -147,7 +154,7 @@ struct SceneTree[M](root: FRoseTree[Actor[M]], camX: Float, camY: Float, camScal
147
154
  self
148
155
  else
149
156
  empty: FRoseTree[Actor[M]] := FRoseEmpty
150
- SceneTree(..self, root: applyChain(self.root, w, empty))
157
+ self.withRoot(applyChain(self.root, w, empty))
151
158
 
152
159
  # The tree after the pointer event `e` (in tree coordinates; a key event changes
153
160
  # nothing): the topmost shown actor under it that says it is hit (as `hit` finds it)
@@ -157,7 +164,7 @@ struct SceneTree[M](root: FRoseTree[Actor[M]], camX: Float, camY: Float, camScal
157
164
  fun input(self, ctx: Ctx[M], e: InputEvent) -> SceneTree[M] = match e.position()
158
165
  None => self
159
166
  Some(p) => match inputChain(self.root, ctx, p, e)
160
- Some(r) => SceneTree(..self, root: r)
167
+ Some(r) => self.withRoot(r)
161
168
  None => self
162
169
 
163
170
  # What `draw` would draw, in order: each shown actor with its tree transform and alpha,
@@ -373,7 +380,7 @@ fun drawChain[M](t: FRoseTree[Actor[M]], io: Io, parent: Affine, alpha: Float) =
373
380
  fun inputChain[M](t: FRoseTree[Actor[M]], ctx: Ctx[M], p: Vec2, e: InputEvent) -> Option[FRoseTree[Actor[M]]] = match t
374
381
  FRoseEmpty => None
375
382
  FRoseNode(a, k, n) => match inputChain(n, ctx, p, e)
376
- Some(n2) => Some(FRoseNode(value: a, firstChild: k, nextSibling: n2))
383
+ Some(n2) => Some(if ref.same(n2, n) then t else FRoseNode(value: a, firstChild: k, nextSibling: n2))
377
384
  None =>
378
385
  if !isShown(a)
379
386
  None
@@ -382,10 +389,13 @@ fun inputChain[M](t: FRoseTree[Actor[M]], ctx: Ctx[M], p: Vec2, e: InputEvent) -
382
389
  q := local.inverse().apply(p)
383
390
  rk := if k.isEmpty() then None else inputChain(k, ctx.under(local, a.opacity()), q, e)
384
391
  match rk
392
+ Some(k2) =>
393
+ na := a.input(ctx, InputEvent.pointerAt(e, q))
385
- Some(k2) => Some(FRoseNode(value: a.input(ctx, InputEvent.pointerAt(e, q)), firstChild: k2, nextSibling: n))
394
+ Some(if ref.same(na, a) && ref.same(k2, k) then t else FRoseNode(value: na, firstChild: k2, nextSibling: n))
386
395
  None =>
387
396
  if a.hit(q)
397
+ na := a.input(ctx, InputEvent.pointerAt(e, q))
388
- Some(FRoseNode(value: a.input(ctx, InputEvent.pointerAt(e, q)), firstChild: k, nextSibling: n))
398
+ Some(if ref.same(na, a) then t else FRoseNode(value: na, firstChild: k, nextSibling: n))
389
399
  else
390
400
  None
391
401
 
@@ -451,6 +461,15 @@ struct TProbe(id: Int, at: Place, seen: Affine, seenA: Float) is Actor[Int] =
451
461
  fun step(self, ctx: Ctx[Int], dt: Float) -> TProbe =
452
462
  TProbe(..self, seen: ctx.worldOf(self.at.local()), seenA: ctx.alphaOf(self.opacity()))
453
463
 
464
+ # A 10 by 10 box at (x, 0) that counts the pointer events it gets.
465
+ struct TClicker(id: Int, x: Float, clicks: Int) is Actor[Int] =
466
+ fun key(self) -> Int = self.id
467
+ fun place(self) -> Place = place.at(self.x, 0.0)
468
+ fun hit(self, p: Vec2) -> Bool = actor.boxHit(10.0, 10.0, p)
469
+ fun input(self, ctx: Ctx[Int], e: InputEvent) -> TClicker = TClicker(..self, clicks: self.clicks + 1)
470
+
471
+ fun tclicker(id: Int, x: Float) -> FRoseTree[Actor[Int]] = FRoseTree.leaf(TClicker(id: id, x: x, clicks: 0))
472
+
454
473
  # Pushes `Kill(target)` in each step.
455
474
  struct TKiller(id: Int, target: Int) is Actor[Int] =
456
475
  fun key(self) -> Int = self.id
@@ -500,6 +519,9 @@ fun tfade(s: SceneTree[Int], id: Int, a: Float) -> SceneTree[Int] = s.updateAs[T
500
519
 
501
520
  fun thide(s: SceneTree[Int], id: Int) -> SceneTree[Int] = s.updateAs[TBody](id, |b| TBody(..b, visible: false))
502
521
 
522
+ # Steps a tree that nothing else holds, so an in-place update could take the old cells.
523
+ fun tstepFresh(vx: Float) -> SceneTree[Int] = ttree().add(0, trect(1, 0.0, 0.0, 5.0)).add(0, tdrifter(2, 0.0, vx, -1)).step(Ctx[Int](), 0.5)
524
+
503
525
  test "step returns a new tree and leaves a kept one as it was"
504
526
  s0 := ttree().add(0, tdrifter(1, 0.0, 10.0, -1)).add(0, tdrifter(2, 5.0, -10.0, -1))
505
527
  ctx := Ctx[Int]()
@@ -518,6 +540,32 @@ test "a step that changes nothing keeps every actor"
518
540
  assert tids(s1) == "0,1,2,3"
519
541
  assert s1.find(3).unwrap() == s0.find(3).unwrap()
520
542
 
543
+ test "input or apply that changes nothing returns the very same tree"
544
+ 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)]))
545
+ assert ref.same(s0.apply(Slice[Cmd[Int]]()), s0)
546
+ assert ref.same(s0.input(Ctx[Int](), PointerDown(x: 1000.0, y: 1000.0)), s0)
547
+ # A hit on a rect whose `input` is the default: the same tree.
548
+ assert ref.same(s0.input(Ctx[Int](), PointerDown(x: 1.0, y: 1.0)), s0)
549
+
550
+ test "input keeps the nodes off the hit actor's path"
551
+ s0 := ttree().add(0, tgroup(1, 0.0, 0.0, 1.0, 0.0, [trect(2, 0.0, 0.0, 5.0)])).add(0, tclicker(3, 100.0)).add(0, trect(4, 500.0, 0.0, 5.0))
552
+ s1 := s0.input(Ctx[Int](), PointerDown(x: 101.0, y: 1.0))
553
+ assert s1.findAs[TClicker](3).unwrap().clicks == 1
554
+ assert s0.findAs[TClicker](3).unwrap().clicks == 0
555
+ assert ref.same(nodeOf(s1.root, 4), nodeOf(s0.root, 4))
556
+ assert ref.same(s1.find(1).unwrap(), s0.find(1).unwrap())
557
+ assert ref.same(s1.find(2).unwrap(), s0.find(2).unwrap())
558
+
559
+ test "an actor whose step changes it is seen as changed, also where nothing else holds the tree"
560
+ # Under the default, `--no-fbip` and `--no-fusion` alike (the sweep runs all three): were
561
+ # the drifter written in place, `ref.same` would keep the old node and the old place.
562
+ assert tx(tstepFresh(10.0), 2) == 5.0
563
+ assert tx(tstepFresh(-4.0), 2) == -2.0
564
+ assert tx(tstepFresh(10.0).step(Ctx[Int](), 0.5), 2) == 10.0
565
+ clicked := ttree().add(0, tclicker(1, 0.0)).input(Ctx[Int](), PointerDown(x: 1.0, y: 1.0))
566
+ assert clicked.findAs[TClicker](1).unwrap().clicks == 1
567
+ assert clicked.input(Ctx[Int](), PointerDown(x: 1.0, y: 1.0)).findAs[TClicker](1).unwrap().clicks == 2
568
+
521
569
  test "an actor whose step returns it gone is dropped with its subtree in the same step"
522
570
  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))
523
571
  assert tids(s) == "0,1,3,2"