Skip to content

Animation

Module: terminaltexteffects.engine.animation

Appearance Reuse

New in 0.16.0

set_appearance_if_changed() is available on development main and is not in the published 0.15.0 package.

Animation.set_appearance_if_changed(symbol=None, colors=None) follows the ordinary setter's symbol defaults, color overrides, and width tracking. It reuses its last visual when the effective request, color policy, visual identity, and all visual instance fields remain unchanged. Scene stepping, an ordinary setter call, or direct style, color-code, width, or formatted-symbol edits force the next helper call to reapply the requested appearance. The helper does not stop an active scene from overwriting that appearance on its next step.

The snapshot is allocated lazily for each animation using the helper. It retains one visual and field snapshot; visuals are not shared across characters. Callers should not rely on receiving a new visual object each call; use Animation.set_appearance() when a fresh visual is required.

For input-derived characters in existing_color_handling="always" mode, the helper ignores requested colors in the comparison because parsed input colors override them. Helper characters without input-color ownership still compare the requested colors.

Opt in only after measuring (see Performance Testing): comparing and retaining snapshots can cost more than it saves when effective appearances change frequently. Overflow row coloring and Spotlights use the helper only in always mode.

Animation Reference

Animation handler for an EffectCharacter.

It contains a scene_name -> Scene mapping and the active Scene. Calls to step_animation() progress the Scene and apply the next visual to the character.

Attributes:

Name Type Description
scenes dict[str, Scene]

a mapping of scene IDs to Scene objects

character EffectCharacter

the EffectCharacter object to animate

active_scene Scene | None

the active Scene

use_xterm_colors bool

whether to convert all colors to XTerm-256 colors

no_color bool

whether to ignore colors

existing_color_handling str

how to handle color ANSI sequences from the input data

input_fg_color Color | None

the input foreground Color

input_bg_color Color | None

the input background Color

input_bold bool

whether the input character was parsed with active bold SGR styling

xterm_color_map dict[str, int]

shared bounded mapping of RGB color codes to XTerm-256 color codes

current_character_visual CharacterVisual

the current visual of the character

Methods:

Name Description
new_scene

Creates a new Scene and adds it to the Animation.

query_scene

Returns a Scene from the Animation.

active_scene_is_complete

Returns whether the active scene is complete.

set_appearance

Applies a symbol and color to the character.

set_appearance_if_changed

Applies appearance only when its effective visual has changed.

adjust_color_brightness

Adjusts the brightness of a given color.

_ease_animation

Returns the percentage of total distance that should be moved based on the easing function.

step_animation

Apply the next symbol in the scene to the character.

activate_scene

Activates a Scene.

