Skip to content

Motion

Module: terminaltexteffects.engine.motion

Motion class for managing the movement of a character.

A character's position is measured in its parent's frame: (column, row, height) on the text plane, where it starts. Waypoints take a Coord (height 0), a Vec3, or a node to home in on.

Attributes:

Name Type Description
paths dict[str, Path]

dictionary of paths

character EffectCharacter

The EffectCharacter to move.

position Vec3

The exact position in the parent's frame. Setting it moves the character now.

current_coord Coord

The cell the character is drawn in.

previous_coord Coord

previous coordinate

active_path Path | None

active path

Methods:

Name Description
set_coordinate

Moves the character to a cell in its parent's frame, keeping its height.

new_path

Creates a new Path and adds it to the Motion.paths dictionary with the path_id as key.

query_path

Returns the path with the given path_id.

movement_is_complete

Returns whether the character has an active path.

chain_paths

Creates a chain of paths by registering activation events for each path such that paths[n] activates paths[n+1] when reached. If loop is True, paths[-1] activates paths[0] when reached.

activate_path

Activates the first waypoint in the path.

deactivate_path

Unsets the current path if the current path is path.

move

Moves the character one step closer to the target position based on an easing function if present, otherwise linearly.

Source code in terminaltexteffects/engine/motion.py
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
class Motion:
    """Motion class for managing the movement of a character.

    A character's position is measured in its parent's frame: `(column, row, height)` on the text plane, where it
    starts. Waypoints take a `Coord` (height 0), a `Vec3`, or a node to home in on.

    Attributes:
        paths (dict[str, Path]): dictionary of paths
        character (base_character.EffectCharacter): The EffectCharacter to move.
        position (g3.Vec3): The exact position in the parent's frame. Setting it moves the character now.
        current_coord (Coord): The cell the character is drawn in.
        previous_coord (Coord): previous coordinate
        active_path (Path | None): active path

    Methods:
        set_coordinate:
            Moves the character to a cell in its parent's frame, keeping its height.
        new_path:
            Creates a new Path and adds it to the Motion.paths dictionary with the path_id as key.
        query_path:
            Returns the path with the given path_id.
        movement_is_complete:
            Returns whether the character has an active path.
        chain_paths:
            Creates a chain of paths by registering activation events for each path such
            that paths[n] activates paths[n+1] when reached. If loop is True, paths[-1] activates
            paths[0] when reached.
        activate_path:
            Activates the first waypoint in the path.
        deactivate_path:
            Unsets the current path if the current path is path.
        move:
            Moves the character one step closer to the target position based on an easing function if
                present, otherwise linearly.

    """

    def __init__(self, character: base_character.EffectCharacter) -> None:
        """Initialize the Motion object with the given EffectCharacter.

        Args:
            character (base_character.EffectCharacter): The EffectCharacter to move.

        """
        self.paths: dict[str, Path] = {}
        self.character = character
        self.current_coord: Coord = Coord(character.input_coord.column, character.input_coord.row)
        # The cell the engine last wrote to `current_coord`. When `current_coord` is no longer this object, an
        # effect assigned it, and the position follows at the next move or read.
        self._cell: Coord = self.current_coord
        # The exact position in the parent's frame, as floats; `position` reads it as a `Vec3`.
        self._xyz: XYZ = (self._cell.column, self._cell.row, 0.0)
        self._depth_from_view = False
        # Whether the view hides the character: behind the camera, or facing away on a body that hides those.
        self._view_hidden = False
        # Whether the effect wants the character shown once the view sees it again.
        self._show_when_seen = False
        self.previous_coord: Coord = Coord(-1, -1)
        self.active_path: Path | None = None
        # Detect callback-driven restarts even when the active path's identity is unchanged.
        self._path_generation = 0

    def set_coordinate(self, coord: Coord) -> None:
        """Move the character to a cell, now: column and row in its parent's frame, keeping its height.

        Assigning `current_coord` does the same.

        Args:
            coord (Coord): coordinate

        """
        self.current_coord = coord
        self._sync()

    @property
    def position(self) -> g3.Vec3:
        """The character's position in its parent's frame: `(column, row, height)` on the text plane."""
        if self.current_coord is not self._cell:
            self._sync()
        return g3.Vec3(*self._xyz)

    @position.setter
    def position(self, value: Point | g3.Point3) -> None:
        self._xyz = _as_xyz(value)
        self._resolve()

    def _sync(self) -> None:
        """Move the position to the cell an effect assigned to `current_coord`, keeping the height."""
        cell = self.current_coord
        self._cell = cell
        height = self._xyz[2]
        self._xyz = (cell.column, cell.row, height)
        character = self.character
        if height or not (character._parent or character.parent)._flat:
            self._resolve()

    def _row(self) -> float:
        """Return how many units a row is in the frame this motion moves in: 2 on a surface, otherwise 1."""
        node = self.character
        return _ROW if node._ON_SURFACE and node.parent._surface is not None else 1.0

    def _surface(self) -> Surface | None:
        """Return the surface this motion moves over, if the mover sits on one."""
        node = self.character
        return node.parent._surface if node._ON_SURFACE else None

    def _from_world(self, point: g3.Vec3) -> XYZ:
        """Return a world point in the frame this motion moves in."""
        node = self.character
        local = node.parent.from_world(point, surface=node._ON_SURFACE)
        return (local.x, local.y, local.z)

    def _resolve(self) -> None:
        """Project the position to the cell `current_coord` reports, and order the character by its depth."""
        position = self._xyz
        character = self.character
        parent = character._parent or character.parent
        if parent._flat and (not position[2] or parent._screen):
            # On an untouched text plane under the default camera, or on the screen, a cell is the rounded column
            # and row.
            column, row = round(position[0]), round(position[1])
            cell = self._cell
            if cell.column != column or cell.row != row:
                cell = self._cell = Coord(column, row)
                self.current_coord = cell
            if self._depth_from_view:
                self._depth_from_view = False
                character._set_depth_order(0.0)
            if self._view_hidden:
                self._show(hidden=False)
            return
        surface = parent._surface
        if surface is not None and surface.closed:
            # Positions on a closed surface are kept normalized: the column within the grid, the row pole to pole.
            position = self._xyz = surface._normalize(position)
        camera = parent.world.camera
        point = parent.to_world(position)
        projected = camera.project(point)
        hide = projected is None
        if not hide and surface is not None and parent.hide_facing_away:
            normal = parent._world_normal(surface._normal(position))
            hide = normal.dot(camera.view_direction(point)) <= 0
        if hide != self._view_hidden:
            self._show(hidden=hide)
        if projected is None:
            return  # behind the near plane: stay on the last cell
        # Halves round up, as drawn bodies do, so neighboring points land on neighboring cells.
        column, row = math.floor(projected.column + 0.5), math.floor(projected.row + 0.5)
        cell = self._cell
        if cell.column != column or cell.row != row:
            cell = self._cell = Coord(column, row)
            self.current_coord = cell
        # Nearer than the text plane paints later within the layer, farther paints earlier.
        reference = camera.distance
        order = max(-0.49, min(0.49, (reference - projected.depth) / (4 * reference)))
        self._depth_from_view = True
        character._set_depth_order(order)

    def _show(self, *, hidden: bool) -> None:
        """Hide the character while it is behind the camera or faces away, or show it again once it isn't.

        The view tracks hiding whether or not the character is shown. Only a character that was shown when the view
        hid it, or that the effect showed while hidden, is shown again, so one the effect hid itself stays hidden.
        """
        character = self.character
        owner = character._terminal_owner_token() if character._terminal_owner_token is not None else None
        if hidden:
            self._view_hidden = True
            if character.is_visible and owner is not None:
                owner.set_character_visibility(character, is_visible=False)
                self._show_when_seen = True
        else:
            self._view_hidden = False
            if self._show_when_seen:
                self._show_when_seen = False
                if not character.is_visible and owner is not None:
                    owner.set_character_visibility(character, is_visible=True)

    def new_path(
        self,
        *,
        speed: float = 1,
        ease: easing.EasingFunction | None = None,
        layer: int | None = None,
        hold_time: int = 0,
        loop: bool = False,
        path_id: str = "",
    ) -> Path:
        """Create a new Path and add it to the Motion.paths dictionary with the path_id as key.

        Args:
            speed (float, optional): speed > 0. Defaults to 1.
            ease (easing.EasingFunction | None, optional): easing function for character movement. Defaults to None.
            layer (int | None, optional): layer to move the character to, if None, layer is unchanged. Defaults to None.
            hold_time (int, optional): number of frames to hold the character at the end of the path. Defaults to 0.
            loop (bool, optional): Whether the path should loop back to the beginning. Default is False.
            path_id (str, optional): Unique identifier for the path. Used to query for the path. Defaults to "".

        Raises:
            DuplicatePathIDError: If a path with the provided id already exists.
            PathInvalidSpeedError: If `speed` is less than or equal to 0.

        Returns:
            Path: The new path.

        """
        if not path_id:
            found_unique = False
            current_id = len(self.paths)
            while not found_unique:
                path_id = f"{current_id}"
                if path_id not in self.paths:
                    found_unique = True
                else:
                    current_id += 1
        if path_id in self.paths:
            raise DuplicatePathIDError(path_id)
        new_path = Path(path_id, speed, ease, layer, hold_time, loop)
        self.paths[path_id] = new_path
        return new_path

    @typing.overload
    def query_path(self, path_id: str) -> Path: ...
    @typing.overload
    def query_path(self, path_id: str, not_found_action: typing.Literal["raise"]) -> Path: ...
    @typing.overload
    def query_path(self, path_id: str, not_found_action: None) -> Path | None: ...
    def query_path(self, path_id: str, not_found_action: typing.Literal["raise"] | None = "raise") -> Path | None:
        """Return the path with the given path_id, or None if no path with the given ID exists.

        Args:
            path_id (str): path_id
            not_found_action (Literal["raise"] | None, optional): Action to take if a path with the given
                path_id is not found. If "raise", a PathNotFoundError will be raised. If `None`, method will
                return `None`.

        Returns:
            Path | None: The path with the given path_id, or None.

        Raises:
            PathNotFoundError: If `not_found_action` is "raise" and a Path with the given
                `path_id` is not found.

        """
        found_path = self.paths.get(path_id, None)
        if not_found_action and found_path is None:
            raise PathNotFoundError(path_id)
        return found_path

    def movement_is_complete(self) -> bool:
        """Return whether movement is complete.

        Returns:
            bool: True if the character has no active path, False otherwise.

        """
        return self.active_path is None

    def chain_paths(self, paths: list[Path], *, loop: bool = False) -> None:
        """Create a chain of paths.

        Paths are chained by registering activation events for each path such
        that paths[n] activates paths[n+1] when reached. If loop is True, paths[-1] activates
        paths[0] when reached.

        Args:
            paths (list[Path]): list of paths to chain
            loop (bool, optional): Whether the chain should loop. Defaults to False.

        """
        if len(paths) < 2:
            return
        for i, path in enumerate(paths):
            if i == 0:
                continue
            self.character.event_handler.register_event(
                self.character.event_handler.Event.PATH_COMPLETE,
                paths[i - 1],
                self.character.event_handler.Action.ACTIVATE_PATH,
                path,
            )
        if loop:
            self.character.event_handler.register_event(
                self.character.event_handler.Event.PATH_COMPLETE,
                paths[-1],
                self.character.event_handler.Action.ACTIVATE_PATH,
                paths[0],
            )

    def activate_path(self, path: Path | str) -> None:  # noqa: PLR0915
        """Activates the first waypoint in the given path and updates the path's properties accordingly.

        If the provided `path` arg is not a `Path` object, it must be a `path_id` string.

        This method sets the active path to the given path and mutates the Path to reflect the character's
        current starting position. It calculates the distance to the first waypoint and updates the total
        distance of the path. If the path has an origin segment, it removes it from the segments list and
        subtracts its distance from the total distance. Then, it creates a new origin segment from the
        current coordinate to the first waypoint and inserts it at the beginning of the segments list.

        The method also resets the current step, hold time remaining, and max steps of the path based on the total
        distance and speed. It ensures that the enter and exit events for each segment are not triggered. If
        the path has a layer, it sets the character's layer to it. Finally, it triggers the PATH_ACTIVATED event
        for the character.

        Args:
            path (Path | str): The path to activate. Must be the Path itself, or the Path's ID.

        """
        if isinstance(path, str):
            found_path = self.query_path(path)
            if found_path is None:
                raise PathNotFoundError(path)
        else:
            found_path = path
        if not found_path.waypoints:
            raise ActivateEmptyPathError(found_path.path_id)
        self.active_path = found_path
        self._path_generation += 1
        found_path._measure(self)
        first_waypoint = self.active_path.waypoints[0]
        # Start from the exact position. A character sitting on a cell starts from that `Coord`, which keeps the
        # cached 2D lengths.
        if self.current_coord is not self._cell:
            self._sync()
        position = self._xyz
        cell = self._cell
        origin: Waypoint[Coord] | Waypoint[g3.Vec3] = (
            Waypoint("origin", cell)
            if position == (cell.column, cell.row, 0.0)
            else Waypoint("origin", g3.Vec3(*position))
        )
        row = found_path._row
        if first_waypoint._live:
            first = _read(first_waypoint, self) if first_waypoint._target is not None else first_waypoint._xyz
            if first_waypoint._curve_controls:
                distance_to_first_waypoint = _curve_length((position, *_controls(first_waypoint, self), first), row)
            else:
                distance_to_first_waypoint = _line_length(position, first, row)
        elif first_waypoint.bezier_control:
            distance_to_first_waypoint = _segment_length(
                origin.coord,
                first_waypoint.bezier_control,  # type: ignore[arg-type]
                first_waypoint.coord,  # type: ignore[arg-type]
                row,
            )
        else:
            # This small calculation is cheaper than hashing coordinates through the geometry cache.
            distance_to_first_waypoint = _line_length(position, first_waypoint._xyz, row)
        new_origin_segment = Segment(
            origin,
            first_waypoint,
            distance_to_first_waypoint,
        )
        self.active_path.total_distance += distance_to_first_waypoint
        if self.active_path.origin_segment:
            self.active_path.total_distance -= self.active_path.origin_segment.distance
            self.active_path.segments[0] = new_origin_segment
        else:
            self.active_path.segments.insert(0, new_origin_segment)
        self.active_path.origin_segment = new_origin_segment
        surface = self._surface()
        if found_path._walks or (surface is not None and surface.closed):
            found_path._route(surface)
        else:
            found_path._routed = False
        self.active_path.current_step = 0
        self.active_path.last_distance_reached = 0
        self.active_path.hold_time_remaining = self.active_path.hold_time
        self.active_path.max_steps = round(self.active_path.total_distance / self.active_path.speed)
        for segment in self.active_path.segments:
            segment.enter_event_triggered = False
            segment.exit_event_triggered = False
        if self.active_path.layer is not None:
            self.character.layer = self.active_path.layer
        self.character.event_handler._handle_event(self.character.event_handler.Event.PATH_ACTIVATED, self.active_path)

    @typing.overload
    def deactivate_path(self) -> None: ...
    @typing.overload
    def deactivate_path(self, path: Path) -> None: ...
    @typing.overload
    def deactivate_path(self, path: str) -> None: ...
    def deactivate_path(self, path: Path | str | None = None) -> None:
        """Deactivate a path if it is currently active.

        If `path` is omitted, the current active path is deactivated if one exists.
        If `path` is a string, it is resolved as a path ID before deactivation.

        Args:
            path (Path | str | None): Path to deactivate, its ID, or None to deactivate the
                current active path.

        Raises:
            PathNotFoundError: If `path` is a string and no path with that ID exists.

        """
        if path is None:
            if self.active_path is not None:
                self._path_generation += 1
            self.active_path = None
            return
        if isinstance(path, str):
            found_path = self.query_path(path)
            if found_path is None:
                raise PathNotFoundError(path)
        else:
            found_path = path
        if self.active_path and self.active_path is found_path:
            self.active_path = None
            self._path_generation += 1

    def move(self) -> None:
        """Move the character along the active path.

        The character's current coordinate is updated to the next step in the active path. If the active path
        is completed, an event is triggered based on whether the path is set to loop or not. Looping paths are
        reactivated from the current coordinate when they contain more than one segment. Otherwise, the path
        is deactivated and a PATH_COMPLETE event is triggered.

        If the path has a hold time, the character will pause at the end of the path for the specified duration. During
        this hold time, a PATH_HOLDING event is triggered on the first frame, and the hold time is decremented on each
        subsequent frame until it reaches zero.

        If there is no active path or if the active path has no segments, the character does not move.

        The character's previous coordinate is preserved before moving to allow for clearing the location
        in the terminal.

        If a segment or holding callback deactivates, replaces, or restarts the path,
        processing of the old traversal stops. Callback coordinates are preserved and
        any newly activated traversal begins moving on the next tick.
        """
        # preserve previous coordinate to allow for clearing the location in the terminal
        cell = self.current_coord
        if cell is not self._cell:
            self._sync()
        self.previous_coord = cell

        if not self.active_path or not self.active_path.segments:
            return
        path = self.active_path
        path_generation = self._path_generation
        next_position = path._step(self.character.event_handler)
        if self.active_path is not path or self._path_generation != path_generation:
            return
        self._xyz = next_position
        character = self.character
        parent = character._parent or character.parent
        if parent._flat and not next_position[2] and not self._depth_from_view:
            # _resolve()'s text-plane shortcut, inline: this runs for every moving character on every frame.
            column, row = round(next_position[0]), round(next_position[1])
            cell = self._cell
            if cell.column != column or cell.row != row:
                self.current_coord = self._cell = Coord(column, row)
        else:
            self._resolve()
        if self.active_path.current_step == self.active_path.max_steps:
            final_segment = self.active_path.segments[-1]
            if final_segment.enter_event_triggered and not final_segment.exit_event_triggered:
                final_segment.exit_event_triggered = True
                self.character.event_handler._handle_event(
                    self.character.event_handler.Event.SEGMENT_EXITED,
                    final_segment.end,
                )
                if self.active_path is not path or self._path_generation != path_generation:
                    return
            if self.active_path.hold_time and self.active_path.hold_time_remaining == self.active_path.hold_time:
                self.character.event_handler._handle_event(
                    self.character.event_handler.Event.PATH_HOLDING,
                    self.active_path,
                )
                if self.active_path is not path or self._path_generation != path_generation:
                    return
                self.active_path.hold_time_remaining -= 1
                return
            if self.active_path.hold_time_remaining:
                self.active_path.hold_time_remaining -= 1
                return
            if self.active_path.loop and len(self.active_path.segments) > 1:
                looping_path = self.active_path
                self.deactivate_path(self.active_path)
                self.activate_path(looping_path)
            else:
                self.completed_path = self.active_path
                self.deactivate_path(self.active_path)
                self.character.event_handler._handle_event(
                    self.character.event_handler.Event.PATH_COMPLETE,
                    self.completed_path,
                )

