ttyengine 0.2.0__tar.gz → 0.2.2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. {ttyengine-0.2.0 → ttyengine-0.2.2}/PKG-INFO +58 -1
  2. {ttyengine-0.2.0 → ttyengine-0.2.2}/README.md +57 -0
  3. {ttyengine-0.2.0 → ttyengine-0.2.2}/pyproject.toml +1 -1
  4. ttyengine-0.2.2/tests/test_perf.py +342 -0
  5. ttyengine-0.2.2/tests/test_speedups.py +630 -0
  6. {ttyengine-0.2.0 → ttyengine-0.2.2}/ttyengine/__init__.py +2 -2
  7. {ttyengine-0.2.0 → ttyengine-0.2.2}/ttyengine/ansi.py +44 -0
  8. ttyengine-0.2.2/ttyengine/broadphase.py +142 -0
  9. {ttyengine-0.2.0 → ttyengine-0.2.2}/ttyengine/components/inherit.py +4 -3
  10. {ttyengine-0.2.0 → ttyengine-0.2.2}/ttyengine/components/light.py +82 -23
  11. {ttyengine-0.2.0 → ttyengine-0.2.2}/ttyengine/components/physics.py +306 -21
  12. ttyengine-0.2.2/ttyengine/components/shared.py +343 -0
  13. {ttyengine-0.2.0 → ttyengine-0.2.2}/ttyengine/components/transform.py +196 -70
  14. {ttyengine-0.2.0 → ttyengine-0.2.2}/ttyengine/compositor.py +132 -50
  15. {ttyengine-0.2.0 → ttyengine-0.2.2}/ttyengine/image_reader.py +71 -19
  16. {ttyengine-0.2.0 → ttyengine-0.2.2}/ttyengine/input_handler.py +38 -21
  17. {ttyengine-0.2.0 → ttyengine-0.2.2}/ttyengine/launcher.py +235 -7
  18. {ttyengine-0.2.0 → ttyengine-0.2.2}/ttyengine/scene.py +107 -6
  19. {ttyengine-0.2.0 → ttyengine-0.2.2}/ttyengine/sound.py +66 -6
  20. {ttyengine-0.2.0 → ttyengine-0.2.2}/ttyengine.egg-info/PKG-INFO +58 -1
  21. {ttyengine-0.2.0 → ttyengine-0.2.2}/ttyengine.egg-info/SOURCES.txt +3 -0
  22. ttyengine-0.2.0/ttyengine/components/shared.py +0 -194
  23. {ttyengine-0.2.0 → ttyengine-0.2.2}/LICENSE +0 -0
  24. {ttyengine-0.2.0 → ttyengine-0.2.2}/setup.cfg +0 -0
  25. {ttyengine-0.2.0 → ttyengine-0.2.2}/tests/test_engine.py +0 -0
  26. {ttyengine-0.2.0 → ttyengine-0.2.2}/tests/test_net.py +0 -0
  27. {ttyengine-0.2.0 → ttyengine-0.2.2}/tests/test_smoke.py +0 -0
  28. {ttyengine-0.2.0 → ttyengine-0.2.2}/ttyengine/ascii_styler.py +0 -0
  29. {ttyengine-0.2.0 → ttyengine-0.2.2}/ttyengine/components/__init__.py +0 -0
  30. {ttyengine-0.2.0 → ttyengine-0.2.2}/ttyengine/components/force.py +0 -0
  31. {ttyengine-0.2.0 → ttyengine-0.2.2}/ttyengine/components/humanoid.py +0 -0
  32. {ttyengine-0.2.0 → ttyengine-0.2.2}/ttyengine/components/joint.py +0 -0
  33. {ttyengine-0.2.0 → ttyengine-0.2.2}/ttyengine/components/pen.py +0 -0
  34. {ttyengine-0.2.0 → ttyengine-0.2.2}/ttyengine/errors.py +0 -0
  35. {ttyengine-0.2.0 → ttyengine-0.2.2}/ttyengine/figlet-LICENSE.txt +0 -0
  36. {ttyengine-0.2.0 → ttyengine-0.2.2}/ttyengine/figlet.py +0 -0
  37. {ttyengine-0.2.0 → ttyengine-0.2.2}/ttyengine/fonts.zip +0 -0
  38. {ttyengine-0.2.0 → ttyengine-0.2.2}/ttyengine/net/__init__.py +0 -0
  39. {ttyengine-0.2.0 → ttyengine-0.2.2}/ttyengine/net/codec.py +0 -0
  40. {ttyengine-0.2.0 → ttyengine-0.2.2}/ttyengine/net/errors.py +0 -0
  41. {ttyengine-0.2.0 → ttyengine-0.2.2}/ttyengine/net/layers.py +0 -0
  42. {ttyengine-0.2.0 → ttyengine-0.2.2}/ttyengine/net/node.py +0 -0
  43. {ttyengine-0.2.0 → ttyengine-0.2.2}/ttyengine/net/sync.py +0 -0
  44. {ttyengine-0.2.0 → ttyengine-0.2.2}/ttyengine/net/transport.py +0 -0
  45. {ttyengine-0.2.0 → ttyengine-0.2.2}/ttyengine/region.py +0 -0
  46. {ttyengine-0.2.0 → ttyengine-0.2.2}/ttyengine/terminal.py +0 -0
  47. {ttyengine-0.2.0 → ttyengine-0.2.2}/ttyengine.egg-info/dependency_links.txt +0 -0
  48. {ttyengine-0.2.0 → ttyengine-0.2.2}/ttyengine.egg-info/requires.txt +0 -0
  49. {ttyengine-0.2.0 → ttyengine-0.2.2}/ttyengine.egg-info/top_level.txt +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: ttyengine
