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

xterm_color_map dict[str, int]

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

active_scene_current_step int

the current step in the active Scene

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
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
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
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
        xterm_color_map (dict[str, int]): a mapping of RGB color codes to XTerm-256 color codes
        active_scene_current_step (int): the current step in the active Scene
        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.xterm_color_map: dict[str, int] = {}
        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 adds it to the Animation. If no ID is provided, a unique ID is generated.

        Args:
            scene_id (str): Unique name for the scene. Used to query for the scene.
            is_looping (bool): Whether the scene should loop.
            sync (Scene.SyncMetric): The type of sync to use for the scene.
            ease (easing.EasingFunction): 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
        if self.existing_color_handling == "always":
            preexisting_colors = graphics.ColorPair(fg=self.input_fg_color, bg=self.input_bg_color)
        else:
            preexisting_colors = None
        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
        self.scenes[scene_id] = new_scene
        return new_scene

    def query_scene(self, scene_id: str) -> Scene:
        """Return a Scene from the Animation. If the scene doesn't exist, raises a ValueError.

        Args:
            scene_id (str): the ID of the Scene

        Raises:
            ValueError: if the Scene does not exist

        Returns:
            Scene: the Scene

        """
        scene = self.scenes.get(scene_id, None)
        if not scene:
            raise SceneNotFoundError(scene_id)
        return scene

    def active_scene_is_complete(self) -> bool:
        """Return whether the active scene is complete.

        A scene is complete if all sequences have been played. Looping scenes are always complete.

        Returns:
            bool: True if 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, colors: graphics.ColorPair | None = None) -> None:
        """Update the current character visual with the symbol and colors provided.

        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): The symbol to apply.
            colors (graphics.ColorPair | None): The colors to apply.

        """
        if colors is None:
            colors = graphics.ColorPair(fg=None, bg=None)
        # override fg and bg colors if they are set in the Scene due to existing color handling = always
        if self.existing_color_handling == "always":
            if self.input_fg_color:
                colors = graphics.ColorPair(fg=self.input_fg_color, bg=colors.bg_color)
            if self.input_bg_color:
                colors = graphics.ColorPair(fg=colors.fg_color, bg=self.input_bg_color)

        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,
            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.

        If the active scene is complete, 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) -> None:
        """Set the active scene and updates the current character visual.

        A SCENE_ACTIVATED event is triggered.

        Args:
            scene (Scene): the Scene to set as active

        """
        self.active_scene = 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, scene)

    def deactivate_scene(self, scene: Scene) -> None:
        """Deactivates a scene.

        Args:
            scene (Scene): the Scene to deactivate

        """
        if self.active_scene is 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.xterm_color_map: dict[str, int] = {}
    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.

A SCENE_ACTIVATED event is triggered.

Parameters:

Name Type Description Default
scene Scene

the Scene to set as active

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

    A SCENE_ACTIVATED event is triggered.

    Args:
        scene (Scene): the Scene to set as active

    """
    self.active_scene = 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, scene)

active_scene_is_complete()

Return whether the active scene is complete.

A scene is complete if all sequences have been played. Looping scenes are always complete.

Returns:

Name Type Description
bool bool

True if complete, False otherwise

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

    A scene is complete if all sequences have been played. Looping scenes are always complete.

    Returns:
        bool: True if 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)

Deactivates a scene.

Parameters:

Name Type Description Default
scene Scene

the Scene to deactivate

required
Source code in terminaltexteffects/engine/animation.py
def deactivate_scene(self, scene: Scene) -> None:
    """Deactivates a scene.

    Args:
        scene (Scene): the Scene to deactivate

    """
    if self.active_scene is scene:
        self.active_scene = None

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

Create a new Scene and adds it to the Animation. If no ID is provided, a unique ID is generated.

Parameters:

Name Type Description Default
scene_id str

Unique name for the scene. Used to query for the scene.

''
is_looping bool

Whether the scene should loop.

False
sync SyncMetric

The type of sync to use for the scene.

None
ease EasingFunction

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 adds it to the Animation. If no ID is provided, a unique ID is generated.

    Args:
        scene_id (str): Unique name for the scene. Used to query for the scene.
        is_looping (bool): Whether the scene should loop.
        sync (Scene.SyncMetric): The type of sync to use for the scene.
        ease (easing.EasingFunction): 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
    if self.existing_color_handling == "always":
        preexisting_colors = graphics.ColorPair(fg=self.input_fg_color, bg=self.input_bg_color)
    else:
        preexisting_colors = None
    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
    self.scenes[scene_id] = new_scene
    return new_scene

query_scene(scene_id)

Return a Scene from the Animation. If the scene doesn't exist, raises a ValueError.

Parameters:

Name Type Description Default
scene_id str

the ID of the Scene

required

Raises:

Type Description
ValueError

if the Scene does not exist

Returns:

Name Type Description
Scene Scene

the Scene

Source code in terminaltexteffects/engine/animation.py
def query_scene(self, scene_id: str) -> Scene:
    """Return a Scene from the Animation. If the scene doesn't exist, raises a ValueError.

    Args:
        scene_id (str): the ID of the Scene

    Raises:
        ValueError: if the Scene does not exist

    Returns:
        Scene: the Scene

    """
    scene = self.scenes.get(scene_id, None)
    if not scene:
        raise SceneNotFoundError(scene_id)
    return scene

set_appearance(symbol, colors=None)

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

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

The symbol to apply.

required
colors ColorPair | None

The colors to apply.

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

    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): The symbol to apply.
        colors (graphics.ColorPair | None): The colors to apply.

    """
    if colors is None:
        colors = graphics.ColorPair(fg=None, bg=None)
    # override fg and bg colors if they are set in the Scene due to existing color handling = always
    if self.existing_color_handling == "always":
        if self.input_fg_color:
            colors = graphics.ColorPair(fg=self.input_fg_color, bg=colors.bg_color)
        if self.input_bg_color:
            colors = graphics.ColorPair(fg=colors.fg_color, bg=self.input_bg_color)

    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,
        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.

If the active scene is complete, 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.

    If the active scene is complete, 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,
            )