position property writable

The character's position in its parent's frame: (column, row, height) on the text plane.

__init__(character)

Initialize the Motion object with the given EffectCharacter.

Parameters:

Name Type Description Default
character EffectCharacter

The EffectCharacter to move.

required
Source code in terminaltexteffects/engine/motion.py
def __init__(self, character: base_character.EffectCharacter) -> None:
    """Initialize the Motion object with the given EffectCharacter.

    Args:
        character (base_character.EffectCharacter): The EffectCharacter to move.

    """
    self.paths: dict[str, Path] = {}
    self.character = character
    self.current_coord: Coord = Coord(character.input_coord.column, character.input_coord.row)
    # The cell the engine last wrote to `current_coord`. When `current_coord` is no longer this object, an
    # effect assigned it, and the position follows at the next move or read.
    self._cell: Coord = self.current_coord
    # The exact position in the parent's frame, as floats; `position` reads it as a `Vec3`.
    self._xyz: XYZ = (self._cell.column, self._cell.row, 0.0)
    self._depth_from_view = False
    # Whether the view hides the character: behind the camera, or facing away on a body that hides those.
    self._view_hidden = False
    # Whether the effect wants the character shown once the view sees it again.
    self._show_when_seen = False
    self.previous_coord: Coord = Coord(-1, -1)
    self.active_path: Path | None = None
    # Detect callback-driven restarts even when the active path's identity is unchanged.
    self._path_generation = 0