3
- Version: 0.2.0
3
+ Version: 0.2.2
4
4
  Summary: A terminal rendering, physics and sound engine
5
5
  Project-URL: Homepage, https://github.com/asard6348/tty-engine
6
6
  Project-URL: Source, https://github.com/asard6348/tty-engine
@@ -328,6 +328,63 @@ class main:
328
328
 
329
329
  </details>
330
330
 
331
+ <details>
332
+ <summary><b>Waiting, timers and tasks</b></summary>
333
+
334
+ &nbsp;
335
+
336
+ A handle can pause its own code, or schedule code to run later, without stopping anything else. The frame loop, physics, rendering, input and the handle's other functions keep running. Request the `handle` argument like any other (see the table above).
337
+
338
+ **`handle.wait(duration, frames=False)`** suspends the function that calls it. The rest of that function runs once `duration` seconds have passed, or `duration` frames with `frames=True`:
339
+
340
+ ```python
341
+ def final(self, scene, handle):
342
+ if self.scored():
343
+ self.reset_ball() # runs now
344
+ handle.wait(1) # this function stops here for one second
345
+ self.release_ball() # runs one second later
346
+ ```
347
+
348
+ **`handle.until(condition, timeout=None, frames=False)`** suspends until `condition()` returns true. It returns `True` when the condition was met and `False` when `timeout` ran out first:
349
+
350
+ ```python
351
+ def start(self, handle, session):
352
+ if not handle.until(lambda: session.inp.held('space'), timeout=5):
353
+ print('nobody pressed space')
354
+ ```
355
+
356
+ **`handle.after(delay, fn, frames=False)`** and **`handle.every(interval, fn, frames=False, delay=None)`** run `fn` later, once or repeatedly. `fn` receives the same arguments as `start`, `update` and `final` (`scene`, `handle` and so on, matched by name), and `every` first fires after `delay`, which defaults to `interval`. Both work from anywhere, including input callbacks and helper functions, and both return a `Task`:
357
+
358
+ ```python
359
+ blink = handle.every(0.5, lambda scene: scene.obj().create('*', 2, -2))
360
+ handle.after(10, blink.cancel)
361
+ ```
362
+
363
+ **`Task`** is one scheduled callback or one suspended function. It is created by `after` and `every`, or directly with `Task(handle, fn, delay=0.0, interval=None, frames=False)`, and `from ttyengine import Task` imports it. A task is cancelled the same way as a handle:
364
+
365
+ | Member | Meaning |
366
+ |---|---|
367
+ | `task.cancel()` | Stops the task. A function suspended in `wait` or `until` never runs the code after it, and a repeating task stops repeating. `world.cancel(task)` does the same. |
368
+ | `task.done` | `True` once the callback has finished (a repeating task never is). |
369
+ | `task.cancelled` | `True` after `cancel()`. |
370
+ | `task.result` | The return value of the last run. |
371
+
372
+ `handle.tasks` lists every live task of the handle: its timers and its suspended `start`, `update` and `final` calls. `handle.cancel()` cancels all of them, and cancelling one task leaves the handle and its other tasks running, so a "skip the cutscene" button is `for task in handle.tasks: task.cancel()`.
373
+
374
+ Things to know:
375
+
376
+ - `start`, `update` and `final` each wait on their own. A `wait` in `final` does not stop `update`, so players can keep moving while the ball is held.
377
+ - While a function is waiting, the world does not call it again. It is called normally once it has finished.
378
+ - `start` can wait too. Its code resumes on the following frames, and a function used as a handle (see [A function works too](#quick-start)) can wait the same way.
379
+ - Write `wait` and `until` directly in `start`, `update`, `final` or the function you pass to `after` or `every`. Inside a helper they cannot suspend the caller: `wait` just sleeps, which blocks the whole engine for that time, and `until` raises a `RuntimeError`. Called from an input callback, `wait` also just sleeps.
380
+ - Everything is checked once per frame, so a delay is accurate to one frame time.
381
+ - While a handle is paused (`handle.pause = True`), its world is paused or the session is paused, the clock of its waits and timers stands still, and frame counts only advance on frames the handle actually ran. Time spent paused does not count towards a delay.
382
+ - Only one piece of your code runs at a time, so a waiting function never runs at the same moment as the frame loop and needs no locking. An error raised after a `wait` is reported like any other error inside a handle.
383
+
384
+ `pause` is a property on handles, worlds and the session, as are `pausephysics` and `pauserendering` on worlds and the session. They accept any truthy or falsy value and store a bool.
385
+
386
+ </details>
387
+
331
388
  <sub>[↑ Back to top](#top)</sub>
332
389
 
333
390
  ## Usage guide
@@ -294,6 +294,63 @@ class main:
294
294
 
295
295
  </details>
296
296
 
297
+ <details>
298
+ <summary><b>Waiting, timers and tasks</b></summary>
299
+
300
+ &nbsp;
301
+
302
+ A handle can pause its own code, or schedule code to run later, without stopping anything else. The frame loop, physics, rendering, input and the handle's other functions keep running. Request the `handle` argument like any other (see the table above).
303
+
304
+ **`handle.wait(duration, frames=False)`** suspends the function that calls it. The rest of that function runs once `duration` seconds have passed, or `duration` frames with `frames=True`:
305
+
306
+ ```python
307
+ def final(self, scene, handle):
308
+ if self.scored():
309
+ self.reset_ball() # runs now
310
+ handle.wait(1) # this function stops here for one second
311
+ self.release_ball() # runs one second later
312
+ ```
313
+
314
+ **`handle.until(condition, timeout=None, frames=False)`** suspends until `condition()` returns true. It returns `True` when the condition was met and `False` when `timeout` ran out first:
315
+
316
+ ```python
317
+ def start(self, handle, session):
318
+ if not handle.until(lambda: session.inp.held('space'), timeout=5):
319
+ print('nobody pressed space')
320
+ ```
321
+
322
+ **`handle.after(delay, fn, frames=False)`** and **`handle.every(interval, fn, frames=False, delay=None)`** run `fn` later, once or repeatedly. `fn` receives the same arguments as `start`, `update` and `final` (`scene`, `handle` and so on, matched by name), and `every` first fires after `delay`, which defaults to `interval`. Both work from anywhere, including input callbacks and helper functions, and both return a `Task`:
323
+
324
+ ```python
325
+ blink = handle.every(0.5, lambda scene: scene.obj().create('*', 2, -2))
326
+ handle.after(10, blink.cancel)
327
+ ```
328
+
329
+ **`Task`** is one scheduled callback or one suspended function. It is created by `after` and `every`, or directly with `Task(handle, fn, delay=0.0, interval=None, frames=False)`, and `from ttyengine import Task` imports it. A task is cancelled the same way as a handle:
330
+
331
+ | Member | Meaning |
332
+ |---|---|
333
+ | `task.cancel()` | Stops the task. A function suspended in `wait` or `until` never runs the code after it, and a repeating task stops repeating. `world.cancel(task)` does the same. |
334
+ | `task.done` | `True` once the callback has finished (a repeating task never is). |
335
+ | `task.cancelled` | `True` after `cancel()`. |
336
+ | `task.result` | The return value of the last run. |
337
+
338
+ `handle.tasks` lists every live task of the handle: its timers and its suspended `start`, `update` and `final` calls. `handle.cancel()` cancels all of them, and cancelling one task leaves the handle and its other tasks running, so a "skip the cutscene" button is `for task in handle.tasks: task.cancel()`.
339
+
340
+ Things to know:
341
+
342
+ - `start`, `update` and `final` each wait on their own. A `wait` in `final` does not stop `update`, so players can keep moving while the ball is held.
343
+ - While a function is waiting, the world does not call it again. It is called normally once it has finished.
344
+ - `start` can wait too. Its code resumes on the following frames, and a function used as a handle (see [A function works too](#quick-start)) can wait the same way.
345
+ - Write `wait` and `until` directly in `start`, `update`, `final` or the function you pass to `after` or `every`. Inside a helper they cannot suspend the caller: `wait` just sleeps, which blocks the whole engine for that time, and `until` raises a `RuntimeError`. Called from an input callback, `wait` also just sleeps.
346
+ - Everything is checked once per frame, so a delay is accurate to one frame time.
347
+ - While a handle is paused (`handle.pause = True`), its world is paused or the session is paused, the clock of its waits and timers stands still, and frame counts only advance on frames the handle actually ran. Time spent paused does not count towards a delay.
348
+ - Only one piece of your code runs at a time, so a waiting function never runs at the same moment as the frame loop and needs no locking. An error raised after a `wait` is reported like any other error inside a handle.
349
+
350
+ `pause` is a property on handles, worlds and the session, as are `pausephysics` and `pauserendering` on worlds and the session. They accept any truthy or falsy value and store a bool.
351
+
352
+ </details>
353
+
297
354
  <sub>[↑ Back to top](#top)</sub>
298
355
 
299
356
  ## Usage guide
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "ttyengine"
7
- version = "0.2.0"
7
+ version = "0.2.2"
8
8
  description = "A terminal rendering, physics and sound engine"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.8"
@@ -0,0 +1,342 @@
1
+ import base64
2
+ import functools
3
+ import hashlib
4
+ import inspect
5
+ import os
6
+ import random
7
+ import struct
8
+ import unittest
9
+ import zlib
10
+
11
+ os.environ.setdefault("COLUMNS", "100")
12
+ os.environ.setdefault("LINES", "40")
13
+
14
+ from array import array
15
+
16
+ from ttyengine import ansi, image_reader, input_handler
17
+ from ttyengine import scene as scene_mod
18
+ from ttyengine.components import shared
19
+ from ttyengine.sound import Mixer, Sound, Voice
20
+
21
+
22
+ JPEGS = {
23
+ 'color420': ('6d9d4390946f8a79c733dd87ec70d5e0', '/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAoHBwgHBgoICAgLCgoLDhgQDg0NDh0VFhEYIx8lJCIfIiEmKzcvJik0KSEiMEExNDk7Pj4+JS5ESUM8SDc9Pjv/2wBDAQoLCw4NDhwQEBw7KCIoOzs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozv/wAARCAATABoDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6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qqSkr2qxj6xlGaaa2a0Wjuk9VZ6n6N4WZVg8xlVeKpqXs1CUfVt3va117q0d1vpq7+hfDHVL/UfBuo6hd3Be6htoJUkVQhDfYbeYk7QM/vHc4ORzjpxX5vgMtwtHFU6cIJJzlH5c842+5L7r7nRxlSjgMLUlhrxcYTktXvCpUUd30UIprZpap3d/lDxt8SvGtn4z1y0t9ZCwwajcRxhrSFiFWRgMkoSeB1PNf1plvC2UTwdGToK7jHv2XmfmOX8OZdjMJSxNeDlOcYyk3KV22k2373V6n/2Q=='),
25
+ 'progressive': ('e4cff2d124597f40c597e17df3bff23c', '/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAA0JCgsKCA0LCgsODg0PEyAVExISEyccHhcgLikxMC4pLSwzOko+MzZGNywtQFdBRkxOUlNSMj5aYVpQYEpRUk//2wBDAQ4ODhMREyYVFSZPNS01T09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT0//wgARCAATABoDASIAAhEBAxEB/8QAGAABAQEBAQAAAAAAAAAAAAAABAAFBgL/xAAWAQEBAQAAAAAAAAAAAAAAAAADAQL/2gAMAwEAAhADEAAAAclK1ngAOiz9p5TVBvO09//EABoQAAMBAQEBAAAAAAAAAAAAAAECAwASIQT/2gAIAQEAAQUCCYTwnjP1Z5UxXzgbtg/1OyCLEzpegp//xAAdEQABBAIDAAAAAAAAAAAAAAABAAIDBBETIUHw/9oACAEDAQE/AYbCtT5A5VVo2M90pmgyYK//xAAcEQACAgIDAAAAAAAAAAAAAAABAgASBSERMXH/2gAIAQIBAT8BQ2iOg63EAqPJj0U86n//xAAgEAABAwMFAQAAAAAAAAAAAAABABExAhASAyFBUZHh/9oACAEBAAY/ArQi99lB9WoHiPCqcSzyiTPxVDLnpf/EACAQAAICAQMFAAAAAAAAAAAAAAABESExEEGBUWFxwfD/2gAIAQEAAT8h0Zu3gPuXNnY0YHg2yXIGsKRwxd6Jk4WvnI56iTngxVqJ1h1P/9oADAMBAAIAA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/9k='),
27
+ }
28
+
29
+
30
+ def make_scene(gravity=(0, 0)):
31
+ sc = scene_mod.Scene()
32
+ sc.termx, sc.termy, sc.dimx, sc.dimy = 120, 40, 120, 40
33
+ sc.camx, sc.camy = -60, 20
34
+ sc.gravity = gravity
35
+ return sc
36
+
37
+
38
+ def frame(sc):
39
+ sc.tick(True)
40
+ return sc.render()
41
+
42
+
43
+ class BroadphaseTests(unittest.TestCase):
44
+ def test_near_matches_brute_force_while_objects_move(self):
45
+ rng = random.Random(7)
46
+ sc = make_scene()
47
+ for _ in range(60):
48
+ sc.obj().create(rng.choice(["O", "##\n##", "@@@"]), rng.randint(-50, 50), rng.randint(-15, 15), dynamic=False, solid=True)
49
+ wall = "\n".join("#" * 90 for _ in range(12))
50
+ sc.obj().create(wall, -45, 10, dynamic=False, solid=True)
51
+ broad = sc._broad
52
+ for step in range(5):
53
+ for obj in rng.sample(list(sc.solids), 20):
54
+ obj.transform.x += rng.randint(-9, 9)
55
+ obj.transform.y += rng.randint(-5, 5)
56
+ for _ in range(25):
57
+ x0 = rng.randint(-60, 50)
58
+ y0 = rng.randint(-20, 15)
59
+ x1 = x0 + rng.randint(0, 25)
60
+ y1 = y0 + rng.randint(0, 12)
61
+ expected = []
62
+ for obj in sc.solids:
63
+ box = obj.physics.bounds()
64
+ if box is not None and not (box[1] < x0 or box[0] > x1 or box[3] < y0 or box[2] > y1):
65
+ expected.append(obj)
66
+ self.assertEqual(broad.near(x0, x1, y0, y1), expected)
67
+
68
+ def test_new_and_removed_solids_are_tracked(self):
69
+ sc = make_scene()
70
+ a = sc.obj().create("#", 0, 0, dynamic=False, solid=True)
71
+ self.assertEqual(sc._broad.near(-1, 1, -1, 1), [a])
72
+ b = sc.obj().create("#", 1, 0, dynamic=False, solid=True)
73
+ self.assertEqual(sc._broad.near(-1, 2, -1, 1), [a, b])
74
+ sc.solids.remove(a)
75
+ self.assertEqual(sc._broad.near(-1, 2, -1, 1), [b])
76
+
77
+
78
+ class MotionTests(unittest.TestCase):
79
+ def test_fast_body_does_not_tunnel(self):
80
+ sc = make_scene()
81
+ wall = "\n".join("#" for _ in range(30))
82
+ sc.obj().create(wall, 40, 15, dynamic=False, solid=True)
83
+ ball = sc.obj().create("O", 0, 0, xvel=5000, bounciness=0.0)
84
+ for _ in range(20):
85
+ frame(sc)
86
+ self.assertLess(ball.transform.x, 40)
87
+
88
+ def test_huge_fast_body_stays_inside_walls(self):
89
+ sc = make_scene()
90
+ top = "#" * 100
91
+ side = "\n".join("#" for _ in range(30))
92
+ sc.obj().create(top, -50, 15, dynamic=False, solid=True)
93
+ sc.obj().create(top, -50, -15, dynamic=False, solid=True)
94
+ sc.obj().create(side, -50, 15, dynamic=False, solid=True)
95
+ sc.obj().create(side, 50, 15, dynamic=False, solid=True)
96
+ block = "\n".join("#" * 20 for _ in range(6))
97
+ body = sc.obj().create(block, -10, 5, xvel=9000, yvel=4000, bounciness=0.8)
98
+ for _ in range(40):
99
+ frame(sc)
100
+ self.assertTrue(-50 < body.transform.x < 50)
101
+ self.assertTrue(-15 < body.transform.y < 15)
102
+
103
+ def test_rotation_result_is_stable_after_cache(self):
104
+ sc = make_scene()
105
+ obj = sc.obj().create("###\n###", 0, 0)
106
+ t = obj.transform
107
+ t.rotation = 37
108
+ first = (t.text, t.vx, t.vy)
109
+ t.rotation = 90
110
+ t.rotation = 37
111
+ self.assertEqual((t.text, t.vx, t.vy), first)
112
+
113
+
114
+ class MaskedPenetrationTests(unittest.TestCase):
115
+ def reference(self, mine, other, aspect):
116
+ best = None
117
+ for dx, dy, cost in ((1, 0, aspect), (-1, 0, aspect), (0, 1, 1.0), (0, -1, 1.0)):
118
+ for k in range(1, 64):
119
+ moved = {(x + dx * k, y + dy * k) for x, y in mine}
120
+ if not moved & other:
121
+ score = k * cost - (0.01 if dy == 1 else 0)
122
+ if best is None or score < best[0]:
123
+ best = (score, dx, dy, k)
124
+ break
125
+ return best
126
+
127
+ def test_matches_set_based_search(self):
128
+ rng = random.Random(3)
129
+ for _ in range(200):
130
+ mine = {(rng.randint(0, 9), rng.randint(0, 6)) for _ in range(rng.randint(1, 30))}
131
+ other = {(rng.randint(-3, 12), rng.randint(-3, 9)) for _ in range(rng.randint(1, 40))}
132
+ self.assertEqual(shared._mtv_cells(mine, other, 2.0), self.reference(mine, other, 2.0))
133
+
134
+
135
+ class MixerTests(unittest.TestCase):
136
+ def build(self, speeds):
137
+ rng = random.Random(5)
138
+ mixer = Mixer(backend=lambda *a: None)
139
+ sounds = [mixer.tone(rng.uniform(100, 1500), 0.5, wave, 0.9) for wave in ("sine", "square", "saw")]
140
+ voices = []
141
+ for i, speed in enumerate(speeds):
142
+ voice = Voice(mixer, sounds[i % 3].at_rate(mixer.rate), rng.uniform(0.2, 2.5), rng.uniform(-1, 1), True, None, speed, None, None, None)
143
+ voice._pos = rng.randint(0, 9000)
144
+ mixer._voices.append(voice)
145
+ return mixer, voices
146
+
147
+ def scalar(self, mixer, voices, frames):
148
+ left = [0] * frames
149
+ right = [0] * frames
150
+ for v in voices:
151
+ gain = v._volume * mixer._volume * 256.0
152
+ pan = max(-1.0, min(1.0, v._pan))
153
+ gl = int(gain * (1.0 if pan <= 0 else 1.0 - pan))
154
+ gr = int(gain * (1.0 if pan >= 0 else 1.0 + pan))
155
+ total = v._sound.frames
156
+ for n in range(frames):
157
+ i = (v._pos + n) % total
158
+ left[n] += (v._sound.left[i] * gl) >> 8
159
+ right[n] += (v._sound.right[i] * gr) >> 8
160
+ out = array("h", bytes(4 * frames))
161
+ clip = lambda s: 32767 if s > 32767 else -32768 if s < -32768 else s
162
+ out[0::2] = array("h", [clip(s) for s in left])
163
+ out[1::2] = array("h", [clip(s) for s in right])
164
+ return out.tobytes()
165
+
166
+ def test_plain_voices_match_scalar_mix(self):
167
+ mixer, voices = self.build([1.0] * 12)
168
+ voices = list(mixer._voices)
169
+ expected = self.scalar(mixer, voices, mixer.block)
170
+ self.assertEqual(mixer._render(), expected)
171
+
172
+ def test_overdriven_mix_clips_like_scalar(self):
173
+ mixer, voices = self.build([1.0] * 30)
174
+ voices = list(mixer._voices)
175
+ expected = self.scalar(mixer, voices, mixer.block)
176
+ self.assertEqual(mixer._render(), expected)
177
+
178
+
179
+ def _png(rows, ctype, bpp, kind, palette=None):
180
+ width = len(rows[0]) // bpp
181
+ raw = bytearray()
182
+ prev = bytes(len(rows[0]))
183
+ for y, row in enumerate(rows):
184
+ row = bytes(row)
185
+ ft = kind if kind < 5 else y % 5
186
+ raw.append(ft)
187
+ for i in range(len(row)):
188
+ a = row[i - bpp] if i >= bpp else 0
189
+ b = prev[i]
190
+ c = prev[i - bpp] if i >= bpp else 0
191
+ if ft == 0:
192
+ p = 0
193
+ elif ft == 1:
194
+ p = a
195
+ elif ft == 2:
196
+ p = b
197
+ elif ft == 3:
198
+ p = (a + b) >> 1
199
+ else:
200
+ est = a + b - c
201
+ pa, pb, pc = abs(est - a), abs(est - b), abs(est - c)
202
+ p = a if pa <= pb and pa <= pc else (b if pb <= pc else c)
203
+ raw.append((row[i] - p) & 255)
204
+ prev = row
205
+
206
+ def chunk(name, data):
207
+ return struct.pack('>I', len(data)) + name + data + struct.pack('>I', zlib.crc32(name + data) & 0xffffffff)
208
+
209
+ out = b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', struct.pack('>IIBBBBB', width, len(rows), 8, ctype, 0, 0, 0))
210
+ if palette:
211
+ out += chunk(b'PLTE', palette)
212
+ return out + chunk(b'IDAT', zlib.compress(bytes(raw))) + chunk(b'IEND', b'')
213
+
214
+
215
+ class ImageDecodeTests(unittest.TestCase):
216
+ def rows(self, width, height, bpp, seed):
217
+ rng = random.Random(seed)
218
+ smooth = [[(x * 3 + y * 5 + k * 40) & 255 for x in range(width * bpp)] for y in range(height) for k in (0,)]
219
+ noisy = [[rng.randrange(256) for _ in range(width * bpp)] for _ in range(height)]
220
+ return [smooth[y] if y % 2 else noisy[y] for y in range(height)]
221
+
222
+ def test_every_png_filter_round_trips(self):
223
+ for ctype, bpp in ((2, 3), (6, 4), (0, 1), (4, 2)):
224
+ for kind in range(6):
225
+ for width in (1, 2, 7, 33):
226
+ rows = self.rows(width, 9, bpp, ctype * 100 + kind * 10 + width)
227
+ w, h, data = image_reader.decode(_png(rows, ctype, bpp, kind))
228
+ self.assertEqual((w, h), (width, 9))
229
+ for y, row in enumerate(rows):
230
+ got = bytes(data[y * w * 4:(y + 1) * w * 4])
231
+ if ctype == 6:
232
+ want = bytes(row)
233
+ elif ctype == 2:
234
+ want = b''.join(bytes(row[i:i + 3]) + b'\xff' for i in range(0, len(row), 3))
235
+ elif ctype == 0:
236
+ want = b''.join(bytes((v, v, v, 255)) for v in row)
237
+ else:
238
+ want = b''.join(bytes((row[i], row[i], row[i], row[i + 1])) for i in range(0, len(row), 2))
239
+ self.assertEqual(got, want, (ctype, kind, width, y))
240
+
241
+ def test_palette_png_maps_every_index(self):
242
+ palette = bytes(v for i in range(40) for v in (i * 6 % 256, i * 11 % 256, i * 17 % 256))
243
+ rows = [[(x * 7 + y) % 256 for x in range(30)] for y in range(6)]
244
+ w, h, data = image_reader.decode(_png(rows, 3, 1, 5, palette))
245
+ for y, row in enumerate(rows):
246
+ for x, index in enumerate(row):
247
+ got = tuple(data[(y * w + x) * 4:(y * w + x) * 4 + 4])
248
+ want = tuple(palette[index * 3:index * 3 + 3]) + (255,) if index < 40 else (0, 0, 0, 255)
249
+ self.assertEqual(got, want)
250
+
251
+ def test_jpeg_decoding_is_unchanged(self):
252
+ for name, (digest, encoded) in JPEGS.items():
253
+ w, h, data = image_reader.decode(base64.b64decode(encoded))
254
+ self.assertEqual((w, h), (26, 19), name)
255
+ self.assertEqual(hashlib.md5(bytes(data)).hexdigest(), digest, name)
256
+
257
+
258
+ class ColorCollapseTests(unittest.TestCase):
259
+ def test_keeps_only_the_last_color_of_each_kind(self):
260
+ c = ansi.CSI
261
+ style = c + '48;2;0;0;0m' + c + '38;2;1;2;3m' + c + '1m' + c + '38;2;4;5;6m' + c + '48;2;9;9;9m'
262
+ self.assertEqual(ansi.collapse_color(style), c + '1m' + c + '38;2;4;5;6m' + c + '48;2;9;9;9m')
263
+
264
+ def test_mixed_color_forms_collapse_by_kind(self):
265
+ c = ansi.CSI
266
+ self.assertEqual(ansi.collapse_color(c + '31m' + c + '38;5;9m' + c + '4m' + c + '92m'), c + '4m' + c + '92m')
267
+
268
+ def test_other_styles_are_untouched(self):
269
+ c = ansi.CSI
270
+ for style in ('', c + '31m', c + '1m' + c + '31m', c + '1m' + c + '4m' + c + '3m', 'text' + c + '31m' + c + '32m' + c + '33m',
271
+ c + '1;31m' + c + '32m' + c + '4m'):
272
+ self.assertEqual(ansi.collapse_color(style), style)
273
+
274
+ def test_stacked_colors_render_the_same_screen_with_less_output(self):
275
+ sc = make_scene()
276
+ c = ansi.CSI
277
+ row = ''.join(c + '38;2;%d;10;10m%s' % (i * 9, 'ab'[i % 2]) for i in range(20))
278
+ sc.obj().create(row + c + '0m', -10, 0)
279
+ frame_text = sc.render(full=True)
280
+ self.assertEqual(frame_text.count('38;2;'), 20)
281
+ for i in range(20):
282
+ self.assertIn(c + '38;2;%d;10;10m%s' % (i * 9, 'ab'[i % 2]), frame_text)
283
+
284
+
285
+ class CallbackShapeTests(unittest.TestCase):
286
+ def callbacks(self):
287
+ class Holder:
288
+ def method(self, a, b):
289
+ pass
290
+
291
+ def __call__(self, a):
292
+ pass
293
+
294
+ class Unhashable:
295
+ __hash__ = None
296
+
297
+ def __call__(self, a, b, c):
298
+ pass
299
+
300
+ def plain(a, b=1, *rest, key=None, **extra):
301
+ pass
302
+
303
+ return [plain, lambda: None, lambda a: a, Holder().method, Holder(), functools.partial(plain, 1), Unhashable(), len]
304
+
305
+ def test_argument_counts_match_inspect_and_stay_stable(self):
306
+ for cb in self.callbacks():
307
+ expected = len(inspect.signature(cb).parameters)
308
+ for _ in range(3):
309
+ self.assertEqual(shared._argslen(cb), expected)
310
+ self.assertEqual(scene_mod._argslen(cb), expected)
311
+
312
+ def test_input_shapes_match_inspect(self):
313
+ for cb in self.callbacks():
314
+ params = list(inspect.signature(cb).parameters.values())
315
+ var = any(p.kind == p.VAR_POSITIONAL for p in params)
316
+ count = sum(1 for p in params if p.kind in (p.POSITIONAL_ONLY, p.POSITIONAL_OR_KEYWORD))
317
+ for _ in range(2):
318
+ self.assertEqual(input_handler._accepts_arg(cb), var or count >= 1)
319
+ self.assertEqual(input_handler._positional_count(cb), None if var else count)
320
+
321
+
322
+ class LightCullTests(unittest.TestCase):
323
+ def build(self, lx):
324
+ sc = make_scene()
325
+ sc.ambient = 0.4
326
+ sc.obj().create("\n".join("#" * 12 for _ in range(4)), -5, 2, dynamic=False)
327
+ sc.obj().create("*", lx, 0, dynamic=False, light={"radius": 8, "color": "yellow"})
328
+ return sc
329
+
330
+ def test_far_light_matches_scene_without_it(self):
331
+ far = self.build(300).render(full=True)
332
+ sc = make_scene()
333
+ sc.ambient = 0.4
334
+ sc.obj().create("\n".join("#" * 12 for _ in range(4)), -5, 2, dynamic=False)
335
+ self.assertEqual(far, sc.render(full=True))
336
+
337
+ def test_near_light_changes_the_object(self):
338
+ self.assertNotEqual(self.build(0).render(full=True), self.build(300).render(full=True))
339
+
340
+
341
+ if __name__ == "__main__":
342
+ unittest.main()