Source code in terminaltexteffects/engine/animation.py
 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
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
class Animation:
    """Animation handler for an EffectCharacter.

    It contains a scene_name -> Scene mapping and the active Scene. Calls to step_animation()
    progress the Scene and apply the next visual to the character.


    Attributes:
        scenes (dict[str, Scene]): a mapping of scene IDs to Scene objects
        character (base_character.EffectCharacter): the EffectCharacter object to animate
        active_scene (Scene | None): the active Scene
        use_xterm_colors (bool): whether to convert all colors to XTerm-256 colors
        no_color (bool): whether to ignore colors
        existing_color_handling (str): how to handle color ANSI sequences from the input data
        input_fg_color (graphics.Color | None): the input foreground Color
        input_bg_color (graphics.Color | None): the input background Color
        input_bold (bool): whether the input character was parsed with active bold SGR styling
        xterm_color_map (dict[str, int]): shared bounded mapping of RGB color codes to XTerm-256 color codes
        current_character_visual (CharacterVisual): the current visual of the character

    Methods:
        new_scene: Creates a new Scene and adds it to the Animation.
        query_scene: Returns a Scene from the Animation.
        active_scene_is_complete: Returns whether the active scene is complete.
        set_appearance: Applies a symbol and color to the character.
        set_appearance_if_changed: Applies appearance only when its effective visual has changed.
        adjust_color_brightness: Adjusts the brightness of a given color.
        _ease_animation: Returns the percentage of total distance that should be moved based on the easing function.
        step_animation: Apply the next symbol in the scene to the character.
        activate_scene: Activates a Scene.

    """

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

        Args:
            character (base_character.EffectCharacter): the EffectCharacter object to animate

        """
        self.scenes: dict[str, Scene] = {}
        self.character = character
        self.active_scene: Scene | None = None
        self.use_xterm_colors: bool = False
        self.no_color: bool = False
        self.existing_color_handling: typing.Literal["always", "dynamic", "ignore"] = "ignore"
        self.input_fg_color: graphics.Color | None = None
        self.input_bg_color: graphics.Color | None = None
        self.input_bold: bool = False
        self.xterm_color_map = Scene.xterm_color_map
        self.current_character_visual = CharacterVisual(character.input_symbol)
        self._visual_width_mask = 1 << (self.current_character_visual.cell_width - 1)

    def _record_visual_width(self, visual: CharacterVisual) -> None:
        """Record a visual width for selective playback transition tracking."""
        self._visual_width_mask |= 1 << (visual.cell_width - 1)

    def _get_color_code(self, color: graphics.Color | None) -> str | int | None:
        """Get the color code for the given color.

        RGB colors are converted to XTerm-256 colors if use_xterm_colors
        is True. If no_color is True, returns None. Otherwise, returns the RGB color.

        Args:
            color (graphics.Color | None): the color to get the code for

        Returns:
            str | int | None: the color code

        """
        return _get_color_code(
            color,
            no_color=self.no_color,
            use_xterm_colors=self.use_xterm_colors,
            xterm_color_map=self.xterm_color_map,
        )

    def new_scene(
        self,
        *,
        is_looping: bool = False,
        sync: Scene.SyncMetric | None = None,
        ease: easing.EasingFunction | None = None,
        cache_easing: bool = False,
        cache_appearance: bool = False,
        scene_id: str = "",
    ) -> Scene:
        """Create a new Scene and add it to the Animation.

        If no ID is provided, a unique ID is generated. If `existing_color_handling` is `"always"`,
        the Scene inherits the animation's input colors as `preexisting_colors`. If a Scene with the
        same ID already exists, `DuplicateSceneIDError` is raised.

        Args:
            scene_id (str): Name for the scene. Used to query for the scene.
            is_looping (bool): Whether the scene should loop.
            sync (Scene.SyncMetric | None): The type of sync to use for the scene.
            ease (easing.EasingFunction | None): The easing function to use for the scene.
            cache_easing (bool): Opt into shared built-in easing schedules. Defaults to False.
            cache_appearance (bool): Share encoded frame appearances during construction. Defaults to False.

        Returns:
            Scene: The new Scene.

        Raises:
            DuplicateSceneIDError: If `scene_id` is already used by the animation.

        """
        if not scene_id:
            found_unique = False
            current_id = len(self.scenes)
            while not found_unique:
                scene_id = f"{current_id}"
                if scene_id not in self.scenes:
                    found_unique = True
                else:
                    current_id += 1
        if scene_id in self.scenes:
            raise DuplicateSceneIDError(scene_id)
        if self.existing_color_handling == "always" and self.character.uses_input_preexisting_colors:
            preexisting_colors = graphics.ColorPair(fg=self.input_fg_color, bg=self.input_bg_color)
            preexisting_bold = self.input_bold
        else:
            preexisting_colors = None
            preexisting_bold = False
        new_scene = Scene(
            scene_id=scene_id,
            is_looping=is_looping,
            sync=sync,
            ease=ease,
            cache_easing=cache_easing,
            cache_appearance=cache_appearance,
            no_color=self.no_color,
            use_xterm_colors=self.use_xterm_colors,
        )
        new_scene._frame_added_callback = self._record_visual_width
        new_scene.preexisting_colors = preexisting_colors
        new_scene.preexisting_bold = preexisting_bold
        self.scenes[scene_id] = new_scene
        return new_scene

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

        Args:
            scene_id (str): The ID of the Scene.
            not_found_action (Literal["raise"] | None, optional): Action to take if a Scene with the given
                `scene_id` is not found. If "raise", a SceneNotFoundError will be raised. If `None`, method will
                return `None`.

        Returns:
            Scene | None: The Scene with the given `scene_id`, or None.

        Raises:
            SceneNotFoundError: If `not_found_action` is "raise" and a Scene with the given
                `scene_id` is not found.

        """
        found_scene = self.scenes.get(scene_id, None)
        if not_found_action and found_scene is None:
            raise SceneNotFoundError(scene_id)
        return found_scene

    def active_scene_is_complete(self) -> bool:
        """Return whether the active scene should be treated as complete.

        A scene is treated as complete when there is no active scene or when the active
        scene has no remaining frames to play.

        Returns:
            bool: True if the active scene is complete, False otherwise.

        """
        return bool(not self.active_scene or not self.active_scene.frames)

    def set_appearance(self, symbol: str | None = None, colors: graphics.ColorPair | None = None) -> None:
        """Update the current character visual with the symbol and colors provided.

        If no symbol is provided, the character's input symbol is used.

        If `existing_color_handling` is `"always"`, any provided foreground or background
        colors are overridden by the character's input colors where available.

        If the character has an active scene, any appearance set with this method
        will be overwritten when the scene is stepped to the next frame.

        Args:
            symbol (str | None): The symbol to apply.
            colors (graphics.ColorPair | None): The colors to apply.

        Raises:
            InvalidSymbolError: If `symbol` does not contain one independently printable Unicode code point.

        """
        if symbol is None:
            symbol = self.character.input_symbol
        if colors is None:
            colors = graphics.ColorPair(fg=None, bg=None)
        # In always mode, input-derived characters use exactly the parsed input fg/bg pair,
        # even when one or both channels are absent.
        bold = False
        if self.existing_color_handling == "always" and self.character.uses_input_preexisting_colors:
            colors = graphics.ColorPair(fg=self.input_fg_color, bg=self.input_bg_color)
            bold = self.input_bold

        char_vis_fg_color: str | int | None = self._get_color_code(colors.fg)
        char_vis_bg_color: str | int | None = self._get_color_code(colors.bg)

        previous_width = self.current_character_visual.cell_width
        visual = CharacterVisual(
            symbol,
            bold=bold,
            colors=colors,
            _fg_color_code=char_vis_fg_color,
            _bg_color_code=char_vis_bg_color,
        )
        self._record_visual_width(visual)
        self.current_character_visual = visual
        if previous_width != visual.cell_width:
            self.character._notify_current_visual_width_changed(previous_width)

    def set_appearance_if_changed(self, symbol: str | None = None, colors: graphics.ColorPair | None = None) -> None:
        """Apply appearance while reusing an unchanged visual from the previous call.

        Arguments, color overrides, and width tracking follow `set_appearance`. Unlike
        that method, an identical effective appearance retains the current visual object.
        Changes to the visual's fields, replacement by a scene or ordinary setter, and
        changes to color policy cause the appearance to be reapplied. Requested colors
        do not affect the comparison when input colors override them in `"always"` mode.

        State is allocated only for animations using this helper. It retains one visual
        snapshot per animation; visuals are never shared between characters.

        Args:
            symbol (str | None): The symbol to apply, or the input symbol when omitted.
            colors (graphics.ColorPair | None): The colors to apply, or no colors when omitted.

        Raises:
            InvalidSymbolError: If `symbol` does not contain one independently printable Unicode code point.

        """
        if symbol is None:
            symbol = self.character.input_symbol
        override = self.existing_color_handling == "always" and self.character.uses_input_preexisting_colors
        key_colors = None if override else (colors if colors is not None else graphics.ColorPair())
        policy = (
            self.no_color,
            self.use_xterm_colors,
            self.existing_color_handling,
            self.input_fg_color,
            self.input_bg_color,
            self.input_bold,
            self.character.uses_input_preexisting_colors,
        )
        visual = self.current_character_visual
        previous = getattr(self, "_appearance_state", None)
        if (
            previous is not None
            and previous[0] == symbol
            and previous[1] == key_colors
            and previous[2] == policy
            and previous[3] is visual
            and previous[4] == visual.__dict__
        ):
            return
        self.set_appearance(symbol, colors)
        visual = self.current_character_visual
        self._appearance_state = (symbol, key_colors, policy, visual, visual.__dict__.copy())

    @staticmethod
    def adjust_color_brightness(color: graphics.Color, brightness: float) -> graphics.Color:
        """Adjust the brightness of a given color.

        Args:
            color (Color): The color code to adjust.
            brightness (float): The brightness adjustment factor.

        Returns:
            Color: The adjusted color code.

        """

        def hue_to_rgb(lightness_scaled: float, color_intensity: float, hue_value: float) -> float:
            """Convert a hue value to an RGB value component.

            This function is a helper function used in the conversion from HSL (Hue, Saturation, Lightness)
            color space to RGB (Red, Green, Blue) color space. It takes in three parameters: lightness_scaled,
            color_intensity, and hue_value. These parameters are derived from the HSL color space and are used
            to calculate the corresponding RGB value.

            Args:
                lightness_scaled (float): The lightness value from the HSL color space, scaled and shifted to be used in
                    the RGB conversion.
                color_intensity (float): The intensity of the color, used to adjust the RGB values.
                hue_value (float): The hue value from the HSL color space, used to calculate the RGB values.

            Returns:
                float: The calculated RGB component.

            """
            if hue_value < 0:
                hue_value += 1
            if hue_value > 1:
                hue_value -= 1
            if hue_value < 1 / 6:
                return lightness_scaled + (color_intensity - lightness_scaled) * 6 * hue_value
            if hue_value < 1 / 2:
                return color_intensity
            if hue_value < 2 / 3:
                return lightness_scaled + (color_intensity - lightness_scaled) * (2 / 3 - hue_value) * 6
            return lightness_scaled

        normalized_red = int(color.rgb_color[0:2], 16) / 255
        normalized_green = int(color.rgb_color[2:4], 16) / 255
        normalized_blue = int(color.rgb_color[4:6], 16) / 255

        # Convert RGB to HSL
        max_val = max(normalized_red, normalized_green, normalized_blue)
        min_val = min(normalized_red, normalized_green, normalized_blue)
        lightness = (max_val + min_val) / 2

        if max_val == min_val:
            hue_value = saturation = 0.0  # achromatic
        else:
            diff = max_val - min_val
            lightness_threshold = 0.5
            saturation = (
                diff / (2 - max_val - min_val) if lightness > lightness_threshold else diff / (max_val + min_val)
            )
            if max_val == normalized_red:
                hue_value = (normalized_green - normalized_blue) / diff + (
                    6 if normalized_green < normalized_blue else 0
                )
            elif max_val == normalized_green:
                hue_value = (normalized_blue - normalized_red) / diff + 2
            else:
                hue_value = (normalized_red - normalized_green) / diff + 4
            hue_value /= 6

        # Adjust lightness
        lightness = max(min(lightness * brightness, 1), 0)

        # Convert back to RGB
        if saturation == 0:
            red = green = blue = lightness  # achromatic
        else:
            color_intensity = (
                lightness * (1 + saturation)
                if lightness < lightness_threshold  # type: ignore[unbound]
                else lightness + saturation - lightness * saturation
            )
            lightness_scaled = 2 * lightness - color_intensity
            red = hue_to_rgb(lightness_scaled, color_intensity, hue_value + 1 / 3)
            green = hue_to_rgb(lightness_scaled, color_intensity, hue_value)
            blue = hue_to_rgb(lightness_scaled, color_intensity, hue_value - 1 / 3)

        # Convert to hex
        adjusted_color = f"{round(red * 255):02x}{round(green * 255):02x}{round(blue * 255):02x}"
        return graphics.Color(adjusted_color)

    def _ease_animation(self, easing_func: easing.EasingFunction) -> float:
        """Return the percentage of total distance that should be moved based on the easing function.

        Args:
            easing_func (easing.EasingFunction): The easing function to use.

        Returns:
            float: The percentage of total distance to move.

        """
        if self.active_scene is None:
            return 0
        elapsed_step_ratio = self.active_scene.easing_current_step / max(
            self.active_scene.easing_total_steps - 1,
            1,
        )
        return easing_func(elapsed_step_ratio)

    def step_animation(self) -> None:
        """Progress the Scene and apply the next visual to the character.

        Behavior:
            * Synced scenes select a frame based on the active motion path's progress, or on the active 3D mount's
              light or nearness for `SyncMetric.LIGHT` and `SyncMetric.DEPTH`.
            * Eased scenes select a frame using cumulative duration boundaries and easing progress.
            * All other scenes advance by consuming frame duration through `Scene.get_next_visual()`.
            * If a synced scene no longer has an active motion path (or mount, for the 3D metrics), the final
              frame is applied and the scene is marked complete.
            * When a non-looping scene completes, it is reset, deactivated, and a `SCENE_COMPLETE`
              event is triggered.
        """
        scene = self.active_scene
        if scene is None or not scene.frames:
            return
        previous_width = self.current_character_visual.cell_width if self._visual_width_mask == 0b11 else 0

        if scene.sync:
            self._step_synced_scene(scene)
        elif scene.ease:
            self._step_eased_scene(scene)
        else:
            self.current_character_visual = scene.get_next_visual()

        if previous_width and previous_width != self.current_character_visual.cell_width:
            self.character._notify_current_visual_width_changed(previous_width)
        self._complete_scene_if_finished(scene)

    def _step_synced_scene(self, scene: Scene) -> None:
        """Apply the frame that matches the active motion path's progress or the active mount's reading."""
        if scene.sync in (Scene.SyncMetric.LIGHT, Scene.SyncMetric.DEPTH):
            mount = self.character.motion.mount
            if mount is None:
                self._finish_synced_scene(scene)
                return
            reading = mount.light if scene.sync is Scene.SyncMetric.LIGHT else mount.nearness
            final_frame_index = len(scene.frames) - 1
            frame_index = round(final_frame_index * min(max(reading, 0.0), 1.0))
            self.current_character_visual = scene.frames[frame_index].character_visual
            return
        active_path = self.character.motion.active_path
        if active_path is None:
            self._finish_synced_scene(scene)
            return

        frame_index = self._synced_scene_frame_index(scene, active_path)
        self.current_character_visual = scene.frames[frame_index].character_visual

    def _finish_synced_scene(self, scene: Scene) -> None:
        """Apply the final frame and mark the synced scene complete once its motion source is gone."""
        self.current_character_visual = scene.frames[-1].character_visual
        scene.played_frames.extend(scene.frames)
        scene.frames.clear()

    def _synced_scene_frame_index(self, scene: Scene, active_path: motion.Path) -> int:
        """Return the scene frame index for the active path's progress."""
        final_frame_index = len(scene.frames) - 1
        if scene.sync == Scene.SyncMetric.STEP:
            progress_ratio = active_path.current_step / active_path.max_steps if active_path.max_steps > 0 else 0.0
        else:
            progress_ratio = (
                active_path.last_distance_reached / active_path.total_distance
                if active_path.total_distance > 0
                else 0.0
            )

        progress_ratio = min(max(progress_ratio, 0.0), 1.0)
        frame_index = round(final_frame_index * progress_ratio)
        return max(min(frame_index, final_frame_index), 0)

    def _step_eased_scene(self, scene: Scene) -> None:
        """Apply the eased frame and update easing playback state."""
        assert scene.ease is not None
        schedule = scene._get_easing_schedule() if scene.cache_easing else None
        if schedule is None or not 0 <= scene.easing_current_step < scene.easing_total_steps:
            easing_factor = self._ease_animation(scene.ease)
            final_frame_index = max(scene.easing_total_steps - 1, 0)
            frame_index = round(easing_factor * final_frame_index)
            frame_index = max(min(frame_index, final_frame_index), 0)
            frame_position = bisect_right(scene._frame_end_steps, frame_index)
        else:
            frame_position = schedule.positions[scene.easing_current_step]
        self.current_character_visual = scene.frames[frame_position].character_visual

        scene.easing_current_step += 1
        if scene.easing_current_step == scene.easing_total_steps:
            if scene.is_looping:
                scene.easing_current_step = 0
            else:
                scene.played_frames.extend(scene.frames)
                scene.frames.clear()

    def _complete_scene_if_finished(self, scene: Scene) -> None:
        """Reset completed scenes and trigger completion events."""
        if not self.active_scene_is_complete():
            return

        scene.reset_scene()
        if not scene.is_looping:
            self.active_scene = None
            self.character.event_handler._handle_event(
                self.character.event_handler.Event.SCENE_COMPLETE,
                scene,
            )

    def activate_scene(self, scene: Scene | str) -> None:
        """Set the active scene and updates the current character visual.

        If `scene` is a string, a scene query will be performed for a scene with
        a `scene_id` matching the provided string.

        This method does not reset scene playback state before activation. To restart
        a scene from its initial frame sequence, reset the scene before activating it.

        A SCENE_ACTIVATED event is triggered.

        Args:
            scene (Scene | str): Scene instance of Scene ID for the scene that should
                be activated.

        Raises:
            SceneNotFoundError: Raised if the scene_id provided does not correspond to
                a known scene.

        """
        if isinstance(scene, str):
            found_scene = self.query_scene(scene)
            if found_scene is None:
                raise SceneNotFoundError(scene)
        else:
            found_scene = scene
        found_scene._frame_added_callback = self._record_visual_width
        self._visual_width_mask |= found_scene._visual_width_mask
        self.active_scene = found_scene
        previous_width = self.current_character_visual.cell_width
        visual = self.active_scene.activate()
        self._record_visual_width(visual)
        self.current_character_visual = visual
        if previous_width != visual.cell_width:
            self.character._notify_current_visual_width_changed(previous_width)
        self.character.event_handler._handle_event(self.character.event_handler.Event.SCENE_ACTIVATED, found_scene)

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

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

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

        Raises:
            SceneNotFoundError: If `scene` is a string and no scene with that ID exists.

        """
        if scene is None:
            self.active_scene = None
            return
        if isinstance(scene, str):
            found_scene = self.query_scene(scene)
            if found_scene is None:
                raise SceneNotFoundError(scene)
        else:
            found_scene = scene
        if self.active_scene and self.active_scene is found_scene:
            self.active_scene = None

__init__(character)

Initialize the Animation object.

Parameters:

Name Type Description Default
character EffectCharacter

the EffectCharacter object to animate

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

    Args:
        character (base_character.EffectCharacter): the EffectCharacter object to animate

    """
    self.scenes: dict[str, Scene] = {}
    self.character = character
    self.active_scene: Scene | None = None
    self.use_xterm_colors: bool = False
    self.no_color: bool = False
    self.existing_color_handling: typing.Literal["always", "dynamic", "ignore"] = "ignore"
    self.input_fg_color: graphics.Color | None = None
    self.input_bg_color: graphics.Color | None = None
    self.input_bold: bool = False
    self.xterm_color_map = Scene.xterm_color_map
    self.current_character_visual = CharacterVisual(character.input_symbol)
    self._visual_width_mask = 1 << (self.current_character_visual.cell_width - 1)