activate_path(path)

Activates the first waypoint in the given path and updates the path's properties accordingly.

If the provided path arg is not a Path object, it must be a path_id string.

This method sets the active path to the given path and mutates the Path to reflect the character's current starting position. It calculates the distance to the first waypoint and updates the total distance of the path. If the path has an origin segment, it removes it from the segments list and subtracts its distance from the total distance. Then, it creates a new origin segment from the current coordinate to the first waypoint and inserts it at the beginning of the segments list.

The method also resets the current step, hold time remaining, and max steps of the path based on the total distance and speed. It ensures that the enter and exit events for each segment are not triggered. If the path has a layer, it sets the character's layer to it. Finally, it triggers the PATH_ACTIVATED event for the character.

Parameters:

Name Type Description Default
path Path | str

The path to activate. Must be the Path itself, or the Path's ID.

required
Source code in terminaltexteffects/engine/motion.py
def activate_path(self, path: Path | str) -> None:  # noqa: PLR0915
    """Activates the first waypoint in the given path and updates the path's properties accordingly.

    If the provided `path` arg is not a `Path` object, it must be a `path_id` string.

    This method sets the active path to the given path and mutates the Path to reflect the character's
    current starting position. It calculates the distance to the first waypoint and updates the total
    distance of the path. If the path has an origin segment, it removes it from the segments list and
    subtracts its distance from the total distance. Then, it creates a new origin segment from the
    current coordinate to the first waypoint and inserts it at the beginning of the segments list.

    The method also resets the current step, hold time remaining, and max steps of the path based on the total
    distance and speed. It ensures that the enter and exit events for each segment are not triggered. If
    the path has a layer, it sets the character's layer to it. Finally, it triggers the PATH_ACTIVATED event
    for the character.

    Args:
        path (Path | str): The path to activate. Must be the Path itself, or the Path's ID.

    """
    if isinstance(path, str):
        found_path = self.query_path(path)
        if found_path is None:
            raise PathNotFoundError(path)
    else:
        found_path = path
    if not found_path.waypoints:
        raise ActivateEmptyPathError(found_path.path_id)
    self.active_path = found_path
    self._path_generation += 1
    found_path._measure(self)
    first_waypoint = self.active_path.waypoints[0]
    # Start from the exact position. A character sitting on a cell starts from that `Coord`, which keeps the
    # cached 2D lengths.
    if self.current_coord is not self._cell:
        self._sync()
    position = self._xyz
    cell = self._cell
    origin: Waypoint[Coord] | Waypoint[g3.Vec3] = (
        Waypoint("origin", cell)
        if position == (cell.column, cell.row, 0.0)
        else Waypoint("origin", g3.Vec3(*position))
    )
    row = found_path._row
    if first_waypoint._live:
        first = _read(first_waypoint, self) if first_waypoint._target is not None else first_waypoint._xyz
        if first_waypoint._curve_controls:
            distance_to_first_waypoint = _curve_length((position, *_controls(first_waypoint, self), first), row)
        else:
            distance_to_first_waypoint = _line_length(position, first, row)
    elif first_waypoint.bezier_control:
        distance_to_first_waypoint = _segment_length(
            origin.coord,
            first_waypoint.bezier_control,  # type: ignore[arg-type]
            first_waypoint.coord,  # type: ignore[arg-type]
            row,
        )
    else:
        # This small calculation is cheaper than hashing coordinates through the geometry cache.
        distance_to_first_waypoint = _line_length(position, first_waypoint._xyz, row)
    new_origin_segment = Segment(
        origin,
        first_waypoint,
        distance_to_first_waypoint,
    )
    self.active_path.total_distance += distance_to_first_waypoint
    if self.active_path.origin_segment:
        self.active_path.total_distance -= self.active_path.origin_segment.distance
        self.active_path.segments[0] = new_origin_segment
    else:
        self.active_path.segments.insert(0, new_origin_segment)
    self.active_path.origin_segment = new_origin_segment
    surface = self._surface()
    if found_path._walks or (surface is not None and surface.closed):
        found_path._route(surface)
    else:
        found_path._routed = False
    self.active_path.current_step = 0
    self.active_path.last_distance_reached = 0
    self.active_path.hold_time_remaining = self.active_path.hold_time
    self.active_path.max_steps = round(self.active_path.total_distance / self.active_path.speed)
    for segment in self.active_path.segments:
        segment.enter_event_triggered = False
        segment.exit_event_triggered = False
    if self.active_path.layer is not None:
        self.character.layer = self.active_path.layer
    self.character.event_handler._handle_event(self.character.event_handler.Event.PATH_ACTIVATED, self.active_path)

