plum

#treesitter#compiler#wasm

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

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


59f2d55 — Peter John 2026-11-13T12:04:32+05:30
std/game: master's View and Actor[View], actors stepped by the game through the screen's stepped(dt), Screen.hud(window), steps and camera(base) (Viewport.lookAt); one walk over view (Container and paint gone, paintSelf); Circle by its centre, Label align, Overlay's size required and hit inside its box, Sprite.frameAt, math.near, Tween as a value; gfx drawRectEx and drawTextEx in std, the bridge, the native host and the recorder; the right and middle mouse buttons, the extra Keys, Input.axis and one set of readers, the replay's button mask; pointer events dropped and each screen on its own background in a transition; Screen without enter, leave, resize, draw and fresh, Control without restart; Effects' one dispatch slot, Game.pixels, frameDrawn, drawList, the kit's dispatch doing an undo at once; the culled draw's area mapped through the camera (it was compared in world units against pixels)
Files changed (65) hide show
  1. benchmarks/screen_views/scale.plum +20 -19
  2. benchmarks/screen_views/timing.plum +1 -1
  3. compiler/checker/tests/checker/modules_tests.rs +1 -1
  4. compiler/cli/tests/cli/game_in_place_test.rs +1 -1
  5. compiler/game/src/api.rs +5 -0
  6. compiler/game/src/host.rs +5 -0
  7. compiler/game/src/recorder.rs +6 -0
  8. compiler/game/tests/fixtures/assets_fixture.plum +10 -0
  9. compiler/game/tests/fixtures/camera_fixture.plum +70 -0
  10. compiler/game/tests/fixtures/host_fixture.plum +10 -0
  11. compiler/game/tests/fixtures/main_game_fixture.plum +10 -0
  12. compiler/game/tests/fixtures/main_missing_fixture.plum +10 -0
  13. compiler/game/tests/fixtures/state_draw_keeps.plum +10 -0
  14. compiler/game/tests/fixtures/state_in_place.plum +10 -0
  15. compiler/game/tests/fixtures/state_main_alias.plum +10 -0
  16. compiler/game/tests/fixtures/state_reset.plum +10 -0
  17. compiler/game/tests/fixtures/target_fixture.plum +10 -0
  18. compiler/game/tests/fixtures/turn_fixture.plum +33 -0
  19. compiler/game/tests/host_test.rs +108 -5
  20. compiler/game/web-test/fixtures/interleave.plum +10 -0
  21. compiler/game/web-test/fixtures/main_game.plum +10 -0
  22. compiler/game/web-test/fixtures/rendertarget.plum +14 -0
  23. compiler/game/web-test/fixtures/stress.plum +10 -0
  24. compiler/game/web-test/fixtures/stress_state_view.plum +22 -21
  25. compiler/game/web-test/fixtures/text_sizes.plum +10 -0
  26. compiler/game/web-test/tests/web_check.rs +1 -1
  27. compiler/game/web/plum_bridge.js +41 -1
  28. examples/games/balloonpop/BalloonPop.plum +0 -4
  29. examples/games/balloonpop/actors/Balloon.plum +15 -15
  30. examples/games/balloonpop/screens/PlaygroundScreen.plum +26 -27
  31. examples/games/clicks.plum +9 -9
  32. examples/games/orbitrunner/OrbitRunner.plum +0 -7
  33. examples/games/orbitrunner/actors/Mine.plum +10 -14
  34. examples/games/orbitrunner/actors/Orb.plum +6 -13
  35. examples/games/orbitrunner/actors/Ring.plum +6 -7
  36. examples/games/orbitrunner/actors/Ship.plum +31 -46
  37. examples/games/orbitrunner/actors/Star.plum +4 -4
  38. examples/games/orbitrunner/screens/PlayingScreen.plum +52 -52
  39. examples/games/two_screens.plum +14 -9
  40. std/game/Actor.plum +0 -289
  41. std/game/Box.plum +58 -0
  42. std/game/Circle.plum +19 -9
  43. std/game/Control.plum +6 -13
  44. std/game/Effects.plum +65 -0
  45. std/game/Game.plum +111 -85
  46. std/game/Group.plum +26 -0
  47. std/game/History.plum +7 -7
  48. std/game/Label.plum +50 -14
  49. std/game/Overlay.plum +34 -16
  50. std/game/Place.plum +2 -2
  51. std/game/Replay.plum +27 -6
  52. std/game/Screen.plum +114 -80
  53. std/game/ScreenSlice.plum +65 -61
  54. std/game/Sprite.plum +31 -8
  55. std/game/Touch.plum +1 -1
  56. std/game/Tween.plum +113 -0
  57. std/game/View.plum +343 -0
  58. std/game/Viewport.plum +40 -8
  59. std/game/gfx.plum +4 -0
  60. std/game/headless.plum +68 -65
  61. std/game/input.plum +152 -101
  62. std/math/math.plum +3 -0
  63. tests/port/game/replay.plum +19 -7
  64. tests/port/game/routing.plum +11 -11
  65. tests/port/game/screens.plum +135 -39
benchmarks/screen_views/scale.plum CHANGED
@@ -1,9 +1,13 @@
1
1
  # 10,000 actors on one screen, each moving its clock each tick, drawn by the screen's
2
2
  # view (as master's benchmarks/screen_views/scale.plum): with `view`, actors whose view is
3
3
  # one `Sprite`, made again at each draw; with `hand`, the same actors drawing the same
4
- # sprite with a hand-written `paint` (`sprite.drawSpriteFrame`). The screen's tick action
4
+ # sprite with a hand-written `paintSelf` (`sprite.drawSpriteFrame`). Each is an `Actor`,
5
+ # and the game steps every one each tick, before the tick action, through the screen's
6
+ # `stepped` (`view.stepIn` over its list); the tick action does nothing. One difference
5
- # steps every actor (its `stepped`, which returns the actor's next version). 20 ticks to
7
+ # from master: master's stepping walk makes each actor's view to look under it, and this
8
+ # branch's does not (an actor found under another could not be put back into a value), so
9
+ # `update view` makes 10,000 fewer one-`Sprite` lists a tick here. 20 ticks to warm up,
6
- # warm up, then 200 timed.
10
+ # then 200 timed.
7
11
  #
8
12
  # update each tick through the game (`Game.update`)
9
13
  # paint each tick, then the frame (`Game.draw`). Run with PLUM_NULL_GFX=1: there is no
@@ -32,7 +36,7 @@ import std/math/Aabb
32
36
  import std/game/Color
33
37
  import std/game/input
34
38
  import std/game/Place
35
- import std/game/Actor
39
+ import std/game/View
36
40
  import std/game/Sprite
37
41
  import std/game/Screen
38
42
  import std/game/ScreenSlice
@@ -47,9 +51,9 @@ struct ViewDot[Actor](i: Int, at: Place, clock: Float) =
47
51
 
48
52
  fun place(self) -> Place = self.at
49
53
 
50
- fun stepped(self, dt: Float) -> ViewDot = ViewDot(..self, clock: self.clock + dt)
54
+ fun step(self, dt: Float) -> ViewDot = ViewDot(..self, clock: self.clock + dt)
51
55
 
52
- fun view(self) -> List<Actor> =
56
+ fun view(self) -> List<View> =
53
57
  [Sprite(x: 0.0, y: 0.0, tex: Texture(id: 1), w: 16.0, h: 16.0, srcX: 0.0, srcY: 0.0, srcW: 16.0, srcH: 16.0, frame: Int(self.clock * 8.0) % 4, tint: Color.White, touch: Disabled)]
54
58
 
55
59
  struct HandDot[Actor](i: Int, at: Place, clock: Float) =
@@ -57,41 +61,38 @@ struct HandDot[Actor](i: Int, at: Place, clock: Float) =
57
61
 
58
62
  fun place(self) -> Place = self.at
59
63
 
60
- fun stepped(self, dt: Float) -> HandDot = HandDot(..self, clock: self.clock + dt)
64
+ fun step(self, dt: Float) -> HandDot = HandDot(..self, clock: self.clock + dt)
61
65
 
62
- fun paint(self, io: Io, m: Affine, alpha: Float) =
66
+ fun paintSelf(self, io: Io, m: Affine, alpha: Float) =
63
67
  frame := Int(self.clock * 8.0) % 4
64
68
  sprite.drawSpriteFrame(io, m, alpha, 16.0, 16.0, Color.White, Texture(id: 1), Float(frame) * 16.0, 0.0, 16.0, 16.0)
65
69
 
66
70
  enum CrowdAct = CrowdTick(dt: Float)
67
71
 
68
- struct CrowdScreen[ScreenSlice<CrowdAct>](hand: Bool, dots: List<Actor>) =
72
+ struct CrowdScreen[ScreenSlice<CrowdAct>](hand: Bool, dots: List<View>) =
69
73
  fun of(hand: Bool, n: Int) -> CrowdScreen = CrowdScreen(hand: hand, dots: dotsFrom(hand, 0, n))
70
74
 
71
75
  fun name(self) -> Str = "crowd"
72
76
 
73
- fun view(self) -> List<Actor> = self.dots
77
+ fun view(self) -> List<View> = self.dots
78
+
79
+ fun stepped(self, dt: Float) -> CrowdScreen = CrowdScreen(..self, dots: view.stepIn(self.dots, dt))
74
80
 
75
81
  fun tick(self, dt: Float) -> Option<CrowdAct> = Some(CrowdTick(dt: dt))
76
82
 
77
83
  fun reduce(self, a: CrowdAct) -> CrowdScreen = match a
78
- CrowdTick(dt) => CrowdScreen(..self, dots: self.dots.map(|d| stepDot(d, dt)))
84
+ CrowdTick(dt) => self
79
85
 
80
86
  fun frameSum(self) -> Int = timing.hash(self.dots.map(|d| frameOf(d)))
81
87
 
82
- fun dotsFrom(hand: Bool, i: Int, n: Int) -> List<Actor> =
88
+ fun dotsFrom(hand: Bool, i: Int, n: Int) -> List<View> =
83
89
  if i >= n
84
90
  Nil
85
91
  else
86
- d: Actor := if hand then HandDot.of(i) else ViewDot.of(i)
92
+ d: View := if hand then HandDot.of(i) else ViewDot.of(i)
87
93
  Cons(d, dotsFrom(hand, i + 1, n))
88
94
 
89
- fun stepDot(d: Actor, dt: Float) -> Actor = match d
90
- ViewDot as v => v.stepped(dt)
91
- HandDot as h => h.stepped(dt)
92
- _ => d
93
-
94
- fun frameOf(d: Actor) -> Int = match d
95
+ fun frameOf(d: View) -> Int = match d
95
96
  ViewDot as v => Int(v.clock * 8.0) % 4
96
97
  HandDot as h => Int(h.clock * 8.0) % 4
97
98
  _ => 0
benchmarks/screen_views/timing.plum CHANGED
@@ -29,7 +29,7 @@ fun script(seed: Int, tick: Int) -> Input =
29
29
  events := Slice<InputEvent>()
30
30
  if tick % 150 == 149
31
31
  events.push(KeyDown(key: Key.Enter))
32
- Input(held: Held(mouse: false, keys: keys), events: events, pos: Vec2(x: 0.0, y: 0.0), wheel: 0.0)
32
+ Input(held: Held.keysOnly(keys), events: events, pos: Vec2(x: 0.0, y: 0.0), wheel: 0.0)
33
33
 
34
34
  fun hash(xs: List<Int>) -> Int =
35
35
  xs.fold(17, |h, x|
compiler/checker/tests/checker/modules_tests.rs CHANGED
@@ -168,7 +168,7 @@ fn the_old_namespace_form_is_an_error() {
168
168
  fn a_game_calls_the_host_through_module_functions() {
169
169
  run(
170
170
  "gamemods",
171
- "import std/Float\nimport std/Io\nimport std/game/Color\nimport std/game/gfx\nimport std/game/input\n\nfun f(io: Io) -> Float =\n gfx.clear(io, Color.Black)\n input.axis(io, Key.Left, Key.Right)\n",
171
+ "import std/Float\nimport std/Io\nimport std/game/Color\nimport std/game/gfx\nimport std/game/input\n\nfun f(io: Io) -> Float =\n gfx.clear(io, Color.Black)\n _ := input.inHeld(InputEvent.keyCodes()).isDown(Key.Left)\n Input.create().poll(io).axis(Key.Left, Key.Right)\n",
172
172
  )
173
173
  .unwrap();
174
174
  }
compiler/cli/tests/cli/game_in_place_test.rs CHANGED
@@ -57,7 +57,7 @@ fn orbitRunnerKeepsItsInPlaceSpreads() {
57
57
  ("PlayingScreen.deal", 1),
58
58
  ("PlayingScreen.newOrb", 1),
59
59
  ("PlayingScreen.newMine$unique", 1),
60
- ("Mine.update", 1),
60
+ ("Mine.step", 1),
61
61
  ("Mine.put$unique", 1),
62
62
  ("Orb.put$unique", 1),
63
63
  ]);
compiler/game/src/api.rs CHANGED
@@ -23,9 +23,14 @@ pub trait Backend: 'static {
23
23
 
24
24
  fn clear(&mut self, c: Color);
25
25
  fn draw_rect(&mut self, x: f32, y: f32, w: f32, h: f32, c: Color);
26
+ /// The rect `(x, y, w, h)` turned `rotation` radians clockwise about its centre.
27
+ fn draw_rect_ex(&mut self, x: f32, y: f32, w: f32, h: f32, rotation: f32, c: Color);
26
28
  fn draw_circle(&mut self, x: f32, y: f32, r: f32, c: Color);
27
29
  fn draw_line(&mut self, x1: f32, y1: f32, x2: f32, y2: f32, thickness: f32, c: Color);
28
30
  fn draw_text(&mut self, s: &str, x: f32, y: f32, size: f32, c: Color);
31
+ /// The text with its top-left at `(x, y)`, turned `rotation` radians clockwise about it.
32
+ #[allow(clippy::too_many_arguments)]
33
+ fn draw_text_ex(&mut self, s: &str, x: f32, y: f32, size: f32, rotation: f32, c: Color);
29
34
 
30
35
  fn set_camera(&mut self, x: f32, y: f32, scale: f32);
31
36
  fn reset_camera(&mut self);
compiler/game/src/host.rs CHANGED
@@ -195,12 +195,17 @@ fn dispatch<B: Backend>(name: &str, caller: &mut Caller<'_, HostState<B>>, p: &[
195
195
  "frameTime" => r[0] = fv(b!().frame_time()),
196
196
  "clear" => b!().clear(color(p, 0)),
197
197
  "drawRect" => b!().draw_rect(f(p, 0), f(p, 1), f(p, 2), f(p, 3), color(p, 4)),
198
+ "drawRectEx" => b!().draw_rect_ex(f(p, 0), f(p, 1), f(p, 2), f(p, 3), f(p, 4), color(p, 5)),
198
199
  "drawCircle" => b!().draw_circle(f(p, 0), f(p, 1), f(p, 2), color(p, 3)),
199
200
  "drawLine" => b!().draw_line(f(p, 0), f(p, 1), f(p, 2), f(p, 3), f(p, 4), color(p, 5)),
200
201
  "drawText" => {
201
202
  let s = str_arg(caller, p, 0)?;
202
203
  b!().draw_text(&s, f(p, 1), f(p, 2), f(p, 3), color(p, 4));
203
204
  }
205
+ "drawTextEx" => {
206
+ let s = str_arg(caller, p, 0)?;
207
+ b!().draw_text_ex(&s, f(p, 1), f(p, 2), f(p, 3), f(p, 4), color(p, 5));
208
+ }
204
209
  "setCamera" => b!().set_camera(f(p, 0), f(p, 1), f(p, 2)),
205
210
  "resetCamera" => b!().reset_camera(),
206
211
  "textureLoad" => {
compiler/game/src/recorder.rs CHANGED
@@ -73,6 +73,9 @@ impl Backend for Recorder {
73
73
  fn draw_rect(&mut self, x: f32, y: f32, w: f32, h: f32, c: Color) {
74
74
  self.rec(format!("drawRect({x},{y},{w},{h},{})", c4(c)));
75
75
  }
76
+ fn draw_rect_ex(&mut self, x: f32, y: f32, w: f32, h: f32, rotation: f32, c: Color) {
77
+ self.rec(format!("drawRectEx({x},{y},{w},{h},{rotation},{})", c4(c)));
78
+ }
76
79
  fn draw_circle(&mut self, x: f32, y: f32, r: f32, c: Color) {
77
80
  self.rec(format!("drawCircle({x},{y},{r},{})", c4(c)));
78
81
  }
@@ -82,6 +85,9 @@ impl Backend for Recorder {
82
85
  fn draw_text(&mut self, s: &str, x: f32, y: f32, size: f32, c: Color) {
83
86
  self.rec(format!("drawText({s:?},{x},{y},{size},{})", c4(c)));
84
87
  }
88
+ fn draw_text_ex(&mut self, s: &str, x: f32, y: f32, size: f32, rotation: f32, c: Color) {
89
+ self.rec(format!("drawTextEx({s:?},{x},{y},{size},{rotation},{})", c4(c)));
90
+ }
85
91
  fn set_camera(&mut self, x: f32, y: f32, scale: f32) {
86
92
  self.rec(format!("setCamera({x},{y},{scale})"));
87
93
  }
compiler/game/tests/fixtures/assets_fixture.plum CHANGED
@@ -16,6 +16,8 @@ import std/math/Aabb
16
16
  import std/game/Screen
17
17
  import std/game/ScreenSlice
18
18
  import std/game/Game
19
+ import std/game/View
20
+ import std/game/Place
19
21
 
20
22
  # Loads through the raw `io` (a missing file answers -1 or empty, where `Texture.load`
21
23
  # would crash) and draws through it.
@@ -27,6 +29,8 @@ struct State[ScreenSlice<Float>](frames: Int) =
27
29
  fun reduce(self, dt: Float) -> State = State(frames: self.frames + 1)
28
30
 
29
31
  # Loads a texture and files from the asset root and reports what came back as text.
32
+ fun view(self) -> List<View> = [StateDrawing(s: self)]
33
+
30
34
  fun draw(self, io: Io, m: Affine, alpha: Float, area: Aabb) =
31
35
  t := Texture(id: gfx.textureLoad(io, "sprites.png"))
32
36
  gfx.drawText(io, "size {gfx.textureWidth(io, t.id)}x{gfx.textureHeight(io, t.id)}", 0.0, 0.0, 8.0, Color.White)
@@ -40,6 +44,12 @@ struct State[ScreenSlice<Float>](frames: Int) =
40
44
  gfx.drawText(io, "escape {gfx.textureLoad(io, "../sprites.png")} {gfx.fileExists(io, "../hello.txt")} [{gfx.fileLoad(io, "../hello.txt")}]", 0.0, 0.0, 8.0, Color.White)
41
45
  gfx.drawText(io, "abs {gfx.textureLoad(io, "/etc/hosts")} {gfx.fileExists(io, "/etc/hosts")}", 0.0, 0.0, 8.0, Color.White)
42
46
 
47
+ # What the screen draws each frame, with `gfx` by hand.
48
+ struct StateDrawing[View](s: State) =
49
+ fun place(self) -> Place = place.at(0.0, 0.0)
50
+
51
+ fun paintSelf(self, io: Io, m: Affine, alpha: Float) = self.s.draw(io, m, alpha, Aabb.of(0.0, 0.0, 0.0, 0.0))
52
+
43
53
  fun main(io: Io) -> Game =
44
54
  Game(screens: [page(State(frames: 0))])
45
55
 
compiler/game/tests/fixtures/camera_fixture.plum ADDED
@@ -0,0 +1,70 @@
1
+ module camera_fixture
2
+
3
+ import std/Int
4
+ import std/Float
5
+ import std/Str
6
+ import std/Io
7
+ import std/Option
8
+ import std/collections/List
9
+ import std/math/Vec2
10
+ import std/game/Color
11
+ import std/game/input
12
+ import std/game/View
13
+ import std/game/Box
14
+ import std/game/Viewport
15
+ import std/game/Control
16
+ import std/game/Screen
17
+ import std/game/ScreenSlice
18
+ import std/game/Game
19
+
20
+ # F, I, E and S set the first screen's scaling to Fit, Fill, Extend and Stretch; G goes to
21
+ # the second screen, which slides in from the right over one second.
22
+ enum CamAct = Use(scaling: Scaling) | Go
23
+
24
+ # A culled 400 by 300 world: a red box inside it at (10, 100) and a blue one just right of
25
+ # it at (420, 100), both 20 by 20.
26
+ struct CamScreen[ScreenSlice<CamAct>](scaling: Scaling) =
27
+ fun name(self) -> Str = "cam"
28
+
29
+ fun size(self) -> Vec2 = Vec2(x: 400.0, y: 300.0)
30
+
31
+ fun viewport(self) -> Scaling = self.scaling
32
+
33
+ fun culls(self) -> Bool = true
34
+
35
+ fun view(self) -> List<View> = [Box.of(10.0, 100.0, 20.0, 20.0, Color.Red), Box.of(420.0, 100.0, 20.0, 20.0, Color.Blue)]
36
+
37
+ fun onKey(self, e: InputEvent) -> Option<CamAct> = match e
38
+ KeyDown(k) =>
39
+ if k == Key.KeyF then Some(Use(scaling: Fit))
40
+ else if k == Key.KeyI then Some(Use(scaling: Fill))
41
+ else if k == Key.KeyE then Some(Use(scaling: Extend))
42
+ else if k == Key.KeyS then Some(Use(scaling: Stretch))
43
+ else if k == Key.KeyG then Some(Go)
44
+ else None
45
+ _ => None
46
+
47
+ fun reduce(self, a: CamAct) -> CamScreen = match a
48
+ Use(s) => CamScreen(scaling: s)
49
+ Go => self
50
+
51
+ fun effect(self, io: Io, a: CamAct, game: Control) = match a
52
+ Go => game.goTo("two")
53
+ _ => Unit
54
+
55
+ # A culled 400 by 300 world, fitted: a green box at (10, 100) and a white one at (300, 100).
56
+ struct TwoScreen[Screen](n: Int) =
57
+ fun name(self) -> Str = "two"
58
+
59
+ fun size(self) -> Vec2 = Vec2(x: 400.0, y: 300.0)
60
+
61
+ fun culls(self) -> Bool = true
62
+
63
+ fun transition(self, from: Str) -> Transition = Slide(from: FromRight, secs: 1.0)
64
+
65
+ fun view(self) -> List<View> = [Box.of(10.0, 100.0, 20.0, 20.0, Color.Green), Box.of(300.0, 100.0, 20.0, 20.0, Color.White)]
66
+
67
+ fun main(io: Io) -> Game =
68
+ cam: Screen := CamScreen(scaling: Fit)
69
+ two: Screen := TwoScreen(n: 0)
70
+ Game(screens: [cam, two])
compiler/game/tests/fixtures/host_fixture.plum CHANGED
@@ -16,6 +16,8 @@ import std/math/Aabb
16
16
  import std/game/Screen
17
17
  import std/game/ScreenSlice
18
18
  import std/game/Game
19
+ import std/game/View
20
+ import std/game/Place
19
21
 
20
22
  # One raw host read in `draw` (`mousePos`), so the recorded call order is fixed. The game
21
23
  # clears the frame (`Screen.background`, black) before the screen draws. The
@@ -27,6 +29,8 @@ struct State[ScreenSlice<Float>](frames: Int) =
27
29
 
28
30
  fun reduce(self, dt: Float) -> State = State(frames: self.frames + 1)
29
31
 
32
+ fun view(self) -> List<View> = [StateDrawing(s: self)]
33
+
30
34
  fun draw(self, io: Io, m: Affine, alpha: Float, area: Aabb) =
31
35
  gfx.drawRect(io, 1.0, 2.0, 3.0, 4.0, Color.Red)
32
36
  gfx.drawCircle(io, 5.0, 6.0, 7.0, Color.Green)
@@ -35,6 +39,12 @@ struct State[ScreenSlice<Float>](frames: Int) =
35
39
  if self.frames > 0
36
40
  gfx.drawText(io, "frames {self.frames}", 0.0, 0.0, 8.0, Color.White)
37
41
 
42
+ # What the screen draws each frame, with `gfx` by hand.
43
+ struct StateDrawing[View](s: State) =
44
+ fun place(self) -> Place = place.at(0.0, 0.0)
45
+
46
+ fun paintSelf(self, io: Io, m: Affine, alpha: Float) = self.s.draw(io, m, alpha, Aabb.of(0.0, 0.0, 0.0, 0.0))
47
+
38
48
  fun main(io: Io) -> Game =
39
49
  Game(screens: [page(State(frames: 0))])
40
50
 
compiler/game/tests/fixtures/main_game_fixture.plum CHANGED
@@ -17,6 +17,8 @@ import std/game/Screen
17
17
  import std/game/ScreenSlice
18
18
  import std/game/Game
19
19
  import std/Io
20
+ import std/game/View
21
+ import std/game/Place
20
22
 
21
23
  # A game whose entry is `main`, declared to return a `Game`: one screen, `Orbs`, that keeps
22
24
  # the input of its last tick and moves while Right is held.
@@ -35,11 +37,19 @@ struct Orbs[ScreenSlice<Step>](x: Float, ship: Texture, input: Input, frame: Int
35
37
  x := if self.input.isKeyDown(Key.Right) then self.x + 100.0 * dt else self.x
36
38
  Orbs(..self, x: x, frame: self.frame + 1)
37
39
 
40
+ fun view(self) -> List<View> = [OrbsDrawing(s: self)]
41
+
38
42
  fun draw(self, io: Io, m: Affine, alpha: Float, area: Aabb) =
39
43
  first := self.input.events.length()
40
44
  second := self.input.events.length()
41
45
  gfx.drawText(io, "frame {self.frame} ev {first} {second} x {self.x} tex {self.ship.id} w {gfx.screenWidth(io)}", 0.0, 0.0, 8.0, Color.White)
42
46
 
47
+ # What the screen draws each frame, with `gfx` by hand.
48
+ struct OrbsDrawing[View](s: Orbs) =
49
+ fun place(self) -> Place = place.at(0.0, 0.0)
50
+
51
+ fun paintSelf(self, io: Io, m: Affine, alpha: Float) = self.s.draw(io, m, alpha, Aabb.of(0.0, 0.0, 0.0, 0.0))
52
+
43
53
  fun main(io: Io) -> Game =
44
54
  Game(screens: [page(Orbs(x: 0.0, ship: gfx.loadTexture(io, "sprites.png"), input: Input.create(), frame: 0))])
45
55
 
compiler/game/tests/fixtures/main_missing_fixture.plum CHANGED
@@ -14,6 +14,8 @@ import std/math/Aabb
14
14
  import std/game/Screen
15
15
  import std/game/ScreenSlice
16
16
  import std/game/Game
17
+ import std/game/View
18
+ import std/game/Place
17
19
 
18
20
  # Its texture is missing: `main` crashes naming it.
19
21
  struct Broken[ScreenSlice<Float>](tex: Texture) =
@@ -23,9 +25,17 @@ struct Broken[ScreenSlice<Float>](tex: Texture) =
23
25
 
24
26
  fun reduce(self, dt: Float) -> Broken = self
25
27
 
28
+ fun view(self) -> List<View> = [BrokenDrawing(s: self)]
29
+
26
30
  fun draw(self, io: Io, m: Affine, alpha: Float, area: Aabb) =
27
31
  gfx.clear(io, Color.Black)
28
32
 
33
+ # What the screen draws each frame, with `gfx` by hand.
34
+ struct BrokenDrawing[View](s: Broken) =
35
+ fun place(self) -> Place = place.at(0.0, 0.0)
36
+
37
+ fun paintSelf(self, io: Io, m: Affine, alpha: Float) = self.s.draw(io, m, alpha, Aabb.of(0.0, 0.0, 0.0, 0.0))
38
+
29
39
  fun main(io: Io) -> Game =
30
40
  Game(screens: [page(Broken(tex: gfx.loadTexture(io, "nope.png")))])
31
41
 
compiler/game/tests/fixtures/state_draw_keeps.plum CHANGED
@@ -14,6 +14,8 @@ import std/math/Aabb
14
14
  import std/game/Screen
15
15
  import std/game/ScreenSlice
16
16
  import std/game/Game
17
+ import std/game/View
18
+ import std/game/Place
17
19
 
18
20
  # `draw` keeps the screen it is given: the next `reduce` must not write that object in place.
19
21
  struct Log(mut last: Option<Run>)
@@ -25,6 +27,8 @@ struct Run[ScreenSlice<Float>](label: Str, log: Log, t: Int) =
25
27
 
26
28
  fun reduce(self, dt: Float) -> Run = Run(..self, t: self.t + 1)
27
29
 
30
+ fun view(self) -> List<View> = [RunDrawing(s: self)]
31
+
28
32
  fun draw(self, io: Io, m: Affine, alpha: Float, area: Aabb) =
29
33
  before := match self.log.last
30
34
  Some(r) => r.t
@@ -32,6 +36,12 @@ struct Run[ScreenSlice<Float>](label: Str, log: Log, t: Int) =
32
36
  self.log.last = Some(self)
33
37
  gfx.drawText(io, "{before} {self.t}", 0.0, 0.0, 8.0, Color.White)
34
38
 
39
+ # What the screen draws each frame, with `gfx` by hand.
40
+ struct RunDrawing[View](s: Run) =
41
+ fun place(self) -> Place = place.at(0.0, 0.0)
42
+
43
+ fun paintSelf(self, io: Io, m: Affine, alpha: Float) = self.s.draw(io, m, alpha, Aabb.of(0.0, 0.0, 0.0, 0.0))
44
+
35
45
  fun main(io: Io) -> Game = Game(screens: [page(Run(label: "r", log: Log(last: None), t: 0))])
36
46
 
37
47
  fun page(s: Screen) -> Screen = s
compiler/game/tests/fixtures/state_in_place.plum CHANGED
@@ -14,6 +14,8 @@ import std/math/Aabb
14
14
  import std/game/Screen
15
15
  import std/game/ScreenSlice
16
16
  import std/game/Game
17
+ import std/game/View
18
+ import std/game/Place
17
19
 
18
20
  struct Part(label: Str, x: Int) =
19
21
  fun step(self) -> Part = Part(..self, x: self.x + 1)
@@ -30,10 +32,18 @@ struct Run[ScreenSlice<Float>](part: Part, t: Int) =
30
32
 
31
33
  fun drawn(self) -> Run = Run(..self, t: 99)
32
34
 
35
+ fun view(self) -> List<View> = [RunDrawing(s: self)]
36
+
33
37
  fun draw(self, io: Io, m: Affine, alpha: Float, area: Aabb) =
34
38
  d := self.drawn()
35
39
  gfx.drawText(io, "{d.t} {self.t} {self.part.x}", 0.0, 0.0, 8.0, Color.White)
36
40
 
41
+ # What the screen draws each frame, with `gfx` by hand.
42
+ struct RunDrawing[View](s: Run) =
43
+ fun place(self) -> Place = place.at(0.0, 0.0)
44
+
45
+ fun paintSelf(self, io: Io, m: Affine, alpha: Float) = self.s.draw(io, m, alpha, Aabb.of(0.0, 0.0, 0.0, 0.0))
46
+
37
47
  fun main(io: Io) -> Game = Game(screens: [page(Run(part: Part(label: "p", x: 0), t: 0))])
38
48
 
39
49
  fun page(s: Screen) -> Screen = s
compiler/game/tests/fixtures/state_main_alias.plum CHANGED
@@ -14,6 +14,8 @@ import std/math/Aabb
14
14
  import std/game/Screen
15
15
  import std/game/ScreenSlice
16
16
  import std/game/Game
17
+ import std/game/View
18
+ import std/game/Place
17
19
 
18
20
  # `main` starts the game with a local, but the local is a constant: `reduce` must not write
19
21
  # it in place.
@@ -26,9 +28,17 @@ struct Run[ScreenSlice<Float>](label: Str, t: Int) =
26
28
 
27
29
  fun reduce(self, dt: Float) -> Run = Run(..self, t: self.t + 1)
28
30
 
31
+ fun view(self) -> List<View> = [RunDrawing(s: self)]
32
+
29
33
  fun draw(self, io: Io, m: Affine, alpha: Float, area: Aabb) =
30
34
  gfx.drawText(io, "{self.t} {Start.t}", 0.0, 0.0, 8.0, Color.White)
31
35
 
36
+ # What the screen draws each frame, with `gfx` by hand.
37
+ struct RunDrawing[View](s: Run) =
38
+ fun place(self) -> Place = place.at(0.0, 0.0)
39
+
40
+ fun paintSelf(self, io: Io, m: Affine, alpha: Float) = self.s.draw(io, m, alpha, Aabb.of(0.0, 0.0, 0.0, 0.0))
41
+
32
42
  fun main(io: Io) -> Game =
33
43
  s := Start
34
44
  Game(screens: [page(s)])
compiler/game/tests/fixtures/state_reset.plum CHANGED
@@ -14,6 +14,8 @@ import std/math/Aabb
14
14
  import std/game/Screen
15
15
  import std/game/ScreenSlice
16
16
  import std/game/Game
17
+ import std/game/View
18
+ import std/game/Place
17
19
 
18
20
  # The screen goes back to a constant: writing it in place would overwrite the constant.
19
21
  Start = Run(label: "start", t: 0)
@@ -26,9 +28,17 @@ struct Run[ScreenSlice<Float>](label: Str, t: Int) =
26
28
  fun reduce(self, dt: Float) -> Run =
27
29
  if self.t >= 2 then Start else Run(..self, t: self.t + 1)
28
30
 
31
+ fun view(self) -> List<View> = [RunDrawing(s: self)]
32
+
29
33
  fun draw(self, io: Io, m: Affine, alpha: Float, area: Aabb) =
30
34
  gfx.drawText(io, "{self.t} {Start.t}", 0.0, 0.0, 8.0, Color.White)
31
35
 
36
+ # What the screen draws each frame, with `gfx` by hand.
37
+ struct RunDrawing[View](s: Run) =
38
+ fun place(self) -> Place = place.at(0.0, 0.0)
39
+
40
+ fun paintSelf(self, io: Io, m: Affine, alpha: Float) = self.s.draw(io, m, alpha, Aabb.of(0.0, 0.0, 0.0, 0.0))
41
+
32
42
  fun main(io: Io) -> Game = Game(screens: [page(Start)])
33
43
 
34
44
  fun page(s: Screen) -> Screen = s
compiler/game/tests/fixtures/target_fixture.plum CHANGED
@@ -15,6 +15,8 @@ import std/math/Aabb
15
15
  import std/game/Screen
16
16
  import std/game/ScreenSlice
17
17
  import std/game/Game
18
+ import std/game/View
19
+ import std/game/Place
18
20
 
19
21
  # `bad` is a raw `io.textureCreate` of an impossible size: it answers -1 where
20
22
  # `Texture.create` would crash.
@@ -25,6 +27,8 @@ struct State[ScreenSlice<Float>](target: Texture, bad: Int) =
25
27
 
26
28
  fun reduce(self, dt: Float) -> State = self
27
29
 
30
+ fun view(self) -> List<View> = [StateDrawing(s: self)]
31
+
28
32
  fun draw(self, io: Io, m: Affine, alpha: Float, area: Aabb) =
29
33
  self.target.renderTarget(io)
30
34
  gfx.clear(io, Color.Transparent)
@@ -35,6 +39,12 @@ struct State[ScreenSlice<Float>](target: Texture, bad: Int) =
35
39
  gfx.blendMode(io, Blend.Normal)
36
40
  gfx.drawText(io, "size {self.target.width(io)}x{self.target.height(io)} bad {self.bad}", 0.0, 0.0, 8.0, Color.White)
37
41
 
42
+ # What the screen draws each frame, with `gfx` by hand.
43
+ struct StateDrawing[View](s: State) =
44
+ fun place(self) -> Place = place.at(0.0, 0.0)
45
+
46
+ fun paintSelf(self, io: Io, m: Affine, alpha: Float) = self.s.draw(io, m, alpha, Aabb.of(0.0, 0.0, 0.0, 0.0))
47
+
38
48
  fun main(io: Io) -> Game =
39
49
  Game(screens: [page(State(target: gfx.createTexture(io, 64, 32), bad: gfx.textureCreate(io, 0, 5)))])
40
50
 
compiler/game/tests/fixtures/turn_fixture.plum ADDED
@@ -0,0 +1,33 @@
1
+ module turn_fixture
2
+
3
+ import std/Int
4
+ import std/Float
5
+ import std/Str
6
+ import std/Io
7
+ import std/collections/List
8
+ import std/math/Vec2
9
+ import std/game/Color
10
+ import std/game/Place
11
+ import std/game/View
12
+ import std/game/Box
13
+ import std/game/Label
14
+ import std/game/Screen
15
+ import std/game/Game
16
+
17
+ # A group at (100, 100) turned a quarter, holding a red 40 by 20 box and a label, and a
18
+ # label in the hud at (5, 5).
19
+ struct Turned[View](children: List<View>) =
20
+ fun place(self) -> Place = place.at(100.0, 100.0).rotateTo(Float.HalfPi)
21
+
22
+ fun view(self) -> List<View> = self.children
23
+
24
+ struct TurnScreen[Screen](n: Int) =
25
+ fun name(self) -> Str = "turn"
26
+
27
+ fun view(self) -> List<View> = [Turned(children: [Box.of(0.0, 0.0, 40.0, 20.0, Color.Red), Label.of(0.0, 0.0, "hi", 10.0, Color.White)])]
28
+
29
+ fun hud(self, window: Vec2) -> List<View> = [Label.of(5.0, 5.0, "hud", 10.0, Color.White)]
30
+
31
+ fun main(io: Io) -> Game =
32
+ only: Screen := TurnScreen(n: 0)
33
+ Game(screens: [only])
compiler/game/tests/host_test.rs CHANGED
@@ -151,7 +151,7 @@ fn unknownImportTraps() {
151
151
  let path = dir.join("m.plum");
152
152
  std::fs::write(
153
153
  &path,
154
- "import std/Int\nimport std/Float\nimport std/Str\nimport std/Io\nimport std/Slice\nimport std/Option\nimport std/collections/List\nimport std/math/Vec2\nimport std/math/Affine\nimport std/math/Aabb\nimport std/game/Color\nimport std/game/gfx\nimport std/game/input\nimport std/game/Control\nimport std/game/Screen\nimport std/game/ScreenSlice\nimport std/game/Game\nstruct State[ScreenSlice<Int>](n: Int) =\n fun name(self) -> Str = \"page\"\n fun reduce(self, a: Int) -> State = self\n fun draw(self, io: Io, m: Affine, alpha: Float, area: Aabb) =\n x := io.rawExists(\"a\")\n\nfun main(io: Io) -> Game =\n only: Screen := State(n: 0)\n Game(screens: [only])\n",
154
+ "import std/Int\nimport std/Float\nimport std/Str\nimport std/Io\nimport std/Slice\nimport std/Option\nimport std/collections/List\nimport std/math/Vec2\nimport std/math/Affine\nimport std/math/Aabb\nimport std/game/Color\nimport std/game/gfx\nimport std/game/input\nimport std/game/Control\nimport std/game/Screen\nimport std/game/ScreenSlice\nimport std/game/Game\nimport std/game/View\nimport std/game/Place\nstruct State[ScreenSlice<Int>](n: Int) =\n fun name(self) -> Str = \"page\"\n fun reduce(self, a: Int) -> State = self\n fun view(self) -> List<View> = [StateDrawing(s: self)]\n\n# What the screen draws each frame, with `gfx` by hand.\nstruct StateDrawing[View](s: State) =\n fun place(self) -> Place = place.at(0.0, 0.0)\n fun paintSelf(self, io: Io, m: Affine, alpha: Float) =\n x := io.rawExists(\"a\")\n\nfun main(io: Io) -> Game =\n only: Screen := State(n: 0)\n Game(screens: [only])\n",
155
155
  )
156
156
  .unwrap();
157
157
  let wasm = compile(&path);
@@ -364,7 +364,7 @@ fn randomSeedProvidedByHost() {
364
364
  let path = dir.join("m.plum");
365
365
  std::fs::write(
366
366
  &path,
367
- "import std/Int\nimport std/Float\nimport std/Str\nimport std/Io\nimport std/Slice\nimport std/Option\nimport std/collections/List\nimport std/math/Vec2\nimport std/math/Affine\nimport std/math/Aabb\nimport std/game/Color\nimport std/game/gfx\nimport std/game/input\nimport std/game/Control\nimport std/game/Screen\nimport std/game/ScreenSlice\nimport std/game/Game\nstruct State[ScreenSlice<Int>](seed: Int) =\n fun name(self) -> Str = \"page\"\n fun reduce(self, a: Int) -> State = self\n fun draw(self, io: Io, m: Affine, alpha: Float, area: Aabb) =\n gfx.drawText(io, \"seed {self.seed}\", 0.0, 0.0, 8.0, Color.White)\n\nfun main(io: Io) -> Game =\n only: Screen := State(seed: io.randomSeed())\n Game(screens: [only])\n",
367
+ "import std/Int\nimport std/Float\nimport std/Str\nimport std/Io\nimport std/Slice\nimport std/Option\nimport std/collections/List\nimport std/math/Vec2\nimport std/math/Affine\nimport std/math/Aabb\nimport std/game/Color\nimport std/game/gfx\nimport std/game/input\nimport std/game/Control\nimport std/game/Screen\nimport std/game/ScreenSlice\nimport std/game/Game\nimport std/game/View\nimport std/game/Place\nstruct State[ScreenSlice<Int>](seed: Int) =\n fun name(self) -> Str = \"page\"\n fun reduce(self, a: Int) -> State = self\n fun view(self) -> List<View> = [StateDrawing(s: self)]\n\n# What the screen draws each frame, with `gfx` by hand.\nstruct StateDrawing[View](s: State) =\n fun place(self) -> Place = place.at(0.0, 0.0)\n fun paintSelf(self, io: Io, m: Affine, alpha: Float) =\n gfx.drawText(io, \"seed {self.s.seed}\", 0.0, 0.0, 8.0, Color.White)\n\nfun main(io: Io) -> Game =\n only: Screen := State(seed: io.randomSeed())\n Game(screens: [only])\n",
368
368
  )
369
369
  .unwrap();
370
370
  let wasm = compile(&path);
@@ -388,7 +388,7 @@ fn seedGame(name: &str) -> Vec<u8> {
388
388
  let path = dir.join("m.plum");
389
389
  std::fs::write(
390
390
  &path,
391
- "import std/Int\nimport std/Float\nimport std/Str\nimport std/Io\nimport std/Slice\nimport std/Option\nimport std/collections/List\nimport std/math/Vec2\nimport std/math/Affine\nimport std/math/Aabb\nimport std/game/Color\nimport std/game/gfx\nimport std/game/input\nimport std/game/Control\nimport std/game/Screen\nimport std/game/ScreenSlice\nimport std/game/Game\nenum Saw = Held(keys: Int, x: Float) | Ticked\nstruct State[ScreenSlice<Saw>](seed: Int, ticks: Int, keys: Int, x: Float, w: Float) =\n fun name(self) -> Str = \"page\"\n fun resize(self, w: Float, h: Float) -> State = State(..self, w: w)\n fun held(self, i: Input) -> Option<Saw> = Some(Held(keys: i.held.keys.length(), x: i.pos.x))\n fun tick(self, dt: Float) -> Option<Saw> = Some(Ticked)\n fun reduce(self, a: Saw) -> State = match a\n Held(k, x) => State(..self, keys: self.keys + k, x: x)\n Ticked => State(..self, ticks: self.ticks + 1)\n fun draw(self, io: Io, m: Affine, alpha: Float, area: Aabb) =\n gfx.drawText(io, \"seed {self.seed} ticks {self.ticks} keys {self.keys} x {self.x} w {self.w}\", 0.0, 0.0, 8.0, Color.White)\n\nfun main(io: Io) -> Game =\n only: Screen := State(seed: io.randomSeed(), ticks: 0, keys: 0, x: 0.0, w: 0.0)\n Game(screens: [only])\n",
391
+ "import std/Int\nimport std/Float\nimport std/Str\nimport std/Io\nimport std/Slice\nimport std/Option\nimport std/collections/List\nimport std/math/Vec2\nimport std/math/Affine\nimport std/math/Aabb\nimport std/game/Color\nimport std/game/gfx\nimport std/game/input\nimport std/game/Control\nimport std/game/Screen\nimport std/game/ScreenSlice\nimport std/game/Game\nimport std/game/View\nimport std/game/Place\nenum Saw = Held(keys: Int, x: Float) | Ticked\nstruct State[ScreenSlice<Saw>](seed: Int, ticks: Int, keys: Int, x: Float) =\n fun name(self) -> Str = \"page\"\n fun hud(self, window: Vec2) -> List<View> = [StateDrawing(s: self, w: window.x)]\n fun held(self, i: Input) -> Option<Saw> = Some(Held(keys: i.held.keys.length(), x: i.pos.x))\n fun tick(self, dt: Float) -> Option<Saw> = Some(Ticked)\n fun reduce(self, a: Saw) -> State = match a\n Held(k, x) => State(..self, keys: self.keys + k, x: x)\n Ticked => State(..self, ticks: self.ticks + 1)\n\n# What the screen draws each frame, with `gfx` by hand, and the window's width.\nstruct StateDrawing[View](s: State, w: Float) =\n fun place(self) -> Place = place.at(0.0, 0.0)\n fun paintSelf(self, io: Io, m: Affine, alpha: Float) =\n gfx.drawText(io, \"seed {self.s.seed} ticks {self.s.ticks} keys {self.s.keys} x {self.s.x} w {self.w}\", 0.0, 0.0, 8.0, Color.White)\n\nfun main(io: Io) -> Game =\n only: Screen := State(seed: io.randomSeed(), ticks: 0, keys: 0, x: 0.0)\n Game(screens: [only])\n",
392
392
  )
393
393
  .unwrap();
394
394
  let wasm = compile(&path);
@@ -463,7 +463,7 @@ fn everySeedOfARecordedRunReplays() {
463
463
  let path = dir.join("m.plum");
464
464
  std::fs::write(
465
465
  &path,
466
- "import std/Int\nimport std/Float\nimport std/Str\nimport std/Io\nimport std/Slice\nimport std/Option\nimport std/collections/List\nimport std/math/Vec2\nimport std/math/Affine\nimport std/math/Aabb\nimport std/game/Color\nimport std/game/gfx\nimport std/game/input\nimport std/game/Control\nimport std/game/Screen\nimport std/game/ScreenSlice\nimport std/game/Game\nstruct Seeds(mut c: Int)\nstruct State[ScreenSlice<Int>](a: Int, b: Int, seeds: Seeds) =\n fun name(self) -> Str = \"page\"\n fun tick(self, dt: Float) -> Option<Int> = Some(1)\n fun reduce(self, n: Int) -> State = self\n fun effect(self, io: Io, n: Int, game: Control) =\n self.seeds.c = self.seeds.c ^ io.randomSeed()\n fun draw(self, io: Io, m: Affine, alpha: Float, area: Aabb) =\n gfx.drawText(io, \"{self.a} {self.b} {self.seeds.c}\", 0.0, 0.0, 8.0, Color.White)\n\nfun main(io: Io) -> Game =\n a := io.randomSeed()\n seeds := Seeds(c: 0)\n only: Screen := State(a: a, b: io.randomSeed(), seeds: seeds)\n Game(screens: [only])\n",
466
+ "import std/Int\nimport std/Float\nimport std/Str\nimport std/Io\nimport std/Slice\nimport std/Option\nimport std/collections/List\nimport std/math/Vec2\nimport std/math/Affine\nimport std/math/Aabb\nimport std/game/Color\nimport std/game/gfx\nimport std/game/input\nimport std/game/Control\nimport std/game/Screen\nimport std/game/ScreenSlice\nimport std/game/Game\nimport std/game/View\nimport std/game/Place\nstruct Seeds(mut c: Int)\nstruct State[ScreenSlice<Int>](a: Int, b: Int, seeds: Seeds) =\n fun name(self) -> Str = \"page\"\n fun tick(self, dt: Float) -> Option<Int> = Some(1)\n fun reduce(self, n: Int) -> State = self\n fun effect(self, io: Io, n: Int, game: Control) =\n self.seeds.c = self.seeds.c ^ io.randomSeed()\n fun view(self) -> List<View> = [StateDrawing(s: self)]\n\n# What the screen draws each frame, with `gfx` by hand.\nstruct StateDrawing[View](s: State) =\n fun place(self) -> Place = place.at(0.0, 0.0)\n fun paintSelf(self, io: Io, m: Affine, alpha: Float) =\n gfx.drawText(io, \"{self.s.a} {self.s.b} {self.s.seeds.c}\", 0.0, 0.0, 8.0, Color.White)\n\nfun main(io: Io) -> Game =\n a := io.randomSeed()\n seeds := Seeds(c: 0)\n only: Screen := State(a: a, b: io.randomSeed(), seeds: seeds)\n Game(screens: [only])\n",
467
467
  )
468
468
  .unwrap();
469
469
  let wasm = compile(&path);
@@ -668,7 +668,7 @@ fn inputIsPolledOncePerFrameWhateverTheTicks() {
668
668
  g.update(dt).unwrap();
669
669
  let calls = &g.backend().calls;
670
670
  let count = |p: &str| calls.iter().filter(|c| c.starts_with(&format!("{p}("))).count();
671
- assert_eq!(count("isKeyDown"), 47, "{game} dt {dt}: one poll reads every key once");
671
+ assert_eq!(count("isKeyDown"), 56, "{game} dt {dt}: one poll reads every key once");
672
672
  perFrame.push(reads.map(count));
673
673
  }
674
674
  assert!(perFrame.windows(2).all(|w| w[0] == w[1]), "{game}: input reads per frame vary with the ticks: {perFrame:?}");
@@ -687,3 +687,106 @@ fn exampleGamesCompileToTheSameBytesEveryTime() {
687
687
  }
688
688
  }
689
689
  }
690
+
691
+ /// tests/fixtures/camera_fixture.plum in a 1000 by 600 window, after its first tick (which
692
+ /// brings the window's size).
693
+ fn cameraGame() -> PlumGame<Recorder> {
694
+ let mut rec = Recorder::new();
695
+ rec.screen = (1000.0, 600.0);
696
+ let mut g = PlumGame::load(&fixtureOut("camera_fixture.plum").wasm, rec).expect("load game");
697
+ g.init().expect("main");
698
+ g.update(1.0 / 60.0).unwrap();
699
+ g
700
+ }
701
+
702
+ /// The key `k` down for one tick, then up for the next.
703
+ fn tapKey(g: &mut PlumGame<Recorder>, k: i32) {
704
+ g.backend_mut().keys_down = [k].into();
705
+ g.update(1.0 / 60.0).unwrap();
706
+ g.backend_mut().keys_down = Default::default();
707
+ g.update(1.0 / 60.0).unwrap();
708
+ }
709
+
710
+ /// The camera and draw calls of one frame.
711
+ fn frameCalls(g: &mut PlumGame<Recorder>) -> Vec<String> {
712
+ g.backend_mut().calls.clear();
713
+ g.draw().unwrap();
714
+ g.backend().calls.iter().filter(|c| c.starts_with("clear") || c.contains("Camera") || c.starts_with("drawRect")).cloned().collect()
715
+ }
716
+
717
+ /// `got` is `want` call for call, each number within 0.001 (a transition's progress is a
718
+ /// sum of ticks).
719
+ fn assertCallsNear(got: &[String], want: &[&str]) {
720
+ let split = |c: &str| -> (String, Vec<f32>) {
721
+ let (name, args) = c.split_once('(').unwrap();
722
+ let args = args.trim_end_matches(')');
723
+ (name.to_string(), if args.is_empty() { vec![] } else { args.split(',').map(|a| a.parse().unwrap()).collect() })
724
+ };
725
+ assert_eq!(got.len(), want.len(), "{got:?}");
726
+ for (g, w) in got.iter().zip(want) {
727
+ let ((gn, ga), (wn, wa)) = (split(g), split(w));
728
+ assert!(gn == wn && ga.len() == wa.len() && ga.iter().zip(&wa).all(|(a, b)| (a - b).abs() < 0.001), "{g} is not {w}: {got:?}");
729
+ }
730
+ }
731
+
732
+ /// The view is drawn through the camera's transform, in window pixels (the host's camera is
733
+ /// not used), and a screen that culls skips what its camera doesn't show.
734
+ #[test]
735
+ fn eachScalingPlacesTheViewAndCullsToWhatItShows() {
736
+ let mut g = cameraGame();
737
+ // A 400 by 300 world in 1000 by 600 pixels. Fit: 2 pixels a unit, 50 units of
738
+ // letterbox each side; the box right of the world is culled.
739
+ assertCallsNear(&frameCalls(&mut g), &["clear(0,0,0,1)", "drawRect(120,200,40,40,1,0,0,1)"]);
740
+ // Fill: 2.5 a unit, 30 units cut off at the top and the bottom.
741
+ tapKey(&mut g, 73);
742
+ assertCallsNear(&frameCalls(&mut g), &["clear(0,0,0,1)", "drawRect(25,175,50,50,1,0,0,1)"]);
743
+ // Extend: as Fit, with the world grown to 500 wide, so the box at x 420 is shown.
744
+ tapKey(&mut g, 69);
745
+ assertCallsNear(&frameCalls(&mut g), &["clear(0,0,0,1)", "drawRect(120,200,40,40,1,0,0,1)", "drawRect(940,200,40,40,0,0,1,1)"]);
746
+ // Stretch: 2.5 across and 2 down.
747
+ tapKey(&mut g, 83);
748
+ assertCallsNear(&frameCalls(&mut g), &["clear(0,0,0,1)", "drawRect(25,200,50,40,1,0,0,1)"]);
749
+ }
750
+
751
+ #[test]
752
+ fn aSlideMovesBothScreensAndTheirCullAreas() {
753
+ let mut g = cameraGame();
754
+ tapKey(&mut g, 83);
755
+ // G: the second screen slides in from the right over a second; 30 ticks are half way.
756
+ tapKey(&mut g, 71);
757
+ for _ in 0..29 {
758
+ g.update(1.0 / 60.0).unwrap();
759
+ }
760
+ assertCallsNear(
761
+ &frameCalls(&mut g),
762
+ &[
763
+ "clear(0,0,0,1)",
764
+ // Going out, on its own background, stretched, 500 pixels to the left: its red
765
+ // box is off the window and culled, the blue one at x 420 has come into it.
766
+ "drawRect(-500,0,1000,600,0,0,0,1)",
767
+ "drawRect(550,200,50,40,0,0,1,1)",
768
+ // Coming in, on its own background, fitted, 500 pixels (250 units) to the right:
769
+ // the green box at x 10 is drawn, the white one at x 300 is still off the window
770
+ // and culled.
771
+ "drawRect(500,0,1000,600,0,0,0,1)",
772
+ "drawRect(620,200,40,40,0,1,0,1)",
773
+ ],
774
+ );
775
+ }
776
+
777
+ #[test]
778
+ fn aTurnedBoxAndLabelAreDrawnTurnedAndTheHudOnePixelAUnit() {
779
+ let mut rec = Recorder::new();
780
+ rec.screen = (800.0, 600.0);
781
+ let mut g = PlumGame::load(&fixtureOut("turn_fixture.plum").wasm, rec).expect("load game");
782
+ g.init().expect("main");
783
+ g.update(1.0 / 60.0).unwrap();
784
+ g.backend_mut().calls.clear();
785
+ g.draw().unwrap();
786
+ let calls: Vec<String> = g.backend().calls.clone();
787
+ let shapes: Vec<String> = calls.iter().filter(|c| c.starts_with("drawRect")).cloned().collect();
788
+ // The box's centre (20, 10) turned a quarter about (100, 100) is (90, 120).
789
+ assertCallsNear(&shapes, &["drawRectEx(70,110,40,20,1.5707964,1,0,0,1)"]);
790
+ let texts: Vec<&String> = calls.iter().filter(|c| c.starts_with("drawText")).collect();
791
+ assert_eq!(texts, ["drawTextEx(\"hi\",100,100,10,1.5707964,1,1,1,1)", "drawText(\"hud\",5,5,10,1,1,1,1)"], "{calls:?}");
792
+ }
compiler/game/web-test/fixtures/interleave.plum CHANGED
@@ -18,6 +18,8 @@ import std/math/Aabb
18
18
  import std/game/Screen
19
19
  import std/game/ScreenSlice
20
20
  import std/game/Game
21
+ import std/game/View
22
+ import std/game/Place
21
23
 
22
24
  Sprites = 4000
23
25
  Textures = 8
@@ -32,8 +34,16 @@ struct Interleave[ScreenSlice<Float>](tex: Array<Texture>, t: Int) =
32
34
 
33
35
  fun reduce(self, dt: Float) -> Interleave = Interleave(..self, t: self.t + 1)
34
36
 
37
+ fun view(self) -> List<View> = [InterleaveDrawing(s: self)]
38
+
35
39
  fun draw(self, io: Io, m: Affine, alpha: Float, area: Aabb) = drawSprites(io, self.tex, self.t)
36
40
 
41
+ # What the screen draws each frame, with `gfx` by hand.
42
+ struct InterleaveDrawing[View](s: Interleave) =
43
+ fun place(self) -> Place = place.at(0.0, 0.0)
44
+
45
+ fun paintSelf(self, io: Io, m: Affine, alpha: Float) = self.s.draw(io, m, alpha, Aabb.of(0.0, 0.0, 0.0, 0.0))
46
+
37
47
  fun main(io: Io) -> Game =
38
48
  tex := Array.filled(Textures, Texture(id: -1))
39
49
  for i := range Textures
compiler/game/web-test/fixtures/main_game.plum CHANGED
@@ -15,6 +15,8 @@ import std/math/Aabb
15
15
  import std/game/Screen
16
16
  import std/game/ScreenSlice
17
17
  import std/game/Game
18
+ import std/game/View
19
+ import std/game/Place
18
20
 
19
21
  # A game whose `main` returns a `Game`: one screen, a square that moves
20
22
  # with the tick count. It ticks and draws the count.
@@ -25,11 +27,19 @@ struct Mover[ScreenSlice<Float>](frame: Int) =
25
27
 
26
28
  fun reduce(self, dt: Float) -> Mover = Mover(frame: self.frame + 1)
27
29
 
30
+ fun view(self) -> List<View> = [MoverDrawing(s: self)]
31
+
28
32
  fun draw(self, io: Io, m: Affine, alpha: Float, area: Aabb) =
29
33
  gfx.clear(io, Color.rgb(0.2, 0.2, 0.2))
30
34
  gfx.drawRect(io, Float(self.frame % 600), 100.0, 40.0, 40.0, Color.Yellow)
31
35
  gfx.drawText(io, "frame {self.frame}", 20.0, 20.0, 16.0, Color.White)
32
36
 
37
+ # What the screen draws each frame, with `gfx` by hand.
38
+ struct MoverDrawing[View](s: Mover) =
39
+ fun place(self) -> Place = place.at(0.0, 0.0)
40
+
41
+ fun paintSelf(self, io: Io, m: Affine, alpha: Float) = self.s.draw(io, m, alpha, Aabb.of(0.0, 0.0, 0.0, 0.0))
42
+
33
43
  fun main(io: Io) -> Game =
34
44
  Game(screens: [page(Mover(frame: 0))])
35
45
 
compiler/game/web-test/fixtures/rendertarget.plum CHANGED
@@ -10,6 +10,9 @@
10
10
  # 6. a second 16x16 blue target drawn at (400,300)
11
11
  # 7. a 16x16 target holding red at alpha 0.5 drawn at (400,400): translucent target
12
12
  # contents blend once, giving (153,26,26) like item 5
13
+ # 8. a 100x20 white bar at (600,440) turned a quarter about its centre (650,450): it
14
+ # stands from (640,400) to (660,500), so (650,490) is white and (690,450), where the
15
+ # unturned bar would be, is the background
13
16
  module rendertarget
14
17
  import std/Str
15
18
  import std/Int
@@ -26,6 +29,8 @@ import std/math/Aabb
26
29
  import std/game/Screen
27
30
  import std/game/ScreenSlice
28
31
  import std/game/Game
32
+ import std/game/View
33
+ import std/game/Place
29
34
 
30
35
  # The targets and the tick count.
31
36
  struct Targets[ScreenSlice<Float>](big: Texture, small: Texture, glass: Texture, t: Int) =
@@ -35,8 +40,16 @@ struct Targets[ScreenSlice<Float>](big: Texture, small: Texture, glass: Texture,
35
40
 
36
41
  fun reduce(self, dt: Float) -> Targets = Targets(..self, t: self.t + 1)
37
42
 
43
+ fun view(self) -> List<View> = [TargetsDrawing(s: self)]
44
+
38
45
  fun draw(self, io: Io, m: Affine, alpha: Float, area: Aabb) = drawTargets(io, self)
39
46
 
47
+ # What the screen draws each frame, with `gfx` by hand.
48
+ struct TargetsDrawing[View](s: Targets) =
49
+ fun place(self) -> Place = place.at(0.0, 0.0)
50
+
51
+ fun paintSelf(self, io: Io, m: Affine, alpha: Float) = self.s.draw(io, m, alpha, Aabb.of(0.0, 0.0, 0.0, 0.0))
52
+
40
53
  fun main(io: Io) -> Game =
41
54
  targets := Targets(big: gfx.createTexture(io, 64, 64), small: gfx.createTexture(io, 16, 16), glass: gfx.createTexture(io, 16, 16), t: 0)
42
55
  Game(screens: [page(targets)])
@@ -66,6 +79,7 @@ fun drawTargets(io: Io, g: Targets) =
66
79
  gfx.drawRect(io, 850.0, 100.0, 100.0, 100.0, Color(r: 1.0, g: 0.0, b: 0.0, a: 0.5))
67
80
  g.small.draw(io, 400.0, 300.0, Color.White)
68
81
  g.glass.draw(io, 400.0, 400.0, Color.White)
82
+ gfx.drawRectEx(io, 600.0, 440.0, 100.0, 20.0, Float.HalfPi, Color.White)
69
83
  gfx.drawText(io, "frame {g.t}", 20.0, 500.0, 16.0, Color.White)
70
84
  gfx.drawRect(io, Float(g.t % 600), 600.0, 40.0, 6.0, Color.Yellow)
71
85
 
compiler/game/web-test/fixtures/stress.plum CHANGED
@@ -18,6 +18,8 @@ import std/math/Aabb
18
18
  import std/game/Screen
19
19
  import std/game/ScreenSlice
20
20
  import std/game/Game
21
+ import std/game/View
22
+ import std/game/Place
21
23
 
22
24
  Sprites = 5000
23
25
  Rects = 500
@@ -34,8 +36,16 @@ struct Stress[ScreenSlice<Float>](sheet: Texture, t: Int) =
34
36
 
35
37
  fun reduce(self, dt: Float) -> Stress = Stress(..self, t: self.t + 1)
36
38
 
39
+ fun view(self) -> List<View> = [StressDrawing(s: self)]
40
+
37
41
  fun draw(self, io: Io, m: Affine, alpha: Float, area: Aabb) = drawStress(io, self.sheet, self.t)
38
42
 
43
+ # What the screen draws each frame, with `gfx` by hand.
44
+ struct StressDrawing[View](s: Stress) =
45
+ fun place(self) -> Place = place.at(0.0, 0.0)
46
+
47
+ fun paintSelf(self, io: Io, m: Affine, alpha: Float) = self.s.draw(io, m, alpha, Aabb.of(0.0, 0.0, 0.0, 0.0))
48
+
39
49
  fun main(io: Io) -> Game =
40
50
  Game(screens: [page(Stress(sheet: gfx.loadTexture(io, "sprites.png"), t: 0))])
41
51
 
compiler/game/web-test/fixtures/stress_state_view.plum CHANGED
@@ -22,7 +22,8 @@ import std/game/gfx
22
22
  import std/game/Anim
23
23
  import std/game/input
24
24
  import std/game/Place
25
+ import std/game/View
25
- import std/game/Actor
26
+ import std/game/Box
26
27
  import std/game/Sprite
27
28
  import std/game/Label
28
29
  import std/game/Screen
@@ -42,27 +43,27 @@ WorldW = 1600
42
43
  WorldH = 900
43
44
 
44
45
  # The list f(i), f(i + 1) ... f(n - 1).
45
- fun rangeLink(i: Int, n: Int, f: fn(Int) -> Actor) -> List<Actor> =
46
+ fun rangeLink(i: Int, n: Int, f: fn(Int) -> View) -> List<View> =
46
47
  if i >= n then Nil else Cons(head: f(i), tail: rangeLink(i + 1, n, f))
47
48
 
48
49
  # A sprite of the sheet at (x, y), turned by `rotation` about its centre.
49
- struct Dancer[Actor](x: Float, y: Float, rotation: Float, srcX: Float, sheet: Texture) =
50
+ struct Dancer[View](x: Float, y: Float, rotation: Float, srcX: Float, sheet: Texture) =
50
51
  fun place(self) -> Place = place.at(self.x, self.y).rotateTo(self.rotation).pivotAt(8.0, 8.0)
51
52
 
52
- fun paint(self, io: Io, m: Affine, alpha: Float) =
53
+ fun paintSelf(self, io: Io, m: Affine, alpha: Float) =
53
- 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)
54
+ sprite.drawSpriteFrame(io, m, alpha, 16.0, 16.0, Color.White, self.sheet, self.srcX, 0.0, 16.0, 16.0)
54
55
 
55
56
  # A group of dancers turned by `rotation` about (75, 85).
56
- struct Spinner[Actor](x: Float, y: Float, rotation: Float, children: List<Actor>) =
57
+ struct Spinner[View](x: Float, y: Float, rotation: Float, children: List<View>) =
57
58
  fun place(self) -> Place = place.at(self.x, self.y).rotateTo(self.rotation).pivotAt(75.0, 85.0)
58
59
 
59
- fun declared(self) -> List<Actor> = self.children
60
+ fun view(self) -> List<View> = self.children
60
61
 
61
62
  # The world layer: everything in it scaled by `scale`.
62
- struct Scaled[Actor](scale: Float, children: List<Actor>) =
63
+ struct Scaled[View](scale: Float, children: List<View>) =
63
64
  fun place(self) -> Place = place.at(0.0, 0.0).scaleTo(self.scale, self.scale)
64
65
 
65
- fun declared(self) -> List<Actor> = self.children
66
+ fun view(self) -> List<View> = self.children
66
67
 
67
68
  enum StressAction = Ticked(dt: Float) | Clicked(i: Int)
68
69
 
@@ -78,13 +79,13 @@ struct ViewScreen[ScreenSlice<StressAction>](clock: Float, frames: Int, clicks:
78
79
 
79
80
  fun background(self) -> Color = Color.rgb(0.05, 0.06, 0.1)
80
81
 
81
- fun view(self) -> List<Actor> =
82
- world: Actor := Scaled(scale: 0.8, children: rangeLink(0, Groups, |gi| self.spinner(gi)).append(rangeLink(0, Pulsers, |i| self.pulser(i))).append(rangeLink(0, Rects, |i| self.rect(i))).append(rangeLink(0, Circles, |i| self.circle(i))).append(rangeLink(0, Texts, |i| self.counter(i))))
83
- buttons := actor.all(self.buttons)
82
+ fun view(self) -> List<View> =
83
+ world: View := Scaled(scale: 0.8, children: rangeLink(0, Groups, |gi| self.spinner(gi)).append(rangeLink(0, Pulsers, |i| self.pulser(i))).append(rangeLink(0, Rects, |i| self.rect(i))).append(rangeLink(0, Circles, |i| self.circle(i))).append(rangeLink(0, Texts, |i| self.counter(i))))
84
+ buttons := view.all(self.buttons)
84
85
  labels := rangeLink(0, Buttons, |i| self.buttonLabel(i))
85
86
  Cons(world, buttons.append(labels))
86
87
 
87
- fun onPress(self, target: Actor, at: Vec2) -> Option<StressAction> =
88
+ fun onPress(self, target: View, at: Vec2) -> Option<StressAction> =
88
89
  0.until(Buttons).find(|i| @sameRef(target, self.buttons.at(i))).map(|i| Clicked(i: i))
89
90
 
90
91
  fun tick(self, dt: Float) -> Option<StressAction> = Some(Ticked(dt: dt))
@@ -93,32 +94,32 @@ struct ViewScreen[ScreenSlice<StressAction>](clock: Float, frames: Int, clicks:
93
94
  Ticked(dt) => ViewScreen(..self, clock: self.clock + dt, frames: self.frames + 1)
94
95
  Clicked(_) => ViewScreen(..self, clicks: self.clicks + 1)
95
96
 
96
- fun spinner(self, gi: Int) -> Actor =
97
+ fun spinner(self, gi: Int) -> View =
97
98
  Spinner(x: Float(gi % 10 * 160), y: Float(gi / 10 * 180), rotation: 0.24 * self.clock, children: rangeLink(0, Sprites / Groups, |j| self.dancer(gi, j)))
98
99
 
99
- fun dancer(self, gi: Int, j: Int) -> Actor =
100
+ fun dancer(self, gi: Int, j: Int) -> View =
100
101
  i := gi * {Sprites / Groups} + j
101
102
  Dancer(x: Float({j * j * 13 + j * 37} % 150), y: Float({j * j * 29 + j * 53} % 170), rotation: Float(i) + 1.2 * self.clock, srcX: Float(i % 4 * 16), sheet: self.sheet)
102
103
 
103
- fun pulser(self, i: Int) -> Actor =
104
+ fun pulser(self, i: Int) -> View =
104
105
  pose := Anim.at(self.anim, self.clock - Float(i % 10) * 0.1)
105
106
  Sprite(
106
107
  x: Float(i * 97 % 1500) + pose.dx, y: Float(i * 53 % 850) + pose.dy, tex: self.sheet, w: 16.0, h: 16.0, srcX: Float(i % 4 * 16), srcY: 0.0,
107
108
  srcW: 16.0, srcH: 16.0, frame: 0, tint: Color.White, touch: Disabled)
108
109
 
109
- fun rect(self, i: Int) -> Actor = self.drifter(hue(i), Float(i * 61 % WorldW), Float(i * 29 % WorldH), 12.0, 8.0, 2.0, 0.0)
110
+ fun rect(self, i: Int) -> View = self.drifter(hue(i), Float(i * 61 % WorldW), Float(i * 29 % WorldH), 12.0, 8.0, 2.0, 0.0)
110
111
 
111
- fun circle(self, i: Int) -> Actor = self.drifter(hue(i + 3), Float(i * 83 % WorldW), Float(i * 47 % WorldH), 12.0, 12.0, 3.0, 1.0)
112
+ fun circle(self, i: Int) -> View = self.drifter(hue(i + 3), Float(i * 83 % WorldW), Float(i * 47 % WorldH), 12.0, 12.0, 3.0, 1.0)
112
113
 
113
114
  # A square of the white texture that has moved by (dx, dy) each frame, wrapping.
114
- fun drifter(self, c: Color, x: Float, y: Float, w: Float, h: Float, dx: Float, dy: Float) -> Actor =
115
+ fun drifter(self, c: Color, x: Float, y: Float, w: Float, h: Float, dx: Float, dy: Float) -> View =
115
116
  nx := wrap(x + dx * Float(self.frames), Float(WorldW))
116
117
  ny := wrap(y + dy * Float(self.frames), Float(WorldH))
117
118
  Sprite(x: nx, y: ny, tex: self.white, w: w, h: h, srcX: 0.0, srcY: 0.0, srcW: 0.0, srcH: 0.0, frame: 0, tint: c, touch: Disabled)
118
119
 
119
- fun counter(self, i: Int) -> Actor = Label.of(Float(i * 30 % WorldW), Float(i * 17 % WorldH), "n {i + self.frames}", 14.0, Color.White)
120
+ fun counter(self, i: Int) -> View = Label.of(Float(i * 30 % WorldW), Float(i * 17 % WorldH), "n {i + self.frames}", 14.0, Color.White)
120
121
 
121
- fun buttonLabel(self, i: Int) -> Actor = Label.of(Float(i % 10 * 70 + 16), Float(i / 10 * 30 + 14), "b{i}", 14.0, Color.White)
122
+ fun buttonLabel(self, i: Int) -> View = Label.of(Float(i % 10 * 70 + 16), Float(i / 10 * 30 + 14), "b{i}", 14.0, Color.White)
122
123
 
123
124
  fun wrap(v: Float, span: Float) -> Float = v - span * Float(Int(v / span))
124
125
 
compiler/game/web-test/fixtures/text_sizes.plum CHANGED
@@ -17,6 +17,8 @@ import std/math/Aabb
17
17
  import std/game/Screen
18
18
  import std/game/ScreenSlice
19
19
  import std/game/Game
20
+ import std/game/View
21
+ import std/game/Place
20
22
 
21
23
  # The text, one tick older each tick.
22
24
  struct Sizes[ScreenSlice<Float>](t: Int) =
@@ -26,8 +28,16 @@ struct Sizes[ScreenSlice<Float>](t: Int) =
26
28
 
27
29
  fun reduce(self, dt: Float) -> Sizes = Sizes(t: self.t + 1)
28
30
 
31
+ fun view(self) -> List<View> = [SizesDrawing(s: self)]
32
+
29
33
  fun draw(self, io: Io, m: Affine, alpha: Float, area: Aabb) = drawSizes(io, self.t)
30
34
 
35
+ # What the screen draws each frame, with `gfx` by hand.
36
+ struct SizesDrawing[View](s: Sizes) =
37
+ fun place(self) -> Place = place.at(0.0, 0.0)
38
+
39
+ fun paintSelf(self, io: Io, m: Affine, alpha: Float) = self.s.draw(io, m, alpha, Aabb.of(0.0, 0.0, 0.0, 0.0))
40
+
31
41
  fun main(io: Io) -> Game =
32
42
  Game(screens: [page(Sizes(t: 0))])
33
43
 
compiler/game/web-test/tests/web_check.rs CHANGED
@@ -151,7 +151,7 @@ fn render_target_pixels() {
151
151
  eprintln!("SKIP: Playwright Chromium not installed (see compiler/game/web-test/README.md)");
152
152
  return;
153
153
  }
154
- let pixels = ["130,130,255,0,0", "196,196,0,255,0", "130,196,51,51,51", "450,150,102,153,204", "600,150,26,51,26", "750,150,153,153,153", "900,150,153,26,26", "408,308,0,0,255", "408,408,153,26,26"];
154
+ let pixels = ["130,130,255,0,0", "196,196,0,255,0", "130,196,51,51,51", "450,150,102,153,204", "600,150,26,51,26", "750,150,153,153,153", "900,150,153,26,26", "408,308,0,0,255", "408,408,153,26,26", "650,490,255,255,255", "690,450,51,51,51"];
155
155
  let opts = Options { expect_pixels: pixels.iter().map(|p| plum_web_test::ExpectPixel::parse(p).unwrap()).collect(), ..Options::default() };
156
156
  let rt = tokio::runtime::Runtime::new().unwrap();
157
157
  let file = repo_root().join("compiler/game/web-test/fixtures/rendertarget.plum");
compiler/game/web/plum_bridge.js CHANGED
@@ -64,6 +64,15 @@
64
64
  case "ArrowUp": return 265;
65
65
  case "ShiftLeft": return 340;
66
66
  case "ControlLeft": return 341;
67
+ case "BracketLeft": return 91;
68
+ case "Backslash": return 92;
69
+ case "BracketRight": return 93;
70
+ case "AltLeft": return 342;
71
+ case "MetaLeft": return 343;
72
+ case "ShiftRight": return 344;
73
+ case "ControlRight": return 345;
74
+ case "AltRight": return 346;
75
+ case "MetaRight": return 347;
67
76
  default: return -1;
68
77
  }
69
78
  }
@@ -464,6 +473,20 @@
464
473
  drawRect(x, y, w, h, r, g, b, a) {
465
474
  quad(white, x, y, x + w, y, x + w, y + h, x, y + h, 0, 0, 1, 1, packColor(r, g, b, a));
466
475
  },
476
+ // The rect turned `rotation` radians clockwise (y points down) about its centre.
477
+ drawRectEx(x, y, w, h, rotation, r, g, b, a) {
478
+ if (rotation === 0) return self.drawRect(x, y, w, h, r, g, b, a);
479
+ const cx = x + w / 2;
480
+ const cy = y + h / 2;
481
+ const co = Math.cos(rotation);
482
+ const si = Math.sin(rotation);
483
+ const at = (dx, dy) => [cx + dx * co - dy * si, cy + dx * si + dy * co];
484
+ const [x0, y0] = at(-w / 2, -h / 2);
485
+ const [x1, y1] = at(w / 2, -h / 2);
486
+ const [x2, y2] = at(w / 2, h / 2);
487
+ const [x3, y3] = at(-w / 2, h / 2);
488
+ quad(white, x0, y0, x1, y1, x2, y2, x3, y3, 0, 0, 1, 1, packColor(r, g, b, a));
489
+ },
467
490
  drawLine(x1, y1, x2, y2, th, r, g, b, a) {
468
491
  const dx = x2 - x1;
469
492
  const dy = y2 - y1;
@@ -494,9 +517,18 @@
494
517
  // `x, y` is the text's top-left. Each glyph is a quad of the SDF atlas scaled
495
518
  // by size / GLYPH_BASE, so the text stays sharp at any size, zoom or dpr.
496
519
  drawText(str, x, y, size, r, g, b, a) {
520
+ self.drawTextEx(str, x, y, size, 0, r, g, b, a);
521
+ },
522
+ // As drawText, turned `rotation` radians clockwise about the text's top-left: each
523
+ // glyph's quad is turned about (x, y).
524
+ drawTextEx(str, x, y, size, rotation, r, g, b, a) {
497
525
  if (!str) return;
498
526
  const k = size / GLYPH_BASE;
499
527
  const c = packColor(r, g, b, a);
528
+ const co = Math.cos(rotation);
529
+ const si = Math.sin(rotation);
530
+ const tx = (px, py) => x + (px - x) * co - (py - y) * si;
531
+ const ty = (px, py) => y + (px - x) * si + (py - y) * co;
500
532
  let pen = x;
501
533
  for (const ch of str) {
502
534
  const gl = env.glyph(ch.codePointAt(0));
@@ -504,7 +536,13 @@
504
536
  if (gl.w > 0) {
505
537
  const x0 = pen - GLYPH_PAD * k;
506
538
  const y0 = y - GLYPH_PAD * k;
539
+ const x1 = x0 + gl.w * k;
540
+ const y1 = y0 + gl.h * k;
541
+ if (rotation === 0) {
542
+ quad(env.atlas, x0, y0, x1, y0, x1, y1, x0, y1, gl.u0, gl.v0, gl.u1, gl.v1, c);
543
+ } else {
507
- quad(env.atlas, x0, y0, x0 + gl.w * k, y0, x0 + gl.w * k, y0 + gl.h * k, x0, y0 + gl.h * k, gl.u0, gl.v0, gl.u1, gl.v1, c);
544
+ quad(env.atlas, tx(x0, y0), ty(x0, y0), tx(x1, y0), ty(x1, y0), tx(x1, y1), ty(x1, y1), tx(x0, y1), ty(x0, y1), gl.u0, gl.v0, gl.u1, gl.v1, c);
545
+ }
508
546
  }
509
547
  pen += gl.adv * k;
510
548
  }
@@ -1255,9 +1293,11 @@ fn shade(i: VOut) -> vec4f {
1255
1293
  frameTime: () => dt,
1256
1294
  clear: b.clear,
1257
1295
  drawRect: b.drawRect,
1296
+ drawRectEx: b.drawRectEx,
1258
1297
  drawCircle: b.drawCircle,
1259
1298
  drawLine: b.drawLine,
1260
1299
  drawText: (s, ...rest) => b.drawText(strToJs(ctx.plum, s), ...rest),
1300
+ drawTextEx: (s, ...rest) => b.drawTextEx(strToJs(ctx.plum, s), ...rest),
1261
1301
  setCamera: b.setCamera,
1262
1302
  resetCamera: b.resetCamera,
1263
1303
  textureLoad: (s) => {
examples/games/balloonpop/BalloonPop.plum CHANGED
@@ -7,7 +7,6 @@ import std/Io
7
7
  import std/collections/List
8
8
  import std/game/Color
9
9
  import std/game/audio
10
- import std/game/Label
11
10
  import std/game/Screen
12
11
  import std/game/History
13
12
  import std/game/Game
@@ -37,9 +36,6 @@ struct Hue(name: Str, color: Color) =
37
36
 
38
37
  fun count() -> Int = 7
39
38
 
40
- fun centred(s: Str, cx: Float, y: Float, size: Float, color: Color) -> Label =
41
- Label.of(cx - size * 0.3 * Float(s.length()), y, s, size, color)
42
-
43
39
  struct Assets(pop: Sound, party: Sound, music: Sound) =
44
40
  fun load(io: Io) -> Assets = Assets(pop: audio.loadSound(io, "pickup.wav"), party: audio.loadSound(io, "gameover.wav"), music: audio.loadSound(io, "music.wav"))
45
41
 
examples/games/balloonpop/actors/Balloon.plum CHANGED
@@ -14,8 +14,9 @@ import std/math/math
14
14
  import std/game/Color
15
15
  import std/game/gfx
16
16
  import std/game/Place
17
- import std/game/Actor
17
+ import std/game/View
18
18
  import std/game/Circle
19
+ import std/game/Label
19
20
  import std/game/Sized
20
21
  import std/game/Touch
21
22
  import BalloonPop
@@ -56,8 +57,8 @@ struct Balloon[Actor, Sized, Touch](id: Int, x: Float, y: Float, speed: Float, h
56
57
 
57
58
  fun drawnX(self) -> Float = if self.popped() then self.x else self.x + 14.0 * math.sin(self.clock * 1.3 + self.phase)
58
59
 
59
- fun update(self, dt: Float, clock: Float) -> Balloon =
60
+ fun step(self, dt: Float) -> Balloon =
60
- Balloon(..self, clock: clock, y: if self.popped() then self.y else self.y - self.speed * dt)
61
+ Balloon(..self, clock: self.clock + dt, y: if self.popped() then self.y else self.y - self.speed * dt)
61
62
 
62
63
  fun done(self) -> Bool = self.y < 0.0 - Balloon.Radius * 3.0 || {self.popped() && self.clock - self.poppedAt > Balloon.PopTime}
63
64
 
@@ -73,35 +74,34 @@ struct Balloon[Actor, Sized, Touch](id: Int, x: Float, y: Float, speed: Float, h
73
74
  r := Balloon.Radius
74
75
  math.hypot(p.x, p.y) <= r || math.hypot(p.x, p.y - {r + 2.0}) <= 6.0 || nearLine(0.0, r, self.stringX(), r * 2.6, 2.0, p.x, p.y)
75
76
 
76
- fun view(self) -> List<Actor> =
77
+ fun view(self) -> List<View> =
77
78
  hue := Hue.of(self.hue)
78
79
  r := Balloon.Radius
79
80
  if !self.popped()
80
81
  [
81
- Circle.of(-6.0, r + 2.0 - 6.0, 6.0, hue.color),
82
+ Circle.of(0.0, r + 2.0, 6.0, hue.color),
82
- Circle.of(0.0 - r, 0.0 - r, r, hue.color),
83
+ Circle.of(0.0, 0.0, r, hue.color),
83
- Circle.of(0.0 - r * 0.35 - r * 0.22, 0.0 - r * 0.4 - r * 0.22, r * 0.22, Color.White.withAlpha(0.55))]
84
+ Circle.of(0.0 - r * 0.35, 0.0 - r * 0.4, r * 0.22, Color.White.withAlpha(0.55))]
84
85
  else
85
86
  t := {{self.clock - self.poppedAt} / Balloon.PopTime}.min(1.0)
86
87
  fade := 1.0 - t
87
88
  reach := 20.0 + 70.0 * t
88
- title: Actor := balloonpop.centred("{hue.name}!", 0.0, 0.0 - 20.0 - 60.0 * t, 40.0, Color.rgb(0.15, 0.15, 0.3).withAlpha(fade))
89
+ title: View := Label.of(0.0, 0.0 - 20.0 - 60.0 * t, "{hue.name}!", 40.0, Color.rgb(0.15, 0.15, 0.3).withAlpha(fade), Centre)
89
90
  Cons(title, burst(0, reach, hue.color.withAlpha(fade)))
90
91
 
91
- fun paint(self, io: Io, m: Affine, alpha: Float) =
92
+ fun paintSelf(self, io: Io, m: Affine, alpha: Float) =
92
93
  if !self.popped()
93
94
  r := Balloon.Radius
94
95
  a := m.apply(Vec2(x: 0.0, y: r))
95
96
  b := m.apply(Vec2(x: self.stringX(), y: r * 2.6))
96
97
  gfx.drawLine(io, a.x, a.y, b.x, b.y, 2.0 * m.scaleX(), Color.rgb(0.35, 0.35, 0.35).withAlpha(alpha))
97
- actor.paintView(io, self.view(), m, alpha)
98
98
 
99
- fun burst(i: Int, reach: Float, color: Color) -> List<Actor> =
99
+ fun burst(i: Int, reach: Float, color: Color) -> List<View> =
100
100
  if i >= 8
101
101
  Nil
102
102
  else
103
103
  a := Float(i) * Float.Tau / 8.0
104
- Cons(Circle.of(math.cos(a) * reach - 8.0, math.sin(a) * reach - 8.0, 8.0, color), burst(i + 1, reach, color))
104
+ Cons(Circle.of(math.cos(a) * reach, math.sin(a) * reach, 8.0, color), burst(i + 1, reach, color))
105
105
 
106
106
  struct Spawned(balloon: Balloon, rng: Random)
107
107
 
@@ -116,12 +116,12 @@ test "a whole balloon is hit on its body, its knot and its string, and a burst o
116
116
  assert b.pop().touch().disabled()
117
117
 
118
118
  test "a balloon rises and sways as the clock runs, and stays where it burst"
119
- b := Balloon.at(1, 100.0, 500.0, 50.0, 0, 0.0, 0.0).update(1.0, 1.0)
119
+ b := Balloon.at(1, 100.0, 500.0, 50.0, 0, 0.0, 0.0).step(1.0)
120
120
  assert b.place().y == 450.0
121
121
  assert b.place().x != 100.0
122
122
  x := b.place().x
123
- p := b.pop().update(0.5, 1.5)
123
+ p := b.pop().step(0.5)
124
124
  assert p.place().y == 450.0
125
125
  assert p.place().x == x
126
126
  assert !p.done()
127
- assert p.update(0.2, 1.7).done()
127
+ assert p.step(0.2).done()
examples/games/balloonpop/screens/PlaygroundScreen.plum CHANGED
@@ -14,7 +14,8 @@ import std/math/math
14
14
  import std/game/Color
15
15
  import std/game/input
16
16
  import std/game/Replay
17
+ import std/game/View
17
- import std/game/Actor
18
+ import std/game/Box
18
19
  import std/game/Circle
19
20
  import std/game/Label
20
21
  import std/game/Control
@@ -66,11 +67,16 @@ struct PlaygroundScreen[ScreenSlice<PopAction>](
66
67
 
67
68
  fun background(self) -> Color = Color.rgb(0.55, 0.8, 1.0)
68
69
 
69
- fun view(self) -> List<Actor> =
70
- balloons := actor.all(self.balloons)
71
- sky(self.clock).append(balloons).append(self.hud()).append(self.party())
70
+ fun view(self) -> List<View> = sky(self.clock).append(view.all(self.balloons)).append(self.party())
72
71
 
72
+ fun hud(self, window: Vec2) -> List<View> = [
73
+ Box.of(16.0, 14.0, 170.0, 56.0, Color.White.withAlpha(0.7)),
74
+ Circle.of(46.0, 42.0, 18.0, Hue.of(0).color),
75
+ Label.of(80.0, 20.0, "{self.pops}", 44.0, Color.rgb(0.15, 0.15, 0.3))]
76
+
77
+ fun stepped(self, dt: Float) -> PlaygroundScreen = PlaygroundScreen(..self, balloons: view.stepAll(self.balloons, dt))
78
+
73
- fun onPress(self, target: Actor, at: Vec2) -> Option<PopAction> = match target
79
+ fun onPress(self, target: View, at: Vec2) -> Option<PopAction> = match target
74
80
  Balloon as b => Some(Pop(balloon: b))
75
81
  _ => None
76
82
 
@@ -98,7 +104,7 @@ struct PlaygroundScreen[ScreenSlice<PopAction>](
98
104
  fun advance(self, dt: Float) -> PlaygroundScreen =
99
105
  clock := self.clock + dt
100
106
  risen := PlaygroundScreen(..self, clock: clock, balloons: Nil)
101
- self.balloons.map(|b| b.update(dt, clock)).fold(risen, |s, b|
107
+ self.balloons.fold(risen, |s, b|
102
108
  if b.done()
103
109
  sp := Balloon.spawn(b.id, s.rng, 0.0, clock)
104
110
  PlaygroundScreen(..s, rng: sp.rng, balloons: s.balloons.append([sp.balloon]))
@@ -119,24 +125,19 @@ struct PlaygroundScreen[ScreenSlice<PopAction>](
119
125
 
120
126
  fun partyingAt(self, clock: Float) -> Bool = clock - self.partyAt < PlaygroundScreen.PartyTime
121
127
 
122
- fun hud(self) -> List<Actor> = [
123
- Box.of(16.0, 14.0, 170.0, 56.0, Color.White.withAlpha(0.7)),
124
- Circle.of(28.0, 24.0, 18.0, Hue.of(0).color),
125
- Label.of(80.0, 20.0, "{self.pops}", 44.0, Color.rgb(0.15, 0.15, 0.3))]
126
-
127
- fun party(self) -> List<Actor> =
128
+ fun party(self) -> List<View> =
128
129
  if !self.partying()
129
130
  Nil
130
131
  else
131
132
  age := self.clock - self.partyAt
132
133
  k := partyScale(age)
133
134
  cx := Arena.W / 2.0
134
- titles: List<Actor> := [
135
+ titles: List<View> := [
135
- balloonpop.centred("Hooray!", cx, 250.0 - 40.0 * k, 72.0 * k, Color.rgb(0.95, 0.3, 0.5)),
136
+ Label.of(cx, 250.0 - 40.0 * k, "Hooray!", 72.0 * k, Color.rgb(0.95, 0.3, 0.5), Centre),
136
- balloonpop.centred("{self.pops} balloons!", cx, 250.0 + 40.0 * k, 40.0 * k, Color.rgb(0.15, 0.15, 0.3))]
137
+ Label.of(cx, 250.0 + 40.0 * k, "{self.pops} balloons!", 40.0 * k, Color.rgb(0.15, 0.15, 0.3), Centre)]
137
138
  confettiFrom(0, age).append(titles)
138
139
 
139
- fun confettiFrom(i: Int, age: Float) -> List<Actor> =
140
+ fun confettiFrom(i: Int, age: Float) -> List<View> =
140
141
  if i >= 30
141
142
  Nil
142
143
  else
@@ -145,23 +146,21 @@ fun confettiFrom(i: Int, age: Float) -> List<Actor> =
145
146
  wob := 10.0 * math.sin(age * 4.0 + Float(i))
146
147
  Cons(Box.of(x + wob, y, 12.0, 12.0, Hue.of(i).color), confettiFrom(i + 1, age))
147
148
 
148
- fun sky(clock: Float) -> List<Actor> =
149
+ fun sky(clock: Float) -> List<View> =
149
- back: List<Actor> := [
150
+ back: List<View> := [
150
151
  Box.of(0.0, 0.0, Arena.W, Arena.H, Color.rgb(0.55, 0.8, 1.0)),
151
152
  Box.of(0.0, 0.0, Arena.W, 200.0, Color.rgb(0.45, 0.72, 0.98)),
152
- disc(690.0, 90.0, 46.0, Color.rgb(1.0, 0.9, 0.35))]
153
+ Circle.of(690.0, 90.0, 46.0, Color.rgb(1.0, 0.9, 0.35))]
153
- grass: List<Actor> := [Box.of(0.0, Arena.H - 50.0, Arena.W, 50.0, Color.rgb(0.4, 0.78, 0.35))]
154
+ grass: List<View> := [Box.of(0.0, Arena.H - 50.0, Arena.W, 50.0, Color.rgb(0.4, 0.78, 0.35))]
154
155
  back.append(cloud(wrapX(120.0 + clock * 12.0), 130.0)).append(cloud(wrapX(520.0 + clock * 8.0), 220.0)).append(grass)
155
156
 
156
157
  fun wrapX(x: Float) -> Float =
157
158
  span := Arena.W + 200.0
158
159
  x - span * Float(Int(x / span)) - 100.0
159
160
 
160
- fun cloud(x: Float, y: Float) -> List<Actor> =
161
+ fun cloud(x: Float, y: Float) -> List<View> =
161
162
  white := Color.White.withAlpha(0.9)
162
- [disc(x - 30.0, y + 8.0, 24.0, white), disc(x, y, 32.0, white), disc(x + 32.0, y + 8.0, 24.0, white)]
163
+ [Circle.of(x - 30.0, y + 8.0, 24.0, white), Circle.of(x, y, 32.0, white), Circle.of(x + 32.0, y + 8.0, 24.0, white)]
163
-
164
- fun disc(cx: Float, cy: Float, r: Float, color: Color) -> Actor = Circle.of(cx - r, cy - r, r, color)
165
164
 
166
165
  fun field(io: Io, seed: Int) -> TestRig<PlaygroundScreen> = headless.mount(io, PlaygroundScreen.seeded(seed, Assets.none()))
167
166
 
@@ -185,7 +184,7 @@ fun pops(t: TestRig<PlaygroundScreen>) -> List<PopAction> = t.effects<PopAction>
185
184
 
186
185
  fun names(t: TestRig<PlaygroundScreen>) -> Str = t.effects<PopAction>().map(|a| a.toStr()).join(" ")
187
186
 
188
- fun lines(t: TestRig<PlaygroundScreen>) -> Str = t.find<Label>().map(|l| l.line()).join(", ")
187
+ fun lines(t: TestRig<PlaygroundScreen>) -> Str = t.find<Label>().map(|l| l.text).join(", ")
189
188
 
190
189
  fun runInput(i: Int) -> Input =
191
190
  events := Slice<InputEvent>()
@@ -251,7 +250,7 @@ test "every tenth pop starts a party that ends"
251
250
  u := centred(t).clickAt(400.0, 300.0).tick(0.0)
252
251
  assert u.screen.pops == 10
253
252
  assert u.screen.partying()
254
- assert lines(u) == "Yellow!, 10, Hooray!, 10 balloons!"
253
+ assert lines(u) == "Yellow!, Hooray!, 10 balloons!, 10"
255
254
  assert !u.tick(PlaygroundScreen.PartyTime + 0.1).screen.partying()
256
255
 
257
256
  test "the game counts pops as they are dispatched and plays one pop a tick, and the fanfare"
@@ -269,7 +268,7 @@ test "the game counts pops as they are dispatched and plays one pop a tick, and
269
268
  assert w.screen.partiesHeard == 1
270
269
  assert w.tick().screen.popsHeard == 2
271
270
 
272
- test "the game tells the screen the view's size, and a press is found through it"
271
+ test "after a resize the press is found through the camera"
273
272
  t := centred(field(io, 3)).resize(1600.0, 600.0)
274
273
  u := t.clickAt(400.0, 300.0).tick()
275
274
  assert u.toWorld(0.0, 0.0).x == -400.0
examples/games/clicks.plum CHANGED
@@ -10,7 +10,8 @@ import std/math/Vec2
10
10
  import std/game/Color
11
11
  import std/game/input
12
12
  import std/game/Place
13
+ import std/game/View
13
- import std/game/Actor
14
+ import std/game/Box
14
15
  import std/game/Circle
15
16
  import std/game/Label
16
17
  import std/game/Control
@@ -19,16 +20,16 @@ import std/game/ScreenSlice
19
20
  import std/game/Game
20
21
  import std/game/headless
21
22
 
22
- enum TapAction = Tapped | Push(dx: Float) | Tick(dt: Float) | Quit
23
+ enum TapAction = Tapped | Push(dx: Float) | Quit
23
24
 
24
25
  struct Ball[Actor](x: Float, y: Float, vx: Float) =
25
26
  fun place(self) -> Place = place.at(self.x, self.y)
26
27
 
27
- fun view(self) -> List<Actor> = [Circle.of(0.0, 0.0, 10.0, Color.Yellow)]
28
+ fun view(self) -> List<View> = [Circle.of(0.0, 0.0, 10.0, Color.Yellow)]
28
29
 
29
30
  fun push(self, vx: Float) -> Ball = Ball(..self, vx: vx)
30
31
 
31
- fun update(self, dt: Float) -> Ball = Ball(..self, x: self.x + self.vx * dt)
32
+ fun step(self, dt: Float) -> Ball = Ball(..self, x: self.x + self.vx * dt)
32
33
 
33
34
  struct TapScreen[ScreenSlice<TapAction>](taps: Int, box: Box, ball: Ball) =
34
35
  fun start() -> TapScreen =
@@ -36,9 +37,11 @@ struct TapScreen[ScreenSlice<TapAction>](taps: Int, box: Box, ball: Ball) =
36
37
 
37
38
  fun name(self) -> Str = "tap"
38
39
 
39
- fun view(self) -> List<Actor> = [self.box, self.ball, Label.of(20.0, 20.0, "Taps: {self.taps}", 24.0, Color.White)]
40
+ fun view(self) -> List<View> = [self.box, self.ball, Label.of(20.0, 20.0, "Taps: {self.taps}", 24.0, Color.White)]
40
41
 
42
+ fun stepped(self, dt: Float) -> TapScreen = TapScreen(..self, ball: self.ball.step(dt))
43
+
41
- fun onPress(self, target: Actor, at: Vec2) -> Option<TapAction> = if @sameRef(target, self.box) then Some(Tapped) else None
44
+ fun onPress(self, target: View, at: Vec2) -> Option<TapAction> = if @sameRef(target, self.box) then Some(Tapped) else None
42
45
 
43
46
  fun onKey(self, e: InputEvent) -> Option<TapAction> = match e
44
47
  KeyDown(k) => if k == Key.Escape then Some(Quit) else None
@@ -46,12 +49,9 @@ struct TapScreen[ScreenSlice<TapAction>](taps: Int, box: Box, ball: Ball) =
46
49
 
47
50
  fun held(self, input: Input) -> Option<TapAction> = Some(Push(dx: if input.isKeyDown(Key.Right) then 100.0 else 0.0))
48
51
 
49
- fun tick(self, dt: Float) -> Option<TapAction> = Some(Tick(dt: dt))
50
-
51
52
  fun reduce(self, a: TapAction) -> TapScreen = match a
52
53
  Tapped => TapScreen(..self, taps: self.taps + 1)
53
54
  Push(dx) => TapScreen(..self, ball: self.ball.push(dx))
54
- Tick(dt) => TapScreen(..self, ball: self.ball.update(dt))
55
55
  Quit => self
56
56
 
57
57
  fun effect(self, io: Io, a: TapAction, game: Control) = match a
examples/games/orbitrunner/OrbitRunner.plum CHANGED
@@ -22,8 +22,6 @@ struct Sheet =
22
22
  Cell = 16.0
23
23
  Size = 48.0
24
24
 
25
- fun frame(clock: Float, count: Int, fps: Float) -> Int = Int(clock * fps) % count
26
-
27
25
  struct Motion(x: Float, y: Float, vx: Float, vy: Float) =
28
26
  fun spawn(rng: Random, ax: Float, ay: Float, gap: Float, speed: Float) -> Spawned =
29
27
  spot := Motion.spot(rng, ax, ay, gap, 20)
@@ -76,8 +74,3 @@ fun main(io: Io) -> Game =
76
74
  assets.startMusic(io)
77
75
  play: Screen := PlayingScreen.start(Random.seeded(io.randomSeed()), assets)
78
76
  Game(screens: [play])
79
-
80
- test "animation frames cycle"
81
- assert Sheet.frame(0.0, 4, 8.0) == 0
82
- assert Sheet.frame(0.13, 4, 8.0) == 1
83
- assert Sheet.frame(0.5, 4, 8.0) == 0
examples/games/orbitrunner/actors/Mine.plum CHANGED
@@ -2,10 +2,10 @@ module orbit_runner_mine
2
2
 
3
3
  import std/Int
4
4
  import std/Float
5
- import std/Bool
6
5
  import std/collections/List
6
+ import std/math/math
7
7
  import std/game/Place
8
- import std/game/Actor
8
+ import std/game/View
9
9
  import std/game/Sprite
10
10
  import OrbitRunner
11
11
 
@@ -19,25 +19,21 @@ struct Mine[Actor](at: Place, vx: Float, vy: Float, clock: Float, tex: Texture)
19
19
 
20
20
  fun place(self) -> Place = self.at
21
21
 
22
- fun view(self) -> List<Actor> =
22
+ fun view(self) -> List<View> =
23
- [Sprite.cell(0.0, 0.0, self.tex, Sheet.Size, Sheet.Size, 0.0, 2.0 * Sheet.Cell, Sheet.Cell, Sheet.Cell, Sheet.frame(self.clock, 4, 4.0))]
23
+ [Sprite.cell(0.0, 0.0, self.tex, Sheet.Size, Sheet.Size, 0.0, 2.0 * Sheet.Cell, Sheet.Cell, Sheet.Cell, Sprite.frameAt(self.clock, 4.0, 4))]
24
24
 
25
25
  fun motion(self) -> Motion = Motion(x: self.at.x, y: self.at.y, vx: self.vx, vy: self.vy)
26
26
 
27
27
  fun put(self, m: Motion) -> Mine = Mine(..self, at: self.at.moveTo(m.x, m.y), vx: m.vx, vy: m.vy)
28
28
 
29
- fun update(self, dt: Float, frozen: Bool = false) -> Mine =
29
+ fun step(self, dt: Float) -> Mine =
30
- clock := self.clock + dt
31
- if frozen
32
- Mine(..self, clock: clock)
33
- else
34
- moved := Mine(..self, clock: clock).put(self.motion().drifted(Mine.Radius, dt))
30
+ moved := Mine(..self, clock: self.clock + dt).put(self.motion().drifted(Mine.Radius, dt))
35
- Mine(..moved, at: moved.at.rotateBy(2.0 * dt))
31
+ Mine(..moved, at: moved.at.rotateBy(2.0 * dt))
36
32
 
37
33
  test "a mine spins as it drifts"
38
- mine := Mine.create(Motion(x: 400.0, y: 300.0, vx: 10.0, vy: 0.0), Texture.none()).update(0.5)
34
+ mine := Mine.create(Motion(x: 400.0, y: 300.0, vx: 10.0, vy: 0.0), Texture.none()).step(0.5)
39
- assert {mine.at.rotation - 1.0}.abs() < 0.01
35
+ assert math.near(mine.at.rotation, 1.0, 0.01)
40
- assert {mine.at.x - 405.0}.abs() < 0.01
36
+ assert math.near(mine.at.x, 405.0, 0.01)
41
37
 
42
38
  test "more mines are out as the score grows"
43
39
  assert Mine.countFor(0) == 3
examples/games/orbitrunner/actors/Orb.plum CHANGED
@@ -10,7 +10,7 @@ import std/math/Affine
10
10
  import std/game/Color
11
11
  import std/game/gfx
12
12
  import std/game/Place
13
- import std/game/Actor
13
+ import std/game/View
14
14
  import std/game/Sprite
15
15
  import OrbitRunner
16
16
 
@@ -23,32 +23,25 @@ struct Orb[Actor](at: Place, vx: Float, vy: Float, phase: Float, clock: Float, t
23
23
 
24
24
  fun place(self) -> Place = self.at
25
25
 
26
- fun view(self) -> List<Actor> =
26
+ fun view(self) -> List<View> =
27
- [Sprite.cell(0.0, 0.0, self.tex, Sheet.Size, Sheet.Size, 0.0, Sheet.Cell, Sheet.Cell, Sheet.Cell, Sheet.frame(self.clock + self.phase, 4, 8.0))]
27
+ [Sprite.cell(0.0, 0.0, self.tex, Sheet.Size, Sheet.Size, 0.0, Sheet.Cell, Sheet.Cell, Sheet.Cell, Sprite.frameAt(self.clock + self.phase, 8.0, 4))]
28
28
 
29
29
  fun motion(self) -> Motion = Motion(x: self.at.x, y: self.at.y, vx: self.vx, vy: self.vy)
30
30
 
31
31
  fun put(self, m: Motion) -> Orb = Orb(..self, at: self.at.moveTo(m.x, m.y), vx: m.vx, vy: m.vy)
32
32
 
33
- fun update(self, dt: Float, frozen: Bool = false) -> Orb =
34
- ticked := Orb(..self, clock: self.clock + dt)
35
- if frozen then ticked else ticked.put(self.motion().drifted(Orb.Radius, dt))
33
+ fun step(self, dt: Float) -> Orb = Orb(..self, clock: self.clock + dt).put(self.motion().drifted(Orb.Radius, dt))
36
34
 
37
- fun paint(self, io: Io, m: Affine, alpha: Float) =
35
+ fun paintSelf(self, io: Io, m: Affine, alpha: Float) =
38
36
  c := m.apply(Vec2(x: Sheet.Size / 2.0, y: Sheet.Size / 2.0))
39
37
  k := m.scaleX()
40
38
  gfx.blendMode(io, Blend.Add)
41
39
  gfx.drawCircle(io, c.x, c.y, 26.0 * k, Color(r: 0.35, g: 0.22, b: 0.0, a: 0.5 * alpha))
42
40
  gfx.drawCircle(io, c.x, c.y, 17.0 * k, Color(r: 0.6, g: 0.4, b: 0.05, a: 0.5 * alpha))
43
41
  gfx.blendMode(io, Blend.Normal)
44
- actor.paintView(io, self.view(), m, alpha)
45
42
 
46
43
  test "an orb drifts and bounces off the walls"
47
- orb := Orb.create(Motion(x: 795.0, y: 300.0, vx: 100.0, vy: 0.0), 0.0, Texture.none()).update(0.1)
44
+ orb := Orb.create(Motion(x: 795.0, y: 300.0, vx: 100.0, vy: 0.0), 0.0, Texture.none()).step(0.1)
48
45
  assert orb.vx == -100.0
49
46
  assert orb.at.x == Arena.W - 10.0
50
-
51
- test "a frozen orb only animates"
52
- orb := Orb.create(Motion(x: 400.0, y: 300.0, vx: 100.0, vy: 0.0), 0.0, Texture.none()).update(0.1, true)
53
- assert orb.at.x == 400.0
54
47
  assert orb.clock == 0.1
examples/games/orbitrunner/actors/Ring.plum CHANGED
@@ -6,7 +6,7 @@ import std/Bool
6
6
  import std/collections/List
7
7
  import std/game/Color
8
8
  import std/game/Place
9
- import std/game/Actor
9
+ import std/game/View
10
10
  import std/game/Circle
11
11
 
12
12
  struct Ring[Actor](x: Float, y: Float, age: Float) =
@@ -17,21 +17,20 @@ struct Ring[Actor](x: Float, y: Float, age: Float) =
17
17
 
18
18
  fun place(self) -> Place = place.at(self.x, self.y)
19
19
 
20
- fun view(self) -> List<Actor> =
20
+ fun view(self) -> List<View> =
21
21
  k := self.age / Ring.Secs
22
- r := Ring.Reach * k
23
- [Circle.of(0.0 - r, 0.0 - r, r, Color.Red.withAlpha(1.0 - k))]
22
+ [Circle.of(0.0, 0.0, Ring.Reach * k, Color.Red.withAlpha(1.0 - k))]
24
23
 
25
- fun update(self, dt: Float) -> Ring = Ring(..self, age: self.age + dt)
24
+ fun step(self, dt: Float) -> Ring = Ring(..self, age: self.age + dt)
26
25
 
27
26
  fun done(self) -> Bool = self.age >= Ring.Secs
28
27
 
29
28
  test "a ring grows and fades over its time, then is done"
30
- ring := Ring.at(10.0, 20.0).update(0.2)
29
+ ring := Ring.at(10.0, 20.0).step(0.2)
31
30
  assert !ring.done()
32
31
  c := match ring.view().at(0)
33
32
  Circle as c => c
34
33
  _ => Circle.of(0.0, 0.0, 0.0, Color.Black)
35
34
  assert c.r == Ring.Reach / 2.0
36
35
  assert c.color.a == 0.5
37
- assert ring.update(0.2).done()
36
+ assert ring.step(0.2).done()
examples/games/orbitrunner/actors/Ship.plum CHANGED
@@ -7,7 +7,7 @@ import std/collections/List
7
7
  import std/math/math
8
8
  import std/game/Color
9
9
  import std/game/Place
10
- import std/game/Actor
10
+ import std/game/View
11
11
  import std/game/Circle
12
12
  import std/game/Sprite
13
13
  import OrbitRunner
@@ -25,75 +25,60 @@ struct Ship[Actor](tex: Texture, at: Place, vx: Float, vy: Float, ax: Float, ay:
25
25
 
26
26
  fun place(self) -> Place = self.at
27
27
 
28
+ fun visible(self) -> Bool = self.lit()
29
+
28
- fun view(self) -> List<Actor> =
30
+ fun view(self) -> List<View> = [
29
- glow := Sheet.Size / 2.0 - 17.0
30
- if self.lit()
31
- [
32
- Circle.of(glow, glow, 17.0, Color(r: 0.4, g: 0.8, b: 1.0, a: 0.12)),
31
+ Circle.of(Sheet.Size / 2.0, Sheet.Size / 2.0, 17.0, Color(r: 0.4, g: 0.8, b: 1.0, a: 0.12)),
33
- Sprite.cell(0.0, 0.0, self.tex, Sheet.Size, Sheet.Size, 0.0, 0.0, Sheet.Cell, Sheet.Cell, Sheet.frame(self.clock, 4, 14.0))]
32
+ Sprite.cell(0.0, 0.0, self.tex, Sheet.Size, Sheet.Size, 0.0, 0.0, Sheet.Cell, Sheet.Cell, Sprite.frameAt(self.clock, 14.0, 4))]
34
- else
35
- Nil
36
33
 
37
34
  fun steer(self, ax: Float, ay: Float) -> Ship = Ship(..self, ax: ax, ay: ay)
38
35
 
39
36
  fun hurtFor(self, t: Float) -> Ship = Ship(..self, hurt: t)
40
37
 
41
- fun update(self, dt: Float, frozen: Bool = false) -> Ship =
38
+ fun step(self, dt: Float) -> Ship =
42
- clock := self.clock + dt
43
- if frozen
44
- Ship(..self, clock: clock)
45
- else
46
- keep := {1.0 - Ship.Drag * dt}.max(0.0)
39
+ keep := {1.0 - Ship.Drag * dt}.max(0.0)
47
- vx0 := {self.vx + self.ax * Ship.Thrust * dt} * keep
40
+ vx0 := {self.vx + self.ax * Ship.Thrust * dt} * keep
48
- vy0 := {self.vy + self.ay * Ship.Thrust * dt} * keep
41
+ vy0 := {self.vy + self.ay * Ship.Thrust * dt} * keep
49
- x0 := self.at.x + vx0 * dt
42
+ x0 := self.at.x + vx0 * dt
50
- y0 := self.at.y + vy0 * dt
43
+ y0 := self.at.y + vy0 * dt
51
- r := Ship.Radius
44
+ r := Ship.Radius
52
- x := x0.max(r).min(Arena.W - r)
45
+ x := x0.max(r).min(Arena.W - r)
53
- y := y0.max(r).min(Arena.H - r)
46
+ y := y0.max(r).min(Arena.H - r)
54
- vx := if x != x0 then 0.0 else vx0
47
+ vx := if x != x0 then 0.0 else vx0
55
- vy := if y != y0 then 0.0 else vy0
48
+ vy := if y != y0 then 0.0 else vy0
56
- moved := self.at.moveTo(x, y)
49
+ moved := self.at.moveTo(x, y)
57
- Ship(
50
+ Ship(
58
- ..self, clock: clock, hurt: {self.hurt - dt}.max(0.0), vx: vx, vy: vy,
51
+ ..self, clock: self.clock + dt, hurt: {self.hurt - dt}.max(0.0), vx: vx, vy: vy,
59
- at: if vx * vx + vy * vy > 400.0 then moved.rotateTo(math.atan2(vx, 0.0 - vy)) else moved)
52
+ at: if vx * vx + vy * vy > 400.0 then moved.rotateTo(math.atan2(vx, 0.0 - vy)) else moved)
60
-
53
+
61
- fun lit(self) -> Bool = !{self.hurt > 0.0 && Sheet.frame(self.clock, 2, 10.0) == 0}
54
+ fun lit(self) -> Bool = !{self.hurt > 0.0 && Sprite.frameAt(self.clock, 10.0, 2) == 0}
62
55
 
63
56
  struct Blinks(ship: Ship, n: Int)
64
57
 
65
58
  fun shipAt(x: Float, y: Float) -> Ship = Ship.startAt(Texture.none(), x, y)
66
59
 
67
60
  test "steering accelerates and drag slows the ship"
68
- ship := shipAt(400.0, 300.0).steer(1.0, 0.0).update(0.1)
61
+ ship := shipAt(400.0, 300.0).steer(1.0, 0.0).step(0.1)
69
62
  assert ship.vx > 0.0
70
63
  assert ship.at.x > 400.0
71
- slow := 0.until(30).fold(ship.steer(0.0, 0.0), |s, i| s.update(0.1))
64
+ slow := 0.until(30).fold(ship.steer(0.0, 0.0), |s, i| s.step(0.1))
72
65
  assert slow.vx < ship.vx / 4.0
73
66
 
74
67
  test "the ship stops at the arena walls"
75
- ship := 0.until(20).fold(shipAt(20.0, 20.0).steer(-1.0, -1.0), |s, i| s.update(0.1))
68
+ ship := 0.until(20).fold(shipAt(20.0, 20.0).steer(-1.0, -1.0), |s, i| s.step(0.1))
76
69
  assert ship.at.x == Ship.Radius
77
70
  assert ship.at.y == Ship.Radius
78
71
  assert ship.vx == 0.0
79
72
 
80
- test "a frozen ship stays where it is, its clock still running"
81
- ship := shipAt(400.0, 300.0).steer(1.0, 0.0).update(0.1)
82
- still := ship.update(0.1, true)
83
- assert still.at.x == ship.at.x
84
- assert still.clock > 0.15
85
-
86
- test "its view is a glow and a sprite at the frame of its clock, and empty on the blink's off beats"
73
+ test "its view is a glow and a sprite at the frame of its clock, and it is hidden on the blink's off beats"
87
74
  ship := Ship.create(Texture.none())
88
75
  assert ship.view().length() == 2
89
- later := 0.until(5).fold(ship, |s, i| s.update(0.02))
76
+ later := 0.until(5).fold(ship, |s, i| s.step(0.02))
90
77
  sprite := match later.view().at(1)
91
78
  Sprite as s => s.frameX()
92
79
  _ => -1.0
93
80
  assert sprite == Sheet.Cell
94
- hurt := later.hurtFor(Ship.HurtTime)
95
- blinks := 0.until(60).fold(Blinks(ship: hurt, n: 0), |b, i|
81
+ blinks := 0.until(60).fold(Blinks(ship: later.hurtFor(Ship.HurtTime), n: 0), |b, i|
96
- next := b.ship.update(0.02)
82
+ next := b.ship.step(0.02)
97
- Blinks(ship: next, n: if next.view().isEmpty() then b.n + 1 else b.n))
83
+ Blinks(ship: next, n: if next.visible() then b.n else b.n + 1))
98
84
  assert blinks.n > 0 && blinks.n < 60
99
-
examples/games/orbitrunner/actors/Star.plum CHANGED
@@ -6,15 +6,15 @@ import std/collections/List
6
6
  import std/math/math
7
7
  import std/game/Color
8
8
  import std/game/Place
9
- import std/game/Actor
9
+ import std/game/View
10
10
  import std/game/Circle
11
11
 
12
- struct Star[Actor](index: Int, clock: Float) =
12
+ struct Star[View](index: Int, clock: Float) =
13
13
  fun r(self) -> Float = 1.0 + Float(self.index % 3) * 0.5
14
14
 
15
- fun place(self) -> Place = place.at(Float({self.index * 7919} % 800) - self.r(), Float({self.index * 104729} % 600) - self.r())
15
+ fun place(self) -> Place = place.at(Float({self.index * 7919} % 800), Float({self.index * 104729} % 600))
16
16
 
17
- fun view(self) -> List<Actor> = [Circle.of(0.0, 0.0, self.r(), Color(r: 0.7, g: 0.8, b: 1.0, a: self.twinkle()))]
17
+ fun view(self) -> List<View> = [Circle.of(0.0, 0.0, self.r(), Color(r: 0.7, g: 0.8, b: 1.0, a: self.twinkle()))]
18
18
 
19
19
  fun twinkle(self) -> Float = 0.25 + 0.2 * math.sin(self.clock * 2.0 + Float(self.index))
20
20
 
examples/games/orbitrunner/screens/PlayingScreen.plum CHANGED
@@ -14,7 +14,8 @@ import std/math/math
14
14
  import std/game/Color
15
15
  import std/game/input
16
16
  import std/game/Replay
17
+ import std/game/View
17
- import std/game/Actor
18
+ import std/game/Box
18
19
  import std/game/Label
19
20
  import std/game/Sprite
20
21
  import std/game/Overlay
@@ -66,16 +67,21 @@ struct PlayingScreen[ScreenSlice<PlayAction>](
66
67
 
67
68
  fun background(self) -> Color = Color.rgb(0.04, 0.05, 0.1)
68
69
 
70
+ fun steps(self) -> Bool = !self.over
71
+
72
+ fun stepped(self, dt: Float) -> PlayingScreen =
73
+ PlayingScreen(..self, mines: view.stepAll(self.mines, dt), orbs: view.stepAll(self.orbs, dt), ship: self.ship.step(dt), rings: view.stepAll(self.rings, dt))
74
+
69
- fun view(self) -> List<Actor> =
75
+ fun view(self) -> List<View> =
70
- back: List<Actor> := [Box.of(0.0, 0.0, Arena.W, Arena.H, Color.rgb(0.07, 0.08, 0.16))]
76
+ back: List<View> := [Box.of(0.0, 0.0, Arena.W, Arena.H, Color.rgb(0.07, 0.08, 0.16))]
71
- mines := actor.all(self.mines)
77
+ mines := view.all(self.mines)
72
- orbs := actor.all(self.orbs)
78
+ orbs := view.all(self.orbs)
73
- ship: List<Actor> := if self.over then Nil else [self.ship]
79
+ ship: List<View> := if self.over then Nil else [self.ship]
74
- rings := actor.all(self.rings)
80
+ rings := view.all(self.rings)
75
- hud: List<Actor> := [
81
+ hud: List<View> := [
76
82
  Label.of(16.0, 12.0, "Score {self.score}", 28.0, Color.White),
77
83
  Label.of(16.0, 44.0, "Best {self.best.max(self.score)}", 20.0, Color.Yellow)]
78
- over: List<Actor> := if self.over
84
+ over: List<View> := if self.over
79
85
  [Overlay.of(Arena.W, Arena.H, [
80
86
  Label.of(300.0, 258.0, "Game over", 48.0, Color.Red),
81
87
  Label.of(270.0, 316.0, "Press Enter to play again", 24.0, Color.White)])]
@@ -101,11 +107,9 @@ struct PlayingScreen[ScreenSlice<PlayAction>](
101
107
  _ => None
102
108
 
103
109
  fun held(self, input: Input) -> Option<PlayAction> =
104
- left := input.isKeyDown(Key.Left) || input.isKeyDown(Key.KeyA)
105
- right := input.isKeyDown(Key.Right) || input.isKeyDown(Key.KeyD)
110
+ ax := input.axis(Key.Left, Key.Right) + input.axis(Key.KeyA, Key.KeyD)
106
- up := input.isKeyDown(Key.Up) || input.isKeyDown(Key.KeyW)
107
- down := input.isKeyDown(Key.Down) || input.isKeyDown(Key.KeyS)
111
+ ay := input.axis(Key.Up, Key.Down) + input.axis(Key.KeyW, Key.KeyS)
108
- Some(Steer(ax: axis(left, right), ay: axis(up, down)))
112
+ Some(Steer(ax: ax.max(-1.0).min(1.0), ay: ay.max(-1.0).min(1.0)))
109
113
 
110
114
  fun tick(self, dt: Float) -> Option<PlayAction> = Some(Tick(dt: dt))
111
115
 
@@ -125,11 +129,9 @@ struct PlayingScreen[ScreenSlice<PlayAction>](
125
129
  PlayingScreen(..self, best: self.best.max(self.score), score: 0, lives: PlayingScreen.StartLives, over: false).deal()
126
130
 
127
131
  fun advance(self, dt: Float) -> PlayingScreen =
128
- over := self.over
129
- moved := PlayingScreen(
130
- ..self, clock: self.clock + dt, mines: self.mines.map(|m| m.update(dt, over)), orbs: self.orbs.map(|o| o.update(dt, over)),
132
+ rings := if self.over then view.stepAll(self.rings, dt) else self.rings
131
- ship: self.ship.update(dt, over), rings: self.rings.map(|r| r.update(dt)).filter(|r| !r.done()))
133
+ moved := PlayingScreen(..self, clock: self.clock + dt, rings: rings.filter(|r| !r.done()))
132
- ruled := if over then moved else moved.rules()
134
+ ruled := if self.over then moved else moved.rules()
133
135
  if ruled.again then PlayingScreen(..ruled, again: false).dispatch(StartOver) else ruled
134
136
 
135
137
  fun rules(self) -> PlayingScreen =
@@ -167,9 +169,9 @@ struct PlayingScreen[ScreenSlice<PlayAction>](
167
169
 
168
170
  struct Caught(orbs: List<Orb>, rng: Random, points: Int)
169
171
 
170
- fun starsFrom(i: Int, clock: Float) -> List<Actor> = if i >= 40 then Nil else Cons(Star(index: i, clock: clock), starsFrom(i + 1, clock))
172
+ fun starsFrom(i: Int, clock: Float) -> List<View> = if i >= 40 then Nil else Cons(Star(index: i, clock: clock), starsFrom(i + 1, clock))
171
173
 
172
- fun lifeIcons(i: Int, lives: Int, sheet: Texture) -> List<Actor> =
174
+ fun lifeIcons(i: Int, lives: Int, sheet: Texture) -> List<View> =
173
175
  if i >= lives
174
176
  Nil
175
177
  else
@@ -177,20 +179,10 @@ fun lifeIcons(i: Int, lives: Int, sheet: Texture) -> List<Actor> =
177
179
 
178
180
  fun overlaps(ax: Float, ay: Float, ra: Float, bx: Float, by: Float, rb: Float) -> Bool = math.hypot(ax - bx, ay - by) < ra + rb
179
181
 
180
- fun axis(negative: Bool, positive: Bool) -> Float =
181
- if negative && !positive
182
- -1.0
183
- else if positive && !negative
184
- 1.0
185
- else
186
- 0.0
187
-
188
182
  fun rest<T>(xs: List<T>) -> List<T> = match xs
189
183
  Nil => Nil
190
184
  Cons(_, t) => t
191
185
 
192
- fun near(a: Float, b: Float) -> Bool = {a - b}.abs() < 0.01
193
-
194
186
  fun away() -> Motion = Motion(x: 5000.0, y: 0.0, vx: 0.0, vy: 0.0)
195
187
 
196
188
  fun onShip(ship: Ship) -> Motion = Motion(x: ship.at.x, y: ship.at.y, vx: 0.0, vy: 0.0)
@@ -230,7 +222,7 @@ fun lastLife(io: Io) -> TestRig<PlayingScreen> = mineOnShip(emptied(io, 30, 1))
230
222
 
231
223
  fun ruledLast(t: TestRig<PlayingScreen>) -> List<PlayAction> = ruled(t.effects<PlayAction>())
232
224
 
233
- fun isOverlay(hit: Option<Actor>) -> Bool = match hit
225
+ fun isOverlay(hit: Option<View>) -> Bool = match hit
234
226
  Some(a) => match a
235
227
  Overlay as o => true
236
228
  _ => false
@@ -266,15 +258,13 @@ fun runInput(i: Int, p: PlayingScreen) -> Input =
266
258
  events.push(KeyDown(key: Key.Enter))
267
259
  pos := Vec2(x: Float(i) * 0.37, y: 300.0 - Float(i) * 0.11)
268
260
  events.push(PointerMove(x: pos.x, y: pos.y))
269
- Input(held: Held(mouse: false, keys: keys), events: events, pos: pos, wheel: 0.0)
261
+ Input(held: Held.keysOnly(keys), events: events, pos: pos, wheel: 0.0)
270
262
 
271
263
  fun frameDt(f: Int) -> Float = 0.0166 + Float(f % 3) * 0.004 - 0.004
272
264
 
273
- # Frames of the scripted run from frame `f` until the game has run `until` ticks.
274
265
  fun framesUntil(t: TestRig<PlayingScreen>, f: Int, until: Int) -> TestRig<PlayingScreen> =
275
266
  if t.game.ticks >= until then t else framesUntil(t.frame(runInput(f, t.screen), frameDt(f)), f + 1, until)
276
267
 
277
- # A run of `n` frames of one tick each from frame `f`, counting the game overs and restarts.
278
268
  struct Run(rig: TestRig<PlayingScreen>, overs: Int, restarts: Int)
279
269
 
280
270
  fun counted(r: Run, f: Int, n: Int, dt: Float) -> Run =
@@ -340,7 +330,9 @@ test "a mine the rules push is in the view at once, and moves from the next tick
340
330
  u := poked(t, p)
341
331
  assert @sameRef(u.find<Mine>().at(3), late)
342
332
  assert late.clock == 0.0
343
- assert u.tick(0.1).screen.mines.at(3).at.x != late.at.x
333
+ v := u.tick(0.1).screen.mines.at(3)
334
+ assert v.at.x != late.at.x
335
+ assert v.clock == 0.1
344
336
 
345
337
  test "a hit adds a ring where the ship is, which the view draws until it has faded"
346
338
  t := mineOnShip(emptied(io, 0, PlayingScreen.StartLives))
@@ -348,6 +340,7 @@ test "a hit adds a ring where the ship is, which the view draws until it has fad
348
340
  u := t.tick(0.016)
349
341
  assert u.count<Ring>() == 1
350
342
  assert u.first<Ring>().x == u.screen.ship.at.x + Sheet.Size / 2.0
343
+ assert u.first<Ring>().age == 0.0
351
344
  v := u.ticks(30)
352
345
  assert v.count<Ring>() == 0
353
346
  assert v.screen.rings.isEmpty()
@@ -364,11 +357,12 @@ test "the keys held steer the ship"
364
357
  u := t.release(Key.KeyW).hold(Key.Left).tick(0.1)
365
358
  assert u.screen.ship.ax == 0.0
366
359
 
367
- test "the reducer alone plays the slice: Steer, then Tick; the view draws what it left"
360
+ test "the reducer alone plays the slice: Steer sets the thrust, the game steps the ship, not the Tick; the view draws what it left"
368
361
  t := emptied(io, 0, PlayingScreen.StartLives)
369
362
  p := t.screen.reduce(Steer(ax: 1.0, ay: 0.0)).reduce(Tick(dt: 0.1))
370
- assert p.ship.vx > 0.0
363
+ assert p.ship.ax == 1.0
371
- assert p.ship.at.x > Arena.W / 2.0
364
+ assert p.ship.at.x == Arena.W / 2.0
365
+ assert t.hold(Key.Right).tick(0.1).screen.ship.at.x > Arena.W / 2.0
372
366
  q := p.reduce(Scored(points: 20))
373
367
  assert q.score == 20
374
368
  assert hud(poked(t, q)) == "Score 20, Best 20"
@@ -385,22 +379,25 @@ test "the game ends at zero lives, the ship leaves the view, and the keys do not
385
379
  assert ruledLast(u).isEmpty()
386
380
  assert u.screen.ship.at.x == x
387
381
 
388
- test "after game over nothing moves but the animations keep running"
382
+ test "after game over the field stands still, the stars keep twinkling and the ring of the last hit grows on"
389
383
  t := emptied(io, 0, 1)
390
384
  s := t.screen
391
385
  started := poked(t, PlayingScreen(..s, mines: Cons(s.mines.at(0).put(Motion(x: s.ship.at.x, y: s.ship.at.y, vx: 10.0, vy: 0.0)), rest(s.mines)))).tick(0.016)
392
386
  p := started.screen
393
387
  assert p.over
394
388
  mine := p.mines.at(0)
389
+ grown := started.tick(0.1)
390
+ assert grown.screen.rings.at(0).age > 0.09
395
- later := 0.until(10).fold(started.hold(Key.Right), |r, i| r.tick(0.1))
391
+ later := 0.until(10).fold(grown.hold(Key.Right), |r, i| r.tick(0.1))
396
392
  q := later.screen
397
393
  assert q.mines.at(0).at.x == mine.at.x
398
394
  assert q.mines.at(0).at.rotation == mine.at.rotation
399
395
  assert q.ship.at.x == Arena.W / 2.0
400
- assert q.mines.at(0).clock > mine.clock + 0.9
396
+ assert q.mines.at(0).clock == mine.clock
401
- assert q.orbs.at(0).clock > p.orbs.at(0).clock + 0.9
397
+ assert q.orbs.at(0).clock == p.orbs.at(0).clock
402
398
  assert q.clock > p.clock + 0.9
403
399
  assert later.first<Star>().clock == q.clock
400
+ assert q.rings.isEmpty()
404
401
  assert q.score == 0
405
402
 
406
403
  test "more mines appear as the score grows, counting the points of the same tick"
@@ -424,16 +421,19 @@ test "the same seed plays out the same way"
424
421
  test "the arena is fitted into the view, centred"
425
422
  t := mounted(io, 7, 0, 3).resize(1600.0, 600.0)
426
423
  c := t.toWorld(800.0, 300.0)
427
- assert near(c.x, 400.0) && near(c.y, 300.0)
424
+ assert math.near(c.x, 400.0, 0.01) && math.near(c.y, 300.0, 0.01)
428
- assert near(t.toWorld(0.0, 0.0).x, -400.0)
425
+ assert math.near(t.toWorld(0.0, 0.0).x, -400.0, 0.01)
429
426
  u := t.resize(400.0, 600.0).tick()
430
- assert near(u.toWorld(0.0, 0.0).y, -300.0)
427
+ assert math.near(u.toWorld(0.0, 0.0).y, -300.0, 0.01)
431
- assert near(u.toWorld(200.0, 300.0).y, 300.0)
428
+ assert math.near(u.toWorld(200.0, 300.0).y, 300.0, 0.01)
432
-
429
+
433
- test "the axes cancel when both keys are held"
430
+ test "the arrows and WASD steer alike, and the axes cancel when both ways are held"
434
- assert axis(true, false) == -1.0
435
- assert axis(false, true) == 1.0
431
+ p := mounted(io, 7, 0, 3).screen
432
+ steer := |keys: List<Int>| p.held(Input(held: Held.keysOnly(keys.toSlice()), events: Slice<InputEvent>(), pos: Vec2(x: 0.0, y: 0.0), wheel: 0.0)).unwrap().toStr()
433
+ assert steer([Key.Left, Key.KeyW]) == "Steer(-1.0, -1.0)"
436
- assert axis(true, true) == 0.0
434
+ assert steer([Key.KeyD, Key.Down]) == "Steer(1.0, 1.0)"
435
+ assert steer([Key.Right, Key.KeyD]) == "Steer(1.0, 0.0)"
436
+ assert steer([Key.Left, Key.KeyD, Key.Up, Key.KeyS]) == "Steer(0.0, 0.0)"
437
437
 
438
438
  test "the reducer scores, takes lives, ends the game and starts over, and the view follows"
439
439
  t := emptied(io, 0, PlayingScreen.StartLives).dispatch(Scored(points: 10)).dispatch(Scored(points: 20))
examples/games/two_screens.plum CHANGED
@@ -8,7 +8,7 @@ import std/Io
8
8
  import std/collections/List
9
9
  import std/game/Color
10
10
  import std/game/input
11
- import std/game/Actor
11
+ import std/game/View
12
12
  import std/game/Label
13
13
  import std/game/Control
14
14
  import std/game/Screen
@@ -23,7 +23,7 @@ enum PlayAction = Back
23
23
  struct TitleScreen[ScreenSlice<TitleAction>](starts: Int) =
24
24
  fun name(self) -> Str = "title"
25
25
 
26
- fun view(self) -> List<Actor> = [Label.of(20.0, 20.0, "Press Enter", 24.0, Color.White)]
26
+ fun view(self) -> List<View> = [Label.of(20.0, 20.0, "Press Enter ({self.starts} so far)", 24.0, Color.White)]
27
27
 
28
28
  fun frames(self) -> Frames = OnDemand
29
29
 
@@ -38,17 +38,15 @@ struct TitleScreen[ScreenSlice<TitleAction>](starts: Int) =
38
38
  struct PlayScreen[ScreenSlice<PlayAction>](runs: Int) =
39
39
  fun name(self) -> Str = "play"
40
40
 
41
- fun view(self) -> List<Actor> = [Label.of(20.0, 20.0, "run {self.runs}", 24.0, Color.Yellow)]
41
+ fun view(self) -> List<View> = [Label.of(20.0, 20.0, "run {self.runs}", 24.0, Color.Yellow)]
42
42
 
43
43
  fun transition(self, from: Str) -> Transition = Fade(secs: 0.5)
44
44
 
45
- fun enter(self, from: Str) -> PlayScreen = PlayScreen(runs: self.runs + 1)
46
-
47
45
  fun onKey(self, e: InputEvent) -> Option<PlayAction> = match e
48
46
  KeyDown(k) => if k == Key.Escape then Some(Back) else None
49
47
  _ => None
50
48
 
51
- fun reduce(self, a: PlayAction) -> PlayScreen = self
49
+ fun reduce(self, a: PlayAction) -> PlayScreen = PlayScreen(runs: self.runs + 1)
52
50
 
53
51
  fun effect(self, io: Io, a: PlayAction, game: Control) = game.goTo("title")
54
52
 
@@ -59,12 +57,19 @@ fun twoScreens() -> Game =
59
57
 
60
58
  fun main(io: Io) -> Game = twoScreens()
61
59
 
62
- test "Enter fades in the play, which counts its runs; Escape goes back to the title as it was left"
60
+ test "Enter fades in the play; Escape counts a run and goes back to the title as it was left"
63
61
  t := headless.play(io, twoScreens()).press(Key.Enter).tick()
64
62
  assert t.showing() == "play"
65
63
  assert t.game.shifting()
66
- assert t.text(t.first<Label>()) == "run 1"
64
+ assert t.text(t.first<Label>()) == "run 0"
67
65
  u := t.ticks(30).press(Key.Escape).tick()
68
66
  assert u.showing() == "title"
67
+ assert u.text(u.first<Label>()) == "Press Enter (1 so far)"
69
68
  v := u.press(Key.Enter).tick()
70
- assert v.text(v.first<Label>()) == "run 2"
69
+ assert v.text(v.first<Label>()) == "run 1"
70
+
71
+ test "a press while the play slides in is dropped; keys still come"
72
+ t := headless.play(io, twoScreens()).press(Key.Enter).tick()
73
+ assert t.game.shifting()
74
+ u := t.clickAt(20.0, 20.0).press(Key.Escape).tick()
75
+ assert u.showing() == "title"
std/game/Actor.plum DELETED
@@ -1,289 +0,0 @@
1
- module std
2
-
3
- import std/Int
4
- import std/Float
5
- import std/Bool
6
- import std/Str
7
- import std/Option
8
- import std/Slice
9
- import std/collections/List
10
- import std/math/math
11
- import std/Io
12
- import std/math/Vec2
13
- import std/math/Affine
14
- import std/math/Aabb
15
- import std/game/Color
16
- import std/game/gfx
17
- import std/game/Place
18
- import std/game/Sized
19
- import std/game/Touch
20
-
21
- # One thing a screen draws (std/game/Screen). Each kind of actor is its own struct, with
22
- # only its own fields, that implements `Actor`: where it is in its parent (`place`), and
23
- # what it looks like:
24
- #
25
- # place its `Place`: position, scale, rotation, the origin it turns about, and its
26
- # `alpha`, which multiplies down what is drawn under it
27
- # view what it looks like, made again each time it is drawn, from its fields: a
28
- # list of ready-made actors (`Sprite`, `Circle`, ..) placed in its own
29
- # coordinates; empty by default
30
- # paint draws it, seen through `m` (its own coordinates to the world's) at `alpha`
31
- # (the accumulated alpha of its places, its own included). By default it
32
- # draws its `view` (`paintView`); one that draws itself overrides it, and its
33
- # `view` is then never asked for
34
- # shown false: it and what is under it are not drawn or hit. True by default
35
- #
36
- # struct Walker[Actor](at: Place, speed: Float) =
37
- # fun place(self) -> Place = self.at
38
- # fun view(self) -> List<Actor> = [Box.of(0.0, 0.0, 10.0, 10.0, Color.Red)]
39
- # fun update(self, dt: Float) -> Walker = Walker(..self, at: self.at.moveBy(self.speed * dt, 0.0))
40
- #
41
- # An actor is a value. It has no `step` of its own: what moves, the screen's reducer moves,
42
- # by calling the actor's own methods (`update(dt)` in the example games), each returning
43
- # the actor's next version. Beside `Actor`, an actor may be:
44
- #
45
- # Sized it has bounds (std/game/Sized): culled, and hit by a press when it takes
46
- # presses
47
- # Touch it says whether it takes presses (std/game/Touch: `Enabled`, `Disabled`,
48
- # `ChildrenOnly`); one that doesn't say is `ChildrenOnly`
49
- #
50
- # and an actor that draws children it is made with (`Group`, `Overlay`) gives them from
51
- # `declared`, empty by default.
52
- #
53
- # A view is drawn, not live: its items keep nothing from one draw to the next, so each
54
- # takes plain values read from the actor's fields (`Sprite(.., frame: self.frame, ..)`),
55
- # and one that shows only sometimes is left out of the list.
56
- trait Actor =
57
- fun place(self) -> Place
58
-
59
- fun view(self) -> List<Actor> = Nil
60
-
61
- fun paint(self, io: Io, m: Affine, alpha: Float) = paintView(io, self.view(), m, alpha)
62
-
63
- fun shown(self) -> Bool = true
64
-
65
- # The children it is made with, drawn and hit under it (`Group`, `Overlay`); none by
66
- # default. (Master has a `Container` trait for this; here a method of `Actor` spares a
67
- # type test per item drawn.)
68
- fun declared(self) -> List<Actor> = Nil
69
-
70
- # Each of `xs` as an `Actor`: a screen's `List<Mine>` in its view.
71
- fun all<T: Actor>(xs: List<T>) -> List<Actor> = xs.map(|x| one(x))
72
-
73
- fun one<T: Actor>(x: T) -> Actor = x
74
-
75
- # Draws the actors of a view, `m` and `alpha` being those of what the view is drawn
76
- # under: each shown one through its own place under `m`, at `alpha` times its place's
77
- # alpha, with its own `paint` (so its own view, if it has one), and then the children it
78
- # is made with (`declared`).
79
- fun paintView(io: Io, items: List<Actor>, m: Affine, alpha: Float) = items.each(|k| paintItem(io, k, m, alpha))
80
-
81
- fun paintItem(io: Io, a: Actor, m: Affine, alpha: Float) =
82
- if a.shown()
83
- at := a.place()
84
- mk := at.under(m)
85
- ak := alpha * at.alpha
86
- a.paint(io, mk, ak)
87
- paintView(io, a.declared(), mk, ak)
88
-
89
- # `paintView` skipping each `Sized` item (with what is under it) whose bounds, seen
90
- # through its transform, miss `area`: a screen that `culls` (std/game/Screen).
91
- fun paintCulled(io: Io, items: List<Actor>, m: Affine, alpha: Float, area: Aabb) =
92
- items.each(|a|
93
- if a.shown()
94
- at := a.place()
95
- mk := at.under(m)
96
- if !missesArea(a, mk, area)
97
- ak := alpha * at.alpha
98
- a.paint(io, mk, ak)
99
- paintCulled(io, a.declared(), mk, ak, area)
100
- )
101
-
102
- # What a press at `p` (in the coordinates `items` are placed in) is on: the top-most
103
- # shown item that takes presses (`Sized`, and `Enabled`, std/game/Touch) and whose `hit`
104
- # says the point is on it, what is drawn later before what is drawn earlier, what is under
105
- # an item (its declared children, then its own view) before the item. A `Disabled`
106
- # item is passed over with what is under it. None for none.
107
- fun viewHit(items: List<Actor>, p: Vec2) -> Option<Actor> = hitAmong(items.reverse(), p)
108
-
109
- fun hitAmong(rev: List<Actor>, p: Vec2) -> Option<Actor> = match rev
110
- Nil => None
111
- Cons(k, rest) => match hitItem(k, p)
112
- Some(a) => Some(a)
113
- None => hitAmong(rest, p)
114
-
115
- fun hitItem(a: Actor, p: Vec2) -> Option<Actor> =
116
- t := touchOf(a)
117
- if t.disabled() || !a.shown()
118
- None
119
- else
120
- q := a.place().toLocal(p)
121
- kids := viewHit(a.declared(), q)
122
- under := if kids.isSome() then kids else viewHit(a.view(), q)
123
- if under.isSome()
124
- under
125
- else if t.enabled() && sizedHit(a, q)
126
- Some(a)
127
- else
128
- None
129
-
130
- # How `a` takes presses: its own `touch`, or `ChildrenOnly` if it doesn't say.
131
- fun touchOf(a: Actor) -> Touchable = match a
132
- Touch as t => t.touch()
133
- _ => ChildrenOnly
134
-
135
- # Whether `a` is `Sized` and says the point `q` (in its own coordinates) is on it.
136
- fun sizedHit(a: Actor, q: Vec2) -> Bool = match a
137
- Sized as s => s.hit(q)
138
- _ => false
139
-
140
- # One item a view draws: the actor, its transform (its own coordinates to the world's)
141
- # and its alpha.
142
- struct Drawn(actor: Actor, m: Affine, alpha: Float)
143
-
144
- # Pushes onto `out` what `items` draw, in the order drawn: each shown item with its
145
- # transform and alpha, then what its own view draws, then its declared children. With
146
- # `cull`, a `Sized` item whose bounds miss `area` is left out with what is under it.
147
- fun viewDrawn(items: List<Actor>, m: Affine, alpha: Float, out: Slice<Drawn>, area: Aabb, cull: Bool) =
148
- items.each(|a|
149
- if a.shown()
150
- at := a.place()
151
- mk := at.under(m)
152
- if !cull || !missesArea(a, mk, area)
153
- ak := alpha * at.alpha
154
- out.push(Drawn(actor: a, m: mk, alpha: ak))
155
- viewDrawn(a.view(), mk, ak, out, area, cull)
156
- viewDrawn(a.declared(), mk, ak, out, area, cull)
157
- )
158
-
159
- # The transform of the actor `a` (its own coordinates to those `m` maps to) where `items`
160
- # draw it, found by identity through each item's own view and its declared children,
161
- # shown or not; None if it is not there. A test finds an actor a screen holds this way
162
- # (std/game/headless's `worldOf`).
163
- fun worldIn(items: List<Actor>, a: Actor, m: Affine) -> Option<Affine> = match items
164
- Nil => None
165
- Cons(x, rest) =>
166
- mk := x.place().under(m)
167
- if @sameRef(x, a)
168
- Some(mk)
169
- else
170
- inView := worldIn(x.view(), a, mk)
171
- inKids := if inView.isSome() then inView else worldIn(x.declared(), a, mk)
172
- if inKids.isSome() then inKids else worldIn(rest, a, m)
173
-
174
- # Whether `a` is `Sized` and its bounds, seen through `m`, miss `area`.
175
- fun missesArea(a: Actor, m: Affine, area: Aabb) -> Bool = match a
176
- Sized as s => !through(s.bounds(), m).overlaps(area)
177
- _ => false
178
-
179
- # The box around `b` seen through `m`.
180
- fun through(b: Aabb, m: Affine) -> Aabb =
181
- p1 := m.apply(b.min)
182
- p2 := m.apply(Vec2(x: b.max.x, y: b.min.y))
183
- p3 := m.apply(b.max)
184
- p4 := m.apply(Vec2(x: b.min.x, y: b.max.y))
185
- Aabb(
186
- min: Vec2(x: p1.x.min(p2.x).min(p3.x).min(p4.x), y: p1.y.min(p2.y).min(p3.y).min(p4.y)),
187
- max: Vec2(x: p1.x.max(p2.x).max(p3.x).max(p4.x), y: p1.y.max(p2.y).max(p3.y).max(p4.y)))
188
-
189
- # A parent that paints nothing: a layer of the actors it is made with, at (x, y). It is
190
- # `ChildrenOnly` by default (`Group.of`): what is in it takes presses, it doesn't, and
191
- # `touch: Disabled` takes the whole layer out of hit testing.
192
- struct Group[Actor, Touch](x: Float, y: Float, touch: Touchable, children: List<Actor>) =
193
- # At (x, y), `ChildrenOnly`.
194
- fun of(x: Float, y: Float, children: List<Actor>) -> Group = Group(x: x, y: y, touch: ChildrenOnly, children: children)
195
-
196
- fun place(self) -> Place = place.at(self.x, self.y)
197
-
198
- fun declared(self) -> List<Actor> = self.children
199
-
200
- fun touch(self) -> Touchable = self.touch
201
-
202
- # A filled `w` by `h` box in `color` with its top-left at (x, y), at its colour's alpha.
203
- # Decoration by default (`Box.of`, `Disabled`); `touch: Enabled` makes it take presses.
204
- struct Box[Actor, Sized, Touch](x: Float, y: Float, w: Float, h: Float, color: Color, touch: Touchable) =
205
- fun of(x: Float, y: Float, w: Float, h: Float, color: Color) -> Box = Box(x: x, y: y, w: w, h: h, color: color, touch: Disabled)
206
-
207
- fun place(self) -> Place = place.at(self.x, self.y)
208
-
209
- fun bounds(self) -> Aabb = Aabb.of(0.0, 0.0, self.w, self.h)
210
-
211
- fun touch(self) -> Touchable = self.touch
212
-
213
- fun paint(self, io: Io, m: Affine, alpha: Float) = drawBox(io, m, alpha * self.color.a, self.w, self.h, self.color)
214
-
215
- fun hit(self, p: Vec2) -> Bool = boxHit(self.w, self.h, p)
216
-
217
- # A `w` by `h` box at (0, 0) seen through `m`, in `color` at `alpha`.
218
- fun drawBox(io: Io, m: Affine, alpha: Float, w: Float, h: Float, color: Color) =
219
- sx := w * m.scaleX()
220
- sy := h * m.scaleY()
221
- c := m.apply(Vec2(x: w / 2.0, y: h / 2.0))
222
- gfx.drawRect(io, c.x - sx / 2.0, c.y - sy / 2.0, sx, sy, color.withAlpha(alpha))
223
-
224
- # Painting and hit testing for kinds of your own: each draws in the actor's own
225
- # coordinates seen through `m`, in `c` at `c.a * alpha`.
226
-
227
- # Whether `p` is inside a `w` by `h` box at (0, 0); a box with no size is never hit.
228
- fun boxHit(w: Float, h: Float, p: Vec2) -> Bool =
229
- w > 0.0 && h > 0.0 && p.x >= 0.0 && p.x <= w && p.y >= 0.0 && p.y <= h
230
-
231
- # A `w` by `h` box at (0, 0).
232
- fun boxPaint(io: Io, m: Affine, alpha: Float, w: Float, h: Float, c: Color) =
233
- rectPaint(io, m, alpha, 0.0, 0.0, w, h, c)
234
-
235
- # A `w` by `h` box with its top-left at (x, y).
236
- fun rectPaint(io: Io, m: Affine, alpha: Float, x: Float, y: Float, w: Float, h: Float, c: Color) =
237
- sx := w * m.scaleX()
238
- sy := h * m.scaleY()
239
- p := m.apply(Vec2(x: x + w / 2.0, y: y + h / 2.0))
240
- gfx.drawRect(io, p.x - sx / 2.0, p.y - sy / 2.0, sx, sy, c.withAlpha(c.a * alpha))
241
-
242
- # Whether `p` is within `r` of (cx, cy).
243
- fun circleHit(cx: Float, cy: Float, r: Float, p: Vec2) -> Bool =
244
- math.hypot(p.x - cx, p.y - cy) <= r
245
-
246
- # A circle of radius `r` about (cx, cy).
247
- fun circlePaint(io: Io, m: Affine, alpha: Float, cx: Float, cy: Float, r: Float, c: Color) =
248
- p := m.apply(Vec2(x: cx, y: cy))
249
- gfx.drawCircle(io, p.x, p.y, r * m.scaleX(), c.withAlpha(c.a * alpha))
250
-
251
- # Whether `p` is on the line from (x1, y1) to (x2, y2), `thickness` wide (at least 1).
252
- fun lineHit(x1: Float, y1: Float, x2: Float, y2: Float, thickness: Float, p: Vec2) -> Bool =
253
- dx := x2 - x1
254
- dy := y2 - y1
255
- len2 := dx * dx + dy * dy
256
- t := if len2 == 0.0 then 0.0 else {{p.x - x1} * dx + {p.y - y1} * dy} / len2
257
- tc := t.max(0.0).min(1.0)
258
- math.hypot(p.x - {x1 + dx * tc}, p.y - {y1 + dy * tc}) <= thickness.max(1.0) / 2.0
259
-
260
- # A line from (x1, y1) to (x2, y2), `thickness` wide.
261
- fun linePaint(io: Io, m: Affine, alpha: Float, x1: Float, y1: Float, x2: Float, y2: Float, thickness: Float, c: Color) =
262
- p := m.apply(Vec2(x: x1, y: y1))
263
- q := m.apply(Vec2(x: x2, y: y2))
264
- gfx.drawLine(io, p.x, p.y, q.x, q.y, thickness * m.scaleX(), c.withAlpha(c.a * alpha))
265
-
266
- # The region (srcX, srcY, srcW, srcH) of `tex` as a `w` by `h` sprite with its top-left at
267
- # (x, y), tinted `tint`.
268
- 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) =
269
- sw := w * m.scaleX()
270
- sh := h * m.scaleY()
271
- c := m.apply(Vec2(x: x + w / 2.0, y: y + h / 2.0))
272
- 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))
273
-
274
- # `text` with its top-left at (x, y), `size` high.
275
- fun textPaint(io: Io, m: Affine, alpha: Float, text: Str, x: Float, y: Float, size: Float, c: Color) =
276
- p := m.apply(Vec2(x: x, y: y))
277
- gfx.drawText(io, text, p.x, p.y, size * m.scaleY(), c.withAlpha(c.a * alpha))
278
-
279
- test "circles and lines are hit within their size"
280
- assert circleHit(1.0, 1.0, 2.0, Vec2(x: 2.0, y: 2.0))
281
- assert !circleHit(1.0, 1.0, 1.0, Vec2(x: 2.0, y: 2.0))
282
- assert lineHit(0.0, 0.0, 10.0, 0.0, 2.0, Vec2(x: 5.0, y: 0.9))
283
- assert !lineHit(0.0, 0.0, 10.0, 0.0, 2.0, Vec2(x: 5.0, y: 1.1))
284
- assert !lineHit(0.0, 0.0, 10.0, 0.0, 2.0, Vec2(x: 11.5, y: 0.0))
285
- assert !boxHit(0.0, 3.0, Vec2(x: 0.0, y: 0.0))
286
-
287
- test "a box seen through a turn is bounded by its turned corners"
288
- b := through(Aabb.of(0.0, 0.0, 10.0, 20.0), Affine(a: 0.0, b: 1.0, c: -1.0, d: 0.0, e: 100.0, f: 0.0))
289
- assert b.min.x == 80.0 && b.max.x == 100.0 && b.min.y == 0.0 && b.max.y == 10.0
std/game/Box.plum ADDED
@@ -0,0 +1,58 @@
1
+ module std
2
+
3
+ import std/Int
4
+ import std/Float
5
+ import std/Bool
6
+ import std/Io
7
+ import std/math/Vec2
8
+ import std/math/Affine
9
+ import std/math/Aabb
10
+ import std/game/Color
11
+ import std/game/gfx
12
+ import std/game/Place
13
+ import std/game/View
14
+ import std/game/Sized
15
+ import std/game/Touch
16
+
17
+ # A filled `w` by `h` box in `color` (painted at its alpha), its top-left at (x, y), where
18
+ # its place starts. It is decoration unless `touch: Enabled` (std/game/Touch), and then
19
+ # hit inside it. `Box.of` fills in the usual: decoration (`Disabled`).
20
+ struct Box[View, Sized, Touch](x: Float, y: Float, w: Float, h: Float, color: Color, touch: Touchable) =
21
+ fun of(x: Float, y: Float, w: Float, h: Float, color: Color) -> Box = Box(x: x, y: y, w: w, h: h, color: color, touch: Disabled)
22
+
23
+ fun place(self) -> Place = place.at(self.x, self.y)
24
+
25
+ fun bounds(self) -> Aabb = Aabb.of(0.0, 0.0, self.w, self.h)
26
+
27
+ fun touch(self) -> Touchable = self.touch
28
+
29
+ fun paintSelf(self, io: Io, m: Affine, alpha: Float) = drawBox(io, m, alpha * self.color.a, self.w, self.h, self.color)
30
+
31
+ fun hit(self, p: Vec2) -> Bool = boxHit(self.w, self.h, p)
32
+
33
+ # Whether `p` is inside a `w` by `h` box at (0, 0); a box with no size is never hit.
34
+ fun boxHit(w: Float, h: Float, p: Vec2) -> Bool =
35
+ w > 0.0 && h > 0.0 && p.x >= 0.0 && p.x <= w && p.y >= 0.0 && p.y <= h
36
+
37
+ # Draws a `w` by `h` box at the transform `m`, turned as `m` turns it, for your own kinds.
38
+ # Paints with `alpha`, the alpha `paintSelf` receives (what it is drawn under, its own
39
+ # place's included), in place of the colour's alpha: to paint at the colour's too, pass
40
+ # `alpha * color.a`, and to fade one shape of a view, `alpha * fade`. An unturned box is a
41
+ # `drawRect`, a turned one a `drawRectEx`.
42
+ fun drawBox(io: Io, m: Affine, alpha: Float, w: Float, h: Float, color: Color) =
43
+ sx := w * m.scaleX()
44
+ sy := h * m.scaleY()
45
+ c := m.apply(Vec2(x: w / 2.0, y: h / 2.0))
46
+ if m.b == 0.0 && m.a > 0.0
47
+ gfx.drawRect(io, c.x - sx / 2.0, c.y - sy / 2.0, sx, sy, color.withAlpha(alpha))
48
+ else
49
+ gfx.drawRectEx(io, c.x - sx / 2.0, c.y - sy / 2.0, sx, sy, m.rotation(), color.withAlpha(alpha))
50
+
51
+ test "a box is hit inside its size, and is decoration unless it says otherwise"
52
+ b := Box.of(1.0, 2.0, 4.0, 3.0, Color.Red.withAlpha(0.25))
53
+ assert b.hit(Vec2(x: 2.0, y: 1.0))
54
+ assert !b.hit(Vec2(x: 5.0, y: 1.0))
55
+ assert b.touch().disabled()
56
+ assert Box(x: 0.0, y: 0.0, w: 1.0, h: 1.0, color: Color.White, touch: Enabled).touch().enabled()
57
+ assert b.place().x == 1.0
58
+ assert !boxHit(0.0, 3.0, Vec2(x: 0.0, y: 0.0))
std/game/Circle.plum CHANGED
@@ -13,26 +13,36 @@ import std/math/Aabb
13
13
  import std/game/Color
14
14
  import std/game/gfx
15
15
  import std/game/Place
16
- import std/game/Actor
16
+ import std/game/View
17
17
  import std/game/Sized
18
18
  import std/game/Touch
19
19
 
20
- # A disc of radius `r` in `color`, the top-left of its bounding box at (x, y). Decoration
20
+ # A filled circle of radius `r` in `color` centred on its place, which starts at (x, y)
21
+ # (its bounds are -r to r in its own coordinates), painted at its colour's alpha. It is
22
+ # decoration unless `touch: Enabled` (std/game/Touch), and then hit inside the circle, not
21
- # by default (`Circle.of`); hit inside its circle.
23
+ # its whole box. `Circle.of` fills in the usual: decoration (`Disabled`).
22
- struct Circle[Actor, Sized, Touch](x: Float, y: Float, r: Float, color: Color, touch: Touchable) =
24
+ struct Circle[View, Sized, Touch](x: Float, y: Float, r: Float, color: Color, touch: Touchable) =
23
25
  fun of(x: Float, y: Float, r: Float, color: Color) -> Circle = Circle(x: x, y: y, r: r, color: color, touch: Disabled)
24
26
 
25
27
  fun place(self) -> Place = place.at(self.x, self.y)
26
28
 
27
- fun bounds(self) -> Aabb = Aabb.of(0.0, 0.0, 2.0 * self.r, 2.0 * self.r)
29
+ fun bounds(self) -> Aabb = Aabb.of(0.0 - self.r, 0.0 - self.r, 2.0 * self.r, 2.0 * self.r)
28
30
 
29
31
  fun touch(self) -> Touchable = self.touch
30
32
 
31
- fun paint(self, io: Io, m: Affine, alpha: Float) = drawDisc(io, m, alpha * self.color.a, self.r, self.color)
33
+ fun paintSelf(self, io: Io, m: Affine, alpha: Float) = drawDisc(io, m, alpha * self.color.a, self.r, self.color)
32
34
 
33
- fun hit(self, p: Vec2) -> Bool = math.hypot(p.x - self.r, p.y - self.r) <= self.r
35
+ fun hit(self, p: Vec2) -> Bool = math.hypot(p.x, p.y) <= self.r
34
36
 
35
- # A disc of radius `r` whose bounding box has its top-left at (0, 0), seen through `m`.
37
+ # Draws a circle of radius `r` centred on the origin of the transform `m`. Paints with
38
+ # `alpha` in place of the colour's alpha, as `box.drawBox` does.
36
39
  fun drawDisc(io: Io, m: Affine, alpha: Float, r: Float, color: Color) =
37
- c := m.apply(Vec2(x: r, y: r))
40
+ c := m.apply(Vec2(x: 0.0, y: 0.0))
38
41
  gfx.drawCircle(io, c.x, c.y, r * m.scaleX(), color.withAlpha(alpha))
42
+
43
+ test "a circle is hit inside its radius, about its centre"
44
+ c := Circle.of(0.0, 0.0, 5.0, Color.Red)
45
+ assert c.hit(Vec2(x: 0.0, y: 0.0))
46
+ assert c.hit(Vec2(x: 4.0, y: 0.0))
47
+ assert !c.hit(Vec2(x: -4.5, y: -4.5))
48
+ assert c.bounds() == Aabb.of(-5.0, -5.0, 10.0, 10.0)
std/game/Control.plum CHANGED
@@ -6,7 +6,8 @@ import std/Bool
6
6
  import std/Slice
7
7
  import std/collections/List
8
8
 
9
- # What an effect may ask of the game: show another screen, start over, or stop. A slice's
9
+ # What an effect may ask of the game: show another screen, or stop, or move through its
10
+ # history. A slice's
10
11
  # `effect(io, a, game)` is handed one; the game does what it asks once that effect has
11
12
  # run, before the next action's effect, in the order asked:
12
13
  #
@@ -15,12 +16,9 @@ import std/collections/List
15
16
  # Quit => game.exit()
16
17
  # _ => Unit
17
18
  #
18
- # goTo shows the screen of that name from the next tick on: the screen shown
19
+ # goTo shows the screen of that name from the next tick on, as it was left, coming
19
- # `leave`s, the other (back as the game was made with it, if it is `fresh`)
20
- # `enter`s and comes in by its `transition(from)`. A name no screen has stops
20
+ # in by its `transition(from)`. A name no screen has stops the program and
21
- # the program and lists the screens.
21
+ # lists the screens.
22
- # restart every screen back as the game was made with it, and the first one shown, at
23
- # once.
24
22
  # exit no tick runs after this one.
25
23
  # undo after the tick, goes back to just before the last user action
26
24
  # (docs/game.md, "Undo and time travel"); nothing if there is none, or the
@@ -36,8 +34,6 @@ struct Control(asked: Slice<Ask>) =
36
34
 
37
35
  fun goTo(self, name: Str) = self.asked.push(AskGoTo(name: name))
38
36
 
39
- fun restart(self) = self.asked.push(AskRestart)
40
-
41
37
  fun exit(self) = self.asked.push(AskExit)
42
38
 
43
39
  fun undo(self) = self.asked.push(AskUndo)
@@ -52,7 +48,6 @@ struct Control(asked: Slice<Ask>) =
52
48
  # One thing an effect asked of the game.
53
49
  enum Ask =
54
50
  | AskGoTo(name: Str)
55
- | AskRestart
56
51
  | AskExit
57
52
  | AskUndo
58
53
  | AskRedo
@@ -60,7 +55,6 @@ enum Ask =
60
55
 
61
56
  fun toStr(self) -> Str = match self
62
57
  AskGoTo(name) => "goTo({name})"
63
- AskRestart => "restart"
64
58
  AskExit => "exit"
65
59
  AskUndo => "undo"
66
60
  AskRedo => "redo"
@@ -77,11 +71,10 @@ enum Ask =
77
71
  test "a control keeps what was asked, in order"
78
72
  c := Control.create()
79
73
  c.goTo("play")
80
- c.restart()
81
74
  c.exit()
82
75
  c.undo()
83
76
  c.redo()
84
77
  c.rewindTo(12)
85
78
  asked := c.take()
86
- assert asked.map(|a| a.toStr()).fold("", |s, x| if s == "" then x else "{s} {x}") == "goTo(play) restart exit undo redo rewindTo(12)"
79
+ assert asked.map(|a| a.toStr()).fold("", |s, x| if s == "" then x else "{s} {x}") == "goTo(play) exit undo redo rewindTo(12)"
87
80
  assert asked.map(|a| if a.travels() then 1 else 0).fold(0, |n, x| n + x) == 3
std/game/Effects.plum ADDED
@@ -0,0 +1,65 @@
1
+ module std
2
+
3
+ import std/Int
4
+ import std/Io
5
+ import std/Slice
6
+ import std/collections/List
7
+ import std/game/Control
8
+ import std/game/ScreenSlice
9
+
10
+ # The actions dispatched in a tick, waiting for their effects. A delivery
11
+ # (std/game/ScreenSlice's `deliverTo`) queues each action of its slice as it is
12
+ # dispatched, on a queue of the slice's action type (`ActionSink<A>`); after the tick each
13
+ # is held with the slice as the tick left it (`Queued<A>`), so one list holds the actions
14
+ # of every screen whatever their types, and the game runs each one's effect (the slice's
15
+ # `effect(io, a, game)`), in the order dispatched. A test reads the ones that ran with
16
+ # `sent<A>(game.ran)` (std/game/headless's `effects<A>()`).
17
+ #
18
+ # The queue of the dispatch running sits in one slot (`Running`): the game sets it around
19
+ # a screen's `deliver`, std/game/headless around its own `dispatch`, and a slice's own
20
+ # `dispatch` (a reducer dispatching what happened) queues there. Outside them it is empty
21
+ # and `dispatch` only reduces.
22
+
23
+ # One waiting action and the slice whose effect runs it.
24
+ trait Effect =
25
+ fun apply(self, io: Io, game: Control)
26
+
27
+ struct Queued<A>[Effect](slice: ScreenSlice<A>, action: A) =
28
+ fun apply(self, io: Io, game: Control) = self.slice.effect(io, self.action, game)
29
+
30
+ # `a`, to run with the effect of the slice `s`.
31
+ fun queued<A>(s: ScreenSlice<A>, a: A) -> Effect = Queued(slice: s, action: a)
32
+
33
+ # The actions of type `A` among `fx`, in order: `sent<PlayAction>(game.ran)`.
34
+ fun sent<A>(fx: List<Effect>) -> List<A> =
35
+ none: List<A> := Nil
36
+ fx.fold(none, |acc, e| match e
37
+ Queued<A> as q => Cons(q.action, acc)
38
+ _ => acc).reverse()
39
+
40
+ # A delivery's queue, of the slice's action type.
41
+ trait Sink =
42
+ fun size(self) -> Int
43
+
44
+ struct ActionSink<A>[Sink](queue: Slice<A>) =
45
+ fun size(self) -> Int = self.queue.length()
46
+
47
+ # The queue of the dispatch running: empty outside any, one queue inside one.
48
+ Running = Slice<Sink>()
49
+
50
+ # From here to `endDispatch()`, what a slice dispatches is queued on `s`.
51
+ fun startDispatch(s: Sink) =
52
+ Running.clear()
53
+ Running.push(s)
54
+
55
+ fun endDispatch() = Running.clear()
56
+
57
+ # Whether a dispatch is running.
58
+ fun dispatching() -> Bool = !Running.isEmpty()
59
+
60
+ # Queues `a` on the dispatch running, if it queues actions of `a`'s type.
61
+ fun queueAction<A>(a: A) =
62
+ if !Running.isEmpty()
63
+ match Running.at(0)
64
+ ActionSink<A> as k => k.queue.push(a)
65
+ _ => Unit
std/game/Game.plum CHANGED
@@ -11,10 +11,13 @@ import std/collections/List
11
11
  import std/Io
12
12
  import std/math/Vec2
13
13
  import std/math/Affine
14
+ import std/math/Aabb
14
15
  import std/game/Color
15
16
  import std/game/gfx
16
17
  import std/game/input
17
- import std/game/Actor
18
+ import std/game/View
19
+ import std/game/Effects
20
+ import std/game/ScreenSlice
18
21
  import std/game/Viewport
19
22
  import std/game/Control
20
23
  import std/game/Screen
@@ -34,32 +37,38 @@ import std/game/History
34
37
  # screens there are, as two screens of one name do when the game is made.
35
38
  #
36
39
  # A game is a value: each tick returns the next game, and the screens in it are the ones
37
- # the tick left. A screen left and shown again is as it was left, unless it is `fresh`,
40
+ # the tick left. A screen left and shown again is as it was left.
41
+ #
42
+ # The window's size in pixels (`pixels`) comes from the host each tick (`update`), or from
43
+ # the test (`step`). Each screen is seen through a camera worked out from its `size()`,
44
+ # its `viewport()`, the window's size and its `camera(base)` (`camera(i)`,
45
+ # std/game/Screen's `cameraOf`): the game maps a press through it to the world's
38
- # which comes back as the game was made with it. A restart puts every screen back as the
46
+ # coordinates, draws the screen's `view` through it and, for a screen that `culls()`,
39
- # game was made with it (`initial`) and shows the first.
47
+ # skips what it doesn't show.
40
48
  #
41
49
  # The compiler adds the frame entry points the host calls: they run `update` once per
42
50
  # fixed 1/60 s tick of the frame (std/game/input's `Clock`, which also records and replays
43
51
  # the ticks' input, std/game/Replay) and `draw` once a frame.
44
52
  #
45
- # One tick (`update`, or `step` with the screen's size given, as a test runs it): the
53
+ # One tick (`update`, or `step` with the window's size given, as a test runs it): the
46
- # screens are told the screen's size if it changed (`resize`); the current screen gets the
54
+ # current screen gets the tick (`deliver`, with a `Delivery`: the tick's input, its
47
- # tick (`deliver`, with its viewport and the tick's input, and no `Io`), as actions for a
55
+ # camera, what was held at its tick before, and no `Io`), as actions for a slice screen,
56
+ # with its `Actor`s stepped before its tick action (a plain screen's are stepped alone);
48
- # slice screen; then the transition in progress moves on; then, for each action
57
+ # then the transition in progress moves on; then, for each action dispatched in the tick,
49
- # dispatched in the tick, in order, its slice's `effect(io, a, game)` and right after it
58
+ # in order, its slice's `effect(io, a, game)` and right after it what that effect asked of
50
- # what that effect asked of `game` (`goTo`, `restart`, `exit`; an undo, a redo or a
51
- # rewind once the tick is over). Keep any randomness in a screen as a `Random` seeded once
59
+ # `game` (`goTo`, `exit`; an undo, a redo or a rewind once the tick is over). Keep any randomness in a screen as a `Random` seeded once
52
60
  # in `main` from `io.randomSeed()`: then the same seed and the same inputs give the same
53
61
  # game, which is what record and replay use.
54
62
  #
55
- # `draw` clears the screen with the shown screen's `background()` and draws its view
63
+ # `draw` clears with the shown screen's `background()` and draws its `view`, made again
56
- # through its viewport (std/game/Viewport: its `size()` fitted to the screen by its
64
+ # for the frame, through its camera, then its `hud` one unit a pixel; during a
57
- # `viewport()`); during a transition, the screen going out and then the one coming in,
65
+ # transition, the screen going out and then the one coming in, each on its own
66
+ # background, moved and faded by it. The pointer's events reach no screen during a
58
- # each moved and faded.
67
+ # transition.
59
68
  #
60
69
  # A screen whose `frames()` is `OnDemand` sleeps through the ticks in which nothing needs
61
70
  # doing (docs/game.md, "Frames on demand"): `update` delivers it nothing, and once the
62
- # last frame drawn shows the screen as it is (`drawn`), `idle()` is true. `delivered`,
71
+ # last frame drawn shows the screen as it is (`frameDrawn`), `idle()` is true. `delivered`,
63
72
  # `skipped` and `draws` count the ticks delivered, the ticks slept through and the frames
64
73
  # drawn, for tests; `ran` and `asked` are the effects that ran in the last tick and what
65
74
  # they asked of the game (std/game/headless reads them).
@@ -71,7 +80,7 @@ import std/game/History
71
80
  # `ticksRecorded()`; each move returns the game moved, `moved` saying whether it could.
72
81
  # Going back makes the game again from `initial` and plays the recorded ticks into it,
73
82
  # through the same tick as ever (`run`), with no effects run: what they asked of the game
74
- # (a `goTo`, a `restart`) is recorded and done again, an `exit` is not. `pause()` holds
83
+ # (a `goTo`) is recorded and done again, an `exit` is not. `pause()` holds
75
84
  # the game still until `resume()`, which drops what could be redone. `rewound` is how many
76
85
  # ticks the last move played.
77
86
  struct Game(screens: List<Screen>) =
@@ -79,13 +88,13 @@ struct Game(screens: List<Screen>) =
79
88
  self.initial: List<Screen> = self.screens
80
89
  self.current: Int = 0
81
90
  self.shift: Option<Shift> = None
82
- self.view: Vec2 = Vec2(x: 0.0, y: 0.0)
91
+ self.pixels: Vec2 = Vec2(x: 0.0, y: 0.0)
83
92
  self.exited: Bool = false
84
93
  self.ticks: Int = 0
85
94
  # Where the pointer was last, so that the host's pointer move to the same place, which
86
- # comes every frame, wakes no screen; and what was held at the tick before.
95
+ # comes every frame, wakes no screen; and what was held at each screen's tick before.
87
96
  self.pointer: Vec2 = Vec2(x: -1.0, y: -1.0)
88
- self.held: Held = Held.none()
97
+ self.helds: List<Held> = self.screens.map(|s| Held.none())
89
98
  # Whether the next tick of an `OnDemand` screen runs whatever its input, and whether a
90
99
  # tick ran since the last frame drawn.
91
100
  self.wake: Bool = true
@@ -121,26 +130,44 @@ struct Game(screens: List<Screen>) =
121
130
  # Whether a transition is drawing two screens.
122
131
  fun shifting(self) -> Bool = self.shift.isSome()
123
132
 
124
- # The viewport the screen `s` is drawn and hit through, on the game's screen.
133
+ # The camera the screen at index `i` is seen through now (std/game/Screen's
134
+ # `cameraOf`).
125
- fun camera(self, s: Screen) -> Viewport = cameraOf(s, self.view)
135
+ fun camera(self, i: Int) -> Viewport = screen.cameraOf(self.screens.at(i), self.pixels)
136
+
137
+ # A window pixel in the shown screen's world coordinates, through its camera.
138
+ fun toWorld(self, x: Float, y: Float) -> Vec2 = self.camera(self.current).toWorld(x, y)
139
+
140
+ # A point of the shown screen's world in window pixels.
141
+ fun toScreen(self, p: Vec2) -> Vec2 = self.camera(self.current).toScreen(p)
142
+
143
+ # The world rectangle the screen at index `i` shows (the camera's `visible()`), or
144
+ # everything while neither the screen nor the game knows a size.
145
+ fun visible(self, i: Int) -> Aabb =
146
+ c := self.camera(i)
147
+ if c.w > 0.0 && c.h > 0.0 then c.visible() else Aabb(min: Vec2(x: 0.0 - Float.Max, y: 0.0 - Float.Max), max: Vec2(x: Float.Max, y: Float.Max))
126
148
 
127
149
  # One tick of `dt` seconds with `input` on the host's screen: what the host runs.
128
150
  fun update(self, io: Io, input: Input, dt: Float) -> Game =
129
151
  self.step(io, input, dt, Vec2(x: gfx.screenWidth(io), y: gfx.screenHeight(io)))
130
152
 
131
- # One tick of `dt` seconds with `input` on a screen of `view` pixels (see the top of this
153
+ # One tick of `dt` seconds with `input` in a window of `pixels` (see the top of this
132
154
  # file); a test runs ticks with it. With a history, the tick is added to it, and then
133
155
  # what its effects asked of the history is done. An exited or paused game stays as it is.
134
- fun step(self, io: Io, input: Input, dt: Float, view: Vec2) -> Game =
156
+ fun step(self, io: Io, input: Input, dt: Float, pixels: Vec2) -> Game =
135
157
  if self.exited || self.paused
136
158
  self
137
159
  else
138
- ran := self.run(io, input, dt, view, None)
160
+ ran := self.run(io, input, dt, pixels, None)
139
161
  travel := ran.travel
140
162
  noted := match ran.history
141
- Some(h) => Game(..ran, history: Some(h.push(HistoryTick(input: input, view: view, dt: dt, user: ran.acted && travel.isEmpty(), asks: ran.asked))))
163
+ Some(h) => Game(..ran, history: Some(h.push(HistoryTick(input: input, pixels: pixels, dt: dt, user: ran.acted && travel.isEmpty(), asks: ran.asked))))
142
164
  None => ran
165
+ noted.travelAsked(io)
166
+
167
+ # The game after the undos, redos and rewinds the effects asked for, in order (`obey`
168
+ # keeps them for the end of the tick), which it then forgets: what ends a tick, and the
169
+ # kit's `dispatch` (std/game/headless).
143
- travel.fold(Game(..noted, travel: Nil), |g, a| g.travelled(io, a))
170
+ fun travelAsked(self, io: Io) -> Game = self.travel.fold(Game(..self, travel: Nil), |g, a| g.travelled(io, a))
144
171
 
145
172
  # The game after a move through its history that an effect asked for.
146
173
  fun travelled(self, io: Io, a: Ask) -> Game = match a
@@ -151,30 +178,30 @@ struct Game(screens: List<Screen>) =
151
178
 
152
179
  # The tick itself: what `step` does live, and what a rewind does for each tick it plays
153
180
  # again, with `replayed` the asks the tick's effects made when it was played: then no
154
- # effect runs, and only what they asked of the screens (`goTo`, `restart`) is done again.
181
+ # effect runs, and only what they asked of the screens (`goTo`) is done again.
155
182
  # `acted` says whether the tick was a user action (std/game/History).
156
- fun run(self, io: Io, input: Input, dt: Float, view: Vec2, replayed: Option<List<Ask>>) -> Game =
183
+ fun run(self, io: Io, input: Input, dt: Float, pixels: Vec2, replayed: Option<List<Ask>>) -> Game =
157
- sized := if view.x > 0.0 && view.y > 0.0 && {view.x != self.view.x || view.y != self.view.y} then self.resized(view) else self
184
+ sized := if pixels.x > 0.0 && pixels.y > 0.0 && {pixels.x != self.pixels.x || pixels.y != self.pixels.y} then self.resized(pixels) else self
158
185
  news := heardIn(input, sized.pointer)
159
186
  s := sized.screen()
160
187
  base := Game(..sized, pointer: lastPointer(input, sized.pointer), ticks: sized.ticks + 1, ran: Nil, asked: Nil, acted: false)
161
188
  if onDemand(s) && !sized.wake && sized.shift.isNone() && !news && !s.wants(input)
162
189
  Game(..base, skipped: base.skipped + 1)
163
190
  else
164
- d := s.deliver(base.camera(s), input, dt)
165
- acted := d.mapped || {d.held && !base.held.same(input.held)}
191
+ d := s.deliver(Delivery(input: input, dt: dt, before: base.helds.at(base.current), camera: base.camera(base.current), pixels: base.pixels, shifting: base.shift.isSome()))
166
192
  shift := match base.shift
167
193
  Some(sh) => sh.after(dt)
168
194
  None => None
195
+ ticked := Game(
169
- ticked := Game(..base, screens: setAt(base.screens, base.current, d.screen), shift: shift, held: input.held, delivered: base.delivered + 1, dirty: true, acted: acted)
196
+ ..base, screens: setAt(base.screens, base.current, d.screen), helds: setAt(base.helds, base.current, input.held), shift: shift,
197
+ delivered: base.delivered + 1, dirty: true, acted: d.acted)
170
198
  after := match replayed
171
199
  Some(asks) => ticked.redoAsks(asks)
172
200
  None => ticked.apply(io, d.effects)
173
201
  Game(..after, wake: !after.asked.isEmpty() || after.shift.isSome() || after.screen().busy())
174
202
 
175
- # The screen is `view` pixels from now on: every screen is told (`resize`).
203
+ # The window is `pixels` from now on.
176
- fun resized(self, view: Vec2) -> Game =
177
- Game(..self, view: view, screens: self.screens.map(|s| s.resize(view.x, view.y)), wake: true, dirty: true)
204
+ fun resized(self, pixels: Vec2) -> Game = Game(..self, pixels: pixels, wake: true, dirty: true)
178
205
 
179
206
  # Runs the effects `fx` of the tick, in order, each followed by what it asked of the
180
207
  # game.
@@ -191,7 +218,6 @@ struct Game(screens: List<Screen>) =
191
218
  g := Game(..self, asked: self.asked.append([a]))
192
219
  match a
193
220
  AskGoTo(name) => g.goTo(name)
194
- AskRestart => g.restart()
195
221
  AskExit => Game(..g, exited: true)
196
222
  _ => Game(..g, travel: g.travel.append([a]))
197
223
 
@@ -203,11 +229,9 @@ struct Game(screens: List<Screen>) =
203
229
  # What a tick played again asked of the screens, done again.
204
230
  fun redone(self, a: Ask) -> Game = match a
205
231
  AskGoTo(name) => self.goTo(name)
206
- AskRestart => self.restart()
207
232
  _ => self
208
233
 
209
- # Shows the screen named `name` from the next tick on: the screen shown `leave`s, the
234
+ # Shows the screen named `name` from the next tick on, as it was left, coming in by its
210
- # other (as the game was made with it, if it is `fresh`) `enter`s and comes in by its
211
235
  # `transition`. The screen shown already stays as it is.
212
236
  fun goTo(self, name: Str) -> Game =
213
237
  i := self.indexOf(name)
@@ -216,39 +240,58 @@ struct Game(screens: List<Screen>) =
216
240
  if i == self.current
217
241
  self
218
242
  else
219
- from := self.showing()
220
- left := setAt(self.screens, self.current, self.screen().leave(name))
221
- next := if left.at(i).fresh() then sizedTo(self.initial.at(i), self.view) else left.at(i)
222
- entered := next.enter(from)
223
- how := entered.transition(from)
243
+ how := self.screens.at(i).transition(self.showing())
224
244
  shift := if how.secs() > 0.0 then Some(Shift(from: self.current, how: how, t: 0.0)) else None
225
- Game(..self, screens: setAt(left, i, entered), current: i, shift: shift, wake: true)
245
+ Game(..self, current: i, shift: shift, wake: true)
226
-
227
- # Every screen as the game was made with it, and the first one shown, at once.
228
- fun restart(self) -> Game =
229
- Game(..self, screens: self.initial.map(|s| sizedTo(s, self.view)), current: 0, shift: None, wake: true)
230
246
 
231
- # Draws a frame: clears with the shown screen's `background`, then its `draw`. During a
247
+ # Draws a frame: clears with the shown screen's `background`, then draws its view.
232
- # transition, the screen going out and then the one coming in, each moved and faded.
248
+ # During a transition, the screen going out and then the one coming in, each moved and
249
+ # faded by the transition.
233
250
  fun draw(self, io: Io) =
234
- s := self.screen()
235
- gfx.clear(io, s.background())
251
+ gfx.clear(io, self.screen().background())
236
252
  match self.shift
237
253
  Some(sh) =>
238
- self.drawScreen(io, self.screens.at(sh.from), sh.frame(false, self.view))
239
- self.drawScreen(io, s, sh.frame(true, self.view))
254
+ self.drawScreen(io, sh.from, sh.frame(false, self.pixels))
255
+ self.drawScreen(io, self.current, sh.frame(true, self.pixels))
240
- None => self.drawScreen(io, s, ShiftFrame(x: 0.0, y: 0.0, alpha: 1.0))
256
+ None => self.drawScreen(io, self.current, ShiftFrame(x: 0.0, y: 0.0, alpha: 1.0))
241
-
257
+
242
- # Draws `s` through its viewport, moved `f.x`, `f.y` pixels and at `f.alpha`.
258
+ # Draws the view of the screen at index `i` through its camera, moved `f.x`, `f.y` pixels
259
+ # and at `f.alpha`, then its `hud` one unit a pixel, moved and faded alike. During a
260
+ # transition the screen's `background()` is drawn under it first, over the window. The
261
+ # view is drawn through the camera's transform (the world to the window's pixels, both
262
+ # axes, so a `Stretch` camera too); what it culls is what the camera shows, moved back by
263
+ # the transition's offset, seen through that transform.
243
- fun drawScreen(self, io: Io, s: Screen, f: ShiftFrame) =
264
+ fun drawScreen(self, io: Io, i: Int, f: ShiftFrame) =
265
+ s := self.screens.at(i)
266
+ if self.shift.isSome()
267
+ bg := s.background()
268
+ gfx.drawRect(io, f.x, f.y, self.pixels.x, self.pixels.y, bg.withAlpha(bg.a * f.alpha))
244
- cam := self.camera(s)
269
+ c := self.camera(i)
270
+ v := self.visible(i)
271
+ area := Aabb(min: Vec2(x: v.min.x - f.x / c.sx, y: v.min.y - f.y / c.sy), max: Vec2(x: v.max.x - f.x / c.sx, y: v.max.y - f.y / c.sy))
245
- m := Affine(a: 1.0, b: 0.0, c: 0.0, d: 1.0, e: f.x, f: f.y).mul(cam.transform())
272
+ m := Affine(a: 1.0, b: 0.0, c: 0.0, d: 1.0, e: f.x, f: f.y).mul(c.transform())
273
+ if s.culls()
246
- s.draw(io, m, f.alpha, cam.screen())
274
+ view.paintCulled(io, s.view(), m, f.alpha, view.through(area, m))
275
+ else
276
+ view.paintView(io, s.view(), m, f.alpha)
277
+ hud := s.hud(self.pixels)
278
+ if !hud.isEmpty()
279
+ view.paintView(io, hud, Affine(a: 1.0, b: 0.0, c: 0.0, d: 1.0, e: f.x, f: f.y), f.alpha)
280
+
281
+ # What the frame would draw of the shown screen now: each item of its view, and what is
282
+ # under it, with its transform (to the world) and alpha, culled if the screen `culls()`;
283
+ # then its `hud`'s, whose transforms are to the window's pixels.
284
+ fun drawList(self) -> List<Drawn> =
285
+ s := self.screen()
286
+ out := Slice<Drawn>()
287
+ view.drawnIn(s.view(), Affine.Identity, 1.0, out, self.visible(self.current), s.culls())
288
+ view.drawnIn(s.hud(self.pixels), Affine.Identity, 1.0, out, Aabb.of(0.0, 0.0, 0.0, 0.0), false)
289
+ List.fromSlice(out)
247
290
 
248
291
  # The game after a frame was drawn: until the next tick runs, `idle` holds for an
249
292
  # `OnDemand` screen. The host draws with `draw`, which returns nothing; a test calls
250
293
  # this in its place.
251
- fun drawn(self) -> Game = Game(..self, dirty: false, draws: self.draws + 1)
294
+ fun frameDrawn(self) -> Game = Game(..self, dirty: false, draws: self.draws + 1)
252
295
 
253
296
  # Whether the last frame drawn shows what the shown screen is now: only for an
254
297
  # `OnDemand` screen, and never during a transition (or, paused, until a move).
@@ -262,7 +305,7 @@ struct Game(screens: List<Screen>) =
262
305
  fun timeTravel(self, cap: Int) -> Game =
263
306
  if self.delivered + self.skipped > 0
264
307
  crash "game: time travel is switched on before the first tick"
265
- Game(..self, history: Some(History.start(cap, self.view)))
308
+ Game(..self, history: Some(History.start(cap, self.pixels)))
266
309
 
267
310
  # Whether the game keeps a history it can move through (on, and not full).
268
311
  fun travels(self) -> Bool = match self.history
@@ -338,37 +381,20 @@ struct Game(screens: List<Screen>) =
338
381
  # The game made again from its start, with the history `h`, and its ticks played into it.
339
382
  fun remake(self, io: Io, h: History) -> Game =
340
383
  fresh := Game(screens: self.initial)
341
- sized := if h.view.x > 0.0 && h.view.y > 0.0 then fresh.resized(h.view) else fresh
384
+ sized := if h.pixels.x > 0.0 && h.pixels.y > 0.0 then fresh.resized(h.pixels) else fresh
342
385
  Game(..sized, history: Some(h), paused: self.paused).playOn(io, h.played())
343
386
 
344
387
  # `recs` played again from the state the game is in, with no effects run.
345
388
  fun playOn(self, io: Io, recs: List<HistoryTick>) -> Game =
346
- played := recs.fold(self, |g, r| g.run(io, r.input, r.dt, r.view, Some(r.asks)))
389
+ played := recs.fold(self, |g, r| g.run(io, r.input, r.dt, r.pixels, Some(r.asks)))
347
390
  Game(..played, rewound: recs.length(), ran: Nil, asked: Nil, dirty: true, moved: true)
348
391
 
349
- # The viewport of the screen `s` on a screen `view` pixels: its `size()` world by its
350
- # `viewport()`, or the screen's own pixels for a screen with no size. Until the size is
351
- # known (0 by 0), the world unscaled at (0, 0).
352
- fun cameraOf(s: Screen, view: Vec2) -> Viewport =
353
- size := s.size()
354
- known := view.x > 0.0 && view.y > 0.0
355
- if size.x > 0.0 && size.y > 0.0
356
- v := Viewport.of(s.viewport(), size.x, size.y)
357
- if known then v.update(view.x, view.y) else v
358
- else if known
359
- Viewport.of(Pixels, view.x, view.y)
360
- else
361
- Viewport.of(Pixels, 1.0, 1.0)
362
-
363
392
  # Whether `s` sleeps through ticks with nothing to do (`frames()` is `OnDemand`).
364
393
  fun onDemand(s: Screen) -> Bool = match s.frames()
365
394
  OnDemand => true
366
395
  Always => false
367
396
 
368
- # `s` told the screen's size, if it is known.
369
- fun sizedTo(s: Screen, view: Vec2) -> Screen = if view.x > 0.0 && view.y > 0.0 then s.resize(view.x, view.y) else s
370
-
371
- fun setAt(xs: List<Screen>, i: Int, s: Screen) -> List<Screen> = match xs
397
+ fun setAt<T>(xs: List<T>, i: Int, s: T) -> List<T> = match xs
372
398
  Nil => Nil
373
399
  Cons(x, rest) => if i == 0 then Cons(s, rest) else Cons(x, setAt(rest, i - 1, s))
374
400
 
std/game/Group.plum ADDED
@@ -0,0 +1,26 @@
1
+ module std
2
+
3
+ import std/Float
4
+ import std/collections/List
5
+ import std/game/Place
6
+ import std/game/View
7
+ import std/game/Touch
8
+
9
+ # A view that paints nothing and is never hit: a parent for others (a layer, a HUD, the
10
+ # arm of an orbit), at (x, y), with the children it is made with, its `view`, which are
11
+ # placed in its coordinates:
12
+ #
13
+ # Group.of(16.0, 16.0, [Label.of(0.0, 0.0, "Score", 24.0, Color.White), ..])
14
+ #
15
+ # Its `touch` (std/game/Touch) is `ChildrenOnly` with `Group.of`: its children may be hit,
16
+ # it is not; `touch: Disabled` takes everything under it out of hit testing (a layer of
17
+ # decoration the pointer should pass through).
18
+ struct Group[View, Touch](x: Float, y: Float, touch: Touchable, children: List<View>) =
19
+ # At (x, y), `ChildrenOnly`.
20
+ fun of(x: Float, y: Float, children: List<View>) -> Group = Group(x: x, y: y, touch: ChildrenOnly, children: children)
21
+
22
+ fun place(self) -> Place = place.at(self.x, self.y)
23
+
24
+ fun view(self) -> List<View> = self.children
25
+
26
+ fun touch(self) -> Touchable = self.touch
std/game/History.plum CHANGED
@@ -15,7 +15,7 @@ import std/game/Control
15
15
  # game goes back by being made again from the screens it was made with (`Game.initial`)
16
16
  # and having the recorded ticks played into it, with no effects run. So a history is one
17
17
  # `HistoryTick` per tick: its `Input`, the screen's size, its length, whether it was a
18
- # user action, and what its effects asked of the game (a `goTo` or a `restart` changes
18
+ # user action, and what its effects asked of the game (a `goTo` changes
19
19
  # which screen gets the next ticks, so a rewind does it again without running the
20
20
  # effect). It records input, not actions: an action may hold an actor of the view, which
21
21
  # the input mapped again makes anew.
@@ -34,15 +34,15 @@ import std/game/Control
34
34
  #
35
35
  # `cap` bounds it: once the timeline would hold `cap` ticks the history is full, lets its
36
36
  # ticks go, and every rewind, undo and step is refused from then on (the game plays on).
37
- struct HistoryTick(input: Input, view: Vec2, dt: Float, user: Bool, asks: List<Ask>)
37
+ struct HistoryTick(input: Input, pixels: Vec2, dt: Float, user: Bool, asks: List<Ask>)
38
38
 
39
- struct History(cap: Int, view: Vec2, ticks: List<HistoryTick>, count: Int, future: List<HistoryTick>, fork: Int, full: Bool, over: Int) =
39
+ struct History(cap: Int, pixels: Vec2, ticks: List<HistoryTick>, count: Int, future: List<HistoryTick>, fork: Int, full: Bool, over: Int) =
40
40
  # 30 minutes of ticks.
41
41
  Cap = 108000
42
42
 
43
- # An empty history of at most `cap` ticks, of a game whose screen is `view` pixels.
43
+ # An empty history of at most `cap` ticks, of a game whose window is `pixels`.
44
- fun start(cap: Int, view: Vec2) -> History =
44
+ fun start(cap: Int, pixels: Vec2) -> History =
45
- History(cap: cap, view: view, ticks: Nil, count: 0, future: Nil, fork: 0, full: false, over: 0)
45
+ History(cap: cap, pixels: pixels, ticks: Nil, count: 0, future: Nil, fork: 0, full: false, over: 0)
46
46
 
47
47
  # The tick the game is at: how many ticks it has played to reach the state it is in.
48
48
  fun now(self) -> Int = if self.full then self.cap + self.over else self.count
@@ -125,7 +125,7 @@ fun dropN<T>(xs: List<T>, n: Int) -> List<T> =
125
125
  Cons(_, rest) => dropN(rest, n - 1)
126
126
 
127
127
  fun histTick(user: Bool) -> HistoryTick =
128
- HistoryTick(input: Input.create(), view: Vec2(x: 800.0, y: 600.0), dt: 0.1, user: user, asks: Nil)
128
+ HistoryTick(input: Input.create(), pixels: Vec2(x: 800.0, y: 600.0), dt: 0.1, user: user, asks: Nil)
129
129
 
130
130
  test "a history goes back, keeps the future for a redo, and a user action cuts it"
131
131
  h := [true, false, true, false, false].fold(History.start(100, Vec2(x: 800.0, y: 600.0)), |acc, u| acc.push(histTick(u)))
std/game/Label.plum CHANGED
@@ -13,30 +13,66 @@ import std/math/Aabb
13
13
  import std/game/Color
14
14
  import std/game/gfx
15
15
  import std/game/Place
16
- import std/game/Actor
16
+ import std/game/View
17
17
  import std/game/Sized
18
18
  import std/game/Touch
19
19
 
20
+ # Where a `Label` sits on its x: its text starting there (`Left`, the default), centred
21
+ # on it (`Centre`) or ending there (`Right`).
22
+ enum Align = Left | Centre | Right
23
+
24
+ # Text whose top is at its place's y, which starts at (x, y), placed on its x by `align`,
20
- # A line of `text`, `size` high, in `color`, with its top-left at (x, y). Decoration by
25
+ # `size` high, in `color` (painted at its alpha). Its width is an estimate (`textWidth`:
26
+ # 0.6 of its size per letter), which its bounds and its alignment go by. It turns with its
27
+ # place. It is decoration unless `touch: Enabled` (std/game/Touch). In a view it is made
28
+ # again each frame, so its text is read from the state as it is made
29
+ # (`Label.of(16.0, 12.0, "Score {self.score}", 28.0, Color.White)`). `Label.of` fills in
21
- # default (`Label.of`).
30
+ # the usual: decoration (`Disabled`), and `Left` unless `align` is given.
22
- struct Label[Actor, Sized, Touch](x: Float, y: Float, text: Str, size: Float, color: Color, touch: Touchable) =
31
+ struct Label[View, Sized, Touch](x: Float, y: Float, text: Str, size: Float, color: Color, align: Align, touch: Touchable) =
23
- fun of(x: Float, y: Float, text: Str, size: Float, color: Color) -> Label = Label(x: x, y: y, text: text, size: size, color: color, touch: Disabled)
32
+ fun of(x: Float, y: Float, text: Str, size: Float, color: Color, align: Align = Left) -> Label =
33
+ Label(x: x, y: y, text: text, size: size, color: color, align: align, touch: Disabled)
24
34
 
25
35
  fun place(self) -> Place = place.at(self.x, self.y)
26
36
 
27
- # What it shows.
37
+ # How far left of its place its text starts.
28
- fun line(self) -> Str = self.text
38
+ fun lead(self) -> Float = leadOf(self.align, textWidth(self.text, self.size))
29
39
 
30
- fun bounds(self) -> Aabb = Aabb.of(0.0, 0.0, textWidth(self.text, self.size), self.size)
40
+ fun bounds(self) -> Aabb = Aabb.of(0.0 - self.lead(), 0.0, textWidth(self.text, self.size), self.size)
31
41
 
32
42
  fun touch(self) -> Touchable = self.touch
33
43
 
34
- fun paint(self, io: Io, m: Affine, alpha: Float) = drawLabel(io, m, alpha * self.color.a, self.text, self.size, self.color)
44
+ fun paintSelf(self, io: Io, m: Affine, alpha: Float) = drawLabel(io, m, alpha * self.color.a, self.text, self.size, self.color, self.align)
35
45
 
36
- # About how wide `s` is at `size`: the host's text is drawn monospaced near 0.6 of its
46
+ # An estimate of how wide `s` is at `size`: 0.6 of the size per letter.
37
- # height a character.
38
47
  fun textWidth(s: Str, size: Float) -> Float = size * 0.6 * Float(s.length())
39
48
 
49
+ # How far left of the anchor text `w` wide starts, placed by `align`.
50
+ fun leadOf(align: Align, w: Float) -> Float = match align
51
+ Left => 0.0
52
+ Centre => w / 2.0
53
+ Right => w
54
+
55
+ # Draws text with its top on the transform `m`'s origin, placed on it by `align`, turned
56
+ # and scaled as `m` turns and scales it. Paints with `alpha` in place of the colour's
57
+ # alpha, as `box.drawBox` does. Unturned text is a `drawText`, turned text a `drawTextEx`.
40
- fun drawLabel(io: Io, m: Affine, alpha: Float, s: Str, size: Float, color: Color) =
58
+ fun drawLabel(io: Io, m: Affine, alpha: Float, s: Str, size: Float, color: Color, align: Align = Left) =
41
- p := m.apply(Vec2(x: 0.0, y: 0.0))
59
+ p := m.apply(Vec2(x: 0.0 - leadOf(align, textWidth(s, size)), y: 0.0))
60
+ if m.b == 0.0 && m.a > 0.0
42
- gfx.drawText(io, s, p.x, p.y, size * m.scaleY(), color.withAlpha(alpha))
61
+ gfx.drawText(io, s, p.x, p.y, size * m.scaleY(), color.withAlpha(alpha))
62
+ else
63
+ gfx.drawTextEx(io, s, p.x, p.y, size * m.scaleY(), m.rotation(), color.withAlpha(alpha))
64
+
65
+ test "a label is as tall as its size and hit over its text"
66
+ l := Label.of(0.0, 0.0, "ab", 10.0, Color.White)
67
+ assert l.hit(Vec2(x: 11.0, y: 9.0))
68
+ assert !l.hit(Vec2(x: 13.0, y: 9.0))
69
+ assert Label.of(0.0, 0.0, "abc", 10.0, Color.White).hit(Vec2(x: 13.0, y: 9.0))
70
+
71
+ test "a label is placed on its x by its alignment"
72
+ c := Label.of(100.0, 0.0, "abcd", 10.0, Color.White, Centre)
73
+ assert c.bounds() == Aabb.of(-12.0, 0.0, 24.0, 10.0)
74
+ assert c.hit(Vec2(x: -11.0, y: 5.0))
75
+ assert !c.hit(Vec2(x: 13.0, y: 5.0))
76
+ r := Label.of(0.0, 0.0, "abcd", 10.0, Color.White, Right)
77
+ assert r.bounds() == Aabb.of(-24.0, 0.0, 24.0, 10.0)
78
+ assert Label.of(0.0, 0.0, "abcd", 10.0, Color.White).lead() == 0.0
std/game/Overlay.plum CHANGED
@@ -13,29 +13,47 @@ import std/math/Aabb
13
13
  import std/game/Color
14
14
  import std/game/gfx
15
15
  import std/game/Place
16
- import std/game/Actor
16
+ import std/game/View
17
17
  import std/game/Sized
18
18
  import std/game/Touch
19
-
19
+ import std/game/Box
20
+ import std/game/Label
21
+
20
- # A panel over a screen (a game over, a pause): a `w` by `h` box in `color` (black at 0.6
22
+ # A panel over a screen: a game over, a pause, a dialog. It is not a screen of its own. It
23
+ # is an item of the view of the screen it sits on, after (so drawn above) what it covers,
21
- # alpha with `Overlay.of`) at (x, y) that dims what is under it, with `children` drawn on
24
+ # there while the state says so, with its own children on it (a label, buttons):
25
+ #
26
+ # over: List<View> := if self.over then [Overlay.of(Arena.W, Arena.H, [
27
+ # Label.of(300.0, 258.0, "Game over", 48.0, Color.Red)])] else Nil
28
+ #
29
+ # It paints a `w` by `h` box in its `color` (black at 0.6 alpha with `Overlay.of`) over
30
+ # what is under it, then its children (its `view`) at their own opacity. Its size is
31
+ # required. It takes presses (`touch: Enabled`, std/game/Touch) inside its box, so no item
22
- # it. It takes every press on it (`Enabled`, hit anywhere in it), so nothing under it is
32
+ # under it there is pressed; its children are hit first. Keys still go to the screen's
23
- # pressed. In a view it is made `open: true` and left out while it should not show; a
33
+ # mapping (`onKey`, std/game/ScreenSlice), which says what they do while it shows (Enter
24
- # closed one is not drawn or hit.
34
+ # plays again).
25
- struct Overlay[Actor, Sized, Touch](x: Float, y: Float, w: Float, h: Float, color: Color, touch: Touchable, open: Bool, children: List<Actor>) =
35
+ struct Overlay[View, Sized, Touch](x: Float, y: Float, w: Float, h: Float, color: Color, touch: Touchable, children: List<View>) =
26
- fun of(w: Float, h: Float, children: List<Actor>) -> Overlay =
36
+ fun of(w: Float, h: Float, children: List<View>) -> Overlay =
27
- Overlay(x: 0.0, y: 0.0, w: w, h: h, color: Color(r: 0.0, g: 0.0, b: 0.0, a: 0.6), touch: Enabled, open: true, children: children)
37
+ Overlay(x: 0.0, y: 0.0, w: w, h: h, color: Color(r: 0.0, g: 0.0, b: 0.0, a: 0.6), touch: Enabled, children: children)
28
38
 
29
39
  fun place(self) -> Place = place.at(self.x, self.y)
30
40
 
31
- fun shown(self) -> Bool = self.open
32
-
33
41
  fun bounds(self) -> Aabb = Aabb.of(0.0, 0.0, self.w, self.h)
34
42
 
35
- fun declared(self) -> List<Actor> = self.children
43
+ fun view(self) -> List<View> = self.children
36
44
 
37
45
  fun touch(self) -> Touchable = self.touch
38
46
 
39
- fun paint(self, io: Io, m: Affine, alpha: Float) = actor.drawBox(io, m, alpha * self.color.a, self.w, self.h, self.color)
47
+ fun paintSelf(self, io: Io, m: Affine, alpha: Float) = box.drawBox(io, m, alpha * self.color.a, self.w, self.h, self.color)
48
+
40
-
49
+ test "an overlay is hit inside its box, after its children, and hides what is under it from presses"
50
+ under := Box(x: 0.0, y: 0.0, w: 100.0, h: 100.0, color: Color.White, touch: Enabled)
51
+ button := Box(x: 40.0, y: 40.0, w: 10.0, h: 10.0, color: Color.White, touch: Enabled)
52
+ over := Overlay.of(100.0, 100.0, [button, Label.of(0.0, 0.0, "Paused", 24.0, Color.White)])
41
- fun hit(self, p: Vec2) -> Bool = true
53
+ items: List<View> := [under, over]
54
+ assert @sameRef(view.hitIn(items, Vec2(x: 5.0, y: 5.0)).unwrap(), over)
55
+ assert view.hitIn(items, Vec2(x: 5000.0, y: -20.0)).isNone()
56
+ assert @sameRef(view.hitIn(items, Vec2(x: 45.0, y: 45.0)).unwrap(), button)
57
+ assert @sameRef(view.hitIn([under], Vec2(x: 5.0, y: 5.0)).unwrap(), under)
58
+ off := Overlay(..Overlay.of(10.0, 10.0, Nil), touch: Disabled)
59
+ assert @sameRef(view.hitIn([under, off], Vec2(x: 5.0, y: 5.0)).unwrap(), under)
std/game/Place.plum CHANGED
@@ -7,8 +7,8 @@ import std/math/Affine
7
7
 
8
8
  # Where an actor is in its parent: its position, its scale and rotation, the origin (in its
9
9
  # own coordinates) it turns and scales about, and its `alpha`, which multiplies down what
10
- # is drawn under it. Every actor has one (`Actor.place`); a view's draw turns it into the
10
+ # is drawn under it. Every view has one (`View.place`); a view's draw turns it into the
11
- # actor's transform with `local` (std/game/Actor).
11
+ # actor's transform with `local` (std/game/View).
12
12
  #
13
13
  # p := place.at(10.0, 20.0) # unscaled, unturned
14
14
  # q := place.at(400.0, 300.0).rotateTo(0.5)
std/game/Replay.plum CHANGED
@@ -25,10 +25,13 @@ import std/game/input
25
25
  # The text form, one line each:
26
26
  #
27
27
  # plum-replay 1 <seed, high 32 bits> <seed, low 32 bits> <screen width> <screen height>
28
- # <held keys, comma separated, or -> <mouse held, 1 or 0> <pointer x> <pointer y> <wheel> <events>
28
+ # <held keys, comma separated, or -> <mouse buttons held> <pointer x> <pointer y> <wheel> <events>
29
29
  #
30
- # with one tick line per tick. An event is `K<key>` (KeyDown), `k<key>` (KeyUp),
30
+ # with one tick line per tick. The mouse buttons held are a sum: 1 for the left, 2 for the
31
+ # right, 4 for the middle (a replay from before the other buttons has only 0 and 1). An
31
- # `D<x>,<y>` (PointerDown), `U<x>,<y>` (PointerUp) or `M<x>,<y>` (PointerMove). Floats are
32
+ # event is `K<key>` (KeyDown), `k<key>` (KeyUp), `D<x>,<y>` (PointerDown), `U<x>,<y>`
33
+ # (PointerUp), `M<x>,<y>` (PointerMove), `B<button>,<x>,<y>` (ButtonDown) or
34
+ # `b<button>,<x>,<y>` (ButtonUp). Floats are
32
35
  # written exactly, as `m` or `m:e` for the integer m times 2^e, or as `-0`, `inf`, `-inf`
33
36
  # or `nan` (`toStr` rounds to six digits). The screen size is the host's at the start of
34
37
  # the recording, and the replaying host reports it to the game; 0 means not recorded.
@@ -115,7 +118,8 @@ struct Replay(seed: Int, width: Int, height: Int, ticks: Slice<Input>) =
115
118
  if i > 0
116
119
  b.write(",")
117
120
  b.write("{keys.at(i)}")
118
- b.write(if input.held.mouse then " 1 " else " 0 ")
121
+ mask := input.held.buttons.fold(if input.held.mouse then 1 else 0, |m, x| m | {1 << x})
122
+ b.write(" {mask} ")
119
123
  b.write("{floatCode(input.pos.x)} {floatCode(input.pos.y)} {floatCode(input.wheel)}")
120
124
  for i := range input.events.length()
121
125
  b.write(" ")
@@ -126,7 +130,8 @@ struct Replay(seed: Int, width: Int, height: Int, ticks: Slice<Input>) =
126
130
  # One tick's line read back (no newline), or None.
127
131
  fun parseLine(l: Str) -> Option<Input> =
128
132
  t := l.split(" ", 0)
129
- if t.length() < 5 || {t.at(1) != "0" && t.at(1) != "1"}
133
+ mask := if t.length() < 5 then -1 else Int.parse(t.at(1)).ok().unwrapOr(-1)
134
+ if mask < 0 || mask > 7
130
135
  None
131
136
  else
132
137
  keys := if t.at(0) == "-" then Some(Slice<Int>()) else parseKeys(t.at(0).split(",", 0), 0, Slice<Int>())
@@ -135,7 +140,12 @@ struct Replay(seed: Int, width: Int, height: Int, ticks: Slice<Input>) =
135
140
  y := parseFloatCode(t.at(3))?
136
141
  wheel := parseFloatCode(t.at(4))?
137
142
  events := parseEvents(t, 5, Slice<InputEvent>())?
143
+ buttons := Slice<Int>()
144
+ if {mask & 2} != 0
145
+ buttons.push(Mouse.Right)
146
+ if {mask & 4} != 0
147
+ buttons.push(Mouse.Middle)
138
- Some(Input(held: Held(mouse: t.at(1) == "1", keys: held), events: events, pos: Vec2(x: x, y: y), wheel: wheel))
148
+ Some(Input(held: Held(mouse: {mask & 1} != 0, keys: held, buttons: buttons), events: events, pos: Vec2(x: x, y: y), wheel: wheel))
139
149
 
140
150
  fun parseKeys(ks: Slice<Str>, i: Int, out: Slice<Int>) -> Option<Slice<Int>> =
141
151
  if i >= ks.length()
@@ -213,6 +223,8 @@ fun eventCode(e: InputEvent) -> Str = match e
213
223
  PointerDown(x, y) => "D{floatCode(x)},{floatCode(y)}"
214
224
  PointerUp(x, y) => "U{floatCode(x)},{floatCode(y)}"
215
225
  PointerMove(x, y) => "M{floatCode(x)},{floatCode(y)}"
226
+ ButtonDown(n, x, y) => "B{n},{floatCode(x)},{floatCode(y)}"
227
+ ButtonUp(n, x, y) => "b{n},{floatCode(x)},{floatCode(y)}"
216
228
 
217
229
  fun parseEvent(tok: Str) -> Option<InputEvent> =
218
230
  if tok.length() < 2
@@ -222,6 +234,15 @@ fun parseEvent(tok: Str) -> Option<InputEvent> =
222
234
  rest := tok.sub(1, tok.length())
223
235
  if kind == 75 || kind == 107
224
236
  Int.parse(rest).ok().map(|k| if kind == 75 then KeyDown(key: k) else KeyUp(key: k))
237
+ else if kind == 66 || kind == 98
238
+ parts := rest.split(",", 2)
239
+ if parts.length() != 2
240
+ None
241
+ else
242
+ n := Int.parse(parts.at(0)).ok()?
243
+ at := parseEvent("M{parts.at(1)}")?
244
+ p := at.position()?
245
+ Some(if kind == 66 then ButtonDown(button: n, x: p.x, y: p.y) else ButtonUp(button: n, x: p.x, y: p.y))
225
246
  else
226
247
  xy := rest.split(",", 0)
227
248
  if xy.length() != 2
std/game/Screen.plum CHANGED
@@ -12,61 +12,96 @@ import std/math/Affine
12
12
  import std/math/Aabb
13
13
  import std/game/Color
14
14
  import std/game/input
15
- import std/game/Actor
15
+ import std/game/View
16
16
  import std/game/Viewport
17
17
  import std/game/Control
18
+ import std/game/Effects
19
+ import std/game/ScreenSlice
18
20
 
19
- # One screen of a game (a title, the play, a level select): a name, and its `view`, what
21
+ # One screen of a game (a title, the play, a level select): a name, its state, and the
20
- # the frame shows. The game shows one screen at a time (std/game/Game) and goes to another
22
+ # `view` that draws it. The game shows one screen at a time (std/game/Game) and goes to
21
- # by name, when an effect asks it to (`game.goTo(name)`, std/game/Control).
23
+ # another by name, when an effect asks it to (`game.goTo(name)`, std/game/Control).
22
24
  #
23
25
  # A screen with rules is a `ScreenSlice<A>` (std/game/ScreenSlice), which extends
24
26
  # `Screen`: its fields are its state, `A` its actions, and std delivers the tick's input
25
- # and its tick to it as actions. A screen with no rules is a plain `Screen`: it shows its
27
+ # and its tick to it as actions. A screen with no rules is a plain `Screen`: it gets no
26
- # view and nothing moves it.
28
+ # actions, and draws what its fields were made with, its actors stepped.
27
29
  #
28
- # A screen is a value. Each method that changes it returns its next version (`enter`,
30
+ # A screen is a value: each tick the game keeps the next version the tick returned.
29
- # `leave`, `resize`, and a slice's `reduce`), and the game keeps the one it got.
30
31
  #
32
+ # Each tick the screen gets, before its tick action is reduced, the game has it step its
31
- # What sits over a view (a game over, a pause) is not a screen: it is part of the screen's
33
+ # `Actor`s (std/game/View), unless it says `steps()` is false: it calls the screen's
34
+ # `stepped(dt)`, which returns the screen with each actor it holds stepped. The game can't
32
- # view, an `Overlay` (std/game/Overlay) shown from the state.
35
+ # step an actor where it finds it in the view, since the screen holding it is a value, so
36
+ # the screen maps its own fields (`view.stepAll` for a list of actors):
33
37
  #
34
- # name its name, which `goTo` uses ("play"); by convention the struct's name ends
35
- # in `Screen` (`PlayingScreen`)
38
+ # fun stepped(self, dt: Float) -> PlayingScreen =
36
- # view what the frame shows: a list of actors in the world's coordinates, made
39
+ # PlayingScreen(..self, ship: self.ship.step(dt), mines: view.stepAll(self.mines, dt))
37
- # again from the screen's fields every time the frame is drawn (and for a
38
- # press, std/game/ScreenSlice)
39
- # size the world the view is placed in: Orbit Runner's arena, 800 by 600. 0 by 0
40
- # (the default) is the screen's own pixels
41
- # viewport how that world is put on the screen (`Fit` by default, std/game/Viewport)
42
- # culls true skips each `Sized` item whose bounds miss what the screen shows
43
- # busy true asks an `OnDemand` screen's next tick (something it shows still moves)
44
- # background what the frame is cleared with (black by default)
45
- # draw draws the frame through `m` (the world to the screen's pixels) at `alpha`:
46
- # by default its view (culled to `area`, the world shown, if it `culls`).
47
- # The game clears first; define `draw` to draw more (a HUD), not to clear
48
- # resize the screen is `w` by `h` pixels: called for every screen when the size is
49
- # first known and whenever it changes, before the tick is delivered. Nothing
50
- # by default: the viewport fits the world itself
51
- # enter the game goes to this screen from the screen named `from`; by default it
52
- # resumes as it was left
53
- # leave the game goes from this screen to the one named `to`
54
- # fresh true for a screen that starts over each time it is shown: the game goes
55
- # to it as the game was made with it. False by default
56
- # transition how it comes in from the screen named `from`: `Cut` (the default),
57
- # `Fade` or `Slide`
58
- # frames `Always` (the default) or `OnDemand` (see "Frames on demand" in
59
- # docs/game.md)
60
- # deliver std's, not the screen's: one tick of the screen. A plain screen's does
61
- # nothing; a slice's delivers the tick as actions
62
- # wants std's too: whether what is held gives an `OnDemand` screen something to do
63
40
  #
41
+ # A screen holding no actors leaves it out (the default returns the screen as it is).
42
+ #
43
+ # What sits over a view (a game over, a pause, a dialog) is not a screen: it is part of
44
+ # the screen it sits on, an `Overlay` (std/game/Overlay) in its view, there while the
45
+ # state says so, and the screen maps its keys.
46
+ #
47
+ # By convention a screen struct's name ends in `Screen` (`PlayingScreen`); its `name()`
48
+ # stays short ("play").
49
+ #
50
+ # view what it draws, made again each frame from its fields: a list of views
51
+ # (std/game/View) in the world's coordinates, drawn in order (later on
52
+ # top). Empty by default.
53
+ # hud what is drawn over the view, one unit a pixel of the window, which is
54
+ # `window` pixels: a score in a corner. Hit before the view. Empty by
55
+ # default.
56
+ # steps false to step none of its actors this tick (a game paused, a run over).
57
+ # True by default.
58
+ # stepped the screen with its actors stepped `dt` seconds on (above): what the game
59
+ # calls when `steps()`. The screen as it is by default.
60
+ # camera the camera it is seen through, given the one its `size()` and `viewport()`
61
+ # make (`base`): `base` by default, `base.lookAt(x, y, zoom)` to follow
62
+ # something or zoom (std/game/Viewport). Presses, `toWorld`, culling and the
63
+ # draw all go through it.
64
+ # size the world it shows, in its own units (800 by 600): put on the screen by
65
+ # `viewport()`. With none (0 by 0, the default), one unit is one pixel and
66
+ # the world is the screen.
67
+ # viewport how the world is put on the screen (std/game/Viewport): `Fit` (the
68
+ # default), `Fill`, `Stretch`, `Extend` or `Pixels`.
69
+ # culls true to skip, when drawing, each `Sized` item of the view whose bounds miss
70
+ # what the camera shows, with what is under it. False by default.
71
+ # busy true while something moves that the screen wants its next tick for (a
72
+ # slide): an `OnDemand` screen keeps getting ticks. False by default.
73
+ # background what the game clears the frame with first. Black by default.
74
+ # transition how it comes in from the screen named `from`: at once (`Cut`, the
75
+ # default), fading in (`Fade`) or sliding in from an edge (`Slide`).
76
+ # frames whether the game runs the screen's ticks every frame (`Always`, the
77
+ # default) or only when something happened (`OnDemand`: "Frames on demand"
78
+ # in docs/game.md).
79
+ # deliver std's, not the screen's: how the game runs one tick of the screen. A
80
+ # plain screen's steps its actors; a slice's delivers the tick as actions
81
+ # and steps them before its tick action.
82
+ # wants std's too: whether what is held in the tick's input gives an `OnDemand`
83
+ # screen something to do. A plain screen's is never; a slice's is its
84
+ # `held(input)` giving an action.
85
+ #
86
+ # The game keeps a screen as it is when it goes to another, so coming back shows it as it
87
+ # was left.
88
+ #
64
- # During a transition the game draws both screens, the one going out and then the one
89
+ # During a transition the game draws both screens, each on its own `background()`, the
65
- # coming in, each moved and faded; only the one coming in gets ticks.
90
+ # one going out fading or sliding out under the one coming in; only the one coming in
91
+ # gets ticks, and it gets no pointer events until the transition is over (keys still
92
+ # come).
66
93
  trait Screen =
67
94
  fun name(self) -> Str
68
95
 
69
- fun view(self) -> List<Actor> = Nil
96
+ fun view(self) -> List<View> = Nil
97
+
98
+ fun hud(self, window: Vec2) -> List<View> = Nil
99
+
100
+ fun steps(self) -> Bool = true
101
+
102
+ fun stepped(self, dt: Float) -> Self = self
103
+
104
+ fun camera(self, base: Viewport) -> Viewport = base
70
105
 
71
106
  fun size(self) -> Vec2 = Vec2(x: 0.0, y: 0.0)
72
107
 
@@ -78,37 +113,36 @@ trait Screen =
78
113
 
79
114
  fun background(self) -> Color = Color.Black
80
115
 
81
- fun draw(self, io: Io, m: Affine, alpha: Float, area: Aabb) =
82
- if self.culls()
83
- actor.paintCulled(io, self.view(), m, alpha, area)
84
- else
85
- actor.paintView(io, self.view(), m, alpha)
86
-
87
- fun resize(self, w: Float, h: Float) -> Self = self
88
-
89
- fun enter(self, from: Str) -> Self = self
90
-
91
- fun leave(self, to: Str) -> Self = self
92
-
93
- fun fresh(self) -> Bool = false
94
-
95
116
  fun transition(self, from: Str) -> Transition = Cut
96
117
 
97
118
  fun frames(self) -> Frames = Always
98
119
 
99
- fun deliver(self, cam: Viewport, input: Input, dt: Float) -> Delivered = Delivered(screen: self, effects: Nil, mapped: false, held: false)
120
+ fun deliver(self, d: Delivery) -> Delivered = Delivered(screen: d.stepScreen(self), effects: Nil, acted: false)
100
121
 
101
- fun wants(self, input: Input) -> Bool = input.held.mouse || !input.held.keys.isEmpty()
122
+ fun wants(self, input: Input) -> Bool = false
102
123
 
103
124
  # One tick of a screen, delivered: the screen after it, the effects waiting to run (each
104
- # action dispatched, with the slice as the tick left it), whether the input mapping gave
125
+ # action dispatched, with the slice as the tick left it), and whether the tick was a user
105
- # an action for one of the tick's events (`mapped`), and whether `held` gave one.
126
+ # action (std/game/History): the mapping gave an action for one of its events, or `held`
127
+ # gave one while what is held differs from the screen's tick before.
106
- struct Delivered(screen: Screen, effects: List<Effect>, mapped: Bool, held: Bool)
128
+ struct Delivered(screen: Screen, effects: List<Effect>, acted: Bool)
129
+
107
-
130
+ # The camera the screen `s` is seen through in a window of `pixels` (0 by 0 while the
131
+ # game doesn't know it): its world (`size()`) put on the window by its `viewport()`, or,
108
- # One action waiting for its effect after the tick (std/game/ScreenSlice's `Queued<A>`):
132
+ # for a screen with no size, one unit a pixel with the world as large as the window; then
109
- # one list holds the actions of every type.
133
+ # as the screen's `camera` moves it.
110
- trait Effect =
134
+ fun cameraOf(s: Screen, pixels: Vec2) -> Viewport = s.camera(baseCamera(s, pixels))
135
+
111
- fun apply(self, io: Io, game: Control)
136
+ fun baseCamera(s: Screen, pixels: Vec2) -> Viewport =
137
+ size := s.size()
138
+ known := pixels.x > 0.0 && pixels.y > 0.0
139
+ if size.x > 0.0 && size.y > 0.0
140
+ v := Viewport.of(s.viewport(), size.x, size.y)
141
+ if known then v.update(pixels.x, pixels.y) else v
142
+ else if known
143
+ Viewport.of(Pixels, pixels.x, pixels.y)
144
+ else
145
+ Viewport.of(Pixels, 1.0, 1.0)
112
146
 
113
147
  # How often a screen gets its ticks and is drawn: every frame (`Always`), or only when
114
148
  # something happened (`OnDemand`).
@@ -149,18 +183,18 @@ struct Shift(from: Int, how: Transition, t: Float) =
149
183
  # make half a second).
150
184
  fun doneAt(self, t: Float) -> Bool = t >= self.how.secs() - 0.000000001
151
185
 
152
- # How the screen coming in (`incoming`) or going out is drawn on a screen of `view`
186
+ # How the screen coming in (`incoming`) or going out is drawn in a window of `pixels`:
153
- # pixels: its offset in pixels and its opacity.
187
+ # its offset in pixels and its opacity.
154
- fun frame(self, incoming: Bool, view: Vec2) -> ShiftFrame =
188
+ fun frame(self, incoming: Bool, pixels: Vec2) -> ShiftFrame =
155
189
  p := self.progress()
156
190
  d := if incoming then 1.0 - p else 0.0 - p
157
191
  match self.how
158
192
  Fade(_) => ShiftFrame(x: 0.0, y: 0.0, alpha: if incoming then p else 1.0 - p)
159
193
  Slide(edge, _) => match edge
160
- FromLeft => ShiftFrame(x: 0.0 - d * view.x, y: 0.0, alpha: 1.0)
194
+ FromLeft => ShiftFrame(x: 0.0 - d * pixels.x, y: 0.0, alpha: 1.0)
161
- FromRight => ShiftFrame(x: d * view.x, y: 0.0, alpha: 1.0)
195
+ FromRight => ShiftFrame(x: d * pixels.x, y: 0.0, alpha: 1.0)
162
- FromTop => ShiftFrame(x: 0.0, y: 0.0 - d * view.y, alpha: 1.0)
196
+ FromTop => ShiftFrame(x: 0.0, y: 0.0 - d * pixels.y, alpha: 1.0)
163
- FromBottom => ShiftFrame(x: 0.0, y: d * view.y, alpha: 1.0)
197
+ FromBottom => ShiftFrame(x: 0.0, y: d * pixels.y, alpha: 1.0)
164
198
  Cut => ShiftFrame(x: 0.0, y: 0.0, alpha: 1.0)
165
199
 
166
200
  # The transition after `dt` more seconds, or None once it is over.
@@ -172,17 +206,17 @@ struct Shift(from: Int, how: Transition, t: Float) =
172
206
  struct ShiftFrame(x: Float, y: Float, alpha: Float)
173
207
 
174
208
  test "a transition's frames fade or slide the two screens"
175
- view := Vec2(x: 800.0, y: 600.0)
209
+ pixels := Vec2(x: 800.0, y: 600.0)
176
210
  f := Shift(from: 0, how: Fade(secs: 0.5), t: 0.125)
177
211
  assert f.progress() == 0.25
178
- assert f.frame(true, view).alpha == 0.25
212
+ assert f.frame(true, pixels).alpha == 0.25
179
- assert f.frame(false, view).alpha == 0.75
213
+ assert f.frame(false, pixels).alpha == 0.75
180
214
  s := Shift(from: 0, how: Slide(from: FromRight, secs: 1.0), t: 0.25)
181
- assert s.frame(true, view).x == 600.0
215
+ assert s.frame(true, pixels).x == 600.0
182
- assert s.frame(false, view).x == -200.0
216
+ assert s.frame(false, pixels).x == -200.0
183
217
  l := Shift(from: 0, how: Slide(from: FromTop, secs: 1.0), t: 0.5)
184
- assert l.frame(true, view).y == -300.0
218
+ assert l.frame(true, pixels).y == -300.0
185
- assert l.frame(false, view).y == 300.0
219
+ assert l.frame(false, pixels).y == 300.0
186
220
  assert Cut.secs() == 0.0
187
221
  assert Shift(from: 0, how: Cut, t: 0.0).progress() == 1.0
188
222
  half := 0.until(30).fold(Some(Shift(from: 0, how: Fade(secs: 0.5), t: 0.0)), |s, i| match s
std/game/ScreenSlice.plum CHANGED
@@ -10,7 +10,8 @@ import std/Slice
10
10
  import std/collections/List
11
11
  import std/math/Vec2
12
12
  import std/game/input
13
- import std/game/Actor
13
+ import std/game/View
14
+ import std/game/Effects
14
15
  import std/game/Viewport
15
16
  import std/game/Control
16
17
  import std/game/Screen
@@ -41,14 +42,18 @@ import std/game/Screen
41
42
  #
42
43
  # 1. each of the tick's events, in the order they came:
43
44
  # a key `onKey(e)`
44
- # a press `onPress(target, at)`, with the top-most shown item of the view
45
+ # a press `onPress(target, at)`, with the top-most item of the screen's
45
- # under the press that takes presses (`Sized` and `Enabled`,
46
+ # `hud`, or else of its view, under the press that takes presses
46
- # std/game/Actor's `viewHit`) and the press in the world's
47
+ # (`Sized` and `Enabled`, std/game/View's `hitIn`) and the press
47
- # coordinates; if it gives None, or the press is on no such item,
48
+ # in the world's coordinates; if it gives None, or the press is on
48
- # `onPointer` is asked as for any pointer event
49
+ # no such item, `onPointer` is asked as for any pointer event
49
50
  # a pointer event `onPointer(e, at)`, with the event's point in the world
51
+ # (through the screen's camera)
52
+ # While a transition runs, the pointer events are dropped: only keys come.
50
53
  # 2. `held(input)`: an action for what is held (the steering keys), every tick.
54
+ # 3. The game has the screen step its `Actor`s (`stepped(dt)`, std/game/Screen), unless
51
- # 3. `tick(dt)`: the tick action.
55
+ # its `steps()` is false.
56
+ # 4. `tick(dt)`: the tick action, which sees the actors stepped and runs the rules.
52
57
  #
53
58
  # A mapping that gives None sends nothing. Each action is dispatched as it is made:
54
59
  # `reduce(a)` runs at once, so the next mapping and action see what it did, and `a` is
@@ -63,10 +68,10 @@ trait ScreenSlice<A>[Screen] =
63
68
 
64
69
  # Dispatches `a` from this slice's own reducer (the rules dispatching what happened):
65
70
  # reduced at once, and queued for its effect after the tick, before the action being
66
- # reduced. Called outside a tick (a test calling `reduce` itself), it only reduces.
71
+ # reduced. Called outside a dispatch (a test calling `reduce` itself), it only reduces.
67
72
  fun dispatch(self, a: A) -> Self =
68
73
  next := self.reduce(a)
69
- queueAction(a)
74
+ effects.queueAction(a)
70
75
  next
71
76
 
72
77
  # The effects of `a`, after the tick: a sound, a change of screen. Nothing by default.
@@ -76,7 +81,7 @@ trait ScreenSlice<A>[Screen] =
76
81
 
77
82
  fun onPointer(self, e: InputEvent, at: Vec2) -> Option<A> = None
78
83
 
79
- fun onPress(self, target: Actor, at: Vec2) -> Option<A> = None
84
+ fun onPress(self, target: View, at: Vec2) -> Option<A> = None
80
85
 
81
86
  fun held(self, input: Input) -> Option<A> = None
82
87
 
@@ -87,66 +92,65 @@ trait ScreenSlice<A>[Screen] =
87
92
  fun wants(self, input: Input) -> Bool = self.held(input).isSome()
88
93
 
89
94
  # std's: one tick of the screen, delivered as actions (see the top of this file).
90
- fun deliver(self, cam: Viewport, input: Input, dt: Float) -> Delivered = deliverTo<A, Self>(self, cam, input, dt)
95
+ fun deliver(self, d: Delivery) -> Delivered = deliverTo<A, Self>(self, d)
96
+
91
-
97
+ # One tick as the game hands it to a screen's `deliver`: the tick's input and length, what
92
- # Where a slice's own `dispatch` queues what its reducer dispatches: the queue of the
98
+ # was held at the screen's tick before (`before`), the camera the screen is seen through
93
- # delivery running, the innermost last.
99
+ # (window pixels to the world's coordinates), the window's size in pixels, and whether a
94
- trait Sink =
100
+ # transition runs.
95
- fun size(self) -> Int
96
-
97
- struct ActionSink<A>[Sink](queue: Slice<A>) =
98
- fun size(self) -> Int = self.queue.length()
99
-
100
- Dispatching = Slice<Sink>()
101
-
102
- # Queues `a` on the delivery running, if it delivers actions of `a`'s type.
101
+ struct Delivery(input: Input, dt: Float, before: Held, camera: Viewport, pixels: Vec2, shifting: Bool) =
103
- fun queueAction<A>(a: A) =
104
- n := Dispatching.length()
105
- if n > 0
106
- match Dispatching.at(n - 1)
107
- ActionSink<A> as k => k.queue.push(a)
108
- _ => Unit
109
-
110
- # One action waiting for its effect, with the slice whose effect runs it.
102
+ # The item a press at the window pixel `p`, the world point `at`, lands on: in the
111
- struct Queued<A>[Effect](slice: ScreenSlice<A>, action: A) =
103
+ # screen's `hud`, else in its view; None for none.
112
- fun apply(self, io: Io, game: Control) = self.slice.effect(io, self.action, game)
104
+ fun pressed(self, s: Screen, p: Vec2, at: Vec2) -> Option<View> =
113
-
105
+ h := view.hitIn(s.hud(self.pixels), p)
106
+ if h.isSome() then h else view.hitIn(s.view(), at)
107
+
108
+ # `s` with its actors stepped (`stepped(dt)`), unless it says it `steps()` none this
109
+ # tick.
114
- fun queued<A>(s: ScreenSlice<A>, a: A) -> Effect = Queued(slice: s, action: a)
110
+ fun stepScreen<S: Screen>(self, s: S) -> S = if s.steps() then s.stepped(self.dt) else s
115
111
 
116
112
  # One tick of the slice `s`, as `deliver` describes.
117
- fun deliverTo<A, S: ScreenSlice<A>>(s: S, cam: Viewport, input: Input, dt: Float) -> Delivered =
113
+ fun deliverTo<A, S: ScreenSlice<A>>(s: S, d: Delivery) -> Delivered =
118
114
  q := Slice<A>()
119
- mapped := Slice<Bool>()
115
+ acted := Slice<Bool>()
120
- Dispatching.push(ActionSink(queue: q))
116
+ effects.startDispatch(ActionSink(queue: q))
121
- evs := input.events
117
+ evs := d.input.events
122
- afterEvents := 0.until(evs.length()).fold(s, |cur, i| eventInto<A, S>(cur, cam, evs.at(i), q, mapped))
118
+ afterEvents := 0.until(evs.length()).fold(s, |cur, i| eventInto<A, S>(cur, d, evs.at(i), q, acted))
123
- h := afterEvents.held(input)
119
+ h := afterEvents.held(d.input)
124
120
  afterHeld := match h
121
+ Some(a) =>
122
+ if !d.before.same(d.input.held)
123
+ acted.push(true)
125
- Some(a) => reduced<A, S>(afterEvents, a, q)
124
+ reduced<A, S>(afterEvents, a, q)
126
125
  None => afterEvents
126
+ stepped := d.stepScreen(afterHeld)
127
- afterTick := match afterHeld.tick(dt)
127
+ afterTick := match stepped.tick(d.dt)
128
- Some(a) => reduced<A, S>(afterHeld, a, q)
128
+ Some(a) => reduced<A, S>(stepped, a, q)
129
- None => afterHeld
129
+ None => stepped
130
- Dispatching.removeAt(Dispatching.length() - 1)
130
+ effects.endDispatch()
131
131
  final: ScreenSlice<A> := afterTick
132
- fx: List<Effect> := List.fromSlice(q).map(|a| queued(final, a))
132
+ fx: List<Effect> := List.fromSlice(q).map(|a| effects.queued(final, a))
133
- Delivered(screen: afterTick, effects: fx, mapped: mapped.length() > 0, held: h.isSome())
133
+ Delivered(screen: afterTick, effects: fx, acted: acted.length() > 0)
134
134
 
135
- # `s` after the event `e`, mapped to its action.
135
+ # `s` after the event `e`, mapped to its action; a pointer event while a transition runs
136
+ # is dropped.
136
- fun eventInto<A, S: ScreenSlice<A>>(s: S, cam: Viewport, e: InputEvent, q: Slice<A>, mapped: Slice<Bool>) -> S = match e.position()
137
+ fun eventInto<A, S: ScreenSlice<A>>(s: S, d: Delivery, e: InputEvent, q: Slice<A>, acted: Slice<Bool>) -> S = match e.position()
137
138
  Some(p) =>
139
+ if d.shifting
140
+ s
141
+ else
138
- at := cam.toWorld(p.x, p.y)
142
+ at := d.camera.toWorld(p.x, p.y)
139
- target := if e.isPointerDown() then actor.viewHit(s.view(), at) else None
143
+ target := if e.isPointerDown() then d.pressed(s, p, at) else None
140
- pressed := match target
144
+ pressed := match target
141
- Some(t) => s.onPress(t, at)
145
+ Some(t) => s.onPress(t, at)
142
- None => None
146
+ None => None
143
- act := if pressed.isSome() then pressed else s.onPointer(e, at)
147
+ act := if pressed.isSome() then pressed else s.onPointer(e, at)
144
- acted<A, S>(s, act, q, mapped)
148
+ actedOn<A, S>(s, act, q, acted)
145
- None => acted<A, S>(s, s.onKey(e), q, mapped)
149
+ None => actedOn<A, S>(s, s.onKey(e), q, acted)
146
-
150
+
147
- fun acted<A, S: ScreenSlice<A>>(s: S, act: Option<A>, q: Slice<A>, mapped: Slice<Bool>) -> S = match act
151
+ fun actedOn<A, S: ScreenSlice<A>>(s: S, act: Option<A>, q: Slice<A>, acted: Slice<Bool>) -> S = match act
148
152
  Some(a) =>
149
- mapped.push(true)
153
+ acted.push(true)
150
154
  reduced<A, S>(s, a, q)
151
155
  None => s
152
156
 
std/game/Sprite.plum CHANGED
@@ -13,20 +13,31 @@ import std/math/Aabb
13
13
  import std/game/Color
14
14
  import std/game/gfx
15
15
  import std/game/Place
16
- import std/game/Actor
16
+ import std/game/View
17
17
  import std/game/Sized
18
18
  import std/game/Touch
19
19
 
20
- # A `w` by `h` picture with its top-left at (x, y): the `srcW` by `srcH` cell `frame` of
20
+ # A texture region (srcX, srcY, srcW, srcH in texture pixels) drawn `w` by `h`, its
21
- # a strip of `tex` that starts at (srcX, srcY), tinted `tint`. Decoration by default
21
+ # top-left at its place, which starts at (x, y), tinted `tint` (painted at its alpha). It
22
+ # is decoration unless `touch: Enabled` (std/game/Touch), and then hit inside its box.
23
+ # `Sprite.cell` fills in the usual: untinted, decoration (`Disabled`).
24
+ #
25
+ # An animation strip is a `frame`: frame `n` is the region `n` cells of `srcW` to the
26
+ # right of (srcX, srcY). In an actor's `view` (std/game/View), made again at each draw, it
22
- # (`Sprite.cell`).
27
+ # is read from the actor's own clock:
28
+ #
29
+ # Sprite.cell(0.0, 0.0, sheet, 48.0, 48.0, 0.0, 0.0, 16.0, 16.0, Sprite.frameAt(self.clock, 8.0, 4))
23
- struct Sprite[Actor, Sized, Touch](x: Float, y: Float, tex: Texture, w: Float, h: Float, srcX: Float, srcY: Float, srcW: Float, srcH: Float, frame: Int, tint: Color, touch: Touchable) =
30
+ struct Sprite[View, Sized, Touch](x: Float, y: Float, tex: Texture, w: Float, h: Float, srcX: Float, srcY: Float, srcW: Float, srcH: Float, frame: Int, tint: Color, touch: Touchable) =
24
31
  # Frame `frame` of the strip at (srcX, srcY), untinted.
25
32
  fun cell(x: Float, y: Float, tex: Texture, w: Float, h: Float, srcX: Float, srcY: Float, srcW: Float, srcH: Float, frame: Int) -> Sprite =
26
33
  Sprite(x: x, y: y, tex: tex, w: w, h: h, srcX: srcX, srcY: srcY, srcW: srcW, srcH: srcH, frame: frame, tint: Color.White, touch: Disabled)
27
34
 
28
35
  fun place(self) -> Place = place.at(self.x, self.y)
29
36
 
37
+ # The frame of a strip of `count` frames played at `fps` frames a second, `clock`
38
+ # seconds in, looping: `Sprite.cell(.., Sprite.frameAt(self.clock, 8.0, 4))`.
39
+ fun frameAt(clock: Float, fps: Float, count: Int) -> Int = Int(clock * fps) % count
40
+
30
41
  # Where the frame shown starts in the texture.
31
42
  fun frameX(self) -> Float = self.srcX + Float(self.frame) * self.srcW
32
43
 
@@ -34,13 +45,25 @@ struct Sprite[Actor, Sized, Touch](x: Float, y: Float, tex: Texture, w: Float, h
34
45
 
35
46
  fun touch(self) -> Touchable = self.touch
36
47
 
37
- fun paint(self, io: Io, m: Affine, alpha: Float) =
48
+ fun paintSelf(self, io: Io, m: Affine, alpha: Float) =
38
49
  drawSpriteFrame(io, m, alpha * self.tint.a, self.w, self.h, self.tint, self.tex, self.frameX(), self.srcY, self.srcW, self.srcH)
39
50
 
40
- # The region (srcX, srcY, srcW, srcH) of `tex` as a `w` by `h` picture at (0, 0), seen
51
+ # Draws a texture region `w` by `h` at the transform `m`, turned by `m`'s rotation: for
52
+ # your own sprite-like kinds. Paints with `alpha` in place of the colour's alpha, as
41
- # through `m`.
53
+ # `box.drawBox` does.
42
54
  fun drawSpriteFrame(io: Io, m: Affine, alpha: Float, w: Float, h: Float, color: Color, tex: Texture, srcX: Float, srcY: Float, srcW: Float, srcH: Float) =
43
55
  sx := w * m.scaleX()
44
56
  sy := h * m.scaleY()
45
57
  c := m.apply(Vec2(x: w / 2.0, y: h / 2.0))
46
58
  gfx.drawTextureEx(io, tex.id, srcX, srcY, srcW, srcH, c.x - sx / 2.0, c.y - sy / 2.0, sx, sy, m.rotation(), false, color.withAlpha(alpha))
59
+
60
+ test "a sprite shows its frame of its strip"
61
+ s := Sprite.cell(0.0, 0.0, Texture(id: 3), 48.0, 48.0, 16.0, 32.0, 16.0, 16.0, 2)
62
+ assert s.frameX() == 48.0
63
+ assert s.hit(Vec2(x: 47.0, y: 1.0))
64
+
65
+ test "a strip's frame follows the clock and loops"
66
+ assert Sprite.frameAt(0.0, 8.0, 4) == 0
67
+ assert Sprite.frameAt(0.13, 8.0, 4) == 1
68
+ assert Sprite.frameAt(0.5, 8.0, 4) == 0
69
+ assert Sprite.frameAt(9.0, 0.0, 1) == 0
std/game/Touch.plum CHANGED
@@ -2,7 +2,7 @@ module std
2
2
 
3
3
  import std/Bool
4
4
 
5
- # Whether an actor takes presses (std/game/Actor's `viewHit`): `Enabled`, it is hit where
5
+ # Whether an actor takes presses (std/game/View's `hitIn`): `Enabled`, it is hit where
6
6
  # it is (when it is `Sized`) and so is what is under it; `Disabled`, neither it nor
7
7
  # anything under it is; `ChildrenOnly`, what is under it is and it is not. An actor that
8
8
  # doesn't say is `ChildrenOnly`.
std/game/Tween.plum ADDED
@@ -0,0 +1,113 @@
1
+ module std
2
+
3
+ import std/Bool
4
+ import std/Float
5
+ import std/Int
6
+ import std/collections/List
7
+
8
+ # A value that goes from `from` to `to` over `secs` seconds along an `Easing`, `t` seconds
9
+ # in: a slide, a fade, a pulse. It is a plain value an actor or a screen keeps in a field
10
+ # and advances itself, on its tick action, by the tick's `dt`; never by a clock, so a run
11
+ # replays exactly.
12
+ #
13
+ # MenuScreen(..self, highlight: Tween.of(self.highlight.value(), 340.0, 0.15, QuadOut))
14
+ # Tick(dt) => MenuScreen(..self, highlight: self.highlight.advance(dt))
15
+ # Box.of(0.0, self.highlight.value(), ..) # in the view
16
+ # fun busy(self) -> Bool = !self.highlight.done() # an OnDemand screen ticks while it runs
17
+ #
18
+ # of from `from` to `to` over `secs` along `ease` (`Linear` unless given), not
19
+ # started
20
+ # advance the tween `dt` seconds further on
21
+ # value where it is now: `from` at the start, then along its easing, and exactly
22
+ # `to` once it is done
23
+ # done whether its time is up (within a nanosecond, so that 30 ticks of 1/60 s make
24
+ # half a second, as std/game/Screen's `Shift.doneAt` counts); a tween of no
25
+ # time is done from the start
26
+ struct Tween(from: Float, to: Float, secs: Float, ease: Easing, t: Float) =
27
+ Slack = 0.000000001
28
+
29
+ fun of(from: Float, to: Float, secs: Float, ease: Easing = Linear) -> Tween =
30
+ Tween(from: from, to: to, secs: secs, ease: ease, t: 0.0)
31
+
32
+ fun advance(self, dt: Float) -> Tween = Tween(..self, t: self.t + dt)
33
+
34
+ fun done(self) -> Bool = self.t >= self.secs - Tween.Slack
35
+
36
+ fun value(self) -> Float =
37
+ if self.done() then self.to else self.from + {self.to - self.from} * self.ease.apply(self.t / self.secs)
38
+
39
+ # The curve a tween follows: its progress `t` from 0 to 1 eased, as libGDX's
40
+ # `Interpolation`. Every one gives exactly 0 at 0 and 1 at 1.
41
+ #
42
+ # Linear t
43
+ # Smooth t * t * (3 - 2t), slow at both ends (scene2d's `smooth`)
44
+ # QuadIn, QuadOut, QuadInOut the square of t: slow at the start, at the end, at both
45
+ # (scene2d's `pow2In`, `pow2Out`, `pow2`)
46
+ # CubicIn, CubicOut, CubicInOut the cube (`pow3In`, `pow3Out`, `pow3`)
47
+ enum Easing =
48
+ | Linear
49
+ | Smooth
50
+ | QuadIn
51
+ | QuadOut
52
+ | QuadInOut
53
+ | CubicIn
54
+ | CubicOut
55
+ | CubicInOut
56
+
57
+ fun apply(self, t: Float) -> Float = match self
58
+ Linear => t
59
+ Smooth => t * t * {3.0 - 2.0 * t}
60
+ QuadIn => powIn(t, 2)
61
+ QuadOut => powOut(t, 2)
62
+ QuadInOut => powInOut(t, 2)
63
+ CubicIn => powIn(t, 3)
64
+ CubicOut => powOut(t, 3)
65
+ CubicInOut => powInOut(t, 3)
66
+
67
+ # `t` to the power `p`.
68
+ fun powIn(t: Float, p: Int) -> Float = 0.until(p).fold(1.0, |r, i| r * t)
69
+
70
+ # scene2d's `PowOut`: 1 - (1 - t)^p, written as it does.
71
+ fun powOut(t: Float, p: Int) -> Float =
72
+ if p % 2 == 0 then 1.0 - powIn(t - 1.0, p) else powIn(t - 1.0, p) + 1.0
73
+
74
+ # scene2d's `Pow`: the first half `PowIn`, the second `PowOut`, each squeezed into it.
75
+ fun powInOut(t: Float, p: Int) -> Float =
76
+ if t <= 0.5
77
+ powIn(t * 2.0, p) / 2.0
78
+ else if p % 2 == 0
79
+ 1.0 - powIn({t - 1.0} * 2.0, p) / 2.0
80
+ else
81
+ powIn({t - 1.0} * 2.0, p) / 2.0 + 1.0
82
+
83
+ # --- tests ---
84
+
85
+ test "every easing is exactly 0 at 0 and 1 at 1"
86
+ all := [Linear, Smooth, QuadIn, QuadOut, QuadInOut, CubicIn, CubicOut, CubicInOut]
87
+ assert all.all(|e| e.apply(0.0) == 0.0 && e.apply(1.0) == 1.0 && e.apply(0.5) > 0.0 && e.apply(0.5) < 1.0)
88
+ assert QuadIn.apply(0.5) == 0.25
89
+ assert QuadOut.apply(0.5) == 0.75
90
+ assert CubicIn.apply(0.5) == 0.125
91
+ assert CubicOut.apply(0.5) == 0.875
92
+ assert QuadInOut.apply(0.25) == 0.125
93
+ assert CubicInOut.apply(0.75) == 0.9375
94
+ assert Smooth.apply(0.5) == 0.5
95
+
96
+ test "a tween goes from its start along its easing and lands exactly on its end when its time is up"
97
+ t := Tween.of(10.0, 30.0, 0.5, QuadOut)
98
+ assert t.value() == 10.0
99
+ assert !t.done()
100
+ u := t.advance(0.25)
101
+ assert u.value() == 10.0 + 20.0 * 0.75
102
+ v := 0.until(15).fold(u, |x, i| x.advance(1.0 / 60.0))
103
+ assert v.done()
104
+ assert v.value() == 30.0
105
+ assert v.advance(1.0).value() == 30.0
106
+ still := Tween.of(5.0, 7.0, 0.0)
107
+ assert still.done()
108
+ assert still.value() == 7.0
109
+
110
+ test "half a second of ticks is done on the thirtieth"
111
+ t := 0.until(29).fold(Tween.of(0.0, 1.0, 0.5), |x, i| x.advance(1.0 / 60.0))
112
+ assert !t.done()
113
+ assert t.advance(1.0 / 60.0).done()
std/game/View.plum ADDED
@@ -0,0 +1,343 @@
1
+ module std
2
+
3
+ import std/Int
4
+ import std/Float
5
+ import std/Bool
6
+ import std/Str
7
+ import std/Option
8
+ import std/Slice
9
+ import std/collections/List
10
+ import std/math/math
11
+ import std/Io
12
+ import std/math/Vec2
13
+ import std/math/Affine
14
+ import std/math/Aabb
15
+ import std/game/Color
16
+ import std/game/Place
17
+ import std/game/Sized
18
+ import std/game/Touch
19
+ import std/game/Box
20
+ import std/game/Group
21
+ import std/game/Label
22
+ import std/game/Circle
23
+
24
+ # One thing a screen draws (std/game/Screen's `view`). Each kind of view is its own
25
+ # struct, with only its own fields, that implements `View`. A `View` is stateless: it says
26
+ # what to draw.
27
+ #
28
+ # place its `Place`: position, scale, rotation, the origin it turns about, and its
29
+ # `alpha`, which multiplies down through what is drawn under it
30
+ # view what is under it, made again each time it is walked, from its fields: a list
31
+ # of views (`Sprite`, `Circle`, ..) placed in its own coordinates. A `Group`,
32
+ # an `Overlay` or a kind of your own that takes children returns them. Empty
33
+ # by default
34
+ # visible whether it is drawn and hit, with what is under it; true by default (a ship
35
+ # blinking off says false). Its screen's `stepped` still steps it
36
+ # paintSelf what it draws itself, before its view, seen through `m` (its own coordinates
37
+ # to the screen's world) at `alpha` (the accumulated alpha of its places, its
38
+ # own included): a ready-made shape, or what no ready-made view draws (an
39
+ # additive glow, a line), with `gfx` through `m`. Nothing by default
40
+ #
41
+ # A view whose state advances each tick (its place, its clock) is an `Actor`, which
42
+ # extends `View` with `step(self, dt) -> Self`, its next version `dt` seconds on. The game
43
+ # steps the shown screen's actors each tick it gets, before its tick action is reduced
44
+ # (std/game/Screen's `steps` and `stepped`): a screen is a value, so the game cannot step
45
+ # an actor where it finds it in the view, and the screen's `stepped` puts each list of
46
+ # actors it holds through `stepAll` (`ship: self.ship.step(dt)`, `mines:
47
+ # view.stepAll(self.mines, dt)`).
48
+ #
49
+ # struct Walker[Actor](at: Place, speed: Float) =
50
+ # fun place(self) -> Place = self.at
51
+ # fun view(self) -> List<View> = [Box.of(0.0, 0.0, 10.0, 10.0, Color.Red)]
52
+ # fun step(self, dt: Float) -> Walker = Walker(..self, at: self.at.moveBy(self.speed * dt, 0.0))
53
+ #
54
+ # Beside `View` or `Actor`, a view may be:
55
+ #
56
+ # Sized it has bounds (std/game/Sized): culled when the screen `culls()`, and hit
57
+ # by the pointer when it takes presses
58
+ # Touch it says whether it takes presses (std/game/Touch: `Enabled`, `Disabled`,
59
+ # `ChildrenOnly`); one that doesn't say is `ChildrenOnly`
60
+ #
61
+ # The ready-made views are `Group`, `Box`, `Circle`, `Sprite`, `Label` and `Overlay`, all
62
+ # stateless.
63
+ #
64
+ # A view is drawn, not live: an item made inside `view` keeps nothing from one walk to the
65
+ # next, so each takes plain values read from its holder's fields (`Sprite(.., frame: ..)`,
66
+ # `Label.of(.., "{self.hp}", ..)`), and one that is not there is left out of the list. An
67
+ # actor held in a field (a balloon, a walker) is the very object in the view when it is
68
+ # walked: a press on it reaches the screen as that actor (std/game/ScreenSlice's
69
+ # `onPress`).
70
+ #
71
+ # The walks over a list of views are here, each going where the draw goes: an item, then
72
+ # its own view.
73
+ #
74
+ # paintView draws the visible items
75
+ # paintCulled draws them, skipping each `Sized` item whose bounds miss an area, with
76
+ # what is under it (a screen that `culls()`)
77
+ # drawnIn lists what they draw, each item with its transform and alpha (`Drawn`):
78
+ # std/game/headless's finders look in it
79
+ # hitIn the item a press at a point is on, top-most first: what std's delivery
80
+ # gives a slice's `onPress`
81
+ # worldIn where they draw a given view: its transform (std/game/headless's
82
+ # `worldOf`)
83
+ #
84
+ # and the steps a screen's `stepped` uses: `stepAll` (each actor of a list of one kind)
85
+ # and `stepIn` (each `Actor` of a list of views, the others as they are).
86
+ trait View =
87
+ fun place(self) -> Place
88
+
89
+ fun view(self) -> List<View> = Nil
90
+
91
+ fun visible(self) -> Bool = true
92
+
93
+ fun paintSelf(self, io: Io, m: Affine, alpha: Float) = Unit
94
+
95
+ # A view with state that advances each tick: its next version `dt` seconds on. The game
96
+ # has the shown screen step its actors each tick (std/game/Screen's `stepped`), before the
97
+ # tick action is reduced.
98
+ trait Actor[View] =
99
+ fun step(self, dt: Float) -> Self
100
+
101
+ # Each of `xs` stepped by `dt`, in order: what a screen's `stepped` does with a list of
102
+ # actors it holds.
103
+ fun stepAll<T: Actor>(xs: List<T>, dt: Float) -> List<T> = xs.map(|x| x.step(dt))
104
+
105
+ # Each `Actor` of `items` stepped by `dt`, in order, and the other views as they are.
106
+ fun stepIn(items: List<View>, dt: Float) -> List<View> = items.map(|x| stepOne(x, dt))
107
+
108
+ fun stepOne(x: View, dt: Float) -> View = match x
109
+ Actor as a => a.step(dt)
110
+ _ => x
111
+
112
+ # Each of `xs` as a `View`: a screen's `List<Mine>` in its view (a `List<Mine>` is not a
113
+ # `List<View>`).
114
+ fun all<T: View>(xs: List<T>) -> List<View> = xs.map(|x| one(x))
115
+
116
+ fun one<T: View>(x: T) -> View = x
117
+
118
+ # Draws the visible `items`, `m` and `alpha` being those of what holds them (the screen's
119
+ # camera, or the view whose view they are): each through its own place under `m`, at
120
+ # `alpha` times its place's alpha, its `paintSelf` and then its view.
121
+ fun paintView(io: Io, items: List<View>, m: Affine, alpha: Float) = items.each(|k| paintItem(io, k, m, alpha))
122
+
123
+ fun paintItem(io: Io, a: View, m: Affine, alpha: Float) =
124
+ if a.visible()
125
+ at := a.place()
126
+ mk := at.under(m)
127
+ ak := alpha * at.alpha
128
+ a.paintSelf(io, mk, ak)
129
+ paintView(io, a.view(), mk, ak)
130
+
131
+ # `paintView`, skipping each `Sized` item whose bounds, through its transform, miss
132
+ # `area` (in the coordinates `m` maps to), with what is under it.
133
+ fun paintCulled(io: Io, items: List<View>, m: Affine, alpha: Float, area: Aabb) =
134
+ items.each(|a|
135
+ if a.visible()
136
+ at := a.place()
137
+ mk := at.under(m)
138
+ if !missesArea(a, mk, area)
139
+ ak := alpha * at.alpha
140
+ a.paintSelf(io, mk, ak)
141
+ paintCulled(io, a.view(), mk, ak, area)
142
+ )
143
+
144
+ # One entry of a draw list: an item drawn, its transform (its own coordinates to the
145
+ # world's) and its alpha.
146
+ struct Drawn(actor: View, m: Affine, alpha: Float)
147
+
148
+ # Pushes onto `out` what `items` draw, in the order drawn: each visible item with its
149
+ # transform and its alpha, then what its view draws. With `cull`, a `Sized` item whose
150
+ # bounds miss `area` is left out with what is under it.
151
+ fun drawnIn(items: List<View>, m: Affine, alpha: Float, out: Slice<Drawn>, area: Aabb, cull: Bool) =
152
+ items.each(|a|
153
+ if a.visible()
154
+ at := a.place()
155
+ mk := at.under(m)
156
+ if !cull || !missesArea(a, mk, area)
157
+ ak := alpha * at.alpha
158
+ out.push(Drawn(actor: a, m: mk, alpha: ak))
159
+ drawnIn(a.view(), mk, ak, out, area, cull)
160
+ )
161
+
162
+ # The item of `items` that a press at `p` (in the coordinates `items` are placed in) is
163
+ # on: the top-most visible item that takes presses (`Sized`, and `Enabled`,
164
+ # std/game/Touch) and whose `hit` says the point is on it, what is drawn later before what
165
+ # is drawn earlier, what is under an item before the item. A `Disabled` or invisible item
166
+ # is passed over with what is under it. None for none.
167
+ fun hitIn(items: List<View>, p: Vec2) -> Option<View> = hitAmong(items.reverse(), p)
168
+
169
+ fun hitAmong(rev: List<View>, p: Vec2) -> Option<View> = match rev
170
+ Nil => None
171
+ Cons(k, rest) => match hitItem(k, p)
172
+ Some(a) => Some(a)
173
+ None => hitAmong(rest, p)
174
+
175
+ fun hitItem(a: View, p: Vec2) -> Option<View> =
176
+ t := touchOf(a)
177
+ if t.disabled() || !a.visible()
178
+ None
179
+ else
180
+ q := a.place().toLocal(p)
181
+ under := hitIn(a.view(), q)
182
+ if under.isSome()
183
+ under
184
+ else if t.enabled() && sizedHit(a, q)
185
+ Some(a)
186
+ else
187
+ None
188
+
189
+ # How `a` takes presses: its own `touch`, or `ChildrenOnly` if it doesn't say.
190
+ fun touchOf(a: View) -> Touchable = match a
191
+ Touch as t => t.touch()
192
+ _ => ChildrenOnly
193
+
194
+ # Whether `a` is `Sized` and says the point `q` (in its own coordinates) is on it.
195
+ fun sizedHit(a: View, q: Vec2) -> Bool = match a
196
+ Sized as s => s.hit(q)
197
+ _ => false
198
+
199
+ # The transform of the view `a` (its own coordinates to those `m` maps to) where `items`
200
+ # draw it, found by identity through each item's view, visible or not; None if it is not
201
+ # there. std/game/headless's `worldOf` and `click` find a view this way.
202
+ fun worldIn(items: List<View>, a: View, m: Affine) -> Option<Affine> = match items
203
+ Nil => None
204
+ Cons(x, rest) =>
205
+ mk := x.place().under(m)
206
+ if @sameRef(x, a)
207
+ Some(mk)
208
+ else
209
+ inView := worldIn(x.view(), a, mk)
210
+ if inView.isSome() then inView else worldIn(rest, a, m)
211
+
212
+ # Whether `a` is `Sized` and its bounds, seen through `m`, miss `area`.
213
+ fun missesArea(a: View, m: Affine, area: Aabb) -> Bool = match a
214
+ Sized as s => !through(s.bounds(), m).overlaps(area)
215
+ _ => false
216
+
217
+ # The box around `b` seen through `m`.
218
+ fun through(b: Aabb, m: Affine) -> Aabb =
219
+ p1 := m.apply(b.min)
220
+ p2 := m.apply(Vec2(x: b.max.x, y: b.min.y))
221
+ p3 := m.apply(b.max)
222
+ p4 := m.apply(Vec2(x: b.min.x, y: b.max.y))
223
+ Aabb(
224
+ min: Vec2(x: p1.x.min(p2.x).min(p3.x).min(p4.x), y: p1.y.min(p2.y).min(p3.y).min(p4.y)),
225
+ max: Vec2(x: p1.x.max(p2.x).max(p3.x).max(p4.x), y: p1.y.max(p2.y).max(p3.y).max(p4.y)))
226
+
227
+ # --- tests ---
228
+
229
+ # A view that logs where it is painted (the x of its origin) and at what alpha.
230
+ struct ViewProbe[View](x: Float, log: Slice<Float>, fade: Float) =
231
+ fun place(self) -> Place = place.at(self.x, 0.0).fade(self.fade)
232
+
233
+ fun paintSelf(self, io: Io, m: Affine, alpha: Float) =
234
+ self.log.push(m.e)
235
+ self.log.push(alpha)
236
+
237
+ fun probeAt(x: Float, log: Slice<Float>) -> View = ViewProbe(x: x, log: log, fade: 1.0)
238
+
239
+ # A view drawn by its view, which counts each call into `views`: its probes, one shown
240
+ # only while `lit`, one in a group, and a nested viewed one.
241
+ struct Viewed[View](x: Float, log: Slice<Float>, views: Slice<Int>, lit: Bool, inner: Bool) =
242
+ fun place(self) -> Place = place.at(self.x, 0.0).fade(0.5)
243
+
244
+ fun view(self) -> List<View> =
245
+ self.views.push(1)
246
+ first: List<View> := [probeAt(1.0, self.log)]
247
+ lit: List<View> := if self.lit then [probeAt(2.0, self.log)] else Nil
248
+ grouped: List<View> := [Group.of(10.0, 0.0, [ViewProbe(x: 4.0, log: self.log, fade: 0.5)])]
249
+ inner: List<View> := if self.inner then [Viewed(x: 100.0, log: self.log, views: self.views, lit: true, inner: false)] else Nil
250
+ first.append(lit).append(grouped).append(inner)
251
+
252
+ # A view that paints itself (-1) and then has its view drawn, and is invisible unless
253
+ # `shows`.
254
+ struct SelfPainted[View](log: Slice<Float>, shows: Bool) =
255
+ fun place(self) -> Place = place.at(0.0, 0.0)
256
+
257
+ fun visible(self) -> Bool = self.shows
258
+
259
+ fun view(self) -> List<View> = [probeAt(3.0, self.log)]
260
+
261
+ fun paintSelf(self, io: Io, m: Affine, alpha: Float) = self.log.push(-1.0)
262
+
263
+ # An actor that adds up its steps.
264
+ struct Stepper[Actor](time: Float) =
265
+ fun place(self) -> Place = place.at(0.0, 0.0)
266
+
267
+ fun step(self, dt: Float) -> Stepper = Stepper(time: self.time + dt)
268
+
269
+ # A group turned a quarter.
270
+ struct TurnedGroup[View](x: Float, y: Float, children: List<View>) =
271
+ fun place(self) -> Place = place.at(self.x, self.y).rotateTo(Float.HalfPi)
272
+
273
+ fun view(self) -> List<View> = self.children
274
+
275
+ test "a view's view is drawn each time it is drawn, under its place"
276
+ log := Slice<Float>()
277
+ views := Slice<Int>()
278
+ v := Viewed(x: 1000.0, log: log, views: views, lit: true, inner: true)
279
+ assert views.length() == 0
280
+ paintView(io, [v], Affine.Identity, 1.0)
281
+ assert views.length() == 2
282
+ # x then alpha of each probe painted, in order: the inner Viewed's (at 1100, alpha
283
+ # 0.25) come after its parent's own.
284
+ expect := [1001.0, 0.5, 1002.0, 0.5, 1014.0, 0.25, 1101.0, 0.25, 1102.0, 0.25, 1114.0, 0.125]
285
+ assert log.length() == expect.length()
286
+ assert 0.until(expect.length()).all(|i| log.at(i) == expect.at(i))
287
+ paintView(io, [v], Affine.Identity, 1.0)
288
+ assert views.length() == 4
289
+
290
+ test "an item left out is not drawn; a view paints itself, then its view; an invisible one draws nothing"
291
+ log := Slice<Float>()
292
+ views := Slice<Int>()
293
+ paintView(io, [Viewed(x: 0.0, log: log, views: views, lit: false, inner: false)], Affine.Identity, 1.0)
294
+ assert log.length() == 4
295
+ log.clear()
296
+ paintView(io, [SelfPainted(log: log, shows: true)], Affine.Identity, 1.0)
297
+ assert log.length() == 3 && log.at(0) == -1.0 && log.at(1) == 3.0
298
+ log.clear()
299
+ paintView(io, [SelfPainted(log: log, shows: false)], Affine.Identity, 1.0)
300
+ assert log.isEmpty()
301
+ found := Slice<Drawn>()
302
+ drawnIn([SelfPainted(log: log, shows: false), Box.of(0.0, 0.0, 1.0, 1.0, Color.White)], Affine.Identity, 1.0, found, Aabb.of(0.0, 0.0, 0.0, 0.0), false)
303
+ assert found.length() == 1
304
+
305
+ test "stepping a list of actors steps each in order; stepping a view's items steps only its actors"
306
+ steppers := stepAll([Stepper(time: 0.0), Stepper(time: 1.0)], 0.5)
307
+ assert steppers.at(0).time == 0.5 && steppers.at(1).time == 1.5
308
+ items: List<View> := [Stepper(time: 0.0), Box.of(0.0, 0.0, 1.0, 1.0, Color.White), Stepper(time: 2.0)]
309
+ stepped := stepIn(stepIn(items, 0.5), 0.25)
310
+ times := stepped.map(|v| match v
311
+ Stepper as s => s.time
312
+ _ => -1.0)
313
+ assert times.at(0) == 0.75 && times.at(1) == -1.0 && times.at(2) == 2.75
314
+
315
+ test "a press is on the top-most item that takes it, through groups and their turns, never under a Disabled one"
316
+ top := Box(x: 10.0, y: 10.0, w: 20.0, h: 20.0, color: Color.White, touch: Enabled)
317
+ under := Box(x: 10.0, y: 10.0, w: 20.0, h: 20.0, color: Color.White, touch: Enabled)
318
+ inner := Box(x: 0.0, y: 0.0, w: 10.0, h: 10.0, color: Color.White, touch: Enabled)
319
+ turned := TurnedGroup(x: 200.0, y: 100.0, children: [Group.of(50.0, 0.0, [inner])])
320
+ hidden := Group(x: 0.0, y: 0.0, touch: Disabled, children: [Box(x: 400.0, y: 400.0, w: 50.0, h: 50.0, color: Color.White, touch: Enabled)])
321
+ items: List<View> := [under, top, turned, hidden, Label.of(0.0, 0.0, "deco", 24.0, Color.White)]
322
+ assert @sameRef(hitIn(items, Vec2(x: 15.0, y: 15.0)).unwrap(), top)
323
+ # The inner box is 50 along the group's x, which is turned a quarter: 50 down from it.
324
+ assert @sameRef(hitIn(items, Vec2(x: 195.0, y: 155.0)).unwrap(), inner)
325
+ assert hitIn(items, Vec2(x: 420.0, y: 420.0)).isNone()
326
+ assert hitIn(items, Vec2(x: 2.0, y: 2.0)).isNone()
327
+ c := worldIn(items, inner, Affine.Identity).unwrap().apply(Vec2(x: 0.0, y: 0.0))
328
+ assert math.near(c.x, 200.0, 0.001) && math.near(c.y, 150.0, 0.001)
329
+ assert worldIn(items, Box.of(0.0, 0.0, 1.0, 1.0, Color.White), Affine.Identity).isNone()
330
+
331
+ test "the draw list holds every item and what is under it, and culling leaves out what misses the area"
332
+ items: List<View> := [Box.of(0.0, 0.0, 10.0, 10.0, Color.White), Group.of(5000.0, 0.0, [Circle.of(0.0, 0.0, 2.0, Color.White), Label.of(0.0, 0.0, "far", 24.0, Color.White)]), Box.of(5000.0, 0.0, 10.0, 10.0, Color.White)]
333
+ all := Slice<Drawn>()
334
+ drawnIn(items, Affine.Identity, 1.0, all, Aabb.of(0.0, 0.0, 0.0, 0.0), false)
335
+ assert all.length() == 5
336
+ culled := Slice<Drawn>()
337
+ drawnIn(items, Affine.Identity, 1.0, culled, Aabb.of(0.0, 0.0, 800.0, 600.0), true)
338
+ # The group is not Sized, so it stays; its sized children and the far box go.
339
+ assert culled.length() == 2
340
+
341
+ test "a box seen through a turn is bounded by its turned corners"
342
+ b := through(Aabb.of(0.0, 0.0, 10.0, 20.0), Affine(a: 0.0, b: 1.0, c: -1.0, d: 0.0, e: 100.0, f: 0.0))
343
+ assert b.min.x == 80.0 && b.max.x == 100.0 && b.min.y == 0.0 && b.max.y == 10.0
std/game/Viewport.plum CHANGED
@@ -22,16 +22,18 @@ enum Scaling = Fit | Fill | Stretch | Extend | Pixels
22
22
  # A world `w` by `h` on a screen `screenW` by `screenH` pixels, by a `Scaling`: the world
23
23
  # point at the screen's top-left (`x`, `y`) and the pixels per world unit along each axis
24
24
  # (`sx`, `sy`, the same but for `Stretch`). The game makes one for the shown screen from
25
- # its `size()` and `viewport()` (std/game/Screen) and the screen's size in pixels, and
25
+ # its `size()` and `viewport()` (std/game/Screen) and the screen's size in pixels, then
26
+ # the screen's `camera(base)` (std/game/Screen's `cameraOf`), and draws and hit-tests the
26
- # draws and hit-tests the screen's view through it.
27
+ # screen's view through it. `moved` is whether a screen's `camera` moved or zoomed it away
28
+ # from where its scaling puts it (`lookAt`): then what it shows is what is on the window.
27
29
  #
28
30
  # v := Viewport.of(Fit, 800.0, 600.0).update(1600.0, 600.0) # x = -400, y = 0, sx = sy = 1
29
31
  # v.toWorld(800.0, 300.0) # (400, 300)
30
- struct Viewport(scaling: Scaling, w: Float, h: Float, screenW: Float, screenH: Float, x: Float, y: Float, sx: Float, sy: Float) =
32
+ struct Viewport(scaling: Scaling, w: Float, h: Float, screenW: Float, screenH: Float, x: Float, y: Float, sx: Float, sy: Float, moved: Bool) =
31
33
  # The world `w` by `h` on a screen as large as itself, which every scaling shows
32
34
  # unscaled at (0, 0).
33
35
  fun of(scaling: Scaling, w: Float, h: Float) -> Viewport =
34
- Viewport(scaling: scaling, w: w, h: h, screenW: w, screenH: h, x: 0.0, y: 0.0, sx: 1.0, sy: 1.0)
36
+ Viewport(scaling: scaling, w: w, h: h, screenW: w, screenH: h, x: 0.0, y: 0.0, sx: 1.0, sy: 1.0, moved: false)
35
37
 
36
38
  # The camera for a screen `sw` by `sh` pixels.
37
39
  fun update(self, sw: Float, sh: Float) -> Viewport =
@@ -47,6 +49,14 @@ struct Viewport(scaling: Scaling, w: Float, h: Float, screenW: Float, screenH: F
47
49
  fun centred(self, s: Float) -> Viewport =
48
50
  Viewport(..self, sx: s, sy: s, x: 0.0 - {self.screenW / s - self.w} / 2.0, y: 0.0 - {self.screenH / s - self.h} / 2.0)
49
51
 
52
+ # This camera on the same window, moved so that the world point (x, y) is at the
53
+ # window's centre and `zoom` times as close: what a screen's `camera` returns to follow
54
+ # something or zoom (std/game/Screen).
55
+ fun lookAt(self, x: Float, y: Float, zoom: Float = 1.0) -> Viewport =
56
+ sx := self.sx * zoom
57
+ sy := self.sy * zoom
58
+ Viewport(..self, sx: sx, sy: sy, x: x - self.screenW / sx / 2.0, y: y - self.screenH / sy / 2.0, moved: true)
59
+
50
60
  # A screen pixel in world coordinates.
51
61
  fun toWorld(self, px: Float, py: Float) -> Vec2 = Vec2(x: px / self.sx + self.x, y: py / self.sy + self.y)
52
62
 
@@ -62,10 +72,22 @@ struct Viewport(scaling: Scaling, w: Float, h: Float, screenW: Float, screenH: F
62
72
 
63
73
  # The world rectangle that is shown: the world itself for `Fit` and `Stretch`, the part
64
74
  # on the screen for the others.
75
+ # A moved camera (`lookAt`) shows what is on the window.
65
- fun visible(self) -> Aabb = match self.scaling
76
+ fun visible(self) -> Aabb =
77
+ if self.moved
78
+ self.screen()
79
+ else
80
+ match self.scaling
66
- Fit => Aabb.of(0.0, 0.0, self.w, self.h)
81
+ Fit => Aabb.of(0.0, 0.0, self.w, self.h)
67
- Stretch => Aabb.of(0.0, 0.0, self.w, self.h)
82
+ Stretch => Aabb.of(0.0, 0.0, self.w, self.h)
68
- _ => self.screen()
83
+ _ => self.screen()
84
+
85
+ # The world's size as shown: the grown world for `Extend` and `Pixels`, the world itself
86
+ # for the others.
87
+ fun worldSize(self) -> Vec2 = match self.scaling
88
+ Extend => Vec2(x: self.screenW / self.sx, y: self.screenH / self.sy)
89
+ Pixels => Vec2(x: self.screenW, y: self.screenH)
90
+ _ => Vec2(x: self.w, y: self.h)
69
91
 
70
92
  test "fit letterboxes and centres; extend shows more world; the transform maps world to pixels"
71
93
  v := Viewport.of(Fit, 800.0, 600.0).update(1600.0, 600.0)
@@ -82,3 +104,13 @@ test "fit letterboxes and centres; extend shows more world; the transform maps w
82
104
  assert f.sx == 2.0 && f.y == 150.0
83
105
  p := Viewport.of(Pixels, 800.0, 600.0).update(1600.0, 600.0)
84
106
  assert p.sx == 1.0 && p.x == 0.0
107
+
108
+ test "a camera looks at a world point, zoomed, and then shows what is on the window"
109
+ v := Viewport.of(Fit, 800.0, 600.0).update(1600.0, 600.0)
110
+ l := v.lookAt(100.0, 50.0, 2.0)
111
+ assert l.sx == 2.0 && l.sy == 2.0
112
+ assert l.toWorld(800.0, 300.0) == Vec2(x: 100.0, y: 50.0)
113
+ assert l.visible() == Aabb(min: Vec2(x: -300.0, y: -100.0), max: Vec2(x: 500.0, y: 200.0))
114
+ assert v.lookAt(400.0, 300.0).toWorld(0.0, 0.0) == Vec2(x: -400.0, y: 0.0)
115
+ assert !v.moved && l.moved
116
+ assert Viewport.of(Extend, 800.0, 600.0).update(1600.0, 600.0).worldSize() == Vec2(x: 1600.0, y: 600.0)
std/game/gfx.plum CHANGED
@@ -24,9 +24,13 @@ extern fun screenHeight(io: Io) -> Float
24
24
  extern fun frameTime(io: Io) -> Float
25
25
  extern fun clear(io: Io, c: Color)
26
26
  extern fun drawRect(io: Io, x: Float, y: Float, w: Float, h: Float, c: Color)
27
+ # The rect (x, y, w, h) turned `rotation` radians clockwise about its centre.
28
+ extern fun drawRectEx(io: Io, x: Float, y: Float, w: Float, h: Float, rotation: Float, c: Color)
27
29
  extern fun drawCircle(io: Io, x: Float, y: Float, r: Float, c: Color)
28
30
  extern fun drawLine(io: Io, x1: Float, y1: Float, x2: Float, y2: Float, thickness: Float, c: Color)
29
31
  extern fun drawText(io: Io, s: Str, x: Float, y: Float, size: Float, c: Color)
32
+ # `s` with its top-left at (x, y), turned `rotation` radians clockwise about that point.
33
+ extern fun drawTextEx(io: Io, s: Str, x: Float, y: Float, size: Float, rotation: Float, c: Color)
30
34
  extern fun setCamera(io: Io, x: Float, y: Float, scale: Float)
31
35
  extern fun resetCamera(io: Io)
32
36
  # Loads any image the host decodes (PNG at least); -1 on failure.
std/game/headless.plum CHANGED
@@ -13,7 +13,8 @@ import std/math/Affine
13
13
  import std/math/Aabb
14
14
  import std/game/input
15
15
  import std/game/Replay
16
- import std/game/Actor
16
+ import std/game/View
17
+ import std/game/Effects
17
18
  import std/game/Sized
18
19
  import std/game/Label
19
20
  import std/game/Viewport
@@ -35,8 +36,8 @@ import std/game/Game
35
36
  # A rig is a value, like the game in it: each input and each tick returns the next rig.
36
37
  #
37
38
  # `mount(io, screen)` makes a game of the one screen; `play(io, game)` takes a whole game.
38
- # Either sizes the view to `DefaultW` by `DefaultH` (800 by 600; `resize(w, h)` changes
39
+ # Either sizes the window to `DefaultW` by `DefaultH` pixels (800 by 600; `resize(w, h)`
39
- # it), as the host's first frame would. The rig is generic over the screen's type, so
40
+ # changes it), as the host's first frame would. The rig is generic over the screen's type, so
40
41
  # `t.screen` is the screen itself as the last tick left it (for `play`, the game's first
41
42
  # screen, a `Screen`). There is no host: the test's `io` draws and plays nothing.
42
43
  #
@@ -46,16 +47,17 @@ import std/game/Game
46
47
  # and not held after
47
48
  # hold(key) the key goes down and stays held, every tick, until `release(key)`
48
49
  # click(actor) a press and release at the actor's centre (its bounds' centre if it
49
- # is `Sized`, else its origin), in screen pixels: it goes through the
50
+ # is `Sized`, else its origin), in screen pixels through the camera
51
+ # (an item of the hud, one unit a pixel): it goes through the game's
50
- # game's real hit test, so what is in front of the actor gets it. An
52
+ # real hit test, so what is in front of the actor gets it. An actor
51
- # actor not in the view stops the test
53
+ # in neither the view nor the hud stops the test
52
54
  # clickAt(x, y) a press and release at a screen point
53
55
  # pointerMove(x, y) the pointer moves there
54
56
  # send(e) any `InputEvent`, raw; what is held follows it
55
57
  # next(held, evs) the next tick's input is exactly that
56
58
  #
57
59
  # `dispatch(a)` dispatches an action to the shown screen as its reducer would, then runs
58
- # its effects and what they ask, as the end of a tick does.
60
+ # what ends a tick: its effects with what they ask, an undo, a redo or a rewind included.
59
61
  #
60
62
  # Time: `tick()` runs one tick of the game's own path (`Game.step`: the screen's mapping,
61
63
  # its reducer, the transition, the effects and what they ask of the game), with the input
@@ -63,16 +65,16 @@ import std/game/Game
63
65
  # `tick(dt)` runs one of `dt` seconds instead. `frame(input, frameDt)` is the host's
64
66
  # frame, the `Clock` turning wall time into ticks, for scripted runs.
65
67
  #
66
- # Reading: `find<T>()` lists the items of type `T` the shown screen's view draws, in the
68
+ # Reading, all from the shown screen's view and then its `hud`: `find<T>()` lists the
67
- # order drawn; `first<T>()` is the first (none stops the test with "headless: first: no
69
+ # items of type `T` they draw, in the order drawn; `first<T>()` is the first (none stops the test with "headless: first: no
68
70
  # actor of the type asked for is in the view"); `count<T>()` counts them. `text(label)` is
69
- # what a `Label` shows, `shown(actor)` whether the view draws the actor, `hit(x, y)` what a
71
+ # what a `Label` shows, `shown(actor)` whether the view or the hud draws the actor,
70
- # press at that screen pixel lands on, `worldOf(actor)` where the view draws it,
72
+ # `hit(x, y)` what a press at that screen pixel lands on (the hud first),
71
- # `toWorld(x, y)` a screen pixel in the world, `drawn()` what the frame draws.
73
+ # `worldOf(actor)` where the view draws it, `toWorld(x, y)` a screen pixel in the world,
74
+ # `drawn()` what the frame draws (`Game.drawList`).
72
75
  #
73
76
  # What came out of the last `tick` or `ticks`: `effects<A>()` lists the actions of type `A`
74
- # whose effects ran, in order; `restarted()` whether an effect asked for a restart,
75
- # `wentTo()` the screen one asked to go to last, `exited()` whether the game has exited.
77
+ # whose effects ran, in order; `wentTo()` the screen one asked to go to last, `exited()` whether the game has exited.
76
78
  # `showing()` names the screen shown. `record(seed)`, `recorded()` and `replay(r)` record
77
79
  # and replay the game (std/game/Replay).
78
80
  #
@@ -101,22 +103,22 @@ fun play(io: Io, game: Game) -> TestRig<Screen> = rigOf(io, game, game.screens.a
101
103
  fun playWith(io: Io, game: Game) -> TestRig<Screen> = rigOf(io, game.timeTravel(History.Cap), game.screens.at(0))
102
104
 
103
105
  fun rigOf<S>(io: Io, game: Game, screen: S) -> TestRig<S> =
104
- view := Vec2(x: DefaultW, y: DefaultH)
106
+ pixels := Vec2(x: DefaultW, y: DefaultH)
105
107
  TestRig(
106
- io: io, game: game.resized(view), screen: screen, view: view, held: Held.none(), events: Nil, pos: Vec2(x: 0.0, y: 0.0),
108
+ io: io, game: game.resized(pixels), screen: screen, pixels: pixels, held: Held.none(), events: Nil, pos: Vec2(x: 0.0, y: 0.0),
107
109
  ran: Nil, asks: Nil, clock: Clock.create(), recording: false, log: Replay.create(0))
108
110
 
109
- # A game run headless (see the top of this file): the view's size, what is held, the input
111
+ # A game run headless (see the top of this file): the window's size, what is held, the input
110
112
  # waiting for the next tick, the pointer, what the last ticks gave (the effects that ran,
111
113
  # what they asked of the game), and the clock and recording of `frame` and `record`.
112
114
  struct TestRig<S>(
113
- io: Io, game: Game, screen: S, view: Vec2, held: Held, events: List<InputEvent>, pos: Vec2,
115
+ io: Io, game: Game, screen: S, pixels: Vec2, held: Held, events: List<InputEvent>, pos: Vec2,
114
116
  ran: List<Effect>, asks: List<Ask>, clock: Clock, recording: Bool, log: Replay) =
115
117
 
116
- # The view is `w` by `h` pixels from now on: every screen is told at once.
118
+ # The window is `w` by `h` pixels from now on.
117
119
  fun resize(self, w: Float, h: Float) -> TestRig<S> =
118
120
  v := Vec2(x: w, y: h)
119
- TestRig(..self, view: v, game: self.game.resized(v)).follow()
121
+ TestRig(..self, pixels: v, game: self.game.resized(v)).follow()
120
122
 
121
123
  fun press(self, key: Int) -> TestRig<S> =
122
124
  TestRig(..self, events: self.events.append([KeyDown(key: key), KeyUp(key: key)]), held: self.held.after(KeyUp(key: key)))
@@ -125,7 +127,7 @@ struct TestRig<S>(
125
127
 
126
128
  fun release(self, key: Int) -> TestRig<S> = if self.held.isDown(key) then self.send(KeyUp(key: key)) else self
127
129
 
128
- fun click(self, a: Actor) -> TestRig<S> =
130
+ fun click(self, a: View) -> TestRig<S> =
129
131
  p := self.centreOf(a)
130
132
  self.clickAt(p.x, p.y)
131
133
 
@@ -141,17 +143,19 @@ struct TestRig<S>(
141
143
  TestRig(..self, held: held, events: events, pos: events.fold(self.pos, |p, e| e.position().unwrapOr(p)))
142
144
 
143
145
  # Where the actor `a` is clicked, in screen pixels: the centre of its bounds if it is
144
- # `Sized`, else its origin, through its transform and the screen's viewport.
146
+ # `Sized`, else its origin, through its transform and the screen's camera (or, for an
147
+ # item of the `hud`, its transform alone).
145
- fun centreOf(self, a: Actor) -> Vec2 =
148
+ fun centreOf(self, a: View) -> Vec2 =
146
- m := self.worldOf(a)
147
- if m.isNone()
148
- crash "headless: click: the actor is not in the view"
149
149
  p := match a
150
150
  Sized as s =>
151
151
  b := s.bounds()
152
152
  Vec2(x: {b.min.x + b.max.x} / 2.0, y: {b.min.y + b.max.y} / 2.0)
153
153
  _ => Vec2(x: 0.0, y: 0.0)
154
+ match self.worldOf(a)
154
- self.cam().toScreen(m.unwrap().apply(p))
155
+ Some(m) => self.game.toScreen(m.apply(p))
156
+ None => match view.worldIn(self.game.screen().hud(self.pixels), a, Affine.Identity)
157
+ Some(h) => h.apply(p)
158
+ None => notInView()
155
159
 
156
160
  fun tick(self, dt: Float = Clock.Tick) -> TestRig<S> = self.forget().step(dt)
157
161
 
@@ -172,21 +176,22 @@ struct TestRig<S>(
172
176
  fun clockTicked(self) -> TestRig<S> = TestRig(..self, clock: self.clock.ticked())
173
177
 
174
178
  # Dispatches `a` to the shown screen as its reducer would dispatch it (reduced at once,
175
- # with what its reducer dispatches), then runs the effects with what they ask of the
179
+ # with what its reducer dispatches), then runs what ends a tick: the effects with what
180
+ # they ask of the game, an undo, a redo or a rewind included. What it gave is read as a
176
- # game. What it gave is read as a tick's.
181
+ # tick's. An `OnDemand` screen is woken for the next tick.
177
182
  fun dispatch<A>(self, a: A) -> TestRig<S> =
178
183
  g := self.game
179
184
  match g.screen()
180
185
  ScreenSlice<A> as sl =>
181
186
  q := Slice<A>()
182
- screenslice.Dispatching.push(ActionSink(queue: q))
187
+ effects.startDispatch(ActionSink(queue: q))
183
188
  next := sl.reduce(a)
184
189
  q.push(a)
185
- screenslice.Dispatching.removeAt(screenslice.Dispatching.length() - 1)
190
+ effects.endDispatch()
186
191
  final: ScreenSlice<A> := next
187
- fx: List<Effect> := List.fromSlice(q).map(|x| screenslice.queued(final, x))
192
+ fx: List<Effect> := List.fromSlice(q).map(|x| effects.queued(final, x))
188
- withScreen := Game(..g, screens: game.setAt(g.screens, g.current, next), wake: true, dirty: true)
193
+ withScreen := Game(..g, screens: game.setAt(g.screens, g.current, next), wake: true, dirty: true, ran: Nil, asked: Nil)
189
- TestRig(..self.forget(), game: withScreen).kept(withScreen.apply(self.io, fx))
194
+ TestRig(..self.forget(), game: withScreen).kept(withScreen.apply(self.io, fx).travelAsked(self.io))
190
195
  _ =>
191
196
  crash "headless: dispatch: the screen shown takes no actions of that type"
192
197
 
@@ -205,7 +210,7 @@ struct TestRig<S>(
205
210
  else
206
211
  if self.recording
207
212
  self.log.ticks.push(input)
208
- self.kept(self.game.step(self.io, input, dt, self.view))
213
+ self.kept(self.game.step(self.io, input, dt, self.pixels))
209
214
 
210
215
  # The rig with `g`, keeping what its last tick gave.
211
216
  fun kept(self, g: Game) -> TestRig<S> =
@@ -234,23 +239,23 @@ struct TestRig<S>(
234
239
 
235
240
  fun moved(self) -> Bool = self.game.moved
236
241
 
237
- # The viewport the shown screen is drawn through.
242
+ # The camera the shown screen is seen through.
238
- fun cam(self) -> Viewport = self.game.camera(self.game.screen())
243
+ fun cam(self) -> Viewport = self.game.camera(self.game.current)
239
244
 
240
- # What the shown screen's view holds now, each shown item with its transform, not culled.
245
+ # What the shown screen's view and then its hud hold now, the visible items, culled or
246
+ # not, each with its transform.
241
247
  fun viewed(self) -> List<Drawn> =
242
248
  ds := Slice<Drawn>()
243
- actor.viewDrawn(self.game.screen().view(), Affine.Identity, 1.0, ds, Aabb.of(0.0, 0.0, 0.0, 0.0), false)
244
- List.fromSlice(ds)
245
-
246
- # What the frame draws now, culled if the screen culls, each item with its transform
247
- # (in the world) and alpha.
248
- fun drawn(self) -> List<Drawn> =
249
249
  s := self.game.screen()
250
- ds := Slice<Drawn>()
250
+ none := Aabb.of(0.0, 0.0, 0.0, 0.0)
251
- actor.viewDrawn(s.view(), Affine.Identity, 1.0, ds, self.cam().screen(), s.culls())
251
+ view.drawnIn(s.view(), Affine.Identity, 1.0, ds, none, false)
252
+ view.drawnIn(s.hud(self.pixels), Affine.Identity, 1.0, ds, none, false)
252
253
  List.fromSlice(ds)
253
254
 
255
+ # What the frame would draw now: each item of the shown screen's view, and what is under
256
+ # it, with its transform and alpha, culled if the screen `culls()`; then its hud's.
257
+ fun drawn(self) -> List<Drawn> = self.game.drawList()
258
+
254
259
  fun find<T>(self) -> List<T> =
255
260
  none: List<T> := Nil
256
261
  self.viewed().fold(none, |acc, d| match d.actor
@@ -265,27 +270,25 @@ struct TestRig<S>(
265
270
 
266
271
  fun count<T>(self) -> Int = self.find<T>().length()
267
272
 
268
- fun text(self, l: Label) -> Str = l.line()
273
+ fun text(self, l: Label) -> Str = l.text
269
274
 
270
- # Whether the view draws `a` itself (with every item above it shown).
275
+ # Whether the view or the hud draws `a` itself (with every item above it visible).
271
- fun shown(self, a: Actor) -> Bool = self.viewed().any(|d| @sameRef(d.actor, a))
276
+ fun shown(self, a: View) -> Bool = self.viewed().any(|d| @sameRef(d.actor, a))
272
277
 
273
278
  # Where the shown screen's view draws `a`: its transform to the world.
274
- fun worldOf(self, a: Actor) -> Option<Affine> = actor.worldIn(self.game.screen().view(), a, Affine.Identity)
279
+ fun worldOf(self, a: View) -> Option<Affine> = view.worldIn(self.game.screen().view(), a, Affine.Identity)
275
280
 
276
- # What a press at the screen pixel (x, y) lands on.
281
+ # What a press at the screen pixel (x, y) lands on: the item of the shown screen's hud,
277
- fun hit(self, x: Float, y: Float) -> Option<Actor> = actor.viewHit(self.game.screen().view(), self.toWorld(x, y))
282
+ # or else of its view, there that takes presses (std/game/View's `hitIn`).
278
-
279
- # A screen pixel in the world.
280
- fun toWorld(self, x: Float, y: Float) -> Vec2 = self.cam().toWorld(x, y)
283
+ fun hit(self, x: Float, y: Float) -> Option<View> =
284
+ s := self.game.screen()
285
+ h := view.hitIn(s.hud(self.pixels), Vec2(x: x, y: y))
286
+ if h.isSome() then h else view.hitIn(s.view(), self.toWorld(x, y))
281
287
 
288
+ # A screen pixel in the world's coordinates, through the screen's camera.
282
- fun effects<A>(self) -> List<A> =
289
+ fun toWorld(self, x: Float, y: Float) -> Vec2 = self.game.toWorld(x, y)
283
- none: List<A> := Nil
284
- self.ran.fold(none, |acc, e| match e
285
- Queued<A> as q => Cons(q.action, acc)
286
- _ => acc).reverse()
287
290
 
288
- fun restarted(self) -> Bool = self.asks.any(|a| isRestart(a))
291
+ fun effects<A>(self) -> List<A> = effects.sent<A>(self.ran)
289
292
 
290
293
  fun wentTo(self) -> Option<Str> =
291
294
  none: Option<Str> := None
@@ -299,7 +302,7 @@ struct TestRig<S>(
299
302
 
300
303
  # Records the ticks from here as a replay of `seed`.
301
304
  fun record(self, seed: Int) -> TestRig<S> =
302
- TestRig(..self, recording: true, log: Replay(seed: seed, width: Int(self.view.x), height: Int(self.view.y), ticks: Slice<Input>()))
305
+ TestRig(..self, recording: true, log: Replay(seed: seed, width: Int(self.pixels.x), height: Int(self.pixels.y), ticks: Slice<Input>()))
303
306
 
304
307
  fun recorded(self) -> Replay = self.log
305
308
 
@@ -307,6 +310,6 @@ struct TestRig<S>(
307
310
  fun replay(self, r: Replay) -> TestRig<S> =
308
311
  0.until(r.length()).fold(self.forget(), |t, i| t.ran1(r.at(i), Clock.Tick))
309
312
 
313
+ # Stops a test that clicks an actor in neither the view nor the hud.
310
- fun isRestart(a: Ask) -> Bool = match a
314
+ fun notInView() -> Vec2 =
311
- AskRestart => true
315
+ crash "headless: click: the actor is not in the view"
312
- _ => false
std/game/input.plum CHANGED
@@ -4,7 +4,6 @@ import std/Int
4
4
  import std/Float
5
5
  import std/Slice
6
6
  import std/math/Vec2
7
- import std/math/Affine
8
7
  import std/Io
9
8
  import std/Option
10
9
  import std/collections/List
@@ -24,15 +23,9 @@ extern fun isMouseDown(io: Io, b: Int) -> Bool
24
23
  extern fun isMousePressed(io: Io, b: Int) -> Bool
25
24
  extern fun mouseWheel(io: Io) -> Float
26
25
 
27
- # -1, 0 or 1: how far the key `high` is held against the key `low`. `input.axis(io, Key.Left, Key.Right)`
28
- # is the horizontal steering of a ship.
29
- fun axis(io: Io, low: Int, high: Int) -> Float =
30
- right := if isKeyDown(io, high) then 1.0 else 0.0
31
- left := if isKeyDown(io, low) then 1.0 else 0.0
32
- right - left
33
-
34
26
  # Key codes (GLFW numbering) for `isKeyDown` / `isKeyPressed`.
35
- # Letter keys are `KeyA`..`KeyZ` (a constant name needs two characters).
27
+ # Letter keys are `KeyA`..`KeyZ` (a constant name needs two characters). Super is Cmd on a
28
+ # Mac, the Windows key elsewhere.
36
29
  primitive Key =
37
30
  Space = 32
38
31
  KeyA = 65
@@ -71,6 +64,9 @@ primitive Key =
71
64
  Num7 = 55
72
65
  Num8 = 56
73
66
  Num9 = 57
67
+ BracketLeft = 91
68
+ Backslash = 92
69
+ BracketRight = 93
74
70
  Escape = 256
75
71
  Enter = 257
76
72
  Tab = 258
@@ -81,25 +77,38 @@ primitive Key =
81
77
  Up = 265
82
78
  LeftShift = 340
83
79
  LeftControl = 341
84
-
80
+ LeftAlt = 342
81
+ LeftSuper = 343
82
+ RightShift = 344
83
+ RightControl = 345
84
+ RightAlt = 346
85
+ RightSuper = 347
86
+
85
- # Mouse button numbers for `isMouseDown` / `isMousePressed`.
87
+ # Mouse button numbers for `isMouseDown` / `isMousePressed`. The left button (or a touch)
88
+ # is the pointer: `PointerDown` and `PointerUp`; the others come as `ButtonDown` and
89
+ # `ButtonUp`.
86
90
  primitive Mouse =
87
91
  Left = 0
88
92
  Right = 1
89
93
  Middle = 2
90
94
 
91
- # One input: a pointer event in screen pixels, or a key going down or up.
95
+ # One input: a pointer event in screen pixels (the left button or a touch, or a move), the
96
+ # right or middle mouse button going down or up where the pointer is (`button` a `Mouse`
97
+ # number), or a key going down or up.
92
98
  enum InputEvent =
93
99
  | PointerDown(x: Float, y: Float)
94
100
  | PointerUp(x: Float, y: Float)
95
101
  | PointerMove(x: Float, y: Float)
102
+ | ButtonDown(button: Int, x: Float, y: Float)
103
+ | ButtonUp(button: Int, x: Float, y: Float)
96
104
  | KeyDown(key: Int)
97
105
  | KeyUp(key: Int)
98
106
 
99
- # This frame's inputs: the host's mouse button and keys compared with `prev`, what
107
+ # This frame's inputs: the host's mouse buttons and keys compared with `prev`, what was
100
- # was held after the last poll. One pointer input (down, up or move) comes first,
108
+ # held after the last poll. One pointer input (down, up or move) comes first, then a
109
+ # ButtonDown or ButtonUp for the right and the middle button if it changed, then a
101
- # then a KeyDown or KeyUp for each key that changed, in key-code order. A click that
110
+ # KeyDown or KeyUp for each key that changed, in key-code order. A click that began and
102
- # began and ended between two polls gives a PointerDown and a PointerUp.
111
+ # ended between two polls gives a down and an up.
103
112
  fun poll(io: Io, prev: Held) -> Polled =
104
113
  out := Slice<InputEvent>()
105
114
  m := mousePos(io)
@@ -114,6 +123,9 @@ enum InputEvent =
114
123
  out.push(PointerUp(x: m.x, y: m.y))
115
124
  else
116
125
  out.push(PointerMove(x: m.x, y: m.y))
126
+ buttons := Slice<Int>()
127
+ InputEvent.pollButton(io, Mouse.Right, prev, m, out, buttons)
128
+ InputEvent.pollButton(io, Mouse.Middle, prev, m, out, buttons)
117
129
  keys := Slice<Int>()
118
130
  codes := InputEvent.keyCodes()
119
131
  for i := range codes.length()
@@ -126,7 +138,23 @@ enum InputEvent =
126
138
  out.push(KeyDown(key: k))
127
139
  if !now && was
128
140
  out.push(KeyUp(key: k))
129
- Polled(inputs: out, held: Held(mouse: down, keys: keys))
141
+ Polled(inputs: out, held: Held(mouse: down, keys: keys, buttons: buttons))
142
+
143
+ # The mouse button `b` polled, at `m`: its ButtonDown or ButtonUp onto `out` if it
144
+ # changed since `prev` (both if it went down and up between two polls), and `b` onto
145
+ # `buttons` if it is down.
146
+ fun pollButton(io: Io, b: Int, prev: Held, m: Vec2, out: Slice<InputEvent>, buttons: Slice<Int>) =
147
+ now := isMouseDown(io, b)
148
+ was := prev.isButtonDown(b)
149
+ if now
150
+ buttons.push(b)
151
+ if now && !was
152
+ out.push(ButtonDown(button: b, x: m.x, y: m.y))
153
+ else if !now && was
154
+ out.push(ButtonUp(button: b, x: m.x, y: m.y))
155
+ else if !now && isMousePressed(io, b)
156
+ out.push(ButtonDown(button: b, x: m.x, y: m.y))
157
+ out.push(ButtonUp(button: b, x: m.x, y: m.y))
130
158
 
131
159
  # Every `Key` code in std/game/input, in increasing order.
132
160
  fun keyCodes() -> Slice<Int> =
@@ -135,12 +163,14 @@ enum InputEvent =
135
163
  out.push(Key.Num0 + i)
136
164
  for i := range 26
137
165
  out.push(Key.KeyA + i)
166
+ for i := range 3
167
+ out.push(Key.BracketLeft + i)
138
168
  for i := range 4
139
169
  out.push(Key.Escape + i)
140
170
  for i := range 4
141
171
  out.push(Key.Right + i)
172
+ for i := range 8
142
- out.push(Key.LeftShift)
173
+ out.push(Key.LeftShift + i)
143
- out.push(Key.LeftControl)
144
174
  out
145
175
 
146
176
  # The pointer position, or None for a key.
@@ -148,21 +178,10 @@ enum InputEvent =
148
178
  PointerDown(x, y) => Some(Vec2(x: x, y: y))
149
179
  PointerUp(x, y) => Some(Vec2(x: x, y: y))
150
180
  PointerMove(x, y) => Some(Vec2(x: x, y: y))
181
+ ButtonDown(_, x, y) => Some(Vec2(x: x, y: y))
182
+ ButtonUp(_, x, y) => Some(Vec2(x: x, y: y))
151
183
  _ => None
152
184
 
153
- # The input with its position seen through `m` (a key is unchanged).
154
- fun through(self, m: Affine) -> InputEvent = match self
155
- PointerDown(x, y) => InputEvent.pointerAt(PointerDown(x: x, y: y), m.apply(Vec2(x: x, y: y)))
156
- PointerUp(x, y) => InputEvent.pointerAt(PointerUp(x: x, y: y), m.apply(Vec2(x: x, y: y)))
157
- PointerMove(x, y) => InputEvent.pointerAt(PointerMove(x: x, y: y), m.apply(Vec2(x: x, y: y)))
158
- _ => self
159
-
160
- # The pointer input `e` (same kind) at `p`.
161
- fun pointerAt(e: InputEvent, p: Vec2) -> InputEvent = match e
162
- PointerDown(_, _) => PointerDown(x: p.x, y: p.y)
163
- PointerUp(_, _) => PointerUp(x: p.x, y: p.y)
164
- _ => PointerMove(x: p.x, y: p.y)
165
-
166
185
  fun isKeyDownOf(self, key: Int) -> Bool = match self
167
186
  KeyDown(k) => k == key
168
187
  _ => false
@@ -175,52 +194,64 @@ enum InputEvent =
175
194
  PointerUp(_, _) => true
176
195
  _ => false
177
196
 
197
+ fun isPointerMove(self) -> Bool = match self
198
+ PointerMove(_, _) => true
199
+ _ => false
200
+
178
201
  fun isPointer(self) -> Bool =
179
202
  self.position().isSome()
180
203
 
181
- # What is held: the left mouse button and the keys that are down.
204
+ # What is held: the left mouse button (or a touch), the keys that are down, and the other
205
+ # mouse buttons that are down (`Mouse.Right`, `Mouse.Middle`).
182
- struct Held(mouse: Bool, keys: Slice<Int>) =
206
+ struct Held(mouse: Bool, keys: Slice<Int>, buttons: Slice<Int>) =
183
207
  fun none() -> Held =
184
- Held(mouse: false, keys: Slice<Int>())
208
+ Held(mouse: false, keys: Slice<Int>(), buttons: Slice<Int>())
185
209
 
210
+ # The keys `keys` held, and no mouse button.
211
+ fun keysOnly(keys: Slice<Int>) -> Held =
212
+ Held(mouse: false, keys: keys, buttons: Slice<Int>())
213
+
186
- # Whether `o` holds the same button and keys (in any order).
214
+ # Whether `o` holds the same: the mouse buttons, and the same keys in any order.
187
215
  fun same(self, o: Held) -> Bool =
188
216
  self.mouse == o.mouse && self.keys.length() == o.keys.length() && self.keys.all(|k| o.isDown(k))
217
+ && self.buttons.length() == o.buttons.length() && self.buttons.all(|b| o.buttons.contains(b))
189
218
 
190
219
  fun isDown(self, key: Int) -> Bool =
191
220
  self.keys.contains(key)
192
221
 
222
+ # Whether the mouse button `b` (a `Mouse` number) is down.
223
+ fun isButtonDown(self, b: Int) -> Bool =
224
+ if b == Mouse.Left then self.mouse else self.buttons.contains(b)
225
+
193
- # What is held after `e`: KeyDown adds its key, KeyUp removes it, a pointer down
226
+ # What is held after `e`: KeyDown adds its key, KeyUp removes it, a pointer down or up
194
- # or up sets `mouse`.
227
+ # sets `mouse`, a ButtonDown or ButtonUp adds or removes its button.
195
228
  fun after(self, e: InputEvent) -> Held = match e
196
- KeyDown(key) => if self.isDown(key) then self else Held(mouse: self.mouse, keys: self.keysWith(key, true))
229
+ KeyDown(key) => if self.isDown(key) then self else Held(..self, keys: withOrWithout(self.keys, key, true))
197
- KeyUp(key) => Held(mouse: self.mouse, keys: self.keysWith(key, false))
230
+ KeyUp(key) => Held(..self, keys: withOrWithout(self.keys, key, false))
198
- PointerDown(_, _) => Held(mouse: true, keys: self.keys)
231
+ PointerDown(_, _) => Held(..self, mouse: true)
199
- PointerUp(_, _) => Held(mouse: false, keys: self.keys)
232
+ PointerUp(_, _) => Held(..self, mouse: false)
233
+ ButtonDown(b, _, _) => Held(..self, buttons: withOrWithout(self.buttons, b, true))
234
+ ButtonUp(b, _, _) => Held(..self, buttons: withOrWithout(self.buttons, b, false))
200
235
  _ => self
201
236
 
202
- # A fresh copy of the held keys with `key` added (`add`) or removed.
237
+ # A fresh copy of `xs` with `x` added (`add`, once) or removed.
203
- fun keysWith(self, key: Int, add: Bool) -> Slice<Int> =
238
+ fun withOrWithout(xs: Slice<Int>, x: Int, add: Bool) -> Slice<Int> =
204
- out := Slice<Int>()
239
+ out := Slice<Int>()
205
- for i := range self.keys.length()
240
+ for i := range xs.length()
206
- if self.keys.at(i) != key
241
+ if xs.at(i) != x
207
- out.push(self.keys.at(i))
242
+ out.push(xs.at(i))
208
- if add
243
+ if add
209
- out.push(key)
244
+ out.push(x)
210
- out
245
+ out
211
246
 
212
247
  # A poll's inputs and what is held after them (pass it to the next poll).
213
248
  struct Polled(inputs: Slice<InputEvent>, held: Held)
214
249
 
215
- # The mouse or a single touch this frame (the bridge reports touch as the mouse):
216
- # its position in screen pixels, whether it is down, and whether it went down or
217
- # up this frame.
218
- struct Pointer(pos: Vec2, down: Bool, pressed: Bool, released: Bool)
219
-
220
- # The player's input for one tick, a value: `update(self, io, input, dt)` receives it.
250
+ # The player's input for one tick, a value: a slice's `held(input)` receives it. The
221
- # The game's `Clock` reads the host once per frame, so `events`, `isKeyDown` and the
251
+ # game's `Clock` reads the host once per frame, so `events`, `isKeyDown` and the pointer
222
- # pointer reads agree for the whole tick however often they are called, and nothing in
252
+ # reads agree for the whole tick however often they are called, and nothing in a tick
253
+ # reads input from the host. `pos` is where the pointer is, in screen pixels, and `wheel`
223
- # `update` reads input from the host.
254
+ # how far the wheel turned this frame.
224
255
  struct Input(held: Held, events: Slice<InputEvent>, pos: Vec2, wheel: Float) =
225
256
  fun create() -> Input =
226
257
  Input(held: Held.none(), events: Slice<InputEvent>(), pos: Vec2(x: 0.0, y: 0.0), wheel: 0.0)
@@ -234,31 +265,32 @@ struct Input(held: Held, events: Slice<InputEvent>, pos: Vec2, wheel: Float) =
234
265
  fun isKeyDown(self, key: Int) -> Bool =
235
266
  self.held.isDown(key)
236
267
 
268
+ # -1, 0 or 1: the key `high` held against the key `low`, 0 when both or neither are.
269
+ # `input.axis(Key.Left, Key.Right)` is the horizontal steering of a ship.
270
+ fun axis(self, low: Int, high: Int) -> Float =
271
+ {if self.isKeyDown(high) then 1.0 else 0.0} - {if self.isKeyDown(low) then 1.0 else 0.0}
272
+
237
273
  # Went down this frame.
238
274
  fun isKeyPressed(self, key: Int) -> Bool =
239
275
  self.events.any(|e| e.isKeyDownOf(key))
240
276
 
241
- # The left mouse button, or a touch.
277
+ # The mouse button `b` (`Mouse.Left` unless given, which is also a touch) is held.
242
- fun isMouseDown(self) -> Bool =
278
+ fun isMouseDown(self, b: Int = Mouse.Left) -> Bool =
243
- self.held.mouse
279
+ self.held.isButtonDown(b)
244
-
245
- fun isMousePressed(self) -> Bool =
246
- self.pointerPressed()
247
280
 
281
+ # The mouse button `b` went down this frame.
282
+ fun isMousePressed(self, b: Int = Mouse.Left) -> Bool =
283
+ self.events.any(|e| match e
284
+ PointerDown(_, _) => b == Mouse.Left
248
- fun mousePos(self) -> Vec2 =
285
+ ButtonDown(n, _, _) => n == b
249
- self.pos
286
+ _ => false)
250
287
 
251
- fun mouseWheel(self) -> Float =
288
+ # The mouse button `b` went up this frame.
252
- self.wheel
253
-
254
- fun pointer(self) -> Pointer =
255
- Pointer(pos: self.pos, down: self.held.mouse, pressed: self.pointerPressed(), released: self.pointerReleased())
256
-
257
- fun pointerPressed(self) -> Bool =
258
- self.events.any(|e| e.isPointerDown())
259
-
260
- fun pointerReleased(self) -> Bool =
289
+ fun isMouseReleased(self, b: Int = Mouse.Left) -> Bool =
261
- self.events.any(|e| e.isPointerUp())
290
+ self.events.any(|e| match e
291
+ PointerUp(_, _) => b == Mouse.Left
292
+ ButtonUp(n, _, _) => n == b
293
+ _ => false)
262
294
 
263
295
  # A game's clock and input between frames: the input not yet given to a tick (`pending`),
264
296
  # the wall time not yet ticked (`acc`), the ticks run this frame (`n`) and in all
@@ -360,7 +392,7 @@ struct Clock(pending: Input, acc: Float, n: Int, ticks: Int, mode: Int, played:
360
392
  out
361
393
 
362
394
  fun inHeld(keys: Slice<Int>) -> Held =
363
- Held(mouse: false, keys: keys)
395
+ Held.keysOnly(keys)
364
396
 
365
397
  test "held_after_tracks_keys_and_mouse"
366
398
  h := Held.none().after(KeyDown(key: Key.KeyA)).after(KeyDown(key: Key.Left)).after(PointerDown(x: 1.0, y: 2.0))
@@ -373,61 +405,80 @@ test "held_after_tracks_keys_and_mouse"
373
405
  assert !h2.mouse
374
406
  assert h.isDown(Key.KeyA)
375
407
 
408
+ test "the right and middle buttons are held apart from the pointer"
409
+ h := Held.none().after(ButtonDown(button: Mouse.Right, x: 1.0, y: 2.0)).after(ButtonDown(button: Mouse.Middle, x: 1.0, y: 2.0))
410
+ assert h.isButtonDown(Mouse.Right) && h.isButtonDown(Mouse.Middle) && !h.isButtonDown(Mouse.Left)
411
+ assert !h.same(Held.none())
412
+ assert h.same(Held.none().after(ButtonDown(button: Mouse.Middle, x: 0.0, y: 0.0)).after(ButtonDown(button: Mouse.Right, x: 0.0, y: 0.0)))
413
+ up := h.after(ButtonUp(button: Mouse.Right, x: 1.0, y: 2.0))
414
+ assert !up.isButtonDown(Mouse.Right) && up.isButtonDown(Mouse.Middle)
415
+ assert ButtonDown(button: Mouse.Right, x: 3.0, y: 4.0).position().unwrap().x == 3.0
416
+
376
417
  test "key_down_twice_keeps_one_entry"
377
418
  h := Held.none().after(KeyDown(key: Key.KeyA)).after(KeyDown(key: Key.KeyA))
378
419
  assert h.keys.length() == 1
379
420
 
380
421
  test "key_codes_cover_every_key_constant"
381
422
  codes := InputEvent.keyCodes()
382
- assert codes.length() == 47
423
+ assert codes.length() == 56
383
424
  assert inHeld(codes).isDown(Key.Space)
384
425
  assert inHeld(codes).isDown(Key.Num9)
385
426
  assert inHeld(codes).isDown(Key.KeyZ)
427
+ assert inHeld(codes).isDown(Key.Backslash)
386
428
  assert inHeld(codes).isDown(Key.Backspace)
387
429
  assert inHeld(codes).isDown(Key.Up)
388
430
  assert inHeld(codes).isDown(Key.LeftControl)
431
+ assert inHeld(codes).isDown(Key.RightSuper)
432
+ assert 1.until(codes.length()).all(|i| codes.at(i - 1) < codes.at(i))
389
433
 
390
- test "through_moves_pointers_only"
434
+ test "pointer events have a position, keys don't"
391
- m := Affine(a: 1.0, b: 0.0, c: 0.0, d: 1.0, e: 10.0, f: 0.0)
392
- if Some(p) := PointerDown(x: 1.0, y: 2.0).through(m).position()
393
- assert p.x == 11.0
394
- assert p.y == 2.0
395
- else
396
- assert false
397
- assert KeyDown(key: 5).through(m).position().isNone()
398
435
  assert !KeyDown(key: 5).isPointer()
399
436
  assert PointerMove(x: 0.0, y: 0.0).isPointer()
437
+ assert PointerMove(x: 0.0, y: 0.0).isPointerMove()
438
+ assert KeyDown(key: 5).position().isNone()
400
439
 
401
440
  test "input agrees for the whole frame"
402
- held := Held(mouse: true, keys: [Key.KeyA].toSlice())
441
+ held := Held(mouse: true, keys: [Key.KeyA].toSlice(), buttons: Slice<Int>())
403
442
  st := Input(held: held, events: [PointerDown(x: 3.0, y: 4.0), KeyDown(key: Key.KeyA)].toSlice(), pos: Vec2(x: 3.0, y: 4.0), wheel: 1.5)
404
- assert st.events.length() == 2
405
- assert st.events.length() == 2
406
443
  assert st.isKeyPressed(Key.KeyA)
407
444
  assert !st.isKeyPressed(Key.KeyB)
408
445
  assert st.isKeyDown(Key.KeyA)
409
- assert st.pointerPressed()
446
+ assert st.isMousePressed()
410
- assert !st.pointerReleased()
447
+ assert !st.isMouseReleased()
411
448
  assert st.isMouseDown()
412
- assert st.mouseWheel() == 1.5
413
- assert st.mousePos().x == 3.0
414
- assert st.pointer().pressed
449
+ assert !st.isMouseDown(Mouse.Right)
450
+ assert st.wheel == 1.5
451
+ assert st.pos.x == 3.0
452
+
453
+ test "the other buttons have readers of their own"
454
+ st := Input(held: Held(mouse: false, keys: Slice<Int>(), buttons: [Mouse.Right].toSlice()), events: [ButtonDown(button: Mouse.Right, x: 0.0, y: 0.0), ButtonUp(button: Mouse.Middle, x: 0.0, y: 0.0)].toSlice(), pos: Vec2(x: 0.0, y: 0.0), wheel: 0.0)
455
+ assert st.isMouseDown(Mouse.Right) && st.isMousePressed(Mouse.Right) && !st.isMousePressed()
456
+ assert st.isMouseReleased(Mouse.Middle) && !st.isMouseReleased(Mouse.Right)
457
+
458
+ test "an axis is the high key held against the low one"
459
+ i := |keys: List<Int>| Input(held: inHeld(keys.toSlice()), events: Slice<InputEvent>(), pos: Vec2(x: 0.0, y: 0.0), wheel: 0.0)
460
+ assert i([Key.Right]).axis(Key.Left, Key.Right) == 1.0
461
+ assert i([Key.Left]).axis(Key.Left, Key.Right) == -1.0
462
+ assert i([Key.Left, Key.Right]).axis(Key.Left, Key.Right) == 0.0
463
+ assert i(Nil).axis(Key.Left, Key.Right) == 0.0
415
464
 
416
465
  test "only this frame's events count, not what lies past them"
417
466
  all := [KeyDown(key: Key.KeyA), KeyDown(key: Key.KeyB), PointerDown(x: 1.0, y: 1.0), PointerUp(x: 1.0, y: 1.0)].toSlice()
418
- held := Held(mouse: false, keys: [Key.KeyA].toSlice())
467
+ held := inHeld([Key.KeyA].toSlice())
419
468
  one := Input(held: held, events: all.slice(0, 1), pos: Vec2(x: 0.0, y: 0.0), wheel: 0.0)
420
469
  assert one.isKeyPressed(Key.KeyA)
421
470
  assert !one.isKeyPressed(Key.KeyB)
422
471
  downOnly := Input(held: held, events: all.slice(1, 2), pos: Vec2(x: 0.0, y: 0.0), wheel: 0.0)
423
- assert !downOnly.pointerPressed()
472
+ assert !downOnly.isMousePressed()
424
473
  beforeUp := Input(held: held, events: all.slice(2, 3), pos: Vec2(x: 0.0, y: 0.0), wheel: 0.0)
425
- assert beforeUp.pointerPressed()
474
+ assert beforeUp.isMousePressed()
426
- assert !beforeUp.pointerReleased()
475
+ assert !beforeUp.isMouseReleased()
427
476
 
428
477
  test "key and mouse constants use GLFW numbering"
429
478
  assert Key.KeyW == 87
430
479
  assert Key.Left == 263
431
480
  assert Key.Num0 == 48
432
481
  assert Key.LeftControl == 341
482
+ assert Key.BracketLeft == 91
483
+ assert Key.RightSuper == 347
433
484
  assert Mouse.Right == 1
std/math/math.plum CHANGED
@@ -530,6 +530,9 @@ fun atan2(y: Float, x: Float) -> Float =
530
530
  fun atan2Quadrant(m: Int, a: Float, b: Float) -> Float =
531
531
  if m == 0 then a else if m == 1 then -a else if m == 2 then b else -b
532
532
 
533
+ # Whether `a` and `b` are within `eps` of each other: `math.near(p.x, 400.0, 0.01)`.
534
+ fun near(a: Float, b: Float, eps: Float) -> Bool = {a - b}.abs() <= eps
535
+
533
536
  # sqrt(a^2 + b^2), without overflow or underflow on the way: exactly `sqrt(a * a + b * b)`
534
537
  # when that sum is a finite number above 2^-968 (so every term that counts in it is a normal
535
538
  # float), else the larger side times sqrt(1 + r^2), r the ratio of the smaller to it.
tests/port/game/replay.plum CHANGED
@@ -34,7 +34,7 @@ struct Probe[ScreenSlice<Saw>](rng: Random, ticks: Int, presses: Int, held: Int,
34
34
  fun name(self) -> Str = "probe"
35
35
 
36
36
  fun held(self, i: Input) -> Option<Saw> =
37
- Some(Seen(pressed: i.isKeyPressed(Key.Space) || i.pointerPressed(), spaceHeld: i.isKeyDown(Key.Space), x: i.pos.x, y: i.pos.y))
37
+ Some(Seen(pressed: i.isKeyPressed(Key.Space) || i.isMousePressed(), spaceHeld: i.isKeyDown(Key.Space), x: i.pos.x, y: i.pos.y))
38
38
 
39
39
  fun tick(self, dt: Float) -> Option<Saw> = Some(Ticked(dt: dt))
40
40
 
@@ -101,7 +101,7 @@ fun scripted(i: Int) -> Input =
101
101
  keys := Slice<Int>()
102
102
  if {i >= 3 && i < 10} || {i >= 20 && i < 25}
103
103
  keys.push(Key.Space)
104
- Input(held: Held(mouse: i == 30, keys: keys), events: events, pos: Vec2(x: x, y: y), wheel: if i == 12 then 0.1 else 0.0)
104
+ Input(held: Held(mouse: i == 30, keys: keys, buttons: Slice<Int>()), events: events, pos: Vec2(x: x, y: y), wheel: if i == 12 then 0.1 else 0.0)
105
105
 
106
106
  # A jittery frame time around 1/60 s for frame `i`.
107
107
  fun jitter(i: Int) -> Float =
@@ -118,15 +118,18 @@ fun replayed(io: Io, r: Replay, frames: Int) -> Run =
118
118
  test "replay_roundtrip"
119
119
  r := Replay(seed: -6917529027641081853, width: 800, height: 600, ticks: Slice<Input>())
120
120
  r.ticks.push(Input.create())
121
- r.ticks.push(Input(held: Held(mouse: true, keys: [Key.Left, Key.Space].toSlice()), events: [PointerDown(x: 0.1, y: -2.5), KeyDown(key: Key.Space), KeyUp(key: Key.KeyA), PointerUp(x: 0.0, y: 7.0), PointerMove(x: 1.0e-300, y: 640.75)].toSlice(), pos: Vec2(x: 0.1, y: 1.0e-300), wheel: -1.0))
122
- r.ticks.push(Input(held: Held(mouse: false, keys: [Key.Up].toSlice()), events: Slice<InputEvent>(), pos: Vec2(x: 0.3, y: 0.7), wheel: 0.1))
121
+ r.ticks.push(Input(held: Held(mouse: true, keys: [Key.Left, Key.Space].toSlice(), buttons: Slice<Int>()), events: [PointerDown(x: 0.1, y: -2.5), KeyDown(key: Key.Space), KeyUp(key: Key.KeyA), PointerUp(x: 0.0, y: 7.0), PointerMove(x: 1.0e-300, y: 640.75)].toSlice(), pos: Vec2(x: 0.1, y: 1.0e-300), wheel: -1.0))
122
+ r.ticks.push(Input(held: Held.keysOnly([Key.Up].toSlice()), events: Slice<InputEvent>(), pos: Vec2(x: 0.3, y: 0.7), wheel: 0.1))
123
+ r.ticks.push(Input(held: Held(mouse: true, keys: Slice<Int>(), buttons: [Mouse.Middle, Mouse.Right].toSlice()), events: [ButtonDown(button: Mouse.Right, x: 1.5, y: -2.0), ButtonUp(button: Mouse.Middle, x: 0.0, y: 3.0)].toSlice(), pos: Vec2(x: 1.5, y: -2.0), wheel: 0.0))
123
124
  text := r.encode()
124
125
  if Ok(back) := Replay.decode(text)
125
126
  assert back.seed == r.seed
126
127
  assert back.width == 800
127
128
  assert back.height == 600
128
- assert back.length() == 3
129
+ assert back.length() == 4
130
+ assert back.at(3).held.isButtonDown(Mouse.Middle) && back.at(3).held.isButtonDown(Mouse.Right)
131
+ assert back.at(3).held.same(r.at(3).held)
129
- for i := range 3
132
+ for i := range 4
130
133
  assert replay.sameInput(back.at(i), r.at(i))
131
134
  assert back.at(1).pos.x == 0.1
132
135
  assert back.at(1).pos.y == 1.0e-300
@@ -236,7 +239,8 @@ test "a bad replay says what is wrong"
236
239
  assert Replay.decode("").isErr()
237
240
  assert Replay.decode("plum-replay 2 0 0 0 0\n").isErr()
238
241
  assert Replay.decode("plum-replay 1 0 0 x 0\n").isErr()
239
- assert Replay.decode("plum-replay 1 0 0 0 0\n- 0 0 0 0\n- 2 0 0 0\n").isErr()
242
+ assert Replay.decode("plum-replay 1 0 0 0 0\n- 0 0 0 0\n- 9 0 0 0\n").isErr()
243
+ assert Replay.decode("plum-replay 1 0 0 0 0\n- 0 0 0 0 B1,2\n").isErr()
240
244
  assert Replay.decode("plum-replay 1 0 0 0 0\n- 0 0 0 0 Q1\n").isErr()
241
245
  assert Replay.decode("plum-replay 1 0 0 0 0\r\n- 0 0 0 0 K32\r\n").isOk()
242
246
  if Err(why) := Replay.decode("plum-replay 1 0 0 0 0\n- 0 0 0 0\n- 0 0 0\n")
@@ -244,6 +248,14 @@ test "a bad replay says what is wrong"
244
248
  else
245
249
  assert false
246
250
 
251
+ test "a replay recorded before the other mouse buttons reads as it did"
252
+ old := "plum-replay 1 0 7 800 600\n32,262 1 3 4 0 D3,4 K32\n- 0 1:-1 2 -1 U1,1 k32\n"
253
+ r := Replay.decode(old).unwrap()
254
+ assert r.length() == 2
255
+ assert r.at(0).held.mouse && r.at(0).held.buttons.isEmpty() && r.at(0).held.isDown(Key.Space)
256
+ assert !r.at(1).held.mouse && r.at(1).pos.x == 0.5
257
+ assert r.encode() == old
258
+
247
259
  # std's maths is Plum code made of IEEE 754 double operations and wasm's own `f64.sqrt`,
248
260
  # `f64.floor`, ..., which wasm defines exactly, so every browser and the native host compute
249
261
  # the same bits. `sqrt` is correctly rounded: sqrt(2) is `Float.Sqrt2`, 0x3FF6A09E667F3BCD.
tests/port/game/routing.plum CHANGED
@@ -9,12 +9,12 @@ import std/math/Vec2
9
9
  import std/math/Affine
10
10
  import std/math/Aabb
11
11
  import std/game/Place
12
- import std/game/Actor
12
+ import std/game/View
13
13
  import std/game/Sized
14
14
  import std/game/Touch
15
15
 
16
- # A press hit-tested against a view (std/game/Actor's `viewHit`), against a brute-force
16
+ # A press hit-tested against a view (std/game/View's `hitIn`), against a brute-force
17
- # reference. `viewHit` walks the view top-most first: later items before earlier ones,
17
+ # reference. `hitIn` walks the view top-most first: later items before earlier ones,
18
18
  # what is under an item before the item, mapping the point into each item's own
19
19
  # coordinates on the way down. The reference knows nothing of that: from a flat table of
20
20
  # what was built, in draw order, it gives every node its world transform (the product of
@@ -27,12 +27,12 @@ import std/game/Touch
27
27
  # boxes that overlap. A point within 1e-6 of a box's edge is skipped.
28
28
 
29
29
  # A `w` by `h` box node with children: a view item that takes presses as `touch` says.
30
- struct RNode[Actor, Sized, Touch](id: Int, at: Place, w: Float, h: Float, touch: Touchable, visible: Bool, children: List<Actor>) =
30
+ struct RNode[View, Sized, Touch](id: Int, at: Place, w: Float, h: Float, touch: Touchable, shows: Bool, children: List<View>) =
31
31
  fun place(self) -> Place = self.at
32
32
 
33
- fun shown(self) -> Bool = self.visible
33
+ fun visible(self) -> Bool = self.shows
34
34
 
35
- fun declared(self) -> List<Actor> = self.children
35
+ fun view(self) -> List<View> = self.children
36
36
 
37
37
  fun touch(self) -> Touchable = self.touch
38
38
 
@@ -74,7 +74,7 @@ fun touchOf(g: Gen) -> Touchable =
74
74
 
75
75
  # `n` sibling nodes under the node `parent`, each with up to three children while `depth`
76
76
  # is above 0, their specs pushed in draw order.
77
- fun built(g: Gen, parent: Int, depth: Int, n: Int, specs: Slice<Spec>) -> List<Actor> =
77
+ fun built(g: Gen, parent: Int, depth: Int, n: Int, specs: Slice<Spec>) -> List<View> =
78
78
  if n <= 0
79
79
  Nil
80
80
  else
@@ -86,7 +86,7 @@ fun built(g: Gen, parent: Int, depth: Int, n: Int, specs: Slice<Spec>) -> List<A
86
86
  visible := g.below(10) > 0
87
87
  specs.push(Spec(parent: parent, at: at, w: w, h: h, touch: t, visible: visible))
88
88
  kids := if depth > 0 then built(g, id, depth - 1, g.below(4), specs) else Nil
89
- node: Actor := RNode(id: id, at: at, w: w, h: h, touch: t, visible: visible, children: kids)
89
+ node: View := RNode(id: id, at: at, w: w, h: h, touch: t, shows: visible, children: kids)
90
90
  Cons(node, built(g, parent, depth, n - 1, specs))
91
91
 
92
92
  # The world transform of the spec `i`.
@@ -118,7 +118,7 @@ fun reference(specs: Slice<Spec>, p: Vec2) -> Int =
118
118
  if near then -2 else if inside then i else best
119
119
  )
120
120
 
121
- fun hitId(view: List<Actor>, p: Vec2) -> Int = match actor.viewHit(view, p)
121
+ fun hitId(items: List<View>, p: Vec2) -> Int = match view.hitIn(items, p)
122
122
  Some(a) => match a
123
123
  RNode as n => n.id
124
124
  _ => -3
@@ -129,7 +129,7 @@ struct Tally(mut checked: Int, mut hits: Int, mut wrong: Int)
129
129
  fun check(seed: Int, points: Int, tally: Tally) =
130
130
  g := Gen(s: seed)
131
131
  specs := Slice<Spec>()
132
- view := built(g, -1, 4, 1 + g.below(5), specs)
132
+ items := built(g, -1, 4, 1 + g.below(5), specs)
133
133
  for k := range points
134
134
  p := Vec2(x: Float(g.below(500) - 100) + g.unit(), y: Float(g.below(500) - 100) + g.unit())
135
135
  want := reference(specs, p)
@@ -137,7 +137,7 @@ fun check(seed: Int, points: Int, tally: Tally) =
137
137
  tally.checked = tally.checked + 1
138
138
  if want >= 0
139
139
  tally.hits = tally.hits + 1
140
- if hitId(view, p) != want
140
+ if hitId(items, p) != want
141
141
  tally.wrong = tally.wrong + 1
142
142
 
143
143
  test "a view's hit test agrees with the brute-force reference on 300 random views of moved, scaled and turned places"
tests/port/game/screens.plum CHANGED
@@ -1,6 +1,7 @@
1
1
  # A game of screens drawn by their views (std/game/Game, ScreenSlice, headless): presses
2
2
  # hit-tested against the view, actions reduced and their effects run after the tick,
3
- # navigation, transitions, frames on demand, record and replay, undo and rewind.
3
+ # navigation, transitions, frames on demand, record and replay, undo and rewind, the
4
+ # actors stepped by the game, a screen's hud and its camera.
4
5
  import std/Int
5
6
  import std/Float
6
7
  import std/Bool
@@ -12,11 +13,14 @@ import std/collections/List
12
13
  import std/math/Vec2
13
14
  import std/math/Affine
14
15
  import std/math/Random
16
+ import std/math/math
15
17
  import std/game/Color
16
18
  import std/game/input
17
19
  import std/game/Replay
18
20
  import std/game/Place
21
+ import std/game/View
19
- import std/game/Actor
22
+ import std/game/Box
23
+ import std/game/Group
20
24
  import std/game/Touch
21
25
  import std/game/Label
22
26
  import std/game/Overlay
@@ -28,14 +32,13 @@ import std/game/Game
28
32
  import std/game/headless
29
33
 
30
34
  enum ProbeAct =
31
- | Pressed(on: Actor)
35
+ | Pressed(on: View)
32
36
  | Missed
33
37
  | Keyed
34
38
  | Echo
35
39
  | Ticked(dt: Float)
36
40
  | GoPlay
37
41
  | Quit
38
- | Again
39
42
  | Back
40
43
  | Roll
41
44
 
@@ -47,16 +50,15 @@ enum ProbeAct =
47
50
  Ticked(_) => "Ticked"
48
51
  GoPlay => "GoPlay"
49
52
  Quit => "Quit"
50
- Again => "Again"
51
53
  Back => "Back"
52
54
  Roll => "Roll"
53
55
 
54
56
  # A screen drawn by its view: a box it holds, a turned group holding a second box, a
55
57
  # decoration layer that takes no presses over a third, an overlay while `covered`, and a
56
- # label of its keys. It notes what was pressed; G goes to "play", Q quits, R restarts,
58
+ # label of its keys. It notes what was pressed; G goes to "play", Q quits, Space rolls its
57
- # Space rolls its random number.
59
+ # random number.
58
60
  struct ProbeScreen[ScreenSlice<ProbeAct>](
59
- box: Box, inner: Box, under: Box, covered: Bool, hits: List<Actor>, misses: Int, keys: Int, echoes: Int,
61
+ box: Box, inner: Box, under: Box, covered: Bool, hits: List<View>, misses: Int, keys: Int, echoes: Int,
60
62
  ticks: Int, left: Int, frames: Frames, rng: Random, roll: Int) =
61
63
 
62
64
  fun create(frames: Frames) -> ProbeScreen =
@@ -74,9 +76,9 @@ struct ProbeScreen[ScreenSlice<ProbeAct>](
74
76
 
75
77
  fun busy(self) -> Bool = self.left > 0
76
78
 
77
- fun view(self) -> List<Actor> =
79
+ fun view(self) -> List<View> =
78
- turned: Actor := Group(x: 200.0, y: 100.0, touch: ChildrenOnly, children: [Group.of(50.0, 0.0, [self.inner])])
80
+ turned: View := Group(x: 200.0, y: 100.0, touch: ChildrenOnly, children: [Group.of(50.0, 0.0, [self.inner])])
79
- base: List<Actor> := [
81
+ base: List<View> := [
80
82
  self.box,
81
83
  turnedBy(turned),
82
84
  self.under,
@@ -84,7 +86,7 @@ struct ProbeScreen[ScreenSlice<ProbeAct>](
84
86
  Label.of(0.0, 560.0, "keys {self.keys}", 24.0, Color.White)]
85
87
  if self.covered then base.append([Overlay.of(800.0, 600.0, Nil)]) else base
86
88
 
87
- fun onPress(self, target: Actor, at: Vec2) -> Option<ProbeAct> = Some(Pressed(on: target))
89
+ fun onPress(self, target: View, at: Vec2) -> Option<ProbeAct> = Some(Pressed(on: target))
88
90
 
89
91
  fun onPointer(self, e: InputEvent, at: Vec2) -> Option<ProbeAct> = if e.isPointerDown() then Some(Missed) else None
90
92
 
@@ -92,7 +94,6 @@ struct ProbeScreen[ScreenSlice<ProbeAct>](
92
94
  KeyDown(k) =>
93
95
  if k == Key.KeyG then Some(GoPlay)
94
96
  else if k == Key.KeyQ then Some(Quit)
95
- else if k == Key.KeyR then Some(Again)
96
97
  else if k == Key.Space then Some(Roll)
97
98
  else Some(Keyed)
98
99
  _ => None
@@ -113,27 +114,26 @@ struct ProbeScreen[ScreenSlice<ProbeAct>](
113
114
  fun effect(self, io: Io, a: ProbeAct, game: Control) = match a
114
115
  GoPlay => game.goTo("play")
115
116
  Quit => game.exit()
116
- Again => game.restart()
117
117
  _ => Unit
118
118
 
119
119
  # The group turned a quarter.
120
- fun turnedBy(g: Actor) -> Actor = match g
120
+ fun turnedBy(g: View) -> View = match g
121
121
  Group as gr => Turned(group: gr)
122
122
  _ => g
123
123
 
124
124
  # A group turned a quarter about its origin.
125
- struct Turned[Actor, Touch](group: Group) =
125
+ struct Turned[View, Touch](group: Group) =
126
126
  fun place(self) -> Place = place.at(self.group.x, self.group.y).rotateTo(Float.HalfPi)
127
127
 
128
- fun declared(self) -> List<Actor> = self.group.children
128
+ fun view(self) -> List<View> = self.group.children
129
129
 
130
130
  fun touch(self) -> Touchable = ChildrenOnly
131
131
 
132
132
  # The play: Escape goes back, fading in from the probe.
133
- struct PlayProbe[ScreenSlice<ProbeAct>](entered: Int, ticks: Int) =
133
+ struct PlayProbe[ScreenSlice<ProbeAct>](presses: Int, ticks: Int) =
134
134
  fun name(self) -> Str = "play"
135
135
 
136
- fun enter(self, from: Str) -> PlayProbe = PlayProbe(..self, entered: self.entered + 1)
136
+ fun onPointer(self, e: InputEvent, at: Vec2) -> Option<ProbeAct> = if e.isPointerDown() then Some(Missed) else None
137
137
 
138
138
  fun transition(self, from: Str) -> Transition = Fade(secs: 0.5)
139
139
 
@@ -145,14 +145,15 @@ struct PlayProbe[ScreenSlice<ProbeAct>](entered: Int, ticks: Int) =
145
145
 
146
146
  fun reduce(self, a: ProbeAct) -> PlayProbe = match a
147
147
  Ticked(_) => PlayProbe(..self, ticks: self.ticks + 1)
148
+ Missed => PlayProbe(..self, presses: self.presses + 1)
148
149
  _ => self
149
150
 
150
151
  fun effect(self, io: Io, a: ProbeAct, game: Control) = match a
151
152
  Back => game.goTo("probe")
152
153
  _ => Unit
153
154
 
154
- fun isOpenOverlay(a: Actor) -> Bool = match a
155
+ fun isOverlay(a: View) -> Bool = match a
155
- Overlay as o => o.open
156
+ Overlay as o => true
156
157
  _ => false
157
158
 
158
159
  fun probeOf(s: Screen) -> ProbeScreen = match s
@@ -161,18 +162,76 @@ fun probeOf(s: Screen) -> ProbeScreen = match s
161
162
 
162
163
  fun names(xs: List<ProbeAct>) -> Str = xs.fold("", |s, a| if s == "" then a.toStr() else "{s} {a.toStr()}")
163
164
 
164
- fun near(a: Float, b: Float) -> Bool = {a - b}.abs() < 0.001
165
-
166
165
  fun probe(io: Io) -> TestRig<ProbeScreen> = headless.mount(io, ProbeScreen.create(Always))
167
166
 
168
167
  fun twoScreens() -> Game =
169
168
  first: Screen := ProbeScreen.create(Always)
170
- second: Screen := PlayProbe(entered: 0, ticks: 0)
169
+ second: Screen := PlayProbe(presses: 0, ticks: 0)
171
170
  Game(screens: [first, second])
172
171
 
173
172
  fun playOf(t: TestRig<Screen>) -> PlayProbe = match t.game.screens.at(1)
174
173
  PlayProbe as p => p
175
- _ => PlayProbe(entered: -1, ticks: -1)
174
+ _ => PlayProbe(presses: -1, ticks: -1)
175
+
176
+ # A walker that moves right `speed` a second, stepped by the game.
177
+ struct Walker[Actor](x: Float, speed: Float) =
178
+ fun place(self) -> Place = place.at(self.x, 0.0)
179
+
180
+ fun view(self) -> List<View> = [Box.of(0.0, 0.0, 4.0, 4.0, Color.White)]
181
+
182
+ fun step(self, dt: Float) -> Walker = Walker(..self, x: self.x + self.speed * dt)
183
+
184
+ enum WalkAct = Saw(x: Float) | Walked(dt: Float) | Undo | Pause | Follow | HudPressed
185
+
186
+ # A screen of one walker: `held` notes where it is before the step and the tick action
187
+ # after it; P pauses the stepping, F has the camera follow the walker, two times as
188
+ # close; its hud is a button at the window's bottom-right corner; U asks for an undo.
189
+ struct WalkScreen[ScreenSlice<WalkAct>](walker: Walker, seen: List<Float>, paused: Bool, follow: Bool, hudPresses: Int) =
190
+ fun create() -> WalkScreen = WalkScreen(walker: Walker(x: 0.0, speed: 60.0), seen: Nil, paused: false, follow: false, hudPresses: 0)
191
+
192
+ fun name(self) -> Str = "walk"
193
+
194
+ fun size(self) -> Vec2 = Vec2(x: 800.0, y: 600.0)
195
+
196
+ fun view(self) -> List<View> = [self.walker]
197
+
198
+ fun hud(self, window: Vec2) -> List<View> = [Box(x: window.x - 20.0, y: window.y - 20.0, w: 20.0, h: 20.0, color: Color.White, touch: Enabled)]
199
+
200
+ fun steps(self) -> Bool = !self.paused
201
+
202
+ fun stepped(self, dt: Float) -> WalkScreen = WalkScreen(..self, walker: self.walker.step(dt))
203
+
204
+ fun camera(self, base: Viewport) -> Viewport = if self.follow then base.lookAt(self.walker.x, 0.0, 2.0) else base
205
+
206
+ fun held(self, input: Input) -> Option<WalkAct> = Some(Saw(x: self.walker.x))
207
+
208
+ fun tick(self, dt: Float) -> Option<WalkAct> = Some(Walked(dt: dt))
209
+
210
+ fun onPress(self, target: View, at: Vec2) -> Option<WalkAct> = Some(HudPressed)
211
+
212
+ fun onKey(self, e: InputEvent) -> Option<WalkAct> = match e
213
+ KeyDown(k) => if k == Key.KeyP then Some(Pause) else if k == Key.KeyF then Some(Follow) else if k == Key.KeyU then Some(Undo) else None
214
+ _ => None
215
+
216
+ fun reduce(self, a: WalkAct) -> WalkScreen = match a
217
+ Saw(x) => WalkScreen(..self, seen: self.seen.append([x]))
218
+ Walked(_) => WalkScreen(..self, seen: self.seen.append([self.walker.x]))
219
+ Pause => WalkScreen(..self, paused: true)
220
+ Follow => WalkScreen(..self, follow: true)
221
+ HudPressed => WalkScreen(..self, hudPresses: self.hudPresses + 1)
222
+ Undo => self
223
+
224
+ fun effect(self, io: Io, a: WalkAct, game: Control) = match a
225
+ Undo => game.undo()
226
+ _ => Unit
227
+
228
+ # A screen with no rules holding a walker: the game steps it all the same.
229
+ struct StillScreen[Screen](walker: Walker) =
230
+ fun name(self) -> Str = "still"
231
+
232
+ fun view(self) -> List<View> = [self.walker]
233
+
234
+ fun stepped(self, dt: Float) -> StillScreen = StillScreen(walker: self.walker.step(dt))
176
235
 
177
236
  test "a press reaches onPress as the item it is on, through the view's groups and their turns, never under a Disabled one"
178
237
  t := probe(io).clickAt(15.0, 15.0).tick()
@@ -191,16 +250,16 @@ test "an overlay in the view takes the press meant for what is under it"
191
250
  t := probe(io).tick()
192
251
  covered := headless.mount(io, ProbeScreen(..t.screen, covered: true)).clickAt(15.0, 15.0).tick()
193
252
  assert covered.screen.hits.length() == 1
194
- assert isOpenOverlay(covered.screen.hits.at(0))
253
+ assert isOverlay(covered.screen.hits.at(0))
195
254
 
196
255
  test "the press lands through the viewport: a wider screen moves the world"
197
256
  t := probe(io).resize(1600.0, 600.0)
198
257
  p := t.toWorld(800.0, 300.0)
199
- assert near(p.x, 400.0) && near(p.y, 300.0)
258
+ assert math.near(p.x, 400.0, 0.001) && math.near(p.y, 300.0, 0.001)
200
259
  u := t.clickAt(415.0, 15.0).tick()
201
260
  assert u.screen.hits.length() == 1 && @sameRef(u.screen.hits.at(0), u.screen.box)
202
261
  c := u.worldOf(u.screen.inner).unwrap().apply(Vec2(x: 0.0, y: 0.0))
203
- assert near(c.x, 200.0) && near(c.y, 150.0)
262
+ assert math.near(c.x, 200.0, 0.001) && math.near(c.y, 150.0, 0.001)
204
263
  assert u.click(u.screen.inner).tick().screen.hits.length() == 2
205
264
 
206
265
  test "the kit finds, counts and reads what the view draws"
@@ -227,24 +286,23 @@ test "press gives one key down, hold steers every tick, ticks(n) is n ticks"
227
286
  assert u.held.isDown(Key.KeyA)
228
287
  assert !u.release(Key.KeyA).held.isDown(Key.KeyA)
229
288
 
230
- test "effects go to another screen, which enters and fades in; the old one is kept and resumes"
289
+ test "effects go to another screen, which fades in, its presses dropped until it is in; the old one is kept and resumes"
231
290
  t := headless.play(io, twoScreens()).press(Key.KeyG).tick()
232
291
  assert t.wentTo().unwrap() == "play"
233
292
  assert t.showing() == "play"
234
293
  assert t.game.shifting()
294
+ sliding := t.clickAt(5.0, 5.0).tick()
235
- assert playOf(t).entered == 1
295
+ assert playOf(sliding).presses == 0
236
- u := t.ticks(30)
296
+ u := sliding.ticks(29)
297
+ assert playOf(u.clickAt(5.0, 5.0).tick()).presses == 1
237
298
  assert !u.game.shifting()
238
299
  assert playOf(u).ticks == 30
239
300
  back := u.press(Key.Escape).tick()
240
301
  assert back.showing() == "probe"
241
302
  assert probeOf(back.game.screen()).ticks == 1
242
303
 
243
- test "restart puts every screen back as the game was made with it; exit stops the ticks"
304
+ test "exit stops the ticks"
244
305
  t := headless.play(io, twoScreens()).press(Key.KeyA).tick()
245
- r := t.press(Key.KeyR).tick()
246
- assert r.restarted()
247
- assert probeOf(r.game.screen()).keys == 0
248
306
  q := t.press(Key.KeyQ).tick()
249
307
  assert q.exited()
250
308
  assert q.tick().game.ticks == q.game.ticks
@@ -252,15 +310,15 @@ test "restart puts every screen back as the game was made with it; exit stops th
252
310
  test "an OnDemand view screen ticks after an action and while it is busy, and sleeps otherwise"
253
311
  t := headless.mount(io, ProbeScreen.create(OnDemand)).ticks(10)
254
312
  assert t.screen.ticks == 1
255
- d := TestRig(..t, game: t.game.drawn())
313
+ d := TestRig(..t, game: t.game.frameDrawn())
256
314
  assert d.game.idle()
257
315
  k := d.press(Key.KeyA).tick()
258
316
  assert !k.game.idle()
259
- later := TestRig(..k, game: k.game.drawn()).ticks(10)
317
+ later := TestRig(..k, game: k.game.frameDrawn()).ticks(10)
260
318
  assert later.screen.ticks == 1 + 1 + 2
261
- assert TestRig(..later, game: later.game.drawn()).game.idle()
319
+ assert TestRig(..later, game: later.game.frameDrawn()).game.idle()
262
320
  assert later.game.skipped > 0
263
- c := TestRig(..later, game: later.game.drawn()).clickAt(15.0, 15.0).tick()
321
+ c := TestRig(..later, game: later.game.frameDrawn()).clickAt(15.0, 15.0).tick()
264
322
  assert c.screen.hits.length() == 1
265
323
 
266
324
  test "a recorded run replays to the same state"
@@ -294,3 +352,41 @@ test "undo goes back before the last user action, redo forward again, and a rewi
294
352
  p := s.pause().tick()
295
353
  assert p.game.tickNow() == 4
296
354
  assert p.resume().tick().game.tickNow() == 5
355
+
356
+ test "the game steps the screen's actors between held and the tick action; steps() false pauses it"
357
+ t := headless.mount(io, WalkScreen.create()).tick(0.5)
358
+ assert t.screen.seen.length() == 2 && t.screen.seen.at(0) == 0.0 && t.screen.seen.at(1) == 30.0
359
+ u := t.press(Key.KeyP).tick(0.5)
360
+ assert u.screen.walker.x == 30.0
361
+ assert @sameRef(u.first<Walker>(), u.screen.walker)
362
+
363
+ test "a plain screen's actors are stepped too"
364
+ only: Screen := StillScreen(walker: Walker(x: 0.0, speed: 10.0))
365
+ t := headless.play(io, Game(screens: [only])).ticks(6)
366
+ assert math.near(t.first<Walker>().x, 1.0, 0.000001)
367
+
368
+ test "the hud sits on the window, one unit a pixel: hit before the view, and found by the kit"
369
+ t := headless.mount(io, WalkScreen.create()).resize(1600.0, 600.0)
370
+ assert t.count<Box>() == 2
371
+ assert t.hit(1590.0, 590.0).isSome()
372
+ u := t.clickAt(1590.0, 590.0).tick()
373
+ assert u.screen.hudPresses == 1
374
+ assert t.drawn().length() == 3
375
+
376
+ test "a screen's camera looks at what it follows, zoomed, and presses and toWorld follow it"
377
+ t := headless.mount(io, WalkScreen.create()).tick(1.0)
378
+ assert math.near(t.toWorld(0.0, 0.0).x, 0.0, 0.000001)
379
+ u := t.press(Key.KeyF).tick(1.0)
380
+ assert u.screen.walker.x == 120.0
381
+ c := u.toWorld(400.0, 300.0)
382
+ assert math.near(c.x, 120.0, 0.000001) && math.near(c.y, 0.0, 0.000001)
383
+ assert math.near(u.toWorld(0.0, 300.0).x, 120.0 - 200.0, 0.000001)
384
+ assert u.game.visible(0).min.x == u.toWorld(0.0, 0.0).x
385
+
386
+ test "the kit's dispatch does an undo its effect asks for at once"
387
+ t := headless.mountWith(io, WalkScreen.create()).press(Key.KeyP).ticks(3)
388
+ assert t.screen.paused && t.game.tickNow() == 3
389
+ u := t.dispatch(Undo)
390
+ assert u.moved()
391
+ assert !u.screen.paused
392
+ assert u.game.tickNow() == 0