activate_scene(scene)

Set the active scene and updates the current character visual.

If scene is a string, a scene query will be performed for a scene with a scene_id matching the provided string.

This method does not reset scene playback state before activation. To restart a scene from its initial frame sequence, reset the scene before activating it.

A SCENE_ACTIVATED event is triggered.

Parameters:

Name Type Description Default
scene Scene | str

Scene instance of Scene ID for the scene that should be activated.

required

Raises:

Type Description
SceneNotFoundError

Raised if the scene_id provided does not correspond to a known scene.

Source code in terminaltexteffects/engine/animation.py
def activate_scene(self, scene: Scene | str) -> None:
    """Set the active scene and updates the current character visual.

    If `scene` is a string, a scene query will be performed for a scene with
    a `scene_id` matching the provided string.

    This method does not reset scene playback state before activation. To restart
    a scene from its initial frame sequence, reset the scene before activating it.

    A SCENE_ACTIVATED event is triggered.

    Args:
        scene (Scene | str): Scene instance of Scene ID for the scene that should
            be activated.

    Raises:
        SceneNotFoundError: Raised if the scene_id provided does not correspond to
            a known scene.

    """
    if isinstance(scene, str):
        found_scene = self.query_scene(scene)
        if found_scene is None:
            raise SceneNotFoundError(scene)
    else:
        found_scene = scene
    found_scene._frame_added_callback = self._record_visual_width
    self._visual_width_mask |= found_scene._visual_width_mask
    self.active_scene = found_scene
    previous_width = self.current_character_visual.cell_width
    visual = self.active_scene.activate()
    self._record_visual_width(visual)
    self.current_character_visual = visual
    if previous_width != visual.cell_width:
        self.character._notify_current_visual_width_changed(previous_width)
    self.character.event_handler._handle_event(self.character.event_handler.Event.SCENE_ACTIVATED, found_scene)