chain_paths(paths, *, loop=False)

Create a chain of paths.

Paths are chained by registering activation events for each path such that paths[n] activates paths[n+1] when reached. If loop is True, paths[-1] activates paths[0] when reached.

Parameters:

Name Type Description Default
paths list[Path]

list of paths to chain

required
loop bool

Whether the chain should loop. Defaults to False.

False
Source code in terminaltexteffects/engine/motion.py
def chain_paths(self, paths: list[Path], *, loop: bool = False) -> None:
    """Create a chain of paths.

    Paths are chained by registering activation events for each path such
    that paths[n] activates paths[n+1] when reached. If loop is True, paths[-1] activates
    paths[0] when reached.

    Args:
        paths (list[Path]): list of paths to chain
        loop (bool, optional): Whether the chain should loop. Defaults to False.

    """
    if len(paths) < 2:
        return
    for i, path in enumerate(paths):
        if i == 0:
            continue
        self.character.event_handler.register_event(
            self.character.event_handler.Event.PATH_COMPLETE,
            paths[i - 1],
            self.character.event_handler.Action.ACTIVATE_PATH,
            path,
        )
    if loop:
        self.character.event_handler.register_event(
            self.character.event_handler.Event.PATH_COMPLETE,
            paths[-1],
            self.character.event_handler.Action.ACTIVATE_PATH,
            paths[0],
        )

