ttyengine 0.1.0__tar.gz → 0.2.1__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.
- {ttyengine-0.1.0 → ttyengine-0.2.1}/PKG-INFO +182 -6
- {ttyengine-0.1.0 → ttyengine-0.2.1}/README.md +181 -5
- {ttyengine-0.1.0 → ttyengine-0.2.1}/pyproject.toml +1 -1
- ttyengine-0.2.1/tests/test_engine.py +1579 -0
- ttyengine-0.2.1/tests/test_net.py +967 -0
- ttyengine-0.2.1/tests/test_perf.py +342 -0
- ttyengine-0.2.1/tests/test_speedups.py +630 -0
- {ttyengine-0.1.0 → ttyengine-0.2.1}/ttyengine/__init__.py +8 -4
- {ttyengine-0.1.0 → ttyengine-0.2.1}/ttyengine/ansi.py +44 -0
- {ttyengine-0.1.0 → ttyengine-0.2.1}/ttyengine/ascii_styler.py +23 -9
- ttyengine-0.2.1/ttyengine/broadphase.py +142 -0
- ttyengine-0.2.1/ttyengine/components/__init__.py +14 -0
- ttyengine-0.2.1/ttyengine/components/force.py +189 -0
- ttyengine-0.2.1/ttyengine/components/humanoid.py +828 -0
- ttyengine-0.2.1/ttyengine/components/inherit.py +162 -0
- ttyengine-0.2.1/ttyengine/components/joint.py +1249 -0
- ttyengine-0.2.1/ttyengine/components/light.py +657 -0
- ttyengine-0.2.1/ttyengine/components/pen.py +271 -0
- ttyengine-0.2.1/ttyengine/components/physics.py +1161 -0
- ttyengine-0.2.1/ttyengine/components/shared.py +343 -0
- ttyengine-0.2.1/ttyengine/components/transform.py +1530 -0
- {ttyengine-0.1.0 → ttyengine-0.2.1}/ttyengine/compositor.py +132 -50
- {ttyengine-0.1.0 → ttyengine-0.2.1}/ttyengine/errors.py +57 -1
- {ttyengine-0.1.0 → ttyengine-0.2.1}/ttyengine/image_reader.py +71 -19
- ttyengine-0.2.1/ttyengine/input_handler.py +1550 -0
- {ttyengine-0.1.0 → ttyengine-0.2.1}/ttyengine/launcher.py +246 -11
- ttyengine-0.2.1/ttyengine/net/__init__.py +18 -0
- ttyengine-0.2.1/ttyengine/net/codec.py +301 -0
- ttyengine-0.2.1/ttyengine/net/errors.py +10 -0
- ttyengine-0.2.1/ttyengine/net/layers.py +367 -0
- ttyengine-0.2.1/ttyengine/net/node.py +531 -0
- ttyengine-0.2.1/ttyengine/net/sync.py +753 -0
- ttyengine-0.2.1/ttyengine/net/transport.py +543 -0
- {ttyengine-0.1.0 → ttyengine-0.2.1}/ttyengine/scene.py +134 -12
- {ttyengine-0.1.0 → ttyengine-0.2.1}/ttyengine/sound.py +66 -6
- {ttyengine-0.1.0 → ttyengine-0.2.1}/ttyengine.egg-info/PKG-INFO +182 -6
- ttyengine-0.2.1/ttyengine.egg-info/SOURCES.txt +46 -0
- ttyengine-0.1.0/tests/test_engine.py +0 -652
- ttyengine-0.1.0/ttyengine/components.py +0 -4718
- ttyengine-0.1.0/ttyengine/input_handler.py +0 -814
- ttyengine-0.1.0/ttyengine.egg-info/SOURCES.txt +0 -26
- {ttyengine-0.1.0 → ttyengine-0.2.1}/LICENSE +0 -0
- {ttyengine-0.1.0 → ttyengine-0.2.1}/setup.cfg +0 -0
- {ttyengine-0.1.0 → ttyengine-0.2.1}/tests/test_smoke.py +0 -0
- {ttyengine-0.1.0 → ttyengine-0.2.1}/ttyengine/figlet-LICENSE.txt +0 -0
- {ttyengine-0.1.0 → ttyengine-0.2.1}/ttyengine/figlet.py +0 -0
- {ttyengine-0.1.0 → ttyengine-0.2.1}/ttyengine/fonts.zip +0 -0
- {ttyengine-0.1.0 → ttyengine-0.2.1}/ttyengine/region.py +0 -0
- {ttyengine-0.1.0 → ttyengine-0.2.1}/ttyengine/terminal.py +0 -0
- {ttyengine-0.1.0 → ttyengine-0.2.1}/ttyengine.egg-info/dependency_links.txt +0 -0
- {ttyengine-0.1.0 → ttyengine-0.2.1}/ttyengine.egg-info/requires.txt +0 -0
- {ttyengine-0.1.0 → ttyengine-0.2.1}/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.1
|
|
3
|
+
Version: 0.2.1
|
|
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
|
|
@@ -65,7 +65,7 @@ Build animated, interactive scenes out of text, with collisions, joints, lightin
|
|
|
65
65
|
TTY Engine draws everything as styled text and updates the terminal once per frame. Objects are assembled from small components, which are attached automatically based on the keyword arguments you pass when creating them. A box of text becomes a physics body as soon as you give it a velocity, and a light source as soon as you give it a light.
|
|
66
66
|
|
|
67
67
|
- **No dependencies.** Image decoding (PNG, JPEG, GIF, BMP, PNM; many more when ffmpeg is installed), FIGlet text, the audio mixer and the terminal and input handling are all implemented in the standard library.
|
|
68
|
-
- **Component-based objects.** `transform`, `
|
|
68
|
+
- **Component-based objects.** `transform`, `physics`, `pen`, `force`, `joint` and `light` cover position and style, collisions, drawing, area forces, linked bodies and lighting.
|
|
69
69
|
- **Rich text output.** Truecolor, transparency and fades, bundled FIGlet fonts, and image-to-text conversion.
|
|
70
70
|
- **Input and sound included.** Keyboard and mouse input with press, release and held states, plus a built-in mixer with a small synthesizer.
|
|
71
71
|
- **Simple structure.** Write a class (or just a function) with `start`, `update` and `final` methods, and hand it to `start()`.
|
|
@@ -266,17 +266,17 @@ Mouse positions are reported in terminal cells counted from the top-left. With t
|
|
|
266
266
|
|
|
267
267
|
|
|
268
268
|
|
|
269
|
-
An object starts out empty. `create()` looks at its keyword arguments, attaches the components that own them, and passes each value on. `transform`
|
|
269
|
+
An object starts out empty. `create()` looks at its keyword arguments, attaches the components that own them, and passes each value on. `transform` is always attached; the others are added the first time you use one of their settings.
|
|
270
270
|
|
|
271
271
|
| Component | Added when you pass | What it does |
|
|
272
272
|
|---|---|---|
|
|
273
|
-
| `transform` | always | Position, text, colors, opacity, rotation, flipping, shadow. |
|
|
274
|
-
| `rendering` | always | Visibility (`show`), drawing order (`z`) and whether spaces are drawn (`spaces`). |
|
|
273
|
+
| `transform` | always | Position, text, colors, opacity, rotation, flipping, shadow, visibility (`show`), drawing order (`z`) and whether spaces are drawn (`spaces`). |
|
|
275
274
|
| `physics` | `xvel`, `yvel`, `bounciness`, `gravity`, `friction`, `mass`, `phantom`, ... | Velocity, collisions, bouncing, friction and touch callbacks. |
|
|
276
275
|
| `pen` | `pen={...}` | Paints characters at a point relative to the object. Settings: `char`, `x`, `y`, `radius`, `shape`. |
|
|
277
276
|
| `force` | `force=...` or `force={...}` | Pushes other objects, optionally limited by a radius or a filter. Settings: `strength`, `affect`, `cap`, `position`, `radius`, `torque`, `shield`. |
|
|
278
|
-
| `joint` | `preset`, `joints`, `elasticity`, `kind`, ... | Links objects together as a rope, rod, spring, hinge, slider or fixed joint. |
|
|
277
|
+
| `joint` | `preset`, `joints`, `elasticity`, `kind`, `limit`, `target`, ... | Links objects together as a rope, rod, spring, hinge, slider or fixed joint. A pinned `ball` joint can also limit and motor the follower's rotation with `limit`, `target`, `gain` and `effort`. |
|
|
279
278
|
| `light` | `light=True` or `light={...}` | Turns the object into a light source. Settings: `color`, `alpha`, `radius`, `falloff`, `shadows`, `cone`, `direction`, `glow` and more. `scene.ambient` sets the base brightness. |
|
|
279
|
+
| `humanoid` | `humanoid={'parts': {...}}` | Builds a posable figure from a graph of parts, with the object as its root part. Settings: `parts`, `solid`, `physics`, `style`, `joints`, `poses`, `cycles`, `axis`, `elasticity`, `spaces`. |
|
|
280
280
|
|
|
281
281
|
Settings can be given flat, or grouped under the component's name. The two calls below are equivalent:
|
|
282
282
|
|
|
@@ -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
|
+
|
|
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
|
|
@@ -413,6 +470,7 @@ floor = scene.obj().create('#' * 40, 0, -10, dynamic=False) # immovable
|
|
|
413
470
|
| `mass` | Defaults to the number of visible characters. |
|
|
414
471
|
| `gravity` | An `(x, y)` pair that overrides the scene's gravity for this object. |
|
|
415
472
|
| `drag` | Overrides the scene's drag for this object. |
|
|
473
|
+
| `bouncethreshold` | Impact speed below which a collision does not bounce. Defaults to `scene.bouncethreshold` (`0.25`); set it to `0` to let shallow impacts bounce. When two bodies disagree, the lower value wins. |
|
|
416
474
|
|
|
417
475
|
**Reacting to contact.** Two tools cover the two common cases:
|
|
418
476
|
|
|
@@ -432,6 +490,74 @@ player.physics.ontouch(entered)
|
|
|
432
490
|
|
|
433
491
|
`ontouch(callback, when=None, once=False)` accepts a `when(other)` filter and can be limited to a single call with `once=True`.
|
|
434
492
|
|
|
493
|
+
`ontouch` fires when one body moves into another. A body that is only resting against, or pushed against by, another body does not trigger it, so use `touch`, `sides` and `grounded` for that case.
|
|
494
|
+
|
|
495
|
+
**Headings and bouncing.** `transform.forward` and `transform.bounce` use the object's `rotation` as the heading unless you pass `angle=`. Assigning the result to `rotation` also turns the sprite and its collision cells, so keep a separate heading and pass it as `angle` when the object should not rotate:
|
|
496
|
+
|
|
497
|
+
```python
|
|
498
|
+
heading = ball_heading # your own variable, in degrees
|
|
499
|
+
if ball.transform.approaching(normal, angle=heading): # True when moving into the surface
|
|
500
|
+
heading = ball.transform.bounce(normal, angle=heading)
|
|
501
|
+
heading = ball.transform.bounce(normal, angle=heading, incoming_only=True) # same check in one call
|
|
502
|
+
dx, dy = ball.transform.forward(1, angle=heading)
|
|
503
|
+
```
|
|
504
|
+
|
|
505
|
+
</details>
|
|
506
|
+
|
|
507
|
+
<details>
|
|
508
|
+
<summary><b>Humanoid figures</b></summary>
|
|
509
|
+
|
|
510
|
+
|
|
511
|
+
|
|
512
|
+
A `humanoid` component turns an object into the root of a jointed, posable figure. A figure is a graph of parts: every part is built from the text you give it, one part has no parent and becomes the object itself, and every other part hangs off a parent through a joint. Nothing is built in, so the same component makes people, spiders, robots or trees.
|
|
513
|
+
|
|
514
|
+
```python
|
|
515
|
+
parts = {
|
|
516
|
+
'torso': '###\n###\n###',
|
|
517
|
+
'head': {'text': 'O', 'parent': 'torso', 'at': 'top', 'joint': 'neck'},
|
|
518
|
+
'left_arm': {'text': '|\n|\n|', 'parent': 'torso', 'at': 'top_left', 'pin': 'top', 'shift': (-0.5, 0),
|
|
519
|
+
'joint': 'shoulder', 'group': 'arm'},
|
|
520
|
+
'right_arm': {'mirror': 'left_arm'},
|
|
521
|
+
'left_thigh': {'text': '|\n|\n|', 'parent': 'torso', 'at': 'bottom_left', 'pin': 'top', 'shift': (0.5, 0),
|
|
522
|
+
'joint': 'hip', 'group': 'thigh', 'density': 10},
|
|
523
|
+
'right_thigh': {'mirror': 'left_thigh', 'flip': False},
|
|
524
|
+
'left_shin': {'text': '|\n|\n|', 'parent': 'left_thigh', 'joint': 'knee', 'group': 'shin',
|
|
525
|
+
'density': 10},
|
|
526
|
+
'right_shin': {'mirror': 'left_shin', 'flip': False},
|
|
527
|
+
}
|
|
528
|
+
poses = {'arms_out': {'arm': 90}, 'crouch': {'thigh': -60, 'shin': 100}}
|
|
529
|
+
cycles = {'walk': {'left_thigh': {'amp': -32}, 'right_thigh': {'amp': 32}, 'arm': {'amp': 35}}}
|
|
530
|
+
body = scene.obj().create(None, 20, -10, humanoid={'parts': parts, 'poses': poses, 'cycles': cycles})
|
|
531
|
+
figure = body.humanoid
|
|
532
|
+
|
|
533
|
+
figure.apply_pose('arms_out') # poses and cycles are plain dicts: figure.poses, figure.cycles
|
|
534
|
+
figure.pose('arms_out') # a registered pose name works too
|
|
535
|
+
figure.pose({'left_thigh': -30}) # angles are degrees from the rest pose, clamped to joint limits
|
|
536
|
+
figure.velocity = (0.2, None) # moves every part together
|
|
537
|
+
figure.animate('walk', phase) # call each frame with a growing phase
|
|
538
|
+
figure.jump(0.6) # only while grounded
|
|
539
|
+
figure.detach('left_shin') # frees a part and everything attached to it
|
|
540
|
+
figure.ragdoll() # releases every joint; figure.ragdoll(False) stiffens them again
|
|
541
|
+
```
|
|
542
|
+
|
|
543
|
+
**Placement.** A part is placed by two anchors that meet at its joint: `at` is a point on the parent and `pin` is a point on the part itself. An anchor is a name (`top`, `bottom`, `left`, `right`, `center`, `top_left`, `top_right`, `bottom_left`, `bottom_right`) or an `(x, y)` pair of fractions of the part's size. `at` defaults to `bottom` and `pin` defaults to the opposite point, so a part sits against the parent on the side of its anchor. `shift=(dx, dy)` moves the joint in cells. The part is snapped to whole cells and the joint sits exactly on its `pin`.
|
|
544
|
+
|
|
545
|
+
**Mirroring.** `{'mirror': 'name'}` reflects another part across the vertical centre line of the root (or of the part named by the `axis` setting), inherits its text, `density`, `solid`, `z`, `physics`, `style`, `group` and joint, and hangs from the mirror of the source's parent unless `parent` is given. A mirrored joint has its limits and rest angle reversed, and so do the angles you pass through a group name; set `flip` to `False` to keep the same direction on both sides.
|
|
546
|
+
|
|
547
|
+
**Naming.** A pose, cycle, `style`, `get`, `set_text` or `remove_part` key is a part name or a `group`. Every part belongs to a group with its own name and to any `group` names it lists (a string or a list), and mirrored parts share the groups of their source. An exact part name sets the raw angle; a group name applies it with the sign flip of each member.
|
|
548
|
+
|
|
549
|
+
**Joints.** `joint` is a preset name from `joint.presets` or a dict of joint settings (`range`, `rest`, `elasticity`, `durability`, ...). The default is `hinge`. The `joints` setting overrides joints by group or part name.
|
|
550
|
+
|
|
551
|
+
**Ragdoll.** `figure.ragdoll(on=True, solid=None, limits=True)` turns every pose-driven joint into a free hinge that keeps its length, so the figure collapses under gravity and swings with impacts. `solid=True` forces every part to collide with the world while it is limp, while the default `None` keeps each part's own `solid` setting, and `limits=True` keeps the joint ranges. While limp, `pose` and `animate` do nothing; `ragdoll(False)` stiffens the joints in their current angles, after which `pose` works again. `figure.ragdolled` tells the current state.
|
|
552
|
+
|
|
553
|
+
**Elasticity.** The `elasticity` setting is optional and means what it means for every `joint`: unset, each joint keeps the joint default of `1`; set, it is the default for all joints of the figure, and a `joint` dict or the `joints` setting can still override it per part or group. Standing and limp figures use the same value. Values slightly above `1` soften the correction and can remove the sub-cell wobble a heavy standing figure may keep at exactly `1`, and values above about `3` make the figure sag.
|
|
554
|
+
|
|
555
|
+
**Limp figures.** A ragdoll's limbs are real rigid bodies: each limb is a ball joint pinned at its attach point with its own mass, moment of inertia and angular velocity, and the joint limits are angular impulses between the two bodies, so spin and momentum are conserved and only contacts and friction remove energy. `elasticity` sets how firmly the pins pull back together, as it does for every other joint of the figure.
|
|
556
|
+
|
|
557
|
+
**Cycles.** A cycle channel is `bias + amp * sin(phase + shift)`, or a bare number for `amp`; `rectify=True` clamps the sine to positive values. `figure.sample(cycle, phase, scale=1.0)` returns the angles and `figure.animate(cycle, phase, weight=1.0, scale=1.0)` applies them.
|
|
558
|
+
|
|
559
|
+
**Other part settings.** `text`, `parent`, `at`, `pin`, `shift`, `joint`, `mirror`, `flip`, `group`, `density` (mass per non-blank cell), `solid`, `z`, `physics`, `style` and `spaces`. `spaces` (default `False`, also a humanoid setting) makes a part's size ignore a trailing newline like the renderer does; with `spaces=True` the empty last line counts as a row, so `'█\n' * 3` is four rows tall and whatever hangs from it sits one row lower. A part's `solid` is unset by default and then follows the figure's `solid`, whose default `None` makes every part collide with the world; `solid=False` on a part keeps it from ever colliding and `solid=True` makes it always collide. The figure's `solid` can also be a bool or a list of part or group names. The parts of one figure never collide with each other. `add_part(name, spec)` and `add_parts({...})` grow a figure later.
|
|
560
|
+
|
|
435
561
|
</details>
|
|
436
562
|
|
|
437
563
|
<details>
|
|
@@ -469,6 +595,7 @@ session.style('tint', color=(255, 80, 120), bgcolor='darkblue')
|
|
|
469
595
|
- **FIGlet fonts** are bundled. `session.styler.fonts()` lists them, and `font=` accepts any name from that list.
|
|
470
596
|
- **Shapes** are available through `session.styler.shapes`: `circle`, `ellipse`, `block`, `triangle`, `diamond` and `line`.
|
|
471
597
|
- **Images** are converted to text with `session.styler.image(path, width=..., height=...)`. PNG, JPEG, GIF, BMP and PNM are decoded by the engine itself, and other formats (WebP, TIFF, TGA, ...) are decoded through ffmpeg when it is available. If you give neither `width` nor `height`, the image is `80` columns wide (or its own pixel width, if that is smaller), so the result is the same on every terminal.
|
|
598
|
+
`shades` is the string of characters from darkest to brightest, and defaults to a 256-step gradient from a space to `█`. It is plain monochrome unless you pass `color=True`, and `bgcolor=` (a name or `(r, g, b)`) fills every cell with that background and blends transparent pixels into it.
|
|
472
599
|
|
|
473
600
|
```python
|
|
474
601
|
ring = session.styler.shapes.circle(5)
|
|
@@ -635,6 +762,55 @@ The older names keep working: `termxoffset`, `termyoffset`, `termwidth` and `ter
|
|
|
635
762
|
|
|
636
763
|
</details>
|
|
637
764
|
|
|
765
|
+
<details>
|
|
766
|
+
<summary><b>Networking: UDP, TCP, servers and peer-to-peer</b></summary>
|
|
767
|
+
|
|
768
|
+
|
|
769
|
+
|
|
770
|
+
`ttyengine.net` shares a running simulation between processes over TCP, UDP or both, using only the standard library. A `Node` is one participant: it can listen (`host`), connect (`connect`) or do both, so the same code builds a dedicated server, a client, or a peer-to-peer mesh. A `Sync` shares engine state over a node.
|
|
771
|
+
|
|
772
|
+
```python
|
|
773
|
+
from ttyengine import Session, net
|
|
774
|
+
|
|
775
|
+
node = net.Node('alice')
|
|
776
|
+
node.host(7777) # listen on tcp and udp port 7777
|
|
777
|
+
|
|
778
|
+
other = net.Node('bob')
|
|
779
|
+
other.connect(('127.0.0.1', 7777), 'udp') # or 'tcp', or 'auto'
|
|
780
|
+
```
|
|
781
|
+
|
|
782
|
+
- **Topology.** By default a node that hosts relays messages between the nodes connected to it (a star). `Node(mesh=True)` makes every node that joins also connect to the nodes already there, so each pair talks directly and nothing is relayed. `Node(password=...)` rejects nodes with a different password; the check is an HMAC over a per-connection nonce, so the password is never sent and a captured handshake cannot be replayed. A relayed message is only accepted from the node it claims to come from, or from the host this node joined, and `Sync` honours forwarded entities only from that host.
|
|
783
|
+
- **Transports.** TCP links use length-prefixed frames. UDP links add a handshake, reliable ordered delivery with retransmission and fragmentation for large messages, a latest-wins unreliable mode, keep-alives and round-trip timing. Everything is non-blocking and driven by `node.update()`, which `Sync.attach` calls every frame.
|
|
784
|
+
- **Messages.** `node.send(channel, data, to=None, reliable=True)` and `node.on(channel, callback)` carry any mix of `None`, `bool`, `int`, `float`, `str`, `bytes`, `list`, `tuple`, `dict` and `set`. `'@join'` and `'@leave'` report peers coming and going.
|
|
785
|
+
|
|
786
|
+
Every layer of the simulation is shared the same way, from the session down to a single variable:
|
|
787
|
+
|
|
788
|
+
```python
|
|
789
|
+
from ttyengine.net import Node, Sync
|
|
790
|
+
|
|
791
|
+
sync = Sync(node)
|
|
792
|
+
session = Session()
|
|
793
|
+
sync.share(session, 'game') # session -> worlds -> scenes -> objects -> components -> variables
|
|
794
|
+
sync.attach(session) # pump the network inside the frame loop
|
|
795
|
+
```
|
|
796
|
+
|
|
797
|
+
| Share | What travels |
|
|
798
|
+
| --- | --- |
|
|
799
|
+
| `session` | `bgcolor`, `fgcolor`, `pause`, `pausephysics`, `pauserendering` and its worlds |
|
|
800
|
+
| `world` | `layer`, `pause`, `pausephysics`, `pauserendering` and its scene |
|
|
801
|
+
| `scene` | `gravity`, `drag`, `precision`, `bouncethreshold`, `aspect`, `ambient` and its objects |
|
|
802
|
+
| `obj` | every setting of every component it has (`transform`, `physics`, `joint`, `light`, `force`, `pen`), plus plain attributes you name |
|
|
803
|
+
| `(obj, 'x', 'y')` | just those variables |
|
|
804
|
+
|
|
805
|
+
- **Roots have names.** `share(target, 'name')` must be called with the same name on every node that takes part. The cameras, terminal settings and other per-screen values are not shared unless you ask for them with `vars=`.
|
|
806
|
+
- **Choosing variables.** `vars=('transform.x', 'hp')` shares exactly those variables of the object (`'transform'` means the whole component, a bare name such as `'x'` is looked up like `obj['x']`, and names that are not settings are read as plain attributes). `vars={'obj': (...), 'scene': (...)}` applies to every layer of that kind below the root and `exclude=` removes variables the same way. `ignore(obj)` and `filter=` keep objects out of the shared scene.
|
|
807
|
+
- **Ownership.** Each entity has one owner and only the owner's changes are accepted. Roots belong to the host (`owner=net.LOCAL` or a peer id changes that), objects belong to the node that created them. `sync.transfer(obj, peer)` hands an object over, and `sync.transfer(obj, peer, vars=('physics.xvel',))` hands over single variables, so a client can steer an object the host simulates.
|
|
808
|
+
- **Replicas.** An object owned by another node is frozen: the local physics and joints skip it and the owner's values are applied instead. `Sync(replicas='live')` keeps simulating it between updates. When an owner leaves, `orphans='drop'` removes its objects, `'adopt'` gives them to the lowest remaining node id and `'keep'` leaves them in place.
|
|
809
|
+
- **Reliability.** `share(..., reliable=False)` sends variable changes as latest-wins datagrams and refreshes the full state every `Sync(resync=1.0)` seconds so lost packets heal. Creating and removing entities is always reliable. `Sync(rate=30)` limits how often changes are sent.
|
|
810
|
+
- **Unshareable values.** Values that cannot travel, such as the functions used for `light.affect` or `force.affect`, are skipped and listed in `sync.skipped`. Naming one in `vars=` raises `NetError`. Custom components join in with `net.register(MyComponent)`.
|
|
811
|
+
|
|
812
|
+
</details>
|
|
813
|
+
|
|
638
814
|
<sub>[↑ Back to top](#top)</sub>
|
|
639
815
|
|
|
640
816
|
## Examples
|
|
@@ -31,7 +31,7 @@ Build animated, interactive scenes out of text, with collisions, joints, lightin
|
|
|
31
31
|
TTY Engine draws everything as styled text and updates the terminal once per frame. Objects are assembled from small components, which are attached automatically based on the keyword arguments you pass when creating them. A box of text becomes a physics body as soon as you give it a velocity, and a light source as soon as you give it a light.
|
|
32
32
|
|
|
33
33
|
- **No dependencies.** Image decoding (PNG, JPEG, GIF, BMP, PNM; many more when ffmpeg is installed), FIGlet text, the audio mixer and the terminal and input handling are all implemented in the standard library.
|
|
34
|
-
- **Component-based objects.** `transform`, `
|
|
34
|
+
- **Component-based objects.** `transform`, `physics`, `pen`, `force`, `joint` and `light` cover position and style, collisions, drawing, area forces, linked bodies and lighting.
|
|
35
35
|
- **Rich text output.** Truecolor, transparency and fades, bundled FIGlet fonts, and image-to-text conversion.
|
|
36
36
|
- **Input and sound included.** Keyboard and mouse input with press, release and held states, plus a built-in mixer with a small synthesizer.
|
|
37
37
|
- **Simple structure.** Write a class (or just a function) with `start`, `update` and `final` methods, and hand it to `start()`.
|
|
@@ -232,17 +232,17 @@ Mouse positions are reported in terminal cells counted from the top-left. With t
|
|
|
232
232
|
|
|
233
233
|
|
|
234
234
|
|
|
235
|
-
An object starts out empty. `create()` looks at its keyword arguments, attaches the components that own them, and passes each value on. `transform`
|
|
235
|
+
An object starts out empty. `create()` looks at its keyword arguments, attaches the components that own them, and passes each value on. `transform` is always attached; the others are added the first time you use one of their settings.
|
|
236
236
|
|
|
237
237
|
| Component | Added when you pass | What it does |
|
|
238
238
|
|---|---|---|
|
|
239
|
-
| `transform` | always | Position, text, colors, opacity, rotation, flipping, shadow. |
|
|
240
|
-
| `rendering` | always | Visibility (`show`), drawing order (`z`) and whether spaces are drawn (`spaces`). |
|
|
239
|
+
| `transform` | always | Position, text, colors, opacity, rotation, flipping, shadow, visibility (`show`), drawing order (`z`) and whether spaces are drawn (`spaces`). |
|
|
241
240
|
| `physics` | `xvel`, `yvel`, `bounciness`, `gravity`, `friction`, `mass`, `phantom`, ... | Velocity, collisions, bouncing, friction and touch callbacks. |
|
|
242
241
|
| `pen` | `pen={...}` | Paints characters at a point relative to the object. Settings: `char`, `x`, `y`, `radius`, `shape`. |
|
|
243
242
|
| `force` | `force=...` or `force={...}` | Pushes other objects, optionally limited by a radius or a filter. Settings: `strength`, `affect`, `cap`, `position`, `radius`, `torque`, `shield`. |
|
|
244
|
-
| `joint` | `preset`, `joints`, `elasticity`, `kind`, ... | Links objects together as a rope, rod, spring, hinge, slider or fixed joint. |
|
|
243
|
+
| `joint` | `preset`, `joints`, `elasticity`, `kind`, `limit`, `target`, ... | Links objects together as a rope, rod, spring, hinge, slider or fixed joint. A pinned `ball` joint can also limit and motor the follower's rotation with `limit`, `target`, `gain` and `effort`. |
|
|
245
244
|
| `light` | `light=True` or `light={...}` | Turns the object into a light source. Settings: `color`, `alpha`, `radius`, `falloff`, `shadows`, `cone`, `direction`, `glow` and more. `scene.ambient` sets the base brightness. |
|
|
245
|
+
| `humanoid` | `humanoid={'parts': {...}}` | Builds a posable figure from a graph of parts, with the object as its root part. Settings: `parts`, `solid`, `physics`, `style`, `joints`, `poses`, `cycles`, `axis`, `elasticity`, `spaces`. |
|
|
246
246
|
|
|
247
247
|
Settings can be given flat, or grouped under the component's name. The two calls below are equivalent:
|
|
248
248
|
|
|
@@ -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
|
+
|
|
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
|
|
@@ -379,6 +436,7 @@ floor = scene.obj().create('#' * 40, 0, -10, dynamic=False) # immovable
|
|
|
379
436
|
| `mass` | Defaults to the number of visible characters. |
|
|
380
437
|
| `gravity` | An `(x, y)` pair that overrides the scene's gravity for this object. |
|
|
381
438
|
| `drag` | Overrides the scene's drag for this object. |
|
|
439
|
+
| `bouncethreshold` | Impact speed below which a collision does not bounce. Defaults to `scene.bouncethreshold` (`0.25`); set it to `0` to let shallow impacts bounce. When two bodies disagree, the lower value wins. |
|
|
382
440
|
|
|
383
441
|
**Reacting to contact.** Two tools cover the two common cases:
|
|
384
442
|
|
|
@@ -398,6 +456,74 @@ player.physics.ontouch(entered)
|
|
|
398
456
|
|
|
399
457
|
`ontouch(callback, when=None, once=False)` accepts a `when(other)` filter and can be limited to a single call with `once=True`.
|
|
400
458
|
|
|
459
|
+
`ontouch` fires when one body moves into another. A body that is only resting against, or pushed against by, another body does not trigger it, so use `touch`, `sides` and `grounded` for that case.
|
|
460
|
+
|
|
461
|
+
**Headings and bouncing.** `transform.forward` and `transform.bounce` use the object's `rotation` as the heading unless you pass `angle=`. Assigning the result to `rotation` also turns the sprite and its collision cells, so keep a separate heading and pass it as `angle` when the object should not rotate:
|
|
462
|
+
|
|
463
|
+
```python
|
|
464
|
+
heading = ball_heading # your own variable, in degrees
|
|
465
|
+
if ball.transform.approaching(normal, angle=heading): # True when moving into the surface
|
|
466
|
+
heading = ball.transform.bounce(normal, angle=heading)
|
|
467
|
+
heading = ball.transform.bounce(normal, angle=heading, incoming_only=True) # same check in one call
|
|
468
|
+
dx, dy = ball.transform.forward(1, angle=heading)
|
|
469
|
+
```
|
|
470
|
+
|
|
471
|
+
</details>
|
|
472
|
+
|
|
473
|
+
<details>
|
|
474
|
+
<summary><b>Humanoid figures</b></summary>
|
|
475
|
+
|
|
476
|
+
|
|
477
|
+
|
|
478
|
+
A `humanoid` component turns an object into the root of a jointed, posable figure. A figure is a graph of parts: every part is built from the text you give it, one part has no parent and becomes the object itself, and every other part hangs off a parent through a joint. Nothing is built in, so the same component makes people, spiders, robots or trees.
|
|
479
|
+
|
|
480
|
+
```python
|
|
481
|
+
parts = {
|
|
482
|
+
'torso': '###\n###\n###',
|
|
483
|
+
'head': {'text': 'O', 'parent': 'torso', 'at': 'top', 'joint': 'neck'},
|
|
484
|
+
'left_arm': {'text': '|\n|\n|', 'parent': 'torso', 'at': 'top_left', 'pin': 'top', 'shift': (-0.5, 0),
|
|
485
|
+
'joint': 'shoulder', 'group': 'arm'},
|
|
486
|
+
'right_arm': {'mirror': 'left_arm'},
|
|
487
|
+
'left_thigh': {'text': '|\n|\n|', 'parent': 'torso', 'at': 'bottom_left', 'pin': 'top', 'shift': (0.5, 0),
|
|
488
|
+
'joint': 'hip', 'group': 'thigh', 'density': 10},
|
|
489
|
+
'right_thigh': {'mirror': 'left_thigh', 'flip': False},
|
|
490
|
+
'left_shin': {'text': '|\n|\n|', 'parent': 'left_thigh', 'joint': 'knee', 'group': 'shin',
|
|
491
|
+
'density': 10},
|
|
492
|
+
'right_shin': {'mirror': 'left_shin', 'flip': False},
|
|
493
|
+
}
|
|
494
|
+
poses = {'arms_out': {'arm': 90}, 'crouch': {'thigh': -60, 'shin': 100}}
|
|
495
|
+
cycles = {'walk': {'left_thigh': {'amp': -32}, 'right_thigh': {'amp': 32}, 'arm': {'amp': 35}}}
|
|
496
|
+
body = scene.obj().create(None, 20, -10, humanoid={'parts': parts, 'poses': poses, 'cycles': cycles})
|
|
497
|
+
figure = body.humanoid
|
|
498
|
+
|
|
499
|
+
figure.apply_pose('arms_out') # poses and cycles are plain dicts: figure.poses, figure.cycles
|
|
500
|
+
figure.pose('arms_out') # a registered pose name works too
|
|
501
|
+
figure.pose({'left_thigh': -30}) # angles are degrees from the rest pose, clamped to joint limits
|
|
502
|
+
figure.velocity = (0.2, None) # moves every part together
|
|
503
|
+
figure.animate('walk', phase) # call each frame with a growing phase
|
|
504
|
+
figure.jump(0.6) # only while grounded
|
|
505
|
+
figure.detach('left_shin') # frees a part and everything attached to it
|
|
506
|
+
figure.ragdoll() # releases every joint; figure.ragdoll(False) stiffens them again
|
|
507
|
+
```
|
|
508
|
+
|
|
509
|
+
**Placement.** A part is placed by two anchors that meet at its joint: `at` is a point on the parent and `pin` is a point on the part itself. An anchor is a name (`top`, `bottom`, `left`, `right`, `center`, `top_left`, `top_right`, `bottom_left`, `bottom_right`) or an `(x, y)` pair of fractions of the part's size. `at` defaults to `bottom` and `pin` defaults to the opposite point, so a part sits against the parent on the side of its anchor. `shift=(dx, dy)` moves the joint in cells. The part is snapped to whole cells and the joint sits exactly on its `pin`.
|
|
510
|
+
|
|
511
|
+
**Mirroring.** `{'mirror': 'name'}` reflects another part across the vertical centre line of the root (or of the part named by the `axis` setting), inherits its text, `density`, `solid`, `z`, `physics`, `style`, `group` and joint, and hangs from the mirror of the source's parent unless `parent` is given. A mirrored joint has its limits and rest angle reversed, and so do the angles you pass through a group name; set `flip` to `False` to keep the same direction on both sides.
|
|
512
|
+
|
|
513
|
+
**Naming.** A pose, cycle, `style`, `get`, `set_text` or `remove_part` key is a part name or a `group`. Every part belongs to a group with its own name and to any `group` names it lists (a string or a list), and mirrored parts share the groups of their source. An exact part name sets the raw angle; a group name applies it with the sign flip of each member.
|
|
514
|
+
|
|
515
|
+
**Joints.** `joint` is a preset name from `joint.presets` or a dict of joint settings (`range`, `rest`, `elasticity`, `durability`, ...). The default is `hinge`. The `joints` setting overrides joints by group or part name.
|
|
516
|
+
|
|
517
|
+
**Ragdoll.** `figure.ragdoll(on=True, solid=None, limits=True)` turns every pose-driven joint into a free hinge that keeps its length, so the figure collapses under gravity and swings with impacts. `solid=True` forces every part to collide with the world while it is limp, while the default `None` keeps each part's own `solid` setting, and `limits=True` keeps the joint ranges. While limp, `pose` and `animate` do nothing; `ragdoll(False)` stiffens the joints in their current angles, after which `pose` works again. `figure.ragdolled` tells the current state.
|
|
518
|
+
|
|
519
|
+
**Elasticity.** The `elasticity` setting is optional and means what it means for every `joint`: unset, each joint keeps the joint default of `1`; set, it is the default for all joints of the figure, and a `joint` dict or the `joints` setting can still override it per part or group. Standing and limp figures use the same value. Values slightly above `1` soften the correction and can remove the sub-cell wobble a heavy standing figure may keep at exactly `1`, and values above about `3` make the figure sag.
|
|
520
|
+
|
|
521
|
+
**Limp figures.** A ragdoll's limbs are real rigid bodies: each limb is a ball joint pinned at its attach point with its own mass, moment of inertia and angular velocity, and the joint limits are angular impulses between the two bodies, so spin and momentum are conserved and only contacts and friction remove energy. `elasticity` sets how firmly the pins pull back together, as it does for every other joint of the figure.
|
|
522
|
+
|
|
523
|
+
**Cycles.** A cycle channel is `bias + amp * sin(phase + shift)`, or a bare number for `amp`; `rectify=True` clamps the sine to positive values. `figure.sample(cycle, phase, scale=1.0)` returns the angles and `figure.animate(cycle, phase, weight=1.0, scale=1.0)` applies them.
|
|
524
|
+
|
|
525
|
+
**Other part settings.** `text`, `parent`, `at`, `pin`, `shift`, `joint`, `mirror`, `flip`, `group`, `density` (mass per non-blank cell), `solid`, `z`, `physics`, `style` and `spaces`. `spaces` (default `False`, also a humanoid setting) makes a part's size ignore a trailing newline like the renderer does; with `spaces=True` the empty last line counts as a row, so `'█\n' * 3` is four rows tall and whatever hangs from it sits one row lower. A part's `solid` is unset by default and then follows the figure's `solid`, whose default `None` makes every part collide with the world; `solid=False` on a part keeps it from ever colliding and `solid=True` makes it always collide. The figure's `solid` can also be a bool or a list of part or group names. The parts of one figure never collide with each other. `add_part(name, spec)` and `add_parts({...})` grow a figure later.
|
|
526
|
+
|
|
401
527
|
</details>
|
|
402
528
|
|
|
403
529
|
<details>
|
|
@@ -435,6 +561,7 @@ session.style('tint', color=(255, 80, 120), bgcolor='darkblue')
|
|
|
435
561
|
- **FIGlet fonts** are bundled. `session.styler.fonts()` lists them, and `font=` accepts any name from that list.
|
|
436
562
|
- **Shapes** are available through `session.styler.shapes`: `circle`, `ellipse`, `block`, `triangle`, `diamond` and `line`.
|
|
437
563
|
- **Images** are converted to text with `session.styler.image(path, width=..., height=...)`. PNG, JPEG, GIF, BMP and PNM are decoded by the engine itself, and other formats (WebP, TIFF, TGA, ...) are decoded through ffmpeg when it is available. If you give neither `width` nor `height`, the image is `80` columns wide (or its own pixel width, if that is smaller), so the result is the same on every terminal.
|
|
564
|
+
`shades` is the string of characters from darkest to brightest, and defaults to a 256-step gradient from a space to `█`. It is plain monochrome unless you pass `color=True`, and `bgcolor=` (a name or `(r, g, b)`) fills every cell with that background and blends transparent pixels into it.
|
|
438
565
|
|
|
439
566
|
```python
|
|
440
567
|
ring = session.styler.shapes.circle(5)
|
|
@@ -601,6 +728,55 @@ The older names keep working: `termxoffset`, `termyoffset`, `termwidth` and `ter
|
|
|
601
728
|
|
|
602
729
|
</details>
|
|
603
730
|
|
|
731
|
+
<details>
|
|
732
|
+
<summary><b>Networking: UDP, TCP, servers and peer-to-peer</b></summary>
|
|
733
|
+
|
|
734
|
+
|
|
735
|
+
|
|
736
|
+
`ttyengine.net` shares a running simulation between processes over TCP, UDP or both, using only the standard library. A `Node` is one participant: it can listen (`host`), connect (`connect`) or do both, so the same code builds a dedicated server, a client, or a peer-to-peer mesh. A `Sync` shares engine state over a node.
|
|
737
|
+
|
|
738
|
+
```python
|
|
739
|
+
from ttyengine import Session, net
|
|
740
|
+
|
|
741
|
+
node = net.Node('alice')
|
|
742
|
+
node.host(7777) # listen on tcp and udp port 7777
|
|
743
|
+
|
|
744
|
+
other = net.Node('bob')
|
|
745
|
+
other.connect(('127.0.0.1', 7777), 'udp') # or 'tcp', or 'auto'
|
|
746
|
+
```
|
|
747
|
+
|
|
748
|
+
- **Topology.** By default a node that hosts relays messages between the nodes connected to it (a star). `Node(mesh=True)` makes every node that joins also connect to the nodes already there, so each pair talks directly and nothing is relayed. `Node(password=...)` rejects nodes with a different password; the check is an HMAC over a per-connection nonce, so the password is never sent and a captured handshake cannot be replayed. A relayed message is only accepted from the node it claims to come from, or from the host this node joined, and `Sync` honours forwarded entities only from that host.
|
|
749
|
+
- **Transports.** TCP links use length-prefixed frames. UDP links add a handshake, reliable ordered delivery with retransmission and fragmentation for large messages, a latest-wins unreliable mode, keep-alives and round-trip timing. Everything is non-blocking and driven by `node.update()`, which `Sync.attach` calls every frame.
|
|
750
|
+
- **Messages.** `node.send(channel, data, to=None, reliable=True)` and `node.on(channel, callback)` carry any mix of `None`, `bool`, `int`, `float`, `str`, `bytes`, `list`, `tuple`, `dict` and `set`. `'@join'` and `'@leave'` report peers coming and going.
|
|
751
|
+
|
|
752
|
+
Every layer of the simulation is shared the same way, from the session down to a single variable:
|
|
753
|
+
|
|
754
|
+
```python
|
|
755
|
+
from ttyengine.net import Node, Sync
|
|
756
|
+
|
|
757
|
+
sync = Sync(node)
|
|
758
|
+
session = Session()
|
|
759
|
+
sync.share(session, 'game') # session -> worlds -> scenes -> objects -> components -> variables
|
|
760
|
+
sync.attach(session) # pump the network inside the frame loop
|
|
761
|
+
```
|
|
762
|
+
|
|
763
|
+
| Share | What travels |
|
|
764
|
+
| --- | --- |
|
|
765
|
+
| `session` | `bgcolor`, `fgcolor`, `pause`, `pausephysics`, `pauserendering` and its worlds |
|
|
766
|
+
| `world` | `layer`, `pause`, `pausephysics`, `pauserendering` and its scene |
|
|
767
|
+
| `scene` | `gravity`, `drag`, `precision`, `bouncethreshold`, `aspect`, `ambient` and its objects |
|
|
768
|
+
| `obj` | every setting of every component it has (`transform`, `physics`, `joint`, `light`, `force`, `pen`), plus plain attributes you name |
|
|
769
|
+
| `(obj, 'x', 'y')` | just those variables |
|
|
770
|
+
|
|
771
|
+
- **Roots have names.** `share(target, 'name')` must be called with the same name on every node that takes part. The cameras, terminal settings and other per-screen values are not shared unless you ask for them with `vars=`.
|
|
772
|
+
- **Choosing variables.** `vars=('transform.x', 'hp')` shares exactly those variables of the object (`'transform'` means the whole component, a bare name such as `'x'` is looked up like `obj['x']`, and names that are not settings are read as plain attributes). `vars={'obj': (...), 'scene': (...)}` applies to every layer of that kind below the root and `exclude=` removes variables the same way. `ignore(obj)` and `filter=` keep objects out of the shared scene.
|
|
773
|
+
- **Ownership.** Each entity has one owner and only the owner's changes are accepted. Roots belong to the host (`owner=net.LOCAL` or a peer id changes that), objects belong to the node that created them. `sync.transfer(obj, peer)` hands an object over, and `sync.transfer(obj, peer, vars=('physics.xvel',))` hands over single variables, so a client can steer an object the host simulates.
|
|
774
|
+
- **Replicas.** An object owned by another node is frozen: the local physics and joints skip it and the owner's values are applied instead. `Sync(replicas='live')` keeps simulating it between updates. When an owner leaves, `orphans='drop'` removes its objects, `'adopt'` gives them to the lowest remaining node id and `'keep'` leaves them in place.
|
|
775
|
+
- **Reliability.** `share(..., reliable=False)` sends variable changes as latest-wins datagrams and refreshes the full state every `Sync(resync=1.0)` seconds so lost packets heal. Creating and removing entities is always reliable. `Sync(rate=30)` limits how often changes are sent.
|
|
776
|
+
- **Unshareable values.** Values that cannot travel, such as the functions used for `light.affect` or `force.affect`, are skipped and listed in `sync.skipped`. Naming one in `vars=` raises `NetError`. Custom components join in with `net.register(MyComponent)`.
|
|
777
|
+
|
|
778
|
+
</details>
|
|
779
|
+
|
|
604
780
|
<sub>[↑ Back to top](#top)</sub>
|
|
605
781
|
|
|
606
782
|
## Examples
|