active_scene_is_complete()

Return whether the active scene should be treated as complete.

A scene is treated as complete when there is no active scene or when the active scene has no remaining frames to play.

Returns:

Name Type Description
bool bool

True if the active scene is complete, False otherwise.

Source code in terminaltexteffects/engine/animation.py
def active_scene_is_complete(self) -> bool:
    """Return whether the active scene should be treated as complete.

    A scene is treated as complete when there is no active scene or when the active
    scene has no remaining frames to play.

    Returns:
        bool: True if the active scene is complete, False otherwise.

    """
    return bool(not self.active_scene or not self.active_scene.frames)

adjust_color_brightness(color, brightness) staticmethod

Adjust the brightness of a given color.

Parameters:

Name Type Description Default
color Color

The color code to adjust.

required
brightness float

The brightness adjustment factor.

required

Returns:

Name Type Description
Color Color

The adjusted color code.

Source code in terminaltexteffects/engine/animation.py
@staticmethod
def adjust_color_brightness(color: graphics.Color, brightness: float) -> graphics.Color:
    """Adjust the brightness of a given color.

    Args:
        color (Color): The color code to adjust.
        brightness (float): The brightness adjustment factor.

    Returns:
        Color: The adjusted color code.

    """

    def hue_to_rgb(lightness_scaled: float, color_intensity: float, hue_value: float) -> float:
        """Convert a hue value to an RGB value component.

        This function is a helper function used in the conversion from HSL (Hue, Saturation, Lightness)
        color space to RGB (Red, Green, Blue) color space. It takes in three parameters: lightness_scaled,
        color_intensity, and hue_value. These parameters are derived from the HSL color space and are used
        to calculate the corresponding RGB value.

        Args:
            lightness_scaled (float): The lightness value from the HSL color space, scaled and shifted to be used in
                the RGB conversion.
            color_intensity (float): The intensity of the color, used to adjust the RGB values.
            hue_value (float): The hue value from the HSL color space, used to calculate the RGB values.

        Returns:
            float: The calculated RGB component.

        """
        if hue_value < 0:
            hue_value += 1
        if hue_value > 1:
            hue_value -= 1
        if hue_value < 1 / 6:
            return lightness_scaled + (color_intensity - lightness_scaled) * 6 * hue_value
        if hue_value < 1 / 2:
            return color_intensity
        if hue_value < 2 / 3:
            return lightness_scaled + (color_intensity - lightness_scaled) * (2 / 3 - hue_value) * 6
        return lightness_scaled

    normalized_red = int(color.rgb_color[0:2], 16) / 255
    normalized_green = int(color.rgb_color[2:4], 16) / 255
    normalized_blue = int(color.rgb_color[4:6], 16) / 255

    # Convert RGB to HSL
    max_val = max(normalized_red, normalized_green, normalized_blue)
    min_val = min(normalized_red, normalized_green, normalized_blue)
    lightness = (max_val + min_val) / 2

    if max_val == min_val:
        hue_value = saturation = 0.0  # achromatic
    else:
        diff = max_val - min_val
        lightness_threshold = 0.5
        saturation = (
            diff / (2 - max_val - min_val) if lightness > lightness_threshold else diff / (max_val + min_val)
        )
        if max_val == normalized_red:
            hue_value = (normalized_green - normalized_blue) / diff + (
                6 if normalized_green < normalized_blue else 0
            )
        elif max_val == normalized_green:
            hue_value = (normalized_blue - normalized_red) / diff + 2
        else:
            hue_value = (normalized_red - normalized_green) / diff + 4
        hue_value /= 6

    # Adjust lightness
    lightness = max(min(lightness * brightness, 1), 0)

    # Convert back to RGB
    if saturation == 0:
        red = green = blue = lightness  # achromatic
    else:
        color_intensity = (
            lightness * (1 + saturation)
            if lightness < lightness_threshold  # type: ignore[unbound]
            else lightness + saturation - lightness * saturation
        )
        lightness_scaled = 2 * lightness - color_intensity
        red = hue_to_rgb(lightness_scaled, color_intensity, hue_value + 1 / 3)
        green = hue_to_rgb(lightness_scaled, color_intensity, hue_value)
        blue = hue_to_rgb(lightness_scaled, color_intensity, hue_value - 1 / 3)

    # Convert to hex
    adjusted_color = f"{round(red * 255):02x}{round(green * 255):02x}{round(blue * 255):02x}"
    return graphics.Color(adjusted_color)

deactivate_scene(scene=None)

deactivate_scene() -> None
deactivate_scene(scene: Scene) -> None
deactivate_scene(scene: str) -> None

Deactivate a scene if it is currently active.

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

Parameters:

Name Type Description Default
scene Scene | str | None

Scene to deactivate, its ID, or None to deactivate the current active scene.

None

Raises:

Type Description
SceneNotFoundError

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

Source code in terminaltexteffects/engine/animation.py
def deactivate_scene(self, scene: Scene | str | None = None) -> None:
    """Deactivate a scene if it is currently active.

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

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

    Raises:
        SceneNotFoundError: If `scene` is a string and no scene with that ID exists.

    """
    if scene is None:
        self.active_scene = None
        return
    if isinstance(scene, str):
        found_scene = self.query_scene(scene)
        if found_scene is None:
            raise SceneNotFoundError(scene)
    else:
        found_scene = scene
    if self.active_scene and self.active_scene is found_scene:
        self.active_scene = None

new_scene(*, is_looping=False, sync=None, ease=None, cache_easing=False, cache_appearance=False, scene_id='')

Create a new Scene and add it to the Animation.

If no ID is provided, a unique ID is generated. If existing_color_handling is "always", the Scene inherits the animation's input colors as preexisting_colors. If a Scene with the same ID already exists, DuplicateSceneIDError is raised.

Parameters:

Name Type Description Default
scene_id str

Name for the scene. Used to query for the scene.

''
is_looping bool

Whether the scene should loop.

False
sync SyncMetric | None

The type of sync to use for the scene.

None
ease EasingFunction | None

The easing function to use for the scene.

None
cache_easing bool

Opt into shared built-in easing schedules. Defaults to False.

False
cache_appearance bool

Share encoded frame appearances during construction. Defaults to False.

False

Returns:

Name Type Description
Scene Scene

The new Scene.

Raises:

Type Description
DuplicateSceneIDError

If scene_id is already used by the animation.

Source code in terminaltexteffects/engine/animation.py
def new_scene(
    self,
    *,
    is_looping: bool = False,
    sync: Scene.SyncMetric | None = None,
    ease: easing.EasingFunction | None = None,
    cache_easing: bool = False,
    cache_appearance: bool = False,
    scene_id: str = "",
) -> Scene:
    """Create a new Scene and add it to the Animation.

    If no ID is provided, a unique ID is generated. If `existing_color_handling` is `"always"`,
    the Scene inherits the animation's input colors as `preexisting_colors`. If a Scene with the
    same ID already exists, `DuplicateSceneIDError` is raised.

    Args:
        scene_id (str): Name for the scene. Used to query for the scene.
        is_looping (bool): Whether the scene should loop.
        sync (Scene.SyncMetric | None): The type of sync to use for the scene.
        ease (easing.EasingFunction | None): The easing function to use for the scene.
        cache_easing (bool): Opt into shared built-in easing schedules. Defaults to False.
        cache_appearance (bool): Share encoded frame appearances during construction. Defaults to False.

    Returns:
        Scene: The new Scene.

    Raises:
        DuplicateSceneIDError: If `scene_id` is already used by the animation.

    """
    if not scene_id:
        found_unique = False
        current_id = len(self.scenes)
        while not found_unique:
            scene_id = f"{current_id}"
            if scene_id not in self.scenes:
                found_unique = True
            else:
                current_id += 1
    if scene_id in self.scenes:
        raise DuplicateSceneIDError(scene_id)
    if self.existing_color_handling == "always" and self.character.uses_input_preexisting_colors:
        preexisting_colors = graphics.ColorPair(fg=self.input_fg_color, bg=self.input_bg_color)
        preexisting_bold = self.input_bold
    else:
        preexisting_colors = None
        preexisting_bold = False
    new_scene = Scene(
        scene_id=scene_id,
        is_looping=is_looping,
        sync=sync,
        ease=ease,
        cache_easing=cache_easing,
        cache_appearance=cache_appearance,
        no_color=self.no_color,
        use_xterm_colors=self.use_xterm_colors,
    )
    new_scene._frame_added_callback = self._record_visual_width
    new_scene.preexisting_colors = preexisting_colors
    new_scene.preexisting_bold = preexisting_bold
    self.scenes[scene_id] = new_scene
    return new_scene