deactivate_path(path=None)

deactivate_path() -> None
deactivate_path(path: Path) -> None
deactivate_path(path: str) -> None

Deactivate a path if it is currently active.

If path is omitted, the current active path is deactivated if one exists. If path is a string, it is resolved as a path ID before deactivation.

Parameters:

Name Type Description Default
path Path | str | None

Path to deactivate, its ID, or None to deactivate the current active path.

None

Raises:

Type Description
PathNotFoundError

If path is a string and no path with that ID exists.

Source code in terminaltexteffects/engine/motion.py
def deactivate_path(self, path: Path | str | None = None) -> None:
    """Deactivate a path if it is currently active.

    If `path` is omitted, the current active path is deactivated if one exists.
    If `path` is a string, it is resolved as a path ID before deactivation.

    Args:
        path (Path | str | None): Path to deactivate, its ID, or None to deactivate the
            current active path.

    Raises:
        PathNotFoundError: If `path` is a string and no path with that ID exists.

    """
    if path is None:
        if self.active_path is not None:
            self._path_generation += 1
        self.active_path = None
        return
    if isinstance(path, str):
        found_path = self.query_path(path)
        if found_path is None:
            raise PathNotFoundError(path)
    else:
        found_path = path
    if self.active_path and self.active_path is found_path:
        self.active_path = None
        self._path_generation += 1

