Skip to content

Animation

Module: terminaltexteffects.engine.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:

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]

a mapping of RGB color codes to XTerm-256 color codes

active_scene_current_step int

Reserved for scene-step tracking; currently reset on activation but otherwise unused.

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.

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
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
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
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]): a mapping of RGB color codes to XTerm-256 color codes
        active_scene_current_step (int): Reserved for scene-step tracking; currently reset on activation but
            otherwise unused.
        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.
        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: dict[str, int] = {}
        # Future: review whether `active_scene_current_step` should be removed or implemented for real scene tracking.
        self.active_scene_current_step: int = 0
        self.current_character_visual: CharacterVisual = CharacterVisual(character.input_symbol)

    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

        """
        if color:
            if self.no_color:
                return None
            if self.use_xterm_colors:
                if color.xterm_color is not None:
                    return color.xterm_color
                if color.rgb_color in self.xterm_color_map:
                    return self.xterm_color_map[color.rgb_color]
                xterm_color = hexterm.hex_to_xterm(color.rgb_color)
                self.xterm_color_map[color.rgb_color] = xterm_color
                return xterm_color
            return color.rgb_color
        return None

    def new_scene(
        self,
        *,
        is_looping: bool = False,
        sync: Scene.SyncMetric | None = None,
        ease: easing.EasingFunction | None = None,
        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, it is replaced in the animation's scene mapping.

        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.

        Returns:
            Scene: The new Scene.

        """
        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
        # Future: review whether scene IDs should be enforced as unique and raise on duplicates.
        # Confirm no effects intentionally overwrite scenes today, then update this behavior and docs together.
        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,
            no_color=self.no_color,
            use_xterm_colors=self.use_xterm_colors,
        )
        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, when the active
        scene has no remaining frames to play, or when the active scene is looping.

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

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

    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.

        """
        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_color)
        char_vis_bg_color: str | int | None = self._get_color_code(colors.bg_color)

        self.current_character_visual = CharacterVisual(
            symbol,
            bold=bold,
            colors=colors,
            _fg_color_code=char_vis_fg_color,
            _bg_color_code=char_vis_bg_color,
        )

    @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"{int(red * 255):02x}{int(green * 255):02x}{int(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 / self.active_scene.easing_total_steps
        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.
            * Eased scenes select a frame from `frame_index_map` using 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, 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.
        """
        if self.active_scene and self.active_scene.frames:
            # if the active scene is synced to movement, calculate the sequence index based on the
            # current waypoint progress
            if self.active_scene.sync:
                if self.character.motion.active_path:
                    if self.active_scene.sync == Scene.SyncMetric.STEP:
                        sequence_index = round(
                            (len(self.active_scene.frames) - 1)
                            * (
                                max(self.character.motion.active_path.current_step, 1)
                                / max(self.character.motion.active_path.max_steps, 1)
                            ),
                        )
                    elif self.active_scene.sync == Scene.SyncMetric.DISTANCE:
                        sequence_index = round(
                            (len(self.active_scene.frames) - 1)
                            * (
                                max(
                                    max(self.character.motion.active_path.total_distance, 1)
                                    - max(
                                        self.character.motion.active_path.total_distance
                                        - self.character.motion.active_path.last_distance_reached,
                                        1,
                                    ),
                                    1,
                                )
                                / max(self.character.motion.active_path.total_distance, 1)
                            ),
                        )
                    try:
                        self.current_character_visual = self.active_scene.frames[sequence_index].character_visual  # type: ignore[unbound]
                    except IndexError:
                        self.current_character_visual = self.active_scene.frames[-1].character_visual
                # when the active waypoint has been deactivated, use the final symbol in the scene and finish the scene
                else:
                    self.current_character_visual = self.active_scene.frames[-1].character_visual
                    self.active_scene.played_frames.extend(self.active_scene.frames)
                    self.active_scene.frames.clear()

            elif self.active_scene and self.active_scene.ease:
                easing_factor = self._ease_animation(self.active_scene.ease)
                frame_index = round(easing_factor * max(self.active_scene.easing_total_steps - 1, 0))
                frame_index = max(min(frame_index, self.active_scene.easing_total_steps - 1), 0)
                frame = self.active_scene.frame_index_map[frame_index]
                self.current_character_visual = frame.character_visual
                self.active_scene.easing_current_step += 1
                if self.active_scene.easing_current_step == self.active_scene.easing_total_steps:
                    if self.active_scene.is_looping:
                        self.active_scene.easing_current_step = 0
                    else:
                        self.active_scene.played_frames.extend(self.active_scene.frames)
                        self.active_scene.frames.clear()

            else:
                self.current_character_visual = self.active_scene.get_next_visual()
            if self.active_scene_is_complete():
                completed_scene = self.active_scene
                if not self.active_scene.is_looping:
                    self.active_scene.reset_scene()
                    self.active_scene = None

                self.character.event_handler._handle_event(
                    self.character.event_handler.Event.SCENE_COMPLETE,
                    completed_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
        self.active_scene = found_scene
        self.active_scene_current_step = 0
        self.current_character_visual = self.active_scene.activate()
        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: dict[str, int] = {}
    # Future: review whether `active_scene_current_step` should be removed or implemented for real scene tracking.
    self.active_scene_current_step: int = 0
    self.current_character_visual: CharacterVisual = CharacterVisual(character.input_symbol)

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
    self.active_scene = found_scene
    self.active_scene_current_step = 0
    self.current_character_visual = self.active_scene.activate()
    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, when the active scene has no remaining frames to play, or when the active scene is looping.

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, when the active
    scene has no remaining frames to play, or when the active scene is looping.

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

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

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"{int(red * 255):02x}{int(green * 255):02x}{int(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, 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, it is replaced in the animation's scene mapping.

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

Returns:

Name Type Description
Scene Scene

The new Scene.

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,
    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, it is replaced in the animation's scene mapping.

    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.

    Returns:
        Scene: The new Scene.

    """
    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
    # Future: review whether scene IDs should be enforced as unique and raise on duplicates.
    # Confirm no effects intentionally overwrite scenes today, then update this behavior and docs together.
    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,
        no_color=self.no_color,
        use_xterm_colors=self.use_xterm_colors,
    )
    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
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.

    """
    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_color)
    char_vis_bg_color: str | int | None = self._get_color_code(colors.bg_color)

    self.current_character_visual = CharacterVisual(
        symbol,
        bold=bold,
        colors=colors,
        _fg_color_code=char_vis_fg_color,
        _bg_color_code=char_vis_bg_color,
    )

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.
  • Eased scenes select a frame from frame_index_map using 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, 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.
        * Eased scenes select a frame from `frame_index_map` using 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, 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.
    """
    if self.active_scene and self.active_scene.frames:
        # if the active scene is synced to movement, calculate the sequence index based on the
        # current waypoint progress
        if self.active_scene.sync:
            if self.character.motion.active_path:
                if self.active_scene.sync == Scene.SyncMetric.STEP:
                    sequence_index = round(
                        (len(self.active_scene.frames) - 1)
                        * (
                            max(self.character.motion.active_path.current_step, 1)
                            / max(self.character.motion.active_path.max_steps, 1)
                        ),
                    )
                elif self.active_scene.sync == Scene.SyncMetric.DISTANCE:
                    sequence_index = round(
                        (len(self.active_scene.frames) - 1)
                        * (
                            max(
                                max(self.character.motion.active_path.total_distance, 1)
                                - max(
                                    self.character.motion.active_path.total_distance
                                    - self.character.motion.active_path.last_distance_reached,
                                    1,
                                ),
                                1,
                            )
                            / max(self.character.motion.active_path.total_distance, 1)
                        ),
                    )
                try:
                    self.current_character_visual = self.active_scene.frames[sequence_index].character_visual  # type: ignore[unbound]
                except IndexError:
                    self.current_character_visual = self.active_scene.frames[-1].character_visual
            # when the active waypoint has been deactivated, use the final symbol in the scene and finish the scene
            else:
                self.current_character_visual = self.active_scene.frames[-1].character_visual
                self.active_scene.played_frames.extend(self.active_scene.frames)
                self.active_scene.frames.clear()

        elif self.active_scene and self.active_scene.ease:
            easing_factor = self._ease_animation(self.active_scene.ease)
            frame_index = round(easing_factor * max(self.active_scene.easing_total_steps - 1, 0))
            frame_index = max(min(frame_index, self.active_scene.easing_total_steps - 1), 0)
            frame = self.active_scene.frame_index_map[frame_index]
            self.current_character_visual = frame.character_visual
            self.active_scene.easing_current_step += 1
            if self.active_scene.easing_current_step == self.active_scene.easing_total_steps:
                if self.active_scene.is_looping:
                    self.active_scene.easing_current_step = 0
                else:
                    self.active_scene.played_frames.extend(self.active_scene.frames)
                    self.active_scene.frames.clear()

        else:
            self.current_character_visual = self.active_scene.get_next_visual()
        if self.active_scene_is_complete():
            completed_scene = self.active_scene
            if not self.active_scene.is_looping:
                self.active_scene.reset_scene()
                self.active_scene = None

            self.character.event_handler._handle_event(
                self.character.event_handler.Event.SCENE_COMPLETE,
                completed_scene,
            )