query_scene(scene_id, not_found_action='raise')

query_scene(scene_id: str) -> Scene
query_scene(
    scene_id: str, not_found_action: typing.Literal["raise"]
) -> Scene
query_scene(
    scene_id: str, not_found_action: None
) -> Scene | None

Return the Scene with the given scene_id, or None if no Scene with the given ID exists.

Parameters:

Name Type Description Default
scene_id str

The ID of the Scene.

required
not_found_action Literal['raise'] | None

Action to take if a Scene with the given scene_id is not found. If "raise", a SceneNotFoundError will be raised. If None, method will return None.

'raise'

Returns:

Type Description
Scene | None

Scene | None: The Scene with the given scene_id, or None.

Raises:

Type Description
SceneNotFoundError

If not_found_action is "raise" and a Scene with the given scene_id is not found.

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

    Args:
        scene_id (str): The ID of the Scene.
        not_found_action (Literal["raise"] | None, optional): Action to take if a Scene with the given
            `scene_id` is not found. If "raise", a SceneNotFoundError will be raised. If `None`, method will
            return `None`.

    Returns:
        Scene | None: The Scene with the given `scene_id`, or None.

    Raises:
        SceneNotFoundError: If `not_found_action` is "raise" and a Scene with the given
            `scene_id` is not found.

    """
    found_scene = self.scenes.get(scene_id, None)
    if not_found_action and found_scene is None:
        raise SceneNotFoundError(scene_id)
    return found_scene

set_appearance(symbol=None, colors=None)

Update the current character visual with the symbol and colors provided.

If no symbol is provided, the character's input symbol is used.

If existing_color_handling is "always", any provided foreground or background colors are overridden by the character's input colors where available.

If the character has an active scene, any appearance set with this method will be overwritten when the scene is stepped to the next frame.

Parameters:

Name Type Description Default
symbol str | None

The symbol to apply.

None
colors ColorPair | None

The colors to apply.

None

Raises:

Type Description
InvalidSymbolError

If symbol does not contain one independently printable Unicode code point.

Source code in terminaltexteffects/engine/animation.py
def set_appearance(self, symbol: str | None = None, colors: graphics.ColorPair | None = None) -> None:
    """Update the current character visual with the symbol and colors provided.

    If no symbol is provided, the character's input symbol is used.

    If `existing_color_handling` is `"always"`, any provided foreground or background
    colors are overridden by the character's input colors where available.

    If the character has an active scene, any appearance set with this method
    will be overwritten when the scene is stepped to the next frame.

    Args:
        symbol (str | None): The symbol to apply.
        colors (graphics.ColorPair | None): The colors to apply.

    Raises:
        InvalidSymbolError: If `symbol` does not contain one independently printable Unicode code point.

    """
    if symbol is None:
        symbol = self.character.input_symbol
    if colors is None:
        colors = graphics.ColorPair(fg=None, bg=None)
    # In always mode, input-derived characters use exactly the parsed input fg/bg pair,
    # even when one or both channels are absent.
    bold = False
    if self.existing_color_handling == "always" and self.character.uses_input_preexisting_colors:
        colors = graphics.ColorPair(fg=self.input_fg_color, bg=self.input_bg_color)
        bold = self.input_bold

    char_vis_fg_color: str | int | None = self._get_color_code(colors.fg)
    char_vis_bg_color: str | int | None = self._get_color_code(colors.bg)

    previous_width = self.current_character_visual.cell_width
    visual = CharacterVisual(
        symbol,
        bold=bold,
        colors=colors,
        _fg_color_code=char_vis_fg_color,
        _bg_color_code=char_vis_bg_color,
    )
    self._record_visual_width(visual)
    self.current_character_visual = visual
    if previous_width != visual.cell_width:
        self.character._notify_current_visual_width_changed(previous_width)

set_appearance_if_changed(symbol=None, colors=None)

Apply appearance while reusing an unchanged visual from the previous call.

Arguments, color overrides, and width tracking follow set_appearance. Unlike that method, an identical effective appearance retains the current visual object. Changes to the visual's fields, replacement by a scene or ordinary setter, and changes to color policy cause the appearance to be reapplied. Requested colors do not affect the comparison when input colors override them in "always" mode.

State is allocated only for animations using this helper. It retains one visual snapshot per animation; visuals are never shared between characters.

Parameters:

Name Type Description Default
symbol str | None

The symbol to apply, or the input symbol when omitted.

None
colors ColorPair | None

The colors to apply, or no colors when omitted.

None

Raises:

Type Description
InvalidSymbolError

If symbol does not contain one independently printable Unicode code point.

Source code in terminaltexteffects/engine/animation.py
def set_appearance_if_changed(self, symbol: str | None = None, colors: graphics.ColorPair | None = None) -> None:
    """Apply appearance while reusing an unchanged visual from the previous call.

    Arguments, color overrides, and width tracking follow `set_appearance`. Unlike
    that method, an identical effective appearance retains the current visual object.
    Changes to the visual's fields, replacement by a scene or ordinary setter, and
    changes to color policy cause the appearance to be reapplied. Requested colors
    do not affect the comparison when input colors override them in `"always"` mode.

    State is allocated only for animations using this helper. It retains one visual
    snapshot per animation; visuals are never shared between characters.

    Args:
        symbol (str | None): The symbol to apply, or the input symbol when omitted.
        colors (graphics.ColorPair | None): The colors to apply, or no colors when omitted.

    Raises:
        InvalidSymbolError: If `symbol` does not contain one independently printable Unicode code point.

    """
    if symbol is None:
        symbol = self.character.input_symbol
    override = self.existing_color_handling == "always" and self.character.uses_input_preexisting_colors
    key_colors = None if override else (colors if colors is not None else graphics.ColorPair())
    policy = (
        self.no_color,
        self.use_xterm_colors,
        self.existing_color_handling,
        self.input_fg_color,
        self.input_bg_color,
        self.input_bold,
        self.character.uses_input_preexisting_colors,
    )
    visual = self.current_character_visual
    previous = getattr(self, "_appearance_state", None)
    if (
        previous is not None
        and previous[0] == symbol
        and previous[1] == key_colors
        and previous[2] == policy
        and previous[3] is visual
        and previous[4] == visual.__dict__
    ):
        return
    self.set_appearance(symbol, colors)
    visual = self.current_character_visual
    self._appearance_state = (symbol, key_colors, policy, visual, visual.__dict__.copy())

step_animation()

Progress the Scene and apply the next visual to the character.

Behavior
  • Synced scenes select a frame based on the active motion path's progress, or on the active 3D mount's light or nearness for SyncMetric.LIGHT and SyncMetric.DEPTH.
  • Eased scenes select a frame using cumulative duration boundaries and easing progress.
  • All other scenes advance by consuming frame duration through Scene.get_next_visual().
  • If a synced scene no longer has an active motion path (or mount, for the 3D metrics), the final frame is applied and the scene is marked complete.
  • When a non-looping scene completes, it is reset, deactivated, and a SCENE_COMPLETE event is triggered.
Source code in terminaltexteffects/engine/animation.py
def step_animation(self) -> None:
    """Progress the Scene and apply the next visual to the character.

    Behavior:
        * Synced scenes select a frame based on the active motion path's progress, or on the active 3D mount's
          light or nearness for `SyncMetric.LIGHT` and `SyncMetric.DEPTH`.
        * Eased scenes select a frame using cumulative duration boundaries and easing progress.
        * All other scenes advance by consuming frame duration through `Scene.get_next_visual()`.
        * If a synced scene no longer has an active motion path (or mount, for the 3D metrics), the final
          frame is applied and the scene is marked complete.
        * When a non-looping scene completes, it is reset, deactivated, and a `SCENE_COMPLETE`
          event is triggered.
    """
    scene = self.active_scene
    if scene is None or not scene.frames:
        return
    previous_width = self.current_character_visual.cell_width if self._visual_width_mask == 0b11 else 0

    if scene.sync:
        self._step_synced_scene(scene)
    elif scene.ease:
        self._step_eased_scene(scene)
    else:
        self.current_character_visual = scene.get_next_visual()

    if previous_width and previous_width != self.current_character_visual.cell_width:
        self.character._notify_current_visual_width_changed(previous_width)
    self._complete_scene_if_finished(scene)