move()

Move the character along the active path.

The character's current coordinate is updated to the next step in the active path. If the active path is completed, an event is triggered based on whether the path is set to loop or not. Looping paths are reactivated from the current coordinate when they contain more than one segment. Otherwise, the path is deactivated and a PATH_COMPLETE event is triggered.

If the path has a hold time, the character will pause at the end of the path for the specified duration. During this hold time, a PATH_HOLDING event is triggered on the first frame, and the hold time is decremented on each subsequent frame until it reaches zero.

If there is no active path or if the active path has no segments, the character does not move.

The character's previous coordinate is preserved before moving to allow for clearing the location in the terminal.

If a segment or holding callback deactivates, replaces, or restarts the path, processing of the old traversal stops. Callback coordinates are preserved and any newly activated traversal begins moving on the next tick.

Source code in terminaltexteffects/engine/motion.py
def move(self) -> None:
    """Move the character along the active path.

    The character's current coordinate is updated to the next step in the active path. If the active path
    is completed, an event is triggered based on whether the path is set to loop or not. Looping paths are
    reactivated from the current coordinate when they contain more than one segment. Otherwise, the path
    is deactivated and a PATH_COMPLETE event is triggered.

    If the path has a hold time, the character will pause at the end of the path for the specified duration. During
    this hold time, a PATH_HOLDING event is triggered on the first frame, and the hold time is decremented on each
    subsequent frame until it reaches zero.

    If there is no active path or if the active path has no segments, the character does not move.

    The character's previous coordinate is preserved before moving to allow for clearing the location
    in the terminal.

    If a segment or holding callback deactivates, replaces, or restarts the path,
    processing of the old traversal stops. Callback coordinates are preserved and
    any newly activated traversal begins moving on the next tick.
    """
    # preserve previous coordinate to allow for clearing the location in the terminal
    cell = self.current_coord
    if cell is not self._cell:
        self._sync()
    self.previous_coord = cell

    if not self.active_path or not self.active_path.segments:
        return
    path = self.active_path
    path_generation = self._path_generation
    next_position = path._step(self.character.event_handler)
    if self.active_path is not path or self._path_generation != path_generation:
        return
    self._xyz = next_position
    character = self.character
    parent = character._parent or character.parent
    if parent._flat and not next_position[2] and not self._depth_from_view:
        # _resolve()'s text-plane shortcut, inline: this runs for every moving character on every frame.
        column, row = round(next_position[0]), round(next_position[1])
        cell = self._cell
        if cell.column != column or cell.row != row:
            self.current_coord = self._cell = Coord(column, row)
    else:
        self._resolve()
    if self.active_path.current_step == self.active_path.max_steps:
        final_segment = self.active_path.segments[-1]
        if final_segment.enter_event_triggered and not final_segment.exit_event_triggered:
            final_segment.exit_event_triggered = True
            self.character.event_handler._handle_event(
                self.character.event_handler.Event.SEGMENT_EXITED,
                final_segment.end,
            )
            if self.active_path is not path or self._path_generation != path_generation:
                return
        if self.active_path.hold_time and self.active_path.hold_time_remaining == self.active_path.hold_time:
            self.character.event_handler._handle_event(
                self.character.event_handler.Event.PATH_HOLDING,
                self.active_path,
            )
            if self.active_path is not path or self._path_generation != path_generation:
                return
            self.active_path.hold_time_remaining -= 1
            return
        if self.active_path.hold_time_remaining:
            self.active_path.hold_time_remaining -= 1
            return
        if self.active_path.loop and len(self.active_path.segments) > 1:
            looping_path = self.active_path
            self.deactivate_path(self.active_path)
            self.activate_path(looping_path)
        else:
            self.completed_path = self.active_path
            self.deactivate_path(self.active_path)
            self.character.event_handler._handle_event(
                self.character.event_handler.Event.PATH_COMPLETE,
                self.completed_path,
            )

movement_is_complete()

Return whether movement is complete.

Returns:

Name Type Description
bool bool

True if the character has no active path, False otherwise.

Source code in terminaltexteffects/engine/motion.py
def movement_is_complete(self) -> bool:
    """Return whether movement is complete.

    Returns:
        bool: True if the character has no active path, False otherwise.

    """
    return self.active_path is None

new_path(*, speed=1, ease=None, layer=None, hold_time=0, loop=False, path_id='')

Create a new Path and add it to the Motion.paths dictionary with the path_id as key.

Parameters:

Name Type Description Default
speed float

speed > 0. Defaults to 1.

1
ease EasingFunction | None

easing function for character movement. Defaults to None.

None
layer int | None

layer to move the character to, if None, layer is unchanged. Defaults to None.

None
hold_time int

number of frames to hold the character at the end of the path. Defaults to 0.

0
loop bool

Whether the path should loop back to the beginning. Default is False.

False
path_id str

Unique identifier for the path. Used to query for the path. Defaults to "".

''

Raises:

Type Description
DuplicatePathIDError

If a path with the provided id already exists.

PathInvalidSpeedError

If speed is less than or equal to 0.

Returns:

Name Type Description
Path Path

The new path.

Source code in terminaltexteffects/engine/motion.py
def new_path(
    self,
    *,
    speed: float = 1,
    ease: easing.EasingFunction | None = None,
    layer: int | None = None,
    hold_time: int = 0,
    loop: bool = False,
    path_id: str = "",
) -> Path:
    """Create a new Path and add it to the Motion.paths dictionary with the path_id as key.

    Args:
        speed (float, optional): speed > 0. Defaults to 1.
        ease (easing.EasingFunction | None, optional): easing function for character movement. Defaults to None.
        layer (int | None, optional): layer to move the character to, if None, layer is unchanged. Defaults to None.
        hold_time (int, optional): number of frames to hold the character at the end of the path. Defaults to 0.
        loop (bool, optional): Whether the path should loop back to the beginning. Default is False.
        path_id (str, optional): Unique identifier for the path. Used to query for the path. Defaults to "".

    Raises:
        DuplicatePathIDError: If a path with the provided id already exists.
        PathInvalidSpeedError: If `speed` is less than or equal to 0.

    Returns:
        Path: The new path.

    """
    if not path_id:
        found_unique = False
        current_id = len(self.paths)
        while not found_unique:
            path_id = f"{current_id}"
            if path_id not in self.paths:
                found_unique = True
            else:
                current_id += 1
    if path_id in self.paths:
        raise DuplicatePathIDError(path_id)
    new_path = Path(path_id, speed, ease, layer, hold_time, loop)
    self.paths[path_id] = new_path
    return new_path

query_path(path_id, not_found_action='raise')

query_path(path_id: str) -> Path
query_path(
    path_id: str, not_found_action: typing.Literal["raise"]
) -> Path
query_path(
    path_id: str, not_found_action: None
) -> Path | None

Return the path with the given path_id, or None if no path with the given ID exists.

Parameters:

Name Type Description Default
path_id str

path_id

required
not_found_action Literal['raise'] | None

Action to take if a path with the given path_id is not found. If "raise", a PathNotFoundError will be raised. If None, method will return None.

'raise'

Returns:

Type Description
Path | None

Path | None: The path with the given path_id, or None.

Raises:

Type Description
PathNotFoundError

If not_found_action is "raise" and a Path with the given path_id is not found.

Source code in terminaltexteffects/engine/motion.py
def query_path(self, path_id: str, not_found_action: typing.Literal["raise"] | None = "raise") -> Path | None:
    """Return the path with the given path_id, or None if no path with the given ID exists.

    Args:
        path_id (str): path_id
        not_found_action (Literal["raise"] | None, optional): Action to take if a path with the given
            path_id is not found. If "raise", a PathNotFoundError will be raised. If `None`, method will
            return `None`.

    Returns:
        Path | None: The path with the given path_id, or None.

    Raises:
        PathNotFoundError: If `not_found_action` is "raise" and a Path with the given
            `path_id` is not found.

    """
    found_path = self.paths.get(path_id, None)
    if not_found_action and found_path is None:
        raise PathNotFoundError(path_id)
    return found_path

set_coordinate(coord)

Move the character to a cell, now: column and row in its parent's frame, keeping its height.

Assigning current_coord does the same.

Parameters:

Name Type Description Default
coord Coord

coordinate

required
Source code in terminaltexteffects/engine/motion.py
def set_coordinate(self, coord: Coord) -> None:
    """Move the character to a cell, now: column and row in its parent's frame, keeping its height.

    Assigning `current_coord` does the same.

    Args:
        coord (Coord): coordinate

    """
    self.current_coord = coord
    self._sync()

Bases: Motion

Moves a body along paths of Vec3 waypoints in its parent's local frame, in units.

The same paths, easing, holds, loops and events as a character's motion. A body has no cell or layer: a path with a layer can't be activated on a body, and current_coord is only the rounded (x, y) it last took from set_coordinate. The world moves bodies along their paths at the start of every frame.

Source code in terminaltexteffects/engine/motion.py
class BodyMotion(Motion):
    """Moves a body along paths of `Vec3` waypoints in its parent's local frame, in units.

    The same paths, easing, holds, loops and events as a character's motion. A body has no cell or layer: a path
    with a `layer` can't be activated on a body, and `current_coord` is only the rounded `(x, y)` it last took from
    `set_coordinate`. The world moves bodies along their paths at the start of every frame.
    """

    def __init__(self, body: Body) -> None:  # noqa: D107
        self.paths = {}
        self.character = body  # type: ignore[assignment]  # the moving node, under the name Motion uses
        position = body.position
        self.current_coord = Coord(round(position.x), round(position.y))
        self._cell = self.current_coord
        self._xyz = (position.x, position.y, position.z)
        # Bodies have no cell: this keeps move() from taking the characters' text-plane shortcut.
        self._depth_from_view = True
        self._view_hidden = False
        self._show_when_seen = False
        self.previous_coord = Coord(-1, -1)
        self.active_path = None
        self._path_generation = 0

    def _row(self) -> float:
        return 1.0

    def _from_world(self, point: g3.Vec3) -> XYZ:
        local = self.character.parent.from_world(point, surface=False)
        return (local.x, local.y, local.z)

    def _sync(self) -> None:
        cell = self.current_coord
        self._cell = cell
        self._xyz = (cell.column, cell.row, self._xyz[2])
        self._resolve()

    def _resolve(self) -> None:
        body = typing.cast("Body", self.character)
        body._position = g3.Vec3(*self._xyz)
        body._changed()

    def activate_path(self, path: Path | str) -> None:
        """Start moving the body along a path. See `Motion.activate_path`.

        Raises:
            ValueError: For the world root, which never moves, or a path with a `layer`.

        """
        body = typing.cast("Body", self.character)
        body._check_movable()
        found = self.query_path(path) if isinstance(path, str) else path
        if found is not None and found.layer is not None:
            msg = "Bodies have no layer, so a body can't take a path with one."
            raise ValueError(msg)
        super().activate_path(path)

activate_path(path)

Start moving the body along a path. See Motion.activate_path.

Raises:

Type Description
ValueError

For the world root, which never moves, or a path with a layer.

Source code in terminaltexteffects/engine/motion.py
def activate_path(self, path: Path | str) -> None:
    """Start moving the body along a path. See `Motion.activate_path`.

    Raises:
        ValueError: For the world root, which never moves, or a path with a `layer`.

    """
    body = typing.cast("Body", self.character)
    body._check_movable()
    found = self.query_path(path) if isinstance(path, str) else path
    if found is not None and found.layer is not None:
        msg = "Bodies have no layer, so a body can't take a path with one."
        raise ValueError(msg)
    super().activate_path(path)