Face reference

robot.face

The Face Engine - the robot's primary expressive system.

This package groups every piece of the new face-based architecture:

  • :class:FaceModel and the component value types in :mod:robot.face.components - the immutable data the renderer draws.
  • :class:FaceRenderer - display-agnostic pixel art.
  • :class:EmotionEngine - pure function emotion_name -> FaceModel, the single source of truth for "what does emotion X look like?".
  • :class:FaceAnimator - the 30 FPS orchestrator that combines rendering, theming, and the legacy per-eye state machine.
  • :mod:robot.face.themes - pluggable visual styles (Minimal, Cute, Pixel, Retro LCD, Wireframe).

The architecture diagram::

Behavior Engine
        │
        ▼
  Emotion Engine
        │
        ▼
    Face Model  ────────────────┐
        │                       │
        ▼                       ▼
 Face Renderer           Body Language Engine
        │                       │
        ▼                       ▼
   Display Driver        Servo Controller

BUILTIN_THEMES = {'minimal': MinimalTheme, 'cute': CuteTheme, 'pixel': PixelTheme, 'retro_lcd': RetroLcdTheme, 'vector': VectorTheme, 'wireframe': WireframeTheme} module-attribute

EMOTION_DEFS = {'neutral': _EmotionDef(eyes=NEUTRAL_EYES, eyelids=NEUTRAL_EYELIDS, eyebrows=NEUTRAL_EYEBROWS, mouth=NEUTRAL_MOUTH, cheeks=NEUTRAL_CHEEKS, overlay=NEUTRAL_OVERLAY, body_hint=NEUTRAL_HINT), 'happy': _EmotionDef(eyes=(Eye(gaze=Gaze(0.0, 0.05), openness=0.85), Eye(gaze=Gaze(0.0, 0.05), openness=0.85)), eyelids=Eyelids(top=0.05, bottom=0.25), eyebrows=(Eyebrow(shape=EyebrowShape.RAISED, raise_amount=0.3), Eyebrow(shape=EyebrowShape.RAISED, raise_amount=0.3)), mouth=Mouth(shape=MouthShape.SMILE, openness=0.3, width=0.6), cheeks=Cheeks(state=CheekState.SOFT, intensity=0.6), overlay=NEUTRAL_OVERLAY, body_hint=BodyLanguageHint(head_tilt=HeadTilt.CURIOUS, arm_pose=ArmPose.OPEN, intensity=0.7)), 'curious': _EmotionDef(eyes=(Eye(gaze=Gaze(0.2, 0.1), openness=1.0, highlight=Gaze(0.4, 0.4)), Eye(gaze=Gaze(0.2, 0.1), openness=1.0, highlight=Gaze(0.4, 0.4))), eyelids=NEUTRAL_EYELIDS, eyebrows=(Eyebrow(shape=EyebrowShape.RAISED, raise_amount=0.6), Eyebrow(shape=EyebrowShape.RAISED, raise_amount=0.6)), mouth=Mouth(shape=MouthShape.OPEN, openness=0.2, width=0.4), cheeks=NEUTRAL_CHEEKS, overlay=Overlay(kind=OverlayKind.QUESTION, position=Point(0.7, -0.5)), body_hint=BodyLanguageHint(head_tilt=HeadTilt.CURIOUS, arm_pose=ArmPose.POINT, intensity=0.6)), 'thinking': _EmotionDef(eyes=(Eye(gaze=Gaze(0.2, 0.3), openness=0.85), Eye(gaze=Gaze(0.2, 0.3), openness=0.85)), eyelids=NEUTRAL_EYELIDS, eyebrows=(Eyebrow(shape=EyebrowShape.WORRIED, raise_amount=0.2, angle=0.2), Eyebrow(shape=EyebrowShape.WORRIED, raise_amount=0.2, angle=-0.2)), mouth=Mouth(shape=MouthShape.NEUTRAL, openness=0.0, width=0.4), cheeks=NEUTRAL_CHEEKS, overlay=NEUTRAL_OVERLAY, body_hint=BodyLanguageHint(head_tilt=HeadTilt.THINKING, arm_pose=ArmPose.RELAXED, intensity=0.5)), 'sleepy': _EmotionDef(eyes=(Eye(gaze=Gaze(0.0, 0.0), openness=0.15), Eye(gaze=Gaze(0.0, 0.0), openness=0.15)), eyelids=Eyelids(top=0.65, bottom=0.0), eyebrows=(Eyebrow(shape=EyebrowShape.SLEEPY), Eyebrow(shape=EyebrowShape.SLEEPY)), mouth=Mouth(shape=MouthShape.OPEN, openness=0.1, width=0.4), cheeks=NEUTRAL_CHEEKS, overlay=NEUTRAL_OVERLAY, body_hint=BodyLanguageHint(head_tilt=HeadTilt.SLEEPY, arm_pose=ArmPose.DOWN, intensity=0.7)), 'embarrassed': _EmotionDef(eyes=(Eye(gaze=Gaze(0.0, -0.3), openness=0.7, highlight=Gaze(-0.3, -0.3)), Eye(gaze=Gaze(0.0, -0.3), openness=0.7, highlight=Gaze(-0.3, -0.3))), eyelids=Eyelids(top=0.1, bottom=0.05), eyebrows=(Eyebrow(shape=EyebrowShape.WORRIED, angle=0.3), Eyebrow(shape=EyebrowShape.WORRIED, angle=-0.3)), mouth=Mouth(shape=MouthShape.SMILE, openness=0.2, width=0.5, asymmetry=0.3), cheeks=Cheeks(state=CheekState.BRIGHT, intensity=0.9), overlay=NEUTRAL_OVERLAY, body_hint=BodyLanguageHint(head_tilt=HeadTilt.SAD, arm_pose=ArmPose.SHRUG, intensity=0.5)), 'excited': _EmotionDef(eyes=(Eye(gaze=Gaze(0.0, -0.1), openness=1.2, highlight=Gaze(0.0, 0.0)), Eye(gaze=Gaze(0.0, -0.1), openness=1.2, highlight=Gaze(0.0, 0.0))), eyelids=NEUTRAL_EYELIDS, eyebrows=(Eyebrow(shape=EyebrowShape.RAISED, raise_amount=0.8), Eyebrow(shape=EyebrowShape.RAISED, raise_amount=0.8)), mouth=Mouth(shape=MouthShape.SMILE_OPEN, openness=0.6, width=0.7), cheeks=Cheeks(state=CheekState.SOFT, intensity=0.4), overlay=Overlay(kind=OverlayKind.SPARKLE, position=Point(-0.5, -0.4), size=0.3), body_hint=BodyLanguageHint(head_tilt=HeadTilt.EXCITED, arm_pose=ArmPose.WIDE, intensity=1.0, gestures=('bounce',))), 'sad': _EmotionDef(eyes=(Eye(gaze=Gaze(0.0, -0.3), openness=0.65, pupil_dilation=0.7), Eye(gaze=Gaze(0.0, -0.3), openness=0.65, pupil_dilation=0.7)), eyelids=Eyelids(top=0.35, bottom=0.0), eyebrows=(Eyebrow(shape=EyebrowShape.SAD, angle=0.4), Eyebrow(shape=EyebrowShape.SAD, angle=-0.4)), mouth=Mouth(shape=MouthShape.FROWN, openness=0.0, width=0.5), cheeks=Cheeks(state=CheekState.COLD, intensity=0.4), overlay=Overlay(kind=OverlayKind.TEAR, position=Point(-0.3, 0.1), size=0.2), body_hint=BodyLanguageHint(head_tilt=HeadTilt.SAD, arm_pose=ArmPose.DOWN, intensity=0.7)), 'surprised': _EmotionDef(eyes=(Eye(gaze=Gaze(0.0, 0.0), openness=1.0, pupil_dilation=0.2), Eye(gaze=Gaze(0.0, 0.0), openness=1.0, pupil_dilation=0.2)), eyelids=NEUTRAL_EYELIDS, eyebrows=(Eyebrow(shape=EyebrowShape.RAISED, raise_amount=1.0), Eyebrow(shape=EyebrowShape.RAISED, raise_amount=1.0)), mouth=Mouth(shape=MouthShape.WIDE_OPEN, openness=0.9, width=0.6), cheeks=NEUTRAL_CHEEKS, overlay=Overlay(kind=OverlayKind.EXCLAIM, position=Point(0.6, -0.5), size=0.3), body_hint=BodyLanguageHint(head_tilt=HeadTilt.EXCITED, arm_pose=ArmPose.SHRUG, intensity=0.8, gestures=('bounce',))), 'angry': _EmotionDef(eyes=(Eye(gaze=Gaze(0.0, -0.1), openness=0.7, pupil_dilation=0.2), Eye(gaze=Gaze(0.0, -0.1), openness=0.7, pupil_dilation=0.2)), eyelids=Eyelids(top=0.3, bottom=0.0), eyebrows=(Eyebrow(shape=EyebrowShape.ANGRY, angle=0.7), Eyebrow(shape=EyebrowShape.ANGRY, angle=-0.7)), mouth=Mouth(shape=MouthShape.FROWN, openness=0.2, width=0.5), cheeks=Cheeks(state=CheekState.BRIGHT, intensity=0.5), overlay=Overlay(kind=OverlayKind.ANGER, position=Point(0.5, -0.5), size=0.3), body_hint=BodyLanguageHint(head_tilt=HeadTilt.NEUTRAL, arm_pose=ArmPose.SHRUG, intensity=0.7))} module-attribute

__all__ = ['BUILTIN_THEMES', 'EMOTION_DEFS', 'ArmPose', 'BodyLanguageHint', 'CuteTheme', 'EmotionEngine', 'FaceAnimator', 'FaceModel', 'FaceRenderer', 'HeadTilt', 'MinimalTheme', 'PixelTheme', 'RetroLcdTheme', 'Theme', 'WireframeTheme', 'get_theme'] module-attribute

ArmPose

Bases: Enum

Discrete arm-pose hints.

Source code in src/robot/face/model.py
class ArmPose(Enum):
    """Discrete arm-pose hints."""

    RELAXED = "relaxed"
    OPEN = "open"  # slightly raised
    WIDE = "wide"  # celebration
    WAVING = "waving"  # one arm up
    SHRUG = "shrug"  # both up
    DOWN = "down"  # rest
    POINT = "point"  # one arm forward

DOWN = 'down' class-attribute instance-attribute

OPEN = 'open' class-attribute instance-attribute

POINT = 'point' class-attribute instance-attribute

RELAXED = 'relaxed' class-attribute instance-attribute

SHRUG = 'shrug' class-attribute instance-attribute

WAVING = 'waving' class-attribute instance-attribute

WIDE = 'wide' class-attribute instance-attribute

BodyLanguageHint dataclass

A high-level body-language request produced by the EmotionEngine.

Source code in src/robot/face/model.py
@dataclass(slots=True, frozen=True)
class BodyLanguageHint:
    """A high-level body-language request produced by the EmotionEngine."""

    head_tilt: HeadTilt = HeadTilt.NEUTRAL
    arm_pose: ArmPose = ArmPose.RELAXED
    # Intensity scales how strongly the body-language engine applies the
    # pose (0.0 = ignore, 1.0 = full expression).
    intensity: float = 1.0
    # Special transient gestures the body-language engine should run once
    # (e.g. a wave). Empty tuple = "no transient gestures".
    gestures: tuple[str, ...] = ()

arm_pose = ArmPose.RELAXED class-attribute instance-attribute

gestures = () class-attribute instance-attribute

head_tilt = HeadTilt.NEUTRAL class-attribute instance-attribute

intensity = 1.0 class-attribute instance-attribute

__init__(head_tilt=HeadTilt.NEUTRAL, arm_pose=ArmPose.RELAXED, intensity=1.0, gestures=())

CuteTheme

Source code in src/robot/face/themes/cute.py
class CuteTheme:
    name = "cute"
    palette = FacePalette(
        background=(255, 240, 245),
        sclera=(255, 255, 255),
        iris=(180, 100, 180),
        pupil=(40, 20, 50),
        eyelid=(230, 200, 220),
        eyebrow=(120, 70, 120),
        mouth=(255, 90, 130),
        cheek=(255, 160, 200),
        blush=(255, 120, 160),
        outline=(80, 50, 80),
        highlight=(255, 255, 255),
    )

    def apply(self, model: FaceModel) -> FaceModel:
        # Always have soft cheeks for the "cute" look
        cheeks = Cheeks(state=CheekState.SOFT, intensity=0.5)
        return model.with_palette(self.palette).with_cheeks(cheeks)

name = 'cute' class-attribute instance-attribute

palette = FacePalette(background=(255, 240, 245), sclera=(255, 255, 255), iris=(180, 100, 180), pupil=(40, 20, 50), eyelid=(230, 200, 220), eyebrow=(120, 70, 120), mouth=(255, 90, 130), cheek=(255, 160, 200), blush=(255, 120, 160), outline=(80, 50, 80), highlight=(255, 255, 255)) class-attribute instance-attribute

apply(model)

Source code in src/robot/face/themes/cute.py
def apply(self, model: FaceModel) -> FaceModel:
    # Always have soft cheeks for the "cute" look
    cheeks = Cheeks(state=CheekState.SOFT, intensity=0.5)
    return model.with_palette(self.palette).with_cheeks(cheeks)

EmotionEngine

Produces :class:FaceModel + :class:BodyLanguageHint from an emotion.

Source code in src/robot/face/emotions.py
class EmotionEngine:
    """Produces :class:`FaceModel` + :class:`BodyLanguageHint` from an emotion."""

    def __init__(
        self, palette: FacePalette | None = None, width: int = 240, height: int = 240
    ) -> None:
        self._palette = palette or FacePalette()
        self._width = width
        self._height = height

    def set_dimensions(self, width: int, height: int) -> None:
        self._width = width
        self._height = height

    def available(self) -> list[str]:
        return list(EMOTION_DEFS.keys())

    def get(self, name: str) -> _EmotionDef:
        try:
            return EMOTION_DEFS[name]
        except KeyError as exc:
            raise KeyError(
                f"unknown emotion {name!r}; available: {sorted(EMOTION_DEFS.keys())}"
            ) from exc

    def build(self, name: str) -> FaceModel:
        """Build the :class:`FaceModel` for ``name`` with default geometry."""
        d = self.get(name)
        left_eye, right_eye = d.eyes
        left_brow, right_brow = d.eyebrows
        return FaceModel(
            width=self._width,
            height=self._height,
            left_eye=left_eye,
            right_eye=right_eye,
            eyelids=d.eyelids,
            left_eyebrow=left_brow,
            right_eyebrow=right_brow,
            mouth=d.mouth,
            cheeks=d.cheeks,
            overlay=d.overlay,
            palette=self._palette,
            body_hint=d.body_hint,
        )

    def register(self, name: str, definition: _EmotionDef) -> None:
        """Register a new emotion or override an existing one."""
        EMOTION_DEFS[name] = definition

__init__(palette=None, width=240, height=240)

Source code in src/robot/face/emotions.py
def __init__(
    self, palette: FacePalette | None = None, width: int = 240, height: int = 240
) -> None:
    self._palette = palette or FacePalette()
    self._width = width
    self._height = height

available()

Source code in src/robot/face/emotions.py
def available(self) -> list[str]:
    return list(EMOTION_DEFS.keys())

build(name)

Build the :class:FaceModel for name with default geometry.

Source code in src/robot/face/emotions.py
def build(self, name: str) -> FaceModel:
    """Build the :class:`FaceModel` for ``name`` with default geometry."""
    d = self.get(name)
    left_eye, right_eye = d.eyes
    left_brow, right_brow = d.eyebrows
    return FaceModel(
        width=self._width,
        height=self._height,
        left_eye=left_eye,
        right_eye=right_eye,
        eyelids=d.eyelids,
        left_eyebrow=left_brow,
        right_eyebrow=right_brow,
        mouth=d.mouth,
        cheeks=d.cheeks,
        overlay=d.overlay,
        palette=self._palette,
        body_hint=d.body_hint,
    )

get(name)

Source code in src/robot/face/emotions.py
def get(self, name: str) -> _EmotionDef:
    try:
        return EMOTION_DEFS[name]
    except KeyError as exc:
        raise KeyError(
            f"unknown emotion {name!r}; available: {sorted(EMOTION_DEFS.keys())}"
        ) from exc

register(name, definition)

Register a new emotion or override an existing one.

Source code in src/robot/face/emotions.py
def register(self, name: str, definition: _EmotionDef) -> None:
    """Register a new emotion or override an existing one."""
    EMOTION_DEFS[name] = definition

set_dimensions(width, height)

Source code in src/robot/face/emotions.py
def set_dimensions(self, width: int, height: int) -> None:
    self._width = width
    self._height = height

FaceAnimator dataclass

Drive a single circular face display at 30 FPS.

Source code in src/robot/face/animator.py
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
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
@dataclass(slots=True)
class FaceAnimator:
    """Drive a single circular face display at 30 FPS."""

    DEFAULT_FPS: ClassVar[int] = 30

    renderer: FaceRenderer
    display: Display
    clock: Clock
    emotions: EmotionEngine
    theme: Theme
    fps: int = DEFAULT_FPS
    bus: InMemoryEventBus | None = None
    width: int = 240
    height: int = 240

    _current: FaceModel = field(init=False)
    _target: FaceModel = field(init=False)
    _eye: EyeAnimator = field(init=False)
    _stopped: bool = field(default=True, init=False)
    _frame_count: int = field(default=0, init=False)
    _anim_time: float = field(default=0.0, init=False)
    _timeline: Timeline | None = field(default=None, init=False)
    _timeline_t: float = field(default=0.0, init=False)
    _timeline_total: float = field(default=0.0, init=False)
    _speaking_animation: SpeakingAnimation | None = field(default=None, init=False)
    _thinking_animation: ThinkingDotsAnimation | None = field(default=None, init=False)
    _wake_animation: WakeAnimation | None = field(default=None, init=False)
    _frame_profiler: FrameProfiler | None = field(default=None, init=False, repr=False)

    def __post_init__(self) -> None:
        if self.fps <= 0:
            raise ValueError("fps must be > 0")
        if self.width <= 0 or self.height <= 0:
            raise ValueError("width and height must be > 0")
        self._eye = EyeAnimator(
            side=EyeSide.LEFT,
            width=self.width,
            height=self.height,
            fps=self.fps,
        )
        self._current = self.emotions.build("neutral")
        self._target = self._current
        if self.bus is not None:
            from robot.events.events import (
                BlinkRequested,
                EmotionChanged,
                LookRequested,
            )

            self.bus.subscribe(EmotionChanged, self._on_emotion)
            self.bus.subscribe(BlinkRequested, self._on_blink)
            self.bus.subscribe(LookRequested, self._on_look)

    # ------------------------------------------------------------------ properties
    @property
    def current(self) -> FaceModel:
        return self._current

    @property
    def frame_count(self) -> int:
        return self._frame_count

    @property
    def is_running(self) -> bool:
        return not self._stopped

    # ------------------------------------------------------------------ public commands
    def set_emotion(self, name: str, intensity: float = 1.0) -> None:
        """Animate to the given emotion over ~0.3s.

        Calling this method clears any running speaking and thinking
        animations (they are interruptible).  The wake animation is
        *not* cleared -- it plays to completion.
        """
        # Clear interruptible animations on emotion change.
        self._speaking_animation = None
        self._thinking_animation = None
        target = self.emotions.build(name)
        # Apply intensity: scale the change in openness, mouth, etc.
        self._timeline = self._build_emotion_timeline(self._current, target, duration_s=0.3)
        self._target = target

    def blink(self) -> None:
        self._eye.blink()

    def double_blink(self) -> None:
        self._eye.double_blink()

    def wink(self) -> None:
        self._eye.wink()

    def look(self, x: float, y: float, duration_s: float = 0.25) -> None:
        self._eye.look(x, y, duration_s)

    def look_left(self, duration_s: float = 0.25) -> None:
        self._eye.look_left(duration_s)

    def look_right(self, duration_s: float = 0.25) -> None:
        self._eye.look_right(duration_s)

    def look_up(self, duration_s: float = 0.25) -> None:
        self._eye.look_up(duration_s)

    def look_down(self, duration_s: float = 0.25) -> None:
        self._eye.look_down(duration_s)

    def look_center(self, duration_s: float = 0.25) -> None:
        self._eye.look_center(duration_s)

    def drift(self, amplitude: float = 0.10, speed: float = 0.6) -> None:
        self._eye.drift(amplitude=amplitude, speed=speed)

    def bounce(self) -> None:
        """Run a one-shot bounce animation (squash & stretch)."""
        tl = self._build_bounce_timeline()
        self._timeline = tl

    def smile_grow(self) -> None:
        """Animate the mouth from NEUTRAL to SMILE over 0.4s."""
        target = self._current.with_mouth(Mouth(shape=MouthShape.SMILE, openness=0.4, width=0.7))
        self._timeline = self._build_mouth_timeline(self._current, target, 0.4)

    def mouth_open(self, duration_s: float = 0.3) -> None:
        target = self._current.with_mouth(Mouth(shape=MouthShape.OPEN, openness=0.6, width=0.6))
        self._start_timeline(self._build_mouth_timeline(self._current, target, duration_s))

    def eyebrow_raise(self, amount: float = 0.6) -> None:
        target = self._current.with_eyebrows(
            left=Eyebrow(shape=EyebrowShape.RAISED, raise_amount=amount),
            right=Eyebrow(shape=EyebrowShape.RAISED, raise_amount=amount),
        )
        self._timeline = self._build_eyebrow_timeline(self._current, target, 0.3)

    # ------------------------------------------------------------------ animation slots
    def set_speaking_animation(self, animation: SpeakingAnimation | None) -> None:
        """Set (or clear) the speaking animation that drives mouth shapes."""
        self._speaking_animation = animation

    def set_thinking_animation(self, animation: ThinkingDotsAnimation | None) -> None:
        """Set (or clear) the thinking animation that drives gaze shifts."""
        self._thinking_animation = animation

    def set_wake_animation(self, animation: WakeAnimation | None) -> None:
        """Set (or clear) the wake animation (highest priority override)."""
        self._wake_animation = animation

    def reset(self) -> None:
        self._current = self.emotions.build("neutral")
        self._target = self._current
        self._timeline = None
        self._speaking_animation = None
        self._thinking_animation = None
        self._wake_animation = None
        self._eye.reset()

    # ------------------------------------------------------------------ bus
    async def _on_emotion(self, event: object) -> None:
        name = getattr(event, "current", None)
        if name is None:
            return
        # The event's ``current`` can be either an ``EmotionName`` enum or
        # a plain string; normalise to a string before looking it up.
        if hasattr(name, "value"):
            name = name.value
        elif not isinstance(name, str):
            return
        self.set_emotion(name)

    async def _on_blink(self, event: object) -> None:
        self.blink()

    async def _on_look(self, event: object) -> None:
        self.look(
            float(getattr(event, "x", 0.0)),
            float(getattr(event, "y", 0.0)),
            duration_s=float(getattr(event, "duration_s", 0.25)),
        )

    # ------------------------------------------------------------------ frame loop
    def step(self, drift: bool = True) -> EyeFrame:
        """Advance one frame and push to the display.

        The rendering pipeline applies overrides in priority order:

        1. Eye drift + blink state (from :class:`EyeAnimator`).
        2. Thinking animation gaze override.
        3. Timeline-based emotion interpolation.
        4. Speaking animation mouth override.
        5. Wake animation full override (highest priority).
        """
        dt = 1.0 / self.fps
        self._frame_count += 1

        if drift:
            self._eye.drift(amplitude=0.10, speed=0.6)
        # Eye state: pull current gaze from the eye animator
        eye_state = self._eye.step()
        # Translate the eye's (gaze, openness) into left/right Eye components
        new_eyes = self._eyes_from_eye_state(eye_state)

        # Thinking animation: override gaze when active.
        if self._thinking_animation is not None:
            gaze = self._thinking_animation.step(dt)
            new_eyes = (
                Eye(
                    gaze=gaze,
                    openness=new_eyes[0].openness,
                    pupil_dilation=new_eyes[0].pupil_dilation,
                    highlight=new_eyes[0].highlight,
                ),
                Eye(
                    gaze=gaze,
                    openness=new_eyes[1].openness,
                    pupil_dilation=new_eyes[1].pupil_dilation,
                    highlight=new_eyes[1].highlight,
                ),
            )

        # Apply timeline (smile, eyebrows, bounce, …) if any
        if self._timeline is not None:
            self._timeline_t += dt
            progress = min(1.0, self._timeline_t / max(0.001, self._timeline_total))
            # Invoke the on_update callbacks directly. Each builder
            # registered a single tween whose callback writes to
            # ``self._current`` (interpolation, bounce, …).
            for animation in self._timeline._items:
                if hasattr(animation, "on_update"):
                    animation.on_update(progress)
            if progress >= 1.0:
                self._timeline = None
                self._timeline_t = 0.0
        # Merge eye state + current body
        merged = self._current.with_eyes(left_eye=new_eyes[0], right_eye=new_eyes[1])
        # Update the current model so a.current reflects the rendered state.
        self._current = merged

        # Speaking animation: override mouth when active.
        if self._speaking_animation is not None:
            viseme = self._speaking_animation.step(dt)
            mouth_shape = MouthShape.OPEN if viseme.openness > 0.1 else MouthShape.NEUTRAL
            self._current = self._current.with_mouth(
                Mouth(shape=mouth_shape, openness=viseme.openness, width=viseme.width)
            )
            if not self._speaking_animation.has_frames:
                self._speaking_animation = None

        # Wake animation: full override (highest priority).
        if self._wake_animation is not None:
            wake_frame = self._wake_animation.step(dt)
            self._current = self._apply_wake_frame(self._current, wake_frame)
            if self._wake_animation.done:
                self._wake_animation = None

        # Apply theme
        themed = self.theme.apply(self._current)
        return self.renderer.render(themed)

    async def _step_async(self, drift: bool = True) -> EyeFrame:
        frame = self.step(drift=drift)
        await self._push(frame)
        return frame

    async def _push(self, frame: EyeFrame) -> None:
        try:
            await self.display.show(frame)
        except Exception:
            _log.exception("face.animator.display_failed")
        if self.bus is not None:
            from robot.events.events import DisplayUpdated

            with contextlib.suppress(Exception):
                await self.bus.publish(DisplayUpdated(display="face"))

    async def run_forever(self) -> None:
        self._stopped = False
        frame_interval = 1.0 / self.fps
        try:
            while not self._stopped:
                start = time.monotonic()
                await self._step_async(drift=True)
                end = time.monotonic()
                if self._frame_profiler is not None and getattr(
                    self._frame_profiler, "enabled", False
                ):
                    self._frame_profiler.record_frame(start, end)
                await self.clock.sleep(frame_interval)
        finally:
            self._stopped = True

    def stop(self) -> None:
        self._stopped = True

    # ------------------------------------------------------------------ timeline helpers
    def _start_timeline(self, timeline: Timeline) -> None:
        self._timeline = timeline
        self._timeline_t = 0.0
        # _timeline_total is set by the builder (so the builder can also do its own work)

    def _build_emotion_timeline(
        self, start: FaceModel, end: FaceModel, duration_s: float
    ) -> Timeline:
        """Build a timeline that interpolates between two FaceModels.

        We don't yet have a generic FaceModel interpolator, so we use a
        sequence of tween callbacks to lerp scalar fields. The
        renderer is what makes the result look smooth.
        """
        tl = Timeline()
        # Tween the mouth shape change discretely (mid-way)
        tl.tween(
            from_value=0.0,
            to_value=1.0,
            duration_s=duration_s,
            on_update=lambda t: self._set_interp(start, end, t),
        )
        self._timeline_total = duration_s
        return tl

    def _build_mouth_timeline(
        self, start: FaceModel, end: FaceModel, duration_s: float
    ) -> Timeline:
        tl = Timeline()
        tl.tween(
            from_value=0.0,
            to_value=1.0,
            duration_s=duration_s,
            on_update=lambda t: self._set_interp(start, end, t),
        )
        self._timeline_total = duration_s
        return tl

    def _build_eyebrow_timeline(
        self, start: FaceModel, end: FaceModel, duration_s: float
    ) -> Timeline:
        tl = Timeline()
        tl.tween(
            from_value=0.0,
            to_value=1.0,
            duration_s=duration_s,
            on_update=lambda t: self._set_interp(start, end, t),
        )
        self._timeline_total = duration_s
        return tl

    def _build_bounce_timeline(self) -> Timeline:
        """One-shot bounce: bounce up, squash on landing, settle.

        Uses the model's ``bounce`` and ``squash`` fields and writes a
        per-frame value through a single tween.
        """
        # Build a sequence of keyframes as a list of (t, bounce, squash)
        keyframes: list[tuple[float, float, float]] = [
            (0.00, 0.0, 1.00),
            (0.10, 0.50, 0.92),  # anticipation squash
            (0.30, 0.85, 1.10),  # jump stretch
            (0.55, 0.00, 0.95),  # impact squash
            (0.75, 0.30, 1.04),  # small bounce
            (1.00, 0.0, 1.00),  # settle
        ]
        duration = 0.6

        class _Bounce:
            def __init__(self) -> None:
                pass

        # Use a simple Tween + linear interp through keyframes
        def _sample(t: float) -> tuple[float, float]:
            for i in range(len(keyframes) - 1):
                t0, b0, s0 = keyframes[i]
                t1, b1, s1 = keyframes[i + 1]
                if t0 <= t <= t1:
                    local = (t - t0) / max(1e-6, t1 - t0)
                    local = _ease_in_out(local)
                    return (b0 + (b1 - b0) * local, s0 + (s1 - s0) * local)
            return keyframes[-1][1], keyframes[-1][2]

        def _apply(t: float) -> None:
            bounce, squash = _sample(t)
            # Apply in-place: store the bounce/squash on the model.
            # We achieve this by replacing self._current with a new model
            # that has the transformed bounce/squash.
            self._current = self._current.with_transform(bounce=bounce, squash=squash)

        tl = Timeline()
        tl.tween(from_value=0.0, to_value=1.0, duration_s=duration, on_update=_apply)
        self._timeline_total = duration
        return tl

    def _apply_timeline_at(self, model: FaceModel, t: float) -> FaceModel:
        """Most timelines write to ``self._current`` directly via tween
        callbacks. This method is the fallback for any future timeline
        that wants to be queryable.
        """
        return model

    def _apply_wake_frame(self, model: FaceModel, frame: WakeFrame) -> FaceModel:
        """Apply a :class:`WakeFrame` override to the model.

        The wake animation has the highest priority and overrides
        eyes, eyelids, mouth, and eyebrows.
        """
        return (
            model.with_eyes(
                left_eye=Eye(
                    gaze=frame.gaze,
                    openness=frame.eye_openness,
                    pupil_dilation=model.left_eye.pupil_dilation,
                    highlight=model.left_eye.highlight,
                ),
                right_eye=Eye(
                    gaze=frame.gaze,
                    openness=frame.eye_openness,
                    pupil_dilation=model.right_eye.pupil_dilation,
                    highlight=model.right_eye.highlight,
                ),
            )
            .with_eyelids(Eyelids(top=frame.eyelid_top, bottom=0.0))
            .with_mouth(
                Mouth(
                    shape=frame.mouth_shape, openness=frame.mouth_openness, width=frame.mouth_width
                )
            )
            .with_eyebrows(
                left=Eyebrow(shape=frame.eyebrow_shape, raise_amount=frame.eyebrow_raise),
                right=Eyebrow(shape=frame.eyebrow_shape, raise_amount=frame.eyebrow_raise),
            )
        )

    def _set_interp(self, start: FaceModel, end: FaceModel, t: float) -> None:
        """Snap-interpolate scalar fields from start to end at progress t."""
        e = _ease_in_out(t)
        left_eye = _interp_eye(start.left_eye, end.left_eye, e)
        right_eye = _interp_eye(start.right_eye, end.right_eye, e)
        eyelids = _interp_eyelids(start.eyelids, end.eyelids, e)
        left_brow = _interp_eyebrow(start.left_eyebrow, end.left_eyebrow, e)
        right_brow = _interp_eyebrow(start.right_eyebrow, end.right_eyebrow, e)
        mouth = _interp_mouth(start.mouth, end.mouth, e)
        cheeks = _interp_cheeks(start.cheeks, end.cheeks, e)
        overlay = end.overlay if e > 0.5 else start.overlay
        body_hint = end.body_hint if e > 0.5 else start.body_hint
        self._current = FaceModel(
            width=start.width,
            height=start.height,
            left_eye=left_eye,
            right_eye=right_eye,
            eyelids=eyelids,
            left_eyebrow=left_brow,
            right_eyebrow=right_brow,
            mouth=mouth,
            cheeks=cheeks,
            overlay=overlay,
            accessory=start.accessory,
            palette=start.palette,
            bounce=start.bounce,
            squash=start.squash,
            body_hint=body_hint,
        )

    def _eyes_from_eye_state(self, state: object) -> tuple[Eye, Eye]:
        """Translate the eye render state into two :class:`Eye` components."""
        # The legacy EyeState has a ``gaze`` field; the new EyeRenderState
        # has separate ``gaze_x`` / ``gaze_y`` floats. Handle both.
        if hasattr(state, "gaze_x"):
            gaze = Gaze(float(getattr(state, "gaze_x", 0.0)), float(getattr(state, "gaze_y", 0.0)))
        else:
            g = getattr(state, "gaze", Gaze())
            gaze = Gaze(float(g.x), float(g.y))
        openness = float(getattr(state, "openness", 1.0))
        dilation = float(getattr(state, "pupil_dilation", 0.5))
        eye = Eye(gaze=gaze, openness=openness, pupil_dilation=dilation, highlight=Gaze(0.3, 0.3))
        return eye, eye

DEFAULT_FPS = 30 class-attribute

bus = None class-attribute instance-attribute

clock instance-attribute

current property

display instance-attribute

emotions instance-attribute

fps = DEFAULT_FPS class-attribute instance-attribute

frame_count property

height = 240 class-attribute instance-attribute

is_running property

renderer instance-attribute

theme instance-attribute

width = 240 class-attribute instance-attribute

__init__(renderer, display, clock, emotions, theme, fps=DEFAULT_FPS, bus=None, width=240, height=240)

__post_init__()

Source code in src/robot/face/animator.py
def __post_init__(self) -> None:
    if self.fps <= 0:
        raise ValueError("fps must be > 0")
    if self.width <= 0 or self.height <= 0:
        raise ValueError("width and height must be > 0")
    self._eye = EyeAnimator(
        side=EyeSide.LEFT,
        width=self.width,
        height=self.height,
        fps=self.fps,
    )
    self._current = self.emotions.build("neutral")
    self._target = self._current
    if self.bus is not None:
        from robot.events.events import (
            BlinkRequested,
            EmotionChanged,
            LookRequested,
        )

        self.bus.subscribe(EmotionChanged, self._on_emotion)
        self.bus.subscribe(BlinkRequested, self._on_blink)
        self.bus.subscribe(LookRequested, self._on_look)
Source code in src/robot/face/animator.py
def blink(self) -> None:
    self._eye.blink()

bounce()

Run a one-shot bounce animation (squash & stretch).

Source code in src/robot/face/animator.py
def bounce(self) -> None:
    """Run a one-shot bounce animation (squash & stretch)."""
    tl = self._build_bounce_timeline()
    self._timeline = tl
Source code in src/robot/face/animator.py
def double_blink(self) -> None:
    self._eye.double_blink()

drift(amplitude=0.1, speed=0.6)

Source code in src/robot/face/animator.py
def drift(self, amplitude: float = 0.10, speed: float = 0.6) -> None:
    self._eye.drift(amplitude=amplitude, speed=speed)

eyebrow_raise(amount=0.6)

Source code in src/robot/face/animator.py
def eyebrow_raise(self, amount: float = 0.6) -> None:
    target = self._current.with_eyebrows(
        left=Eyebrow(shape=EyebrowShape.RAISED, raise_amount=amount),
        right=Eyebrow(shape=EyebrowShape.RAISED, raise_amount=amount),
    )
    self._timeline = self._build_eyebrow_timeline(self._current, target, 0.3)

look(x, y, duration_s=0.25)

Source code in src/robot/face/animator.py
def look(self, x: float, y: float, duration_s: float = 0.25) -> None:
    self._eye.look(x, y, duration_s)

look_center(duration_s=0.25)

Source code in src/robot/face/animator.py
def look_center(self, duration_s: float = 0.25) -> None:
    self._eye.look_center(duration_s)

look_down(duration_s=0.25)

Source code in src/robot/face/animator.py
def look_down(self, duration_s: float = 0.25) -> None:
    self._eye.look_down(duration_s)

look_left(duration_s=0.25)

Source code in src/robot/face/animator.py
def look_left(self, duration_s: float = 0.25) -> None:
    self._eye.look_left(duration_s)

look_right(duration_s=0.25)

Source code in src/robot/face/animator.py
def look_right(self, duration_s: float = 0.25) -> None:
    self._eye.look_right(duration_s)

look_up(duration_s=0.25)

Source code in src/robot/face/animator.py
def look_up(self, duration_s: float = 0.25) -> None:
    self._eye.look_up(duration_s)

mouth_open(duration_s=0.3)

Source code in src/robot/face/animator.py
def mouth_open(self, duration_s: float = 0.3) -> None:
    target = self._current.with_mouth(Mouth(shape=MouthShape.OPEN, openness=0.6, width=0.6))
    self._start_timeline(self._build_mouth_timeline(self._current, target, duration_s))

reset()

Source code in src/robot/face/animator.py
def reset(self) -> None:
    self._current = self.emotions.build("neutral")
    self._target = self._current
    self._timeline = None
    self._speaking_animation = None
    self._thinking_animation = None
    self._wake_animation = None
    self._eye.reset()

run_forever() async

Source code in src/robot/face/animator.py
async def run_forever(self) -> None:
    self._stopped = False
    frame_interval = 1.0 / self.fps
    try:
        while not self._stopped:
            start = time.monotonic()
            await self._step_async(drift=True)
            end = time.monotonic()
            if self._frame_profiler is not None and getattr(
                self._frame_profiler, "enabled", False
            ):
                self._frame_profiler.record_frame(start, end)
            await self.clock.sleep(frame_interval)
    finally:
        self._stopped = True

set_emotion(name, intensity=1.0)

Animate to the given emotion over ~0.3s.

Calling this method clears any running speaking and thinking animations (they are interruptible). The wake animation is not cleared -- it plays to completion.

Source code in src/robot/face/animator.py
def set_emotion(self, name: str, intensity: float = 1.0) -> None:
    """Animate to the given emotion over ~0.3s.

    Calling this method clears any running speaking and thinking
    animations (they are interruptible).  The wake animation is
    *not* cleared -- it plays to completion.
    """
    # Clear interruptible animations on emotion change.
    self._speaking_animation = None
    self._thinking_animation = None
    target = self.emotions.build(name)
    # Apply intensity: scale the change in openness, mouth, etc.
    self._timeline = self._build_emotion_timeline(self._current, target, duration_s=0.3)
    self._target = target

set_speaking_animation(animation)

Set (or clear) the speaking animation that drives mouth shapes.

Source code in src/robot/face/animator.py
def set_speaking_animation(self, animation: SpeakingAnimation | None) -> None:
    """Set (or clear) the speaking animation that drives mouth shapes."""
    self._speaking_animation = animation

set_thinking_animation(animation)

Set (or clear) the thinking animation that drives gaze shifts.

Source code in src/robot/face/animator.py
def set_thinking_animation(self, animation: ThinkingDotsAnimation | None) -> None:
    """Set (or clear) the thinking animation that drives gaze shifts."""
    self._thinking_animation = animation

set_wake_animation(animation)

Set (or clear) the wake animation (highest priority override).

Source code in src/robot/face/animator.py
def set_wake_animation(self, animation: WakeAnimation | None) -> None:
    """Set (or clear) the wake animation (highest priority override)."""
    self._wake_animation = animation

smile_grow()

Animate the mouth from NEUTRAL to SMILE over 0.4s.

Source code in src/robot/face/animator.py
def smile_grow(self) -> None:
    """Animate the mouth from NEUTRAL to SMILE over 0.4s."""
    target = self._current.with_mouth(Mouth(shape=MouthShape.SMILE, openness=0.4, width=0.7))
    self._timeline = self._build_mouth_timeline(self._current, target, 0.4)

step(drift=True)

Advance one frame and push to the display.

The rendering pipeline applies overrides in priority order:

  1. Eye drift + blink state (from :class:EyeAnimator).
  2. Thinking animation gaze override.
  3. Timeline-based emotion interpolation.
  4. Speaking animation mouth override.
  5. Wake animation full override (highest priority).
Source code in src/robot/face/animator.py
def step(self, drift: bool = True) -> EyeFrame:
    """Advance one frame and push to the display.

    The rendering pipeline applies overrides in priority order:

    1. Eye drift + blink state (from :class:`EyeAnimator`).
    2. Thinking animation gaze override.
    3. Timeline-based emotion interpolation.
    4. Speaking animation mouth override.
    5. Wake animation full override (highest priority).
    """
    dt = 1.0 / self.fps
    self._frame_count += 1

    if drift:
        self._eye.drift(amplitude=0.10, speed=0.6)
    # Eye state: pull current gaze from the eye animator
    eye_state = self._eye.step()
    # Translate the eye's (gaze, openness) into left/right Eye components
    new_eyes = self._eyes_from_eye_state(eye_state)

    # Thinking animation: override gaze when active.
    if self._thinking_animation is not None:
        gaze = self._thinking_animation.step(dt)
        new_eyes = (
            Eye(
                gaze=gaze,
                openness=new_eyes[0].openness,
                pupil_dilation=new_eyes[0].pupil_dilation,
                highlight=new_eyes[0].highlight,
            ),
            Eye(
                gaze=gaze,
                openness=new_eyes[1].openness,
                pupil_dilation=new_eyes[1].pupil_dilation,
                highlight=new_eyes[1].highlight,
            ),
        )

    # Apply timeline (smile, eyebrows, bounce, …) if any
    if self._timeline is not None:
        self._timeline_t += dt
        progress = min(1.0, self._timeline_t / max(0.001, self._timeline_total))
        # Invoke the on_update callbacks directly. Each builder
        # registered a single tween whose callback writes to
        # ``self._current`` (interpolation, bounce, …).
        for animation in self._timeline._items:
            if hasattr(animation, "on_update"):
                animation.on_update(progress)
        if progress >= 1.0:
            self._timeline = None
            self._timeline_t = 0.0
    # Merge eye state + current body
    merged = self._current.with_eyes(left_eye=new_eyes[0], right_eye=new_eyes[1])
    # Update the current model so a.current reflects the rendered state.
    self._current = merged

    # Speaking animation: override mouth when active.
    if self._speaking_animation is not None:
        viseme = self._speaking_animation.step(dt)
        mouth_shape = MouthShape.OPEN if viseme.openness > 0.1 else MouthShape.NEUTRAL
        self._current = self._current.with_mouth(
            Mouth(shape=mouth_shape, openness=viseme.openness, width=viseme.width)
        )
        if not self._speaking_animation.has_frames:
            self._speaking_animation = None

    # Wake animation: full override (highest priority).
    if self._wake_animation is not None:
        wake_frame = self._wake_animation.step(dt)
        self._current = self._apply_wake_frame(self._current, wake_frame)
        if self._wake_animation.done:
            self._wake_animation = None

    # Apply theme
    themed = self.theme.apply(self._current)
    return self.renderer.render(themed)

stop()

Source code in src/robot/face/animator.py
def stop(self) -> None:
    self._stopped = True

wink()

Source code in src/robot/face/animator.py
def wink(self) -> None:
    self._eye.wink()

FaceModel dataclass

The full face, captured at one instant.

All values are immutable. Use the helper methods to build new models with a single field changed (this is what the renderer animates).

Source code in src/robot/face/model.py
@dataclass(slots=True, frozen=True)
class FaceModel:
    """The full face, captured at one instant.

    All values are immutable. Use the helper methods to build new models
    with a single field changed (this is what the renderer animates).
    """

    width: int = 240
    height: int = 240

    left_eye: Eye = field(default_factory=Eye)
    right_eye: Eye = field(default_factory=Eye)

    # Eyelids
    eyelids: Eyelids = field(default_factory=Eyelids)

    # Eyebrows (one per eye)
    left_eyebrow: Eyebrow = field(default_factory=Eyebrow)
    right_eyebrow: Eyebrow = field(default_factory=Eyebrow)

    # Mouth
    mouth: Mouth = field(default_factory=Mouth)

    # Cheeks
    cheeks: Cheeks = field(default_factory=Cheeks)

    # Overlays
    overlay: Overlay = field(default_factory=Overlay)

    # Persistent accessories
    accessory: Accessory = field(default_factory=Accessory)

    # Colour palette (themes override this)
    palette: FacePalette = field(default_factory=FacePalette)

    # Subtle bounce / squash & stretch (in normalised units)
    bounce: float = 0.0  # -1..1 vertical translation
    squash: float = 1.0  # 0..2 horizontal scale (1 = neutral)

    # Body-language hint proposed by the EmotionEngine
    body_hint: BodyLanguageHint = field(default_factory=BodyLanguageHint)

    # ------------------------------------------------------------------
    # Convenience builders (return a new model with one field changed)
    # ------------------------------------------------------------------
    def with_eyes(
        self,
        left_eye: Eye | None = None,
        right_eye: Eye | None = None,
    ) -> FaceModel:
        return replace(
            self, left_eye=left_eye or self.left_eye, right_eye=right_eye or self.right_eye
        )

    def with_eyelids(self, eyelids: Eyelids) -> FaceModel:
        return replace(self, eyelids=eyelids)

    def with_eyebrows(
        self,
        left: Eyebrow | None = None,
        right: Eyebrow | None = None,
    ) -> FaceModel:
        return replace(
            self, left_eyebrow=left or self.left_eyebrow, right_eyebrow=right or self.right_eyebrow
        )

    def with_mouth(self, mouth: Mouth) -> FaceModel:
        return replace(self, mouth=mouth)

    def with_cheeks(self, cheeks: Cheeks) -> FaceModel:
        return replace(self, cheeks=cheeks)

    def with_overlay(self, overlay: Overlay) -> FaceModel:
        return replace(self, overlay=overlay)

    def with_accessory(self, accessory: Accessory) -> FaceModel:
        return replace(self, accessory=accessory)

    def with_palette(self, palette: FacePalette) -> FaceModel:
        return replace(self, palette=palette)

    def with_transform(self, bounce: float | None = None, squash: float | None = None) -> FaceModel:
        return replace(
            self,
            bounce=self.bounce if bounce is None else bounce,
            squash=self.squash if squash is None else squash,
        )

    def with_body_hint(self, body_hint: BodyLanguageHint) -> FaceModel:
        return replace(self, body_hint=body_hint)

accessory = field(default_factory=Accessory) class-attribute instance-attribute

body_hint = field(default_factory=BodyLanguageHint) class-attribute instance-attribute

bounce = 0.0 class-attribute instance-attribute

cheeks = field(default_factory=Cheeks) class-attribute instance-attribute

eyelids = field(default_factory=Eyelids) class-attribute instance-attribute

height = 240 class-attribute instance-attribute

left_eye = field(default_factory=Eye) class-attribute instance-attribute

left_eyebrow = field(default_factory=Eyebrow) class-attribute instance-attribute

mouth = field(default_factory=Mouth) class-attribute instance-attribute

overlay = field(default_factory=Overlay) class-attribute instance-attribute

palette = field(default_factory=FacePalette) class-attribute instance-attribute

right_eye = field(default_factory=Eye) class-attribute instance-attribute

right_eyebrow = field(default_factory=Eyebrow) class-attribute instance-attribute

squash = 1.0 class-attribute instance-attribute

width = 240 class-attribute instance-attribute

__init__(width=240, height=240, left_eye=Eye(), right_eye=Eye(), eyelids=Eyelids(), left_eyebrow=Eyebrow(), right_eyebrow=Eyebrow(), mouth=Mouth(), cheeks=Cheeks(), overlay=Overlay(), accessory=Accessory(), palette=FacePalette(), bounce=0.0, squash=1.0, body_hint=BodyLanguageHint())

with_accessory(accessory)

Source code in src/robot/face/model.py
def with_accessory(self, accessory: Accessory) -> FaceModel:
    return replace(self, accessory=accessory)

with_body_hint(body_hint)

Source code in src/robot/face/model.py
def with_body_hint(self, body_hint: BodyLanguageHint) -> FaceModel:
    return replace(self, body_hint=body_hint)

with_cheeks(cheeks)

Source code in src/robot/face/model.py
def with_cheeks(self, cheeks: Cheeks) -> FaceModel:
    return replace(self, cheeks=cheeks)

with_eyebrows(left=None, right=None)

Source code in src/robot/face/model.py
def with_eyebrows(
    self,
    left: Eyebrow | None = None,
    right: Eyebrow | None = None,
) -> FaceModel:
    return replace(
        self, left_eyebrow=left or self.left_eyebrow, right_eyebrow=right or self.right_eyebrow
    )

with_eyelids(eyelids)

Source code in src/robot/face/model.py
def with_eyelids(self, eyelids: Eyelids) -> FaceModel:
    return replace(self, eyelids=eyelids)

with_eyes(left_eye=None, right_eye=None)

Source code in src/robot/face/model.py
def with_eyes(
    self,
    left_eye: Eye | None = None,
    right_eye: Eye | None = None,
) -> FaceModel:
    return replace(
        self, left_eye=left_eye or self.left_eye, right_eye=right_eye or self.right_eye
    )

with_mouth(mouth)

Source code in src/robot/face/model.py
def with_mouth(self, mouth: Mouth) -> FaceModel:
    return replace(self, mouth=mouth)

with_overlay(overlay)

Source code in src/robot/face/model.py
def with_overlay(self, overlay: Overlay) -> FaceModel:
    return replace(self, overlay=overlay)

with_palette(palette)

Source code in src/robot/face/model.py
def with_palette(self, palette: FacePalette) -> FaceModel:
    return replace(self, palette=palette)

with_transform(bounce=None, squash=None)

Source code in src/robot/face/model.py
def with_transform(self, bounce: float | None = None, squash: float | None = None) -> FaceModel:
    return replace(
        self,
        bounce=self.bounce if bounce is None else bounce,
        squash=self.squash if squash is None else squash,
    )

FaceRenderer

Render a :class:FaceModel to an RGB888 frame.

Source code in src/robot/face/renderer.py
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 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
 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
class FaceRenderer:
    """Render a :class:`FaceModel` to an RGB888 frame."""

    def __init__(self, width: int = 240, height: int = 240) -> None:
        if width <= 0 or height <= 0:
            raise ValueError("width and height must be > 0")
        self._width = width
        self._height = height

    @property
    def width(self) -> int:
        return self._width

    @property
    def height(self) -> int:
        return self._height

    # ------------------------------------------------------------------ public
    def render(self, model: FaceModel) -> EyeFrame:
        """Render ``model`` into a new RGB888 frame."""
        if model.width != self._width or model.height != self._height:
            raise ValueError(
                f"model is {model.width}x{model.height}, renderer is {self._width}x{self._height}"
            )
        raster = self._new_raster()
        # Vector mode bypasses the full face stack and renders only the
        # minimalist "two glowing squares + a horizontal line" used by the
        # Anki Vector 2.0 face. Cheeks/eyebrows/iris/sclera are skipped
        # because the Vector palette does not use them.
        if model.palette.mode == PALETTE_MODE_VECTOR:
            self._draw_background(raster, model)
            self._draw_vector_eyes(raster, model)
            self._draw_vector_mouth(raster, model)
            return EyeFrame(width=self._width, height=self._height, pixels=bytes(raster.pixels))
        self._draw_background(raster, model)
        self._draw_cheeks(raster, model)
        self._draw_sclera(raster, model)
        self._draw_eyelids(raster, model)
        self._draw_iris(raster, model)
        self._draw_pupil(raster, model)
        self._draw_highlight(raster, model)
        self._draw_eyebrows(raster, model)
        self._draw_mouth(raster, model)
        self._draw_overlay(raster, model)
        self._draw_accessory(raster, model)
        return EyeFrame(width=self._width, height=self._height, pixels=bytes(raster.pixels))

    # ------------------------------------------------------------------ vector mode
    def _draw_vector_eyes(self, raster: _Raster, model: FaceModel) -> None:
        """Draw two glowing rounded-squares for the eyes (Vector style).

        Each eye follows the model's gaze position so drift and look
        commands produce visible movement.  The mouth still animates
        independently.
        """
        cx, cy, face_radius, _, _ = self._face_geometry(model)
        # Vector eyes sit a bit above the panel centre, like the Anki robot.
        eye_radius = face_radius * 0.18
        eye_y = cy - face_radius * 0.30
        eye_offset_x = face_radius * 0.45
        # Gaze offset - both eyes share the same gaze direction.
        # A multiplier of 0.35 produces a visible (~3-5 px) shift on a
        # 240 px face so that drift and look commands are perceptible.
        gaze_shift_x = face_radius * 0.35 * model.left_eye.gaze.x
        gaze_shift_y = face_radius * 0.35 * model.left_eye.gaze.y
        for sx in (-1, 1):
            ex = cx + sx * eye_offset_x + gaze_shift_x
            ey = eye_y + gaze_shift_y
            self._fill_rounded_square(
                raster,
                ex - eye_radius,
                ey - eye_radius,
                eye_radius * 2,
                eye_radius * 2,
                eye_radius * 0.25,
                model.palette.iris,
            )

    def _draw_vector_mouth(self, raster: _Raster, model: FaceModel) -> None:
        """Draw a thin horizontal bar mouth that morphs with the mouth shape.

        Shape -> visual:
          NEUTRAL / CLOSED  -> straight horizontal bar
          SMILE / GRIN      -> bar curves up at the ends
          FROWN             -> bar curves down at the ends
          OPEN / WIDE_OPEN  -> bar with a gap in the middle (small "o")
          TONGUE            -> bar with a small dot below
        """
        cx, cy, face_radius, _, _ = self._face_geometry(model)
        bar_y = cy + face_radius * 0.45
        bar_half_w = face_radius * 0.32
        bar_thickness = max(2, int(face_radius * 0.08))
        shape = model.mouth.shape
        openness = model.mouth.openness
        color = model.palette.mouth
        if shape in (MouthShape.SMILE, MouthShape.GRIN, MouthShape.SMILE_OPEN, MouthShape.TONGUE):
            # Curve the ends upward (smile).
            curve = -face_radius * 0.18 * (1.0 + openness)
            self._draw_arc(raster, cx, bar_y, bar_half_w, curve, color, bar_thickness)
            if shape is MouthShape.TONGUE:
                # A tiny tongue dot below the mouth line.
                self._fill_circle(
                    raster,
                    cx,
                    bar_y - face_radius * 0.06,
                    face_radius * 0.06,
                    (255, 130, 180),
                )
        elif shape is MouthShape.FROWN:
            # Curve the ends downward.
            curve = face_radius * 0.18
            self._draw_arc(raster, cx, bar_y, bar_half_w, curve, color, bar_thickness)
        elif shape in (MouthShape.OPEN, MouthShape.WIDE_OPEN):
            # Two short bars with a gap = a small "o" shape.
            r = face_radius * (0.04 + 0.06 * openness) * (1.0 if shape is MouthShape.OPEN else 1.6)
            self._fill_circle(raster, cx, bar_y, r, color)
            if shape is MouthShape.WIDE_OPEN:
                self._fill_circle(raster, cx, bar_y, r * 0.6, model.palette.background)
        else:  # NEUTRAL / CLOSED
            self._draw_thick_line(
                raster,
                cx - bar_half_w,
                bar_y,
                cx + bar_half_w,
                bar_y,
                bar_thickness,
                color,
            )

    def _fill_rounded_square(
        self,
        raster: _Raster,
        x0: float,
        y0: float,
        w: float,
        h: float,
        radius: float,
        color: tuple[int, int, int],
    ) -> None:
        """Fill a rounded-square between ``(x0, y0)`` and ``(x0+w, y0+h)``.

        Used for the Vector-style eye. The corners are rounded by
        ``radius`` pixels (clamped to half the smaller side).
        """
        r = max(0.0, min(radius, min(w, h) / 2.0))
        x1 = x0 + w
        y1 = y0 + h
        col = bytes(color) * raster.width
        # Top + bottom strips + middle strips + corner arcs.
        for y in range(round(y0), round(y1)):
            if y < y0 + r or y >= y1 - r:
                # Top/bottom strip between the corners
                self._fill_rect_row(raster, round(x0 + r), y, round(x1 - r) - 1, col)
            else:
                # Full-width row in the middle
                self._fill_rect_row(raster, round(x0), y, round(x1) - 1, col)
        # Quadrant corner fills (4 circles for the rounded corners)
        cr = max(1, round(r))
        for cx_corner, cy_corner in (
            (x0 + r, y0 + r),
            (x1 - r, y0 + r),
            (x0 + r, y1 - r),
            (x1 - r, y1 - r),
        ):
            # Use the existing _fill_circle for each corner quadrant.
            # We restrict to the inside of the square so the result is a
            # smooth rounded corner rather than a full disc.
            self._fill_corner_quadrant(
                raster,
                round(cx_corner),
                round(cy_corner),
                cr,
                color,
                is_top_left=(cx_corner <= x0 + r and cy_corner <= y0 + r),
                is_top_right=(cx_corner >= x1 - r and cy_corner <= y0 + r),
                is_bottom_left=(cx_corner <= x0 + r and cy_corner >= y1 - r),
                is_bottom_right=(cx_corner >= x1 - r and cy_corner >= y1 - r),
            )

    def _fill_rect_row(self, raster: _Raster, x0: int, y: int, x1: int, color_bytes: bytes) -> None:
        """Fill a horizontal strip from ``(x0, y)`` to ``(x1, y)`` inclusive."""
        if x1 < x0 or y < 0 or y >= raster.height:
            return
        x0 = max(0, x0)
        x1 = min(raster.width - 1, x1)
        if x1 < x0:
            return
        start = (y * raster.width + x0) * 3
        end = (y * raster.width + x1 + 1) * 3
        # Write the 3-byte color (r, g, b) for every pixel in the row.
        i = start
        while i + 3 <= end:
            raster.pixels[i : i + 3] = bytes(color_bytes[:3])
            i += 3

    def _fill_corner_quadrant(
        self,
        raster: _Raster,
        cx: int,
        cy: int,
        r: int,
        color: tuple[int, int, int],
        *,
        is_top_left: bool,
        is_top_right: bool,
        is_bottom_left: bool,
        is_bottom_right: bool,
    ) -> None:
        """Fill the inside-quadrant of a circle of radius ``r`` at (cx, cy).

        Used to round the corners of :meth:`_fill_rounded_square`.
        """
        for dy in range(-r, r + 1):
            for dx in range(-r, r + 1):
                if dx * dx + dy * dy > r * r:
                    continue
                px = cx + dx
                py = cy + dy
                # Only write inside the square.
                inside = True
                if is_top_left and (dx > 0 or dy > 0):
                    inside = False
                if is_top_right and (dx < 0 or dy > 0):
                    inside = False
                if is_bottom_left and (dx > 0 or dy < 0):
                    inside = False
                if is_bottom_right and (dx < 0 or dy < 0):
                    inside = False
                if not inside:
                    continue
                if 0 <= px < raster.width and 0 <= py < raster.height:
                    i = (py * raster.width + px) * 3
                    raster.pixels[i : i + 3] = bytes(color)

    # ------------------------------------------------------------------ helpers
    def _new_raster(self) -> _Raster:
        return _Raster(width=self._width, height=self._height)

    # The model is drawn around a logical centre (cx, cy). The bounce and
    # squash fields are applied here so every layer sees the transformed
    # coordinates.
    def _face_geometry(self, model: FaceModel) -> tuple[float, float, float, float, float]:
        """Return (cx, cy, face_radius, eye_radius, mouth_y) in pixels."""
        cx = self._width / 2.0
        cy = self._height / 2.0
        # Vertical bounce: -1..1 -> -face_radius..+face_radius
        face_radius = min(self._width, self._height) * 0.45
        cy = cy + model.bounce * face_radius * 0.10
        # Horizontal squash: 1.0 = normal, 0.5 = squashed, 1.5 = stretched
        # We model squash as a uniform scale of the face radius (used by
        # sub-elements that respect a "horizontal scale" hint).
        face_radius *= 1.0
        eye_radius = face_radius * 0.30
        mouth_y = cy + face_radius * 0.55
        return cx, cy, face_radius, eye_radius, mouth_y

    def _sclera_radius(self, openness: float, eye_radius: float) -> tuple[float, float]:
        rx = eye_radius
        ry = max(eye_radius * 0.05, eye_radius * openness)
        return rx, ry

    # ------------------------------------------------------------------ layers
    def _draw_background(self, raster: _Raster, model: FaceModel) -> None:
        r, g, b = model.palette.background
        pixel = bytes((r, g, b)) * (raster.width * raster.height)
        raster.pixels[:] = pixel

    def _draw_cheeks(self, raster: _Raster, model: FaceModel) -> None:
        if model.cheeks.state is CheekState.NONE or model.cheeks.intensity <= 0.0:
            return
        cx, cy, face_radius, _, _ = self._face_geometry(model)
        # Cheek positions: left/right of mouth, below eyes
        for sx in (-1, 1):
            x = cx + sx * face_radius * 0.55
            y = cy + face_radius * 0.15
            color = (
                model.palette.blush
                if model.cheeks.state is CheekState.BRIGHT
                else model.palette.cheek
            )
            self._fill_circle_blend(raster, x, y, face_radius * 0.22, color, model.cheeks.intensity)

    def _draw_sclera(self, raster: _Raster, model: FaceModel) -> None:
        cx, cy, face_radius, eye_radius, _ = self._face_geometry(model)
        # Two eyes side by side
        for sx, eye in ((-1, model.left_eye), (1, model.right_eye)):
            ex = cx + sx * face_radius * 0.40
            ey = cy - face_radius * 0.18
            rx, ry = self._sclera_radius(eye.openness, eye_radius)
            self._fill_ellipse(raster, ex, ey, rx, ry, model.palette.sclera)
            if model.palette.outline != model.palette.sclera:
                self._draw_ellipse_outline(
                    raster,
                    ex,
                    ey,
                    rx,
                    ry,
                    model.palette.outline,
                    1,
                )

    def _draw_eyelids(self, raster: _Raster, model: FaceModel) -> None:
        if model.eyelids.top <= 0.0 and model.eyelids.bottom <= 0.0:
            return
        cx, cy, face_radius, eye_radius, _ = self._face_geometry(model)
        for sx in (-1, 1):
            ex = cx + sx * face_radius * 0.40
            ey = cy - face_radius * 0.18
            rx, ry = self._sclera_radius(1.0, eye_radius)
            if model.eyelids.top > 0.0:
                self._draw_horizontal_band(
                    raster,
                    ey - ry,
                    ey - ry + 2 * ry * model.eyelids.top,
                    ex,
                    rx,
                    model.palette.eyelid,
                )
            if model.eyelids.bottom > 0.0:
                self._draw_horizontal_band(
                    raster,
                    ey + ry - 2 * ry * model.eyelids.bottom,
                    ey + ry,
                    ex,
                    rx,
                    model.palette.eyelid,
                )

    def _draw_iris(self, raster: _Raster, model: FaceModel) -> None:
        cx, cy, face_radius, eye_radius, _ = self._face_geometry(model)
        for sx, eye in ((-1, model.left_eye), (1, model.right_eye)):
            ex = cx + sx * face_radius * 0.40
            ey = cy - face_radius * 0.18
            rx, ry = self._sclera_radius(eye.openness, eye_radius)
            if ry <= 1.0:
                continue
            gaze = eye.gaze.clamped()
            ox = gaze.x * self._width * 0.06
            oy = gaze.y * self._height * 0.06
            iris_cx = ex + ox
            iris_cy = ey + oy
            iris_rx = eye_radius * 0.55
            iris_ry = eye_radius * 0.55 * min(1.0, ry / rx) if rx > 0.0 else 0.0
            self._fill_ellipse(raster, iris_cx, iris_cy, iris_rx, iris_ry, model.palette.iris)
            self._draw_ellipse_outline(
                raster,
                iris_cx,
                iris_cy,
                iris_rx,
                iris_ry,
                model.palette.outline,
                1,
            )

    def _draw_pupil(self, raster: _Raster, model: FaceModel) -> None:
        cx, cy, face_radius, eye_radius, _ = self._face_geometry(model)
        for sx, eye in ((-1, model.left_eye), (1, model.right_eye)):
            ex = cx + sx * face_radius * 0.40
            ey = cy - face_radius * 0.18
            _rx, ry = self._sclera_radius(eye.openness, eye_radius)
            if ry <= 1.0:
                continue
            gaze = eye.gaze.clamped()
            ox = gaze.x * self._width * 0.06
            oy = gaze.y * self._height * 0.06
            iris_cx = ex + ox
            iris_cy = ey + oy
            base = eye_radius * 0.55 * 0.55
            pupil_r = base * (0.6 + 0.6 * eye.pupil_dilation)
            self._fill_circle(raster, iris_cx, iris_cy, pupil_r, model.palette.pupil)

    def _draw_highlight(self, raster: _Raster, model: FaceModel) -> None:
        cx, cy, face_radius, eye_radius, _ = self._face_geometry(model)
        for sx, eye in ((-1, model.left_eye), (1, model.right_eye)):
            ex = cx + sx * face_radius * 0.40
            ey = cy - face_radius * 0.18
            _rx, ry = self._sclera_radius(eye.openness, eye_radius)
            if ry <= 1.0:
                continue
            gaze = eye.gaze.clamped()
            ox = gaze.x * self._width * 0.06
            oy = gaze.y * self._height * 0.06
            iris_cx = ex + ox
            iris_cy = ey + oy
            hx = iris_cx + eye.highlight.x * eye_radius * 0.30
            hy = iris_cy + eye.highlight.y * eye_radius * 0.30
            self._fill_circle(raster, hx, hy, max(1.0, eye_radius * 0.08), model.palette.highlight)

    def _draw_eyebrows(self, raster: _Raster, model: FaceModel) -> None:
        cx, cy, face_radius, eye_radius, _ = self._face_geometry(model)
        for sx, brow in ((-1, model.left_eyebrow), (1, model.right_eyebrow)):
            ex = cx + sx * face_radius * 0.40
            ey = cy - face_radius * 0.18
            base_y = ey - eye_radius * (1.05 + brow.raise_amount)
            # Shape -> vertical offset
            if brow.shape is EyebrowShape.ANGRY:
                outer_y = base_y - 0.05 * face_radius
                inner_y = base_y + 0.10 * face_radius
            elif brow.shape is EyebrowShape.WORRIED:
                outer_y = base_y + 0.05 * face_radius
                inner_y = base_y - 0.10 * face_radius
            elif brow.shape is EyebrowShape.SAD:
                outer_y = base_y + 0.15 * face_radius
                inner_y = base_y - 0.05 * face_radius
            elif brow.shape is EyebrowShape.SLEEPY:
                outer_y = base_y - 0.10 * face_radius
                inner_y = base_y - 0.10 * face_radius
            else:  # NEUTRAL or RAISED
                outer_y = base_y
                inner_y = base_y

            # Add the angle tilt
            tilt = brow.angle * eye_radius * 0.4
            outer_y -= tilt
            inner_y += tilt

            thickness = max(1, int(eye_radius * 0.18))
            length = eye_radius * 0.95
            self._draw_thick_line(
                raster,
                ex - length / 2,
                outer_y,
                ex + length / 2,
                inner_y,
                thickness,
                model.palette.eyebrow,
            )

    def _draw_mouth(self, raster: _Raster, model: FaceModel) -> None:
        cx, _cy, face_radius, _, mouth_y = self._face_geometry(model)
        width = face_radius * 0.45
        shape = model.mouth.shape
        openness = model.mouth.openness
        width_scale = model.mouth.width
        actual_width = width * width_scale
        # Base line at mouth_y
        if shape is MouthShape.SMILE or shape is MouthShape.GRIN:
            curve = -face_radius * 0.10 * (1.0 + openness)
            self._draw_arc(raster, cx, mouth_y, actual_width, curve, model.palette.mouth, 3)
        elif shape is MouthShape.SMILE_OPEN:
            self._draw_arc(
                raster, cx, mouth_y, actual_width, -face_radius * 0.12, model.palette.mouth, 3
            )
            self._fill_circle(
                raster,
                cx,
                mouth_y - face_radius * 0.04,
                face_radius * 0.08 * openness,
                model.palette.background,
            )
        elif shape is MouthShape.FROWN:
            self._draw_arc(
                raster, cx, mouth_y, actual_width, face_radius * 0.10, model.palette.mouth, 3
            )
        elif shape is MouthShape.OPEN or shape is MouthShape.WIDE_OPEN:
            r = face_radius * (0.05 + 0.10 * openness) * (1.0 if shape is MouthShape.OPEN else 1.6)
            self._fill_circle(raster, cx, mouth_y, r, model.palette.mouth)
            if shape is MouthShape.WIDE_OPEN:
                # Inner dark
                self._fill_circle(raster, cx, mouth_y, r * 0.6, model.palette.background)
        elif shape is MouthShape.TONGUE:
            self._draw_arc(
                raster, cx, mouth_y, actual_width, -face_radius * 0.05, model.palette.mouth, 3
            )
            # Pink tongue
            self._fill_circle(
                raster, cx, mouth_y - face_radius * 0.01, face_radius * 0.06, (255, 130, 180)
            )
        else:  # CLOSED or NEUTRAL
            self._draw_arc(raster, cx, mouth_y, actual_width, 0.0, model.palette.mouth, 2)
        if model.mouth.asymmetry != 0.0:
            skew = model.mouth.asymmetry * actual_width * 0.3
            self._draw_arc(raster, cx + skew, mouth_y, actual_width, 0.0, model.palette.mouth, 2)

    def _draw_overlay(self, raster: _Raster, model: FaceModel) -> None:
        ov = model.overlay
        if ov.kind is OverlayKind.NONE:
            return
        cx, cy, face_radius, _, _ = self._face_geometry(model)
        # Position is in normalised face coordinates (-1..1) -> pixels
        x = cx + ov.position.x * face_radius
        y = cy + ov.position.y * face_radius
        size = max(2, int(face_radius * ov.size))
        if ov.kind is OverlayKind.SPARKLE or ov.kind is OverlayKind.STAR:
            # 4-pointed star: a small filled diamond
            self._fill_diamond(raster, x, y, size, ov.color)
        elif ov.kind is OverlayKind.HEART:
            self._fill_heart(raster, x, y, size, ov.color)
        elif ov.kind is OverlayKind.TEAR:
            self._fill_teardrop(raster, x, y, size, (80, 150, 255))
        elif ov.kind is OverlayKind.SWEAT:
            self._fill_teardrop(raster, x, y, size, (130, 200, 255))
        elif ov.kind is OverlayKind.ANGER:
            self._fill_diamond(raster, x, y, size, (255, 50, 50))
        elif ov.kind is OverlayKind.QUESTION:
            self._fill_circle(raster, x, y, size * 0.6, (255, 220, 60))
        elif ov.kind is OverlayKind.EXCLAIM:
            self._fill_circle(raster, x, y, size * 0.6, (255, 80, 80))
        elif ov.kind is OverlayKind.MUSIC:
            self._fill_circle(raster, x, y, size * 0.5, (60, 200, 255))

    def _draw_accessory(self, raster: _Raster, model: FaceModel) -> None:
        acc = model.accessory
        if acc.kind is AccessoryKind.NONE:
            return
        cx, cy, face_radius, eye_radius, _ = self._face_geometry(model)
        if acc.kind is AccessoryKind.GLASSES:
            # Two round rims
            for sx in (-1, 1):
                ex = cx + sx * face_radius * 0.40
                ey = cy - face_radius * 0.18
                self._draw_ellipse_outline(
                    raster, ex, ey, eye_radius * 0.85, eye_radius * 0.65, acc.color, 2
                )
            # Bridge
            self._draw_horizontal_band(
                raster,
                cy - face_radius * 0.20,
                cy - face_radius * 0.16,
                cx,
                face_radius * 0.20,
                acc.color,
            )
        elif acc.kind is AccessoryKind.SUNGLASSES:
            for sx in (-1, 1):
                ex = cx + sx * face_radius * 0.40
                ey = cy - face_radius * 0.18
                self._fill_ellipse(raster, ex, ey, eye_radius * 0.85, eye_radius * 0.55, acc.color)
        elif acc.kind is AccessoryKind.MUSTACHE:
            self._draw_mustache(raster, cx, cy + face_radius * 0.30, face_radius * 0.5, acc.color)
        elif acc.kind is AccessoryKind.BOW_TIE:
            self._draw_bow_tie(
                raster, cx, self._height - face_radius * 0.20, face_radius * 0.4, acc.color
            )
        elif acc.kind is AccessoryKind.HAT:
            # A simple band + brim
            self._draw_horizontal_band(
                raster,
                cy - face_radius,
                cy - face_radius * 0.7,
                cx,
                face_radius,
                acc.color,
            )
            self._draw_horizontal_band(
                raster,
                cy - face_radius * 0.7,
                cy - face_radius * 0.55,
                cx,
                face_radius * 1.1,
                acc.color,
            )
        elif acc.kind is AccessoryKind.CROWN:
            self._draw_crown(raster, cx, cy - face_radius * 0.85, face_radius * 0.9, acc.color)
        elif acc.kind is AccessoryKind.BANDAGE:
            self._draw_horizontal_band(
                raster,
                cy - face_radius * 0.6,
                cy - face_radius * 0.30,
                cx,
                face_radius * 0.9,
                (200, 200, 200),
            )
        elif acc.kind is AccessoryKind.HEART_EYES:
            for sx in (-1, 1):
                ex = cx + sx * face_radius * 0.40
                ey = cy - face_radius * 0.18
                self._fill_heart(raster, ex, ey, eye_radius * 0.7, (255, 80, 120))

    # ------------------------------------------------------------------ primitive stubs
    # (Detailed pixel-art primitives live below.)

    def _fill_circle(
        self,
        raster: _Raster,
        cx: float,
        cy: float,
        r: float,
        color: tuple[int, int, int],
    ) -> None:
        if r <= 0:
            return
        self._fill_ellipse(raster, cx, cy, r, r, color)

    def _fill_circle_blend(
        self,
        raster: _Raster,
        cx: float,
        cy: float,
        r: float,
        color: tuple[int, int, int],
        alpha: float,
    ) -> None:
        """Fill a circle with alpha-blending onto the background."""
        if r <= 0 or alpha <= 0.0:
            return
        alpha = max(0.0, min(1.0, alpha))
        w, h = raster.width, raster.height
        pr, pg, pb = color
        x0 = max(0, math.floor(cx - r))
        x1 = min(w - 1, math.ceil(cx + r))
        y0 = max(0, math.floor(cy - r))
        y1 = min(h - 1, math.ceil(cy + r))
        r2 = r * r
        for y in range(y0, y1 + 1):
            dy = y - cy
            row = (y * w) * 3
            for x in range(x0, x1 + 1):
                dx = x - cx
                if dx * dx + dy * dy > r2:
                    continue
                idx = row + x * 3
                # Soft falloff at the edge
                edge = 1.0 - (dx * dx + dy * dy) / r2 if r2 > 0.0 else 0.0
                local_alpha = alpha * (0.4 + 0.6 * edge)
                br = raster.pixels[idx]
                bg = raster.pixels[idx + 1]
                bb = raster.pixels[idx + 2]
                raster.pixels[idx] = int(br * (1 - local_alpha) + pr * local_alpha)
                raster.pixels[idx + 1] = int(bg * (1 - local_alpha) + pg * local_alpha)
                raster.pixels[idx + 2] = int(bb * (1 - local_alpha) + pb * local_alpha)

    def _fill_ellipse(
        self,
        raster: _Raster,
        cx: float,
        cy: float,
        rx: float,
        ry: float,
        color: tuple[int, int, int],
    ) -> None:
        if rx <= 0 or ry <= 0:
            return
        pr, pg, pb = color
        w, h = raster.width, raster.height
        x0 = max(0, math.floor(cx - rx))
        x1 = min(w - 1, math.ceil(cx + rx))
        y0 = max(0, math.floor(cy - ry))
        y1 = min(h - 1, math.ceil(cy + ry))
        if rx == ry:
            r2 = rx * rx
            for y in range(y0, y1 + 1):
                dy = y - cy
                row = (y * w) * 3
                for x in range(x0, x1 + 1):
                    dx = x - cx
                    if dx * dx + dy * dy <= r2:
                        idx = row + x * 3
                        raster.pixels[idx] = pr
                        raster.pixels[idx + 1] = pg
                        raster.pixels[idx + 2] = pb
            return
        inv_rx2 = 1.0 / (rx * rx) if rx > 0.0 else 0.0
        inv_ry2 = 1.0 / (ry * ry) if ry > 0.0 else 0.0
        for y in range(y0, y1 + 1):
            dy = y - cy
            row = (y * w) * 3
            for x in range(x0, x1 + 1):
                dx = x - cx
                if dx * dx * inv_rx2 + dy * dy * inv_ry2 <= 1.0:
                    idx = row + x * 3
                    raster.pixels[idx] = pr
                    raster.pixels[idx + 1] = pg
                    raster.pixels[idx + 2] = pb

    def _draw_ellipse_outline(
        self,
        raster: _Raster,
        cx: float,
        cy: float,
        rx: float,
        ry: float,
        color: tuple[int, int, int],
        width: int,
    ) -> None:
        if rx <= 0 or ry <= 0 or width <= 0:
            return
        for w in range(width):
            self._draw_ellipse(raster, cx, cy, max(0.0, rx - w), max(0.0, ry - w), color)

    def _draw_ellipse(
        self,
        raster: _Raster,
        cx: float,
        cy: float,
        rx: float,
        ry: float,
        color: tuple[int, int, int],
    ) -> None:
        if rx == ry:
            self._draw_circle(raster, cx, cy, rx, color)
            return
        pr, pg, pb = color
        w, h = raster.width, raster.height

        def put(px: int, py: int) -> None:
            if 0 <= px < w and 0 <= py < h:
                idx = (py * w + px) * 3
                raster.pixels[idx] = pr
                raster.pixels[idx + 1] = pg
                raster.pixels[idx + 2] = pb

        rx2 = rx * rx
        ry2 = ry * ry
        x = 0.0
        y = ry
        px = 0.0
        py = 2 * rx2 * y
        d1 = ry2 - rx2 * ry + 0.25 * rx2
        while px < py:
            put(int(cx + x), int(cy + y))
            put(int(cx - x), int(cy + y))
            put(int(cx + x), int(cy - y))
            put(int(cx - x), int(cy - y))
            x += 1
            px += 2 * ry2
            if d1 < 0:
                d1 += ry2 + px
            else:
                y -= 1
                py -= 2 * rx2
                d1 += ry2 + px - py
        d2 = ry2 * (x + 0.5) * (x + 0.5) + rx2 * (y - 1) * (y - 1) - rx2 * ry2
        while y > 0:
            put(int(cx + x), int(cy + y))
            put(int(cx - x), int(cy + y))
            put(int(cx + x), int(cy - y))
            put(int(cx - x), int(cy - y))
            y -= 1
            py -= 2 * rx2
            if d2 > 0:
                d2 += rx2 - py
            else:
                x += 1
                px += 2 * ry2
                d2 += rx2 - py + px

    def _draw_circle(
        self,
        raster: _Raster,
        cx: float,
        cy: float,
        r: float,
        color: tuple[int, int, int],
    ) -> None:
        if r <= 0:
            return
        pr, pg, pb = color
        w, h = raster.width, raster.height

        def put(px: int, py: int) -> None:
            if 0 <= px < w and 0 <= py < h:
                idx = (py * w + px) * 3
                raster.pixels[idx] = pr
                raster.pixels[idx + 1] = pg
                raster.pixels[idx + 2] = pb

        x = round(r)
        y = 0
        err = 0
        icx, icy = round(cx), round(cy)
        while x >= y:
            put(icx + x, icy + y)
            put(icx + y, icy + x)
            put(icx - y, icy + x)
            put(icx - x, icy + y)
            put(icx - x, icy - y)
            put(icx - y, icy - x)
            put(icx + y, icy - x)
            put(icx + x, icy - y)
            y += 1
            err += 1 + 2 * y
            if 2 * (err - x) + 1 > 0:
                x -= 1
                err += 1 - 2 * x

    def _draw_horizontal_band(
        self,
        raster: _Raster,
        y_top: float,
        y_bottom: float,
        cx: float,
        rx: float,
        color: tuple[int, int, int],
    ) -> None:
        pr, pg, pb = color
        w, h = raster.width, raster.height
        x0 = max(0, math.floor(cx - rx))
        x1 = min(w - 1, math.ceil(cx + rx))
        y0 = max(0, math.ceil(y_top))
        y1 = min(h - 1, math.floor(y_bottom))
        rx2 = rx * rx
        band_cy = (y_top + y_bottom) / 2.0
        for y in range(y0, y1 + 1):
            dy = y - band_cy
            row = (y * w) * 3
            for x in range(x0, x1 + 1):
                dx = x - cx
                if dx * dx + dy * dy > rx2:
                    continue
                idx = row + x * 3
                raster.pixels[idx] = pr
                raster.pixels[idx + 1] = pg
                raster.pixels[idx + 2] = pb

    def _draw_arc(
        self,
        raster: _Raster,
        cx: float,
        cy: float,
        width: float,
        curve: float,
        color: tuple[int, int, int],
        thickness: int,
    ) -> None:
        """Draw a smile/frown arc as a thin filled strip.

        ``curve`` is positive for a frown, negative for a smile. The
        arc is sampled at many x positions and a small vertical strip
        of ``thickness`` pixels is drawn.
        """
        if abs(curve) < 0.5:
            # Treat as a horizontal line
            y = int(cy)
            for x in range(int(cx - width / 2), int(cx + width / 2) + 1):
                for t in range(thickness):
                    py = y - thickness // 2 + t
                    if 0 <= x < raster.width and 0 <= py < raster.height:
                        idx = (py * raster.width + x) * 3
                        raster.pixels[idx] = color[0]
                        raster.pixels[idx + 1] = color[1]
                        raster.pixels[idx + 2] = color[2]
            return
        # Parametric arc: y = cy + curve * (1 - ((x-cx) / (width/2)) ** 2)
        steps: int = max(8, round(width))
        half: float = width / 2.0
        if half <= 0.0:
            return
        cx_f: float = float(cx)
        cy_f: float = float(cy)
        curve_f: float = float(curve)
        for i in range(steps + 1):
            x_f: float = cx_f - half + (i / steps) * width
            t_f: float = (x_f - cx_f) / half
            y_f: float = cy_f - curve_f * (1 - t_f * t_f)
            for k in range(-thickness // 2, thickness // 2 + 1):
                px, py = round(x_f), round(y_f + k)
                if 0 <= px < raster.width and 0 <= py < raster.height:
                    idx = (py * raster.width + px) * 3
                    raster.pixels[idx] = color[0]
                    raster.pixels[idx + 1] = color[1]
                    raster.pixels[idx + 2] = color[2]

    def _draw_thick_line(
        self,
        raster: _Raster,
        x0: float,
        y0: float,
        x1: float,
        y1: float,
        thickness: int,
        color: tuple[int, int, int],
    ) -> None:
        # Bresenham with a brush
        steps = max(2, int(max(abs(x1 - x0), abs(y1 - y0)) * 2))
        for i in range(steps + 1):
            t = i / steps
            x = x0 + (x1 - x0) * t
            y = y0 + (y1 - y0) * t
            for dx in range(-thickness // 2, thickness // 2 + 1):
                for dy in range(-thickness // 2, thickness // 2 + 1):
                    px, py = round(x + dx), round(y + dy)
                    if 0 <= px < raster.width and 0 <= py < raster.height:
                        idx = (py * raster.width + px) * 3
                        raster.pixels[idx] = color[0]
                        raster.pixels[idx + 1] = color[1]
                        raster.pixels[idx + 2] = color[2]

    def _fill_diamond(
        self,
        raster: _Raster,
        cx: float,
        cy: float,
        size: float,
        color: tuple[int, int, int],
    ) -> None:
        self._fill_ellipse(raster, cx, cy, size * 0.45, size, color)

    def _fill_heart(
        self,
        raster: _Raster,
        cx: float,
        cy: float,
        size: float,
        color: tuple[int, int, int],
    ) -> None:
        # Two small circles + a downward triangle
        r = size * 0.45
        self._fill_circle(raster, cx - r * 0.6, cy - r * 0.3, r, color)
        self._fill_circle(raster, cx + r * 0.6, cy - r * 0.3, r, color)
        # Triangle (approximated with a rotated square)
        for y in range(int(cy - r * 0.3), int(cy + size * 0.7) + 1):
            t = (y - (cy - r * 0.3)) / (size + 0.2 * r)
            t = max(0.0, min(1.0, t))
            half = size * 0.6 * (1.0 - t)
            for x in range(int(cx - half), int(cx + half) + 1):
                if 0 <= x < raster.width and 0 <= y < raster.height:
                    idx = (y * raster.width + x) * 3
                    raster.pixels[idx] = color[0]
                    raster.pixels[idx + 1] = color[1]
                    raster.pixels[idx + 2] = color[2]

    def _fill_teardrop(
        self,
        raster: _Raster,
        cx: float,
        cy: float,
        size: float,
        color: tuple[int, int, int],
    ) -> None:
        # Circle + triangle pointing down
        r = size * 0.4
        self._fill_circle(raster, cx, cy - size * 0.3, r, color)
        for y in range(int(cy - size * 0.3), int(cy + size * 0.6) + 1):
            t = (y - (cy - size * 0.3)) / (size * 0.9)
            t = max(0.0, min(1.0, t))
            half = size * 0.4 * (1.0 - t)
            for x in range(int(cx - half), int(cx + half) + 1):
                if 0 <= x < raster.width and 0 <= y < raster.height:
                    idx = (y * raster.width + x) * 3
                    raster.pixels[idx] = color[0]
                    raster.pixels[idx + 1] = color[1]
                    raster.pixels[idx + 2] = color[2]

    def _draw_mustache(
        self,
        raster: _Raster,
        cx: float,
        cy: float,
        length: float,
        color: tuple[int, int, int],
    ) -> None:
        # Two curves meeting in the middle
        for sx in (-1, 1):
            self._draw_arc(
                raster,
                cx + sx * length * 0.30,
                cy - sx * length * 0.05,
                length * 0.6,
                -length * 0.10 * sx,
                color,
                3,
            )

    def _draw_bow_tie(
        self,
        raster: _Raster,
        cx: float,
        cy: float,
        size: float,
        color: tuple[int, int, int],
    ) -> None:
        # Two triangles
        for sx in (-1, 1):
            for y in range(int(cy - size / 2), int(cy + size / 2) + 1):
                t = (y - (cy - size / 2)) / size
                half = size * 0.4 * (1.0 - abs(t - 0.5) * 2)
                x_start = cx + sx * size * 0.05
                x_end = x_start + sx * half
                for x in range(int(min(x_start, x_end)), int(max(x_start, x_end)) + 1):
                    if 0 <= x < raster.width and 0 <= y < raster.height:
                        idx = (y * raster.width + x) * 3
                        raster.pixels[idx] = color[0]
                        raster.pixels[idx + 1] = color[1]
                        raster.pixels[idx + 2] = color[2]

    def _draw_crown(
        self,
        raster: _Raster,
        cx: float,
        cy: float,
        length: float,
        color: tuple[int, int, int],
    ) -> None:
        # Three triangles
        points = [
            (cx - length / 2, cy),
            (cx - length / 4, cy - length / 3),
            (cx, cy),
            (cx + length / 4, cy - length / 3),
            (cx + length / 2, cy),
            (cx + length / 2, cy + length / 6),
            (cx - length / 2, cy + length / 6),
        ]
        for i in range(len(points) - 1):
            self._draw_thick_line(
                raster,
                points[i][0],
                points[i][1],
                points[i + 1][0],
                points[i + 1][1],
                2,
                color,
            )

height property

width property

__init__(width=240, height=240)

Source code in src/robot/face/renderer.py
def __init__(self, width: int = 240, height: int = 240) -> None:
    if width <= 0 or height <= 0:
        raise ValueError("width and height must be > 0")
    self._width = width
    self._height = height

render(model)

Render model into a new RGB888 frame.

Source code in src/robot/face/renderer.py
def render(self, model: FaceModel) -> EyeFrame:
    """Render ``model`` into a new RGB888 frame."""
    if model.width != self._width or model.height != self._height:
        raise ValueError(
            f"model is {model.width}x{model.height}, renderer is {self._width}x{self._height}"
        )
    raster = self._new_raster()
    # Vector mode bypasses the full face stack and renders only the
    # minimalist "two glowing squares + a horizontal line" used by the
    # Anki Vector 2.0 face. Cheeks/eyebrows/iris/sclera are skipped
    # because the Vector palette does not use them.
    if model.palette.mode == PALETTE_MODE_VECTOR:
        self._draw_background(raster, model)
        self._draw_vector_eyes(raster, model)
        self._draw_vector_mouth(raster, model)
        return EyeFrame(width=self._width, height=self._height, pixels=bytes(raster.pixels))
    self._draw_background(raster, model)
    self._draw_cheeks(raster, model)
    self._draw_sclera(raster, model)
    self._draw_eyelids(raster, model)
    self._draw_iris(raster, model)
    self._draw_pupil(raster, model)
    self._draw_highlight(raster, model)
    self._draw_eyebrows(raster, model)
    self._draw_mouth(raster, model)
    self._draw_overlay(raster, model)
    self._draw_accessory(raster, model)
    return EyeFrame(width=self._width, height=self._height, pixels=bytes(raster.pixels))

HeadTilt

Bases: Enum

Discrete head-tilt hints the body-language engine understands.

Source code in src/robot/face/model.py
class HeadTilt(Enum):
    """Discrete head-tilt hints the body-language engine understands."""

    NEUTRAL = "neutral"
    CURIOUS = "curious"  # slight tilt
    THINKING = "thinking"  # small side-to-side nod
    SLEEPY = "sleepy"  # droop
    SAD = "sad"  # downward
    EXCITED = "excited"  # quick tilt

CURIOUS = 'curious' class-attribute instance-attribute

EXCITED = 'excited' class-attribute instance-attribute

NEUTRAL = 'neutral' class-attribute instance-attribute

SAD = 'sad' class-attribute instance-attribute

SLEEPY = 'sleepy' class-attribute instance-attribute

THINKING = 'thinking' class-attribute instance-attribute

MinimalTheme

The default minimal theme.

Source code in src/robot/face/themes/minimal.py
class MinimalTheme:
    """The default minimal theme."""

    name = "minimal"
    palette = FacePalette(
        background=(10, 10, 20),
        sclera=(245, 245, 235),
        iris=(40, 110, 200),
        pupil=(10, 10, 20),
        eyelid=(20, 20, 30),
        eyebrow=(40, 30, 30),
        mouth=(180, 60, 80),
        cheek=(255, 130, 130),
        blush=(255, 90, 90),
        outline=(10, 10, 10),
        highlight=(255, 255, 255),
    )

    def apply(self, model: FaceModel) -> FaceModel:
        return model.with_palette(self.palette)

name = 'minimal' class-attribute instance-attribute

palette = FacePalette(background=(10, 10, 20), sclera=(245, 245, 235), iris=(40, 110, 200), pupil=(10, 10, 20), eyelid=(20, 20, 30), eyebrow=(40, 30, 30), mouth=(180, 60, 80), cheek=(255, 130, 130), blush=(255, 90, 90), outline=(10, 10, 10), highlight=(255, 255, 255)) class-attribute instance-attribute

apply(model)

Source code in src/robot/face/themes/minimal.py
def apply(self, model: FaceModel) -> FaceModel:
    return model.with_palette(self.palette)

PixelTheme

Source code in src/robot/face/themes/pixel.py
class PixelTheme:
    name = "pixel"
    palette = FacePalette(
        background=(15, 15, 25),
        sclera=(255, 255, 240),
        iris=(70, 140, 220),
        pupil=(15, 15, 25),
        eyelid=(30, 30, 45),
        eyebrow=(60, 40, 40),
        mouth=(220, 70, 90),
        cheek=(255, 140, 140),
        blush=(255, 90, 90),
        outline=(0, 0, 0),
        highlight=(255, 255, 255),
    )

    def __init__(self, grid: int = 8) -> None:
        self._grid = max(1, grid)

    def apply(self, model: FaceModel) -> FaceModel:
        # Quantise gaze so the iris lands on a pixel grid.
        from robot.face.components import Eye, Gaze

        def _snap_eye(eye: Eye) -> Eye:
            return Eye(
                gaze=Gaze(
                    x=_quantise(eye.gaze.x, 1.0 / self._grid),
                    y=_quantise(eye.gaze.y, 1.0 / self._grid),
                ),
                openness=_quantise(eye.openness, 1.0 / self._grid),
                pupil_dilation=_quantise(eye.pupil_dilation, 1.0 / self._grid),
                highlight=eye.highlight,
                asymmetric=eye.asymmetric,
            )

        return model.with_palette(self.palette).with_eyes(
            left_eye=_snap_eye(model.left_eye),
            right_eye=_snap_eye(model.right_eye),
        )

name = 'pixel' class-attribute instance-attribute

palette = FacePalette(background=(15, 15, 25), sclera=(255, 255, 240), iris=(70, 140, 220), pupil=(15, 15, 25), eyelid=(30, 30, 45), eyebrow=(60, 40, 40), mouth=(220, 70, 90), cheek=(255, 140, 140), blush=(255, 90, 90), outline=(0, 0, 0), highlight=(255, 255, 255)) class-attribute instance-attribute

__init__(grid=8)

Source code in src/robot/face/themes/pixel.py
def __init__(self, grid: int = 8) -> None:
    self._grid = max(1, grid)

apply(model)

Source code in src/robot/face/themes/pixel.py
def apply(self, model: FaceModel) -> FaceModel:
    # Quantise gaze so the iris lands on a pixel grid.
    from robot.face.components import Eye, Gaze

    def _snap_eye(eye: Eye) -> Eye:
        return Eye(
            gaze=Gaze(
                x=_quantise(eye.gaze.x, 1.0 / self._grid),
                y=_quantise(eye.gaze.y, 1.0 / self._grid),
            ),
            openness=_quantise(eye.openness, 1.0 / self._grid),
            pupil_dilation=_quantise(eye.pupil_dilation, 1.0 / self._grid),
            highlight=eye.highlight,
            asymmetric=eye.asymmetric,
        )

    return model.with_palette(self.palette).with_eyes(
        left_eye=_snap_eye(model.left_eye),
        right_eye=_snap_eye(model.right_eye),
    )

RetroLcdTheme

Source code in src/robot/face/themes/retro_lcd.py
class RetroLcdTheme:
    name = "retro_lcd"
    palette = FacePalette(
        background=(0, 0, 0),
        sclera=(40, 180, 60),
        iris=(100, 255, 130),
        pupil=(0, 0, 0),
        eyelid=(20, 60, 30),
        eyebrow=(40, 180, 60),
        mouth=(40, 180, 60),
        cheek=(40, 180, 60),
        blush=(40, 180, 60),
        outline=(0, 0, 0),
        highlight=(180, 255, 200),
    )

    def apply(self, model: FaceModel) -> FaceModel:
        return model.with_palette(self.palette)

name = 'retro_lcd' class-attribute instance-attribute

palette = FacePalette(background=(0, 0, 0), sclera=(40, 180, 60), iris=(100, 255, 130), pupil=(0, 0, 0), eyelid=(20, 60, 30), eyebrow=(40, 180, 60), mouth=(40, 180, 60), cheek=(40, 180, 60), blush=(40, 180, 60), outline=(0, 0, 0), highlight=(180, 255, 200)) class-attribute instance-attribute

apply(model)

Source code in src/robot/face/themes/retro_lcd.py
def apply(self, model: FaceModel) -> FaceModel:
    return model.with_palette(self.palette)

Theme

Bases: Protocol

A visual style applied to a :class:FaceModel.

Source code in src/robot/face/themes/base.py
@runtime_checkable
class Theme(Protocol):
    """A visual style applied to a :class:`FaceModel`."""

    @property
    def name(self) -> str:
        """Human-readable theme name."""

    @property
    def palette(self) -> FacePalette:
        """The colour palette the theme uses."""

    def apply(self, model: FaceModel) -> FaceModel:
        """Return ``model`` with the theme's visual style applied."""

name property

Human-readable theme name.

palette property

The colour palette the theme uses.

apply(model)

Return model with the theme's visual style applied.

Source code in src/robot/face/themes/base.py
def apply(self, model: FaceModel) -> FaceModel:
    """Return ``model`` with the theme's visual style applied."""

WireframeTheme

Source code in src/robot/face/themes/wireframe.py
class WireframeTheme:
    name = "wireframe"
    palette = FacePalette(
        background=(0, 0, 0),
        sclera=(0, 0, 0),
        iris=(0, 0, 0),
        pupil=(255, 255, 255),
        eyelid=(0, 0, 0),
        eyebrow=(255, 255, 255),
        mouth=(255, 255, 255),
        cheek=(0, 0, 0),
        blush=(0, 0, 0),
        outline=(255, 255, 255),
        highlight=(255, 255, 255),
    )

    def apply(self, model: FaceModel) -> FaceModel:
        return model.with_palette(self.palette)

name = 'wireframe' class-attribute instance-attribute

palette = FacePalette(background=(0, 0, 0), sclera=(0, 0, 0), iris=(0, 0, 0), pupil=(255, 255, 255), eyelid=(0, 0, 0), eyebrow=(255, 255, 255), mouth=(255, 255, 255), cheek=(0, 0, 0), blush=(0, 0, 0), outline=(255, 255, 255), highlight=(255, 255, 255)) class-attribute instance-attribute

apply(model)

Source code in src/robot/face/themes/wireframe.py
def apply(self, model: FaceModel) -> FaceModel:
    return model.with_palette(self.palette)

get_theme(name)

Look up a built-in theme by name (case-insensitive).

Source code in src/robot/face/themes/__init__.py
def get_theme(name: str) -> Theme:
    """Look up a built-in theme by name (case-insensitive)."""
    key = name.lower().replace("-", "_")
    if key not in BUILTIN_THEMES:
        raise KeyError(f"unknown theme {name!r}; available: {sorted(BUILTIN_THEMES.keys())}")
    return BUILTIN_THEMES[key]()

Model

robot.face.model

The :class:FaceModel - a complete, immutable snapshot of the face.

The model is the contract between the :class:EmotionEngine, :class:FaceAnimator, and :class:FaceRenderer. Every layer reads / writes this single value type.

Two eyes (left + right) are explicitly separate so asymmetric expressions (winks, side-glances) are first-class.

__all__ = ['ArmPose', 'BodyLanguageHint', 'FaceModel', 'HeadTilt'] module-attribute

Accessory dataclass

A persistent decoration (vs. an :class:Overlay which is transient).

Source code in src/robot/face/components.py
@dataclass(slots=True, frozen=True)
class Accessory:
    """A persistent decoration (vs. an :class:`Overlay` which is transient)."""

    kind: AccessoryKind = AccessoryKind.NONE
    color: tuple[int, int, int] = (255, 255, 255)
    opacity: float = 1.0  # 0..1

color = (255, 255, 255) class-attribute instance-attribute

kind = AccessoryKind.NONE class-attribute instance-attribute

opacity = 1.0 class-attribute instance-attribute

__init__(kind=AccessoryKind.NONE, color=(255, 255, 255), opacity=1.0)

ArmPose

Bases: Enum

Discrete arm-pose hints.

Source code in src/robot/face/model.py
class ArmPose(Enum):
    """Discrete arm-pose hints."""

    RELAXED = "relaxed"
    OPEN = "open"  # slightly raised
    WIDE = "wide"  # celebration
    WAVING = "waving"  # one arm up
    SHRUG = "shrug"  # both up
    DOWN = "down"  # rest
    POINT = "point"  # one arm forward

DOWN = 'down' class-attribute instance-attribute

OPEN = 'open' class-attribute instance-attribute

POINT = 'point' class-attribute instance-attribute

RELAXED = 'relaxed' class-attribute instance-attribute

SHRUG = 'shrug' class-attribute instance-attribute

WAVING = 'waving' class-attribute instance-attribute

WIDE = 'wide' class-attribute instance-attribute

BodyLanguageHint dataclass

A high-level body-language request produced by the EmotionEngine.

Source code in src/robot/face/model.py
@dataclass(slots=True, frozen=True)
class BodyLanguageHint:
    """A high-level body-language request produced by the EmotionEngine."""

    head_tilt: HeadTilt = HeadTilt.NEUTRAL
    arm_pose: ArmPose = ArmPose.RELAXED
    # Intensity scales how strongly the body-language engine applies the
    # pose (0.0 = ignore, 1.0 = full expression).
    intensity: float = 1.0
    # Special transient gestures the body-language engine should run once
    # (e.g. a wave). Empty tuple = "no transient gestures".
    gestures: tuple[str, ...] = ()

arm_pose = ArmPose.RELAXED class-attribute instance-attribute

gestures = () class-attribute instance-attribute

head_tilt = HeadTilt.NEUTRAL class-attribute instance-attribute

intensity = 1.0 class-attribute instance-attribute

__init__(head_tilt=HeadTilt.NEUTRAL, arm_pose=ArmPose.RELAXED, intensity=1.0, gestures=())

Cheeks dataclass

Cheek rendering - base + accent colour, intensity.

Source code in src/robot/face/components.py
@dataclass(slots=True, frozen=True)
class Cheeks:
    """Cheek rendering - base + accent colour, intensity."""

    state: CheekState = CheekState.NONE
    intensity: float = 0.0  # 0..1

intensity = 0.0 class-attribute instance-attribute

state = CheekState.NONE class-attribute instance-attribute

__init__(state=CheekState.NONE, intensity=0.0)

Eye dataclass

A single eye. The face has two of them.

Source code in src/robot/face/components.py
@dataclass(slots=True, frozen=True)
class Eye:
    """A single eye. The face has two of them."""

    gaze: Gaze = field(default_factory=Gaze)
    openness: float = 1.0  # 0.0 = closed, 1.0 = wide
    pupil_dilation: float = 0.5  # 0.0 = constricted, 1.0 = dilated
    highlight: Gaze = field(default_factory=lambda: Gaze(0.3, 0.3))
    asymmetric: bool = False  # for character expressions

asymmetric = False class-attribute instance-attribute

gaze = field(default_factory=Gaze) class-attribute instance-attribute

highlight = field(default_factory=lambda: Gaze(0.3, 0.3)) class-attribute instance-attribute

openness = 1.0 class-attribute instance-attribute

pupil_dilation = 0.5 class-attribute instance-attribute

__init__(gaze=Gaze(), openness=1.0, pupil_dilation=0.5, highlight=(lambda: Gaze(0.3, 0.3))(), asymmetric=False)

Eyebrow dataclass

A single eyebrow.

Source code in src/robot/face/components.py
@dataclass(slots=True, frozen=True)
class Eyebrow:
    """A single eyebrow."""

    shape: EyebrowShape = EyebrowShape.NEUTRAL
    raise_amount: float = 0.0  # 0..1 vertical raise (additive on top of shape)
    angle: float = 0.0  # -1..1 tilt (angry < 0, worried > 0)

angle = 0.0 class-attribute instance-attribute

raise_amount = 0.0 class-attribute instance-attribute

shape = EyebrowShape.NEUTRAL class-attribute instance-attribute

__init__(shape=EyebrowShape.NEUTRAL, raise_amount=0.0, angle=0.0)

Eyelids dataclass

Vertical eyelid positions, 0.0 = retracted, 1.0 = fully closed.

Source code in src/robot/face/components.py
@dataclass(slots=True, frozen=True)
class Eyelids:
    """Vertical eyelid positions, ``0.0`` = retracted, ``1.0`` = fully closed."""

    top: float = 0.0
    bottom: float = 0.0

bottom = 0.0 class-attribute instance-attribute

top = 0.0 class-attribute instance-attribute

__init__(top=0.0, bottom=0.0)

FaceModel dataclass

The full face, captured at one instant.

All values are immutable. Use the helper methods to build new models with a single field changed (this is what the renderer animates).

Source code in src/robot/face/model.py
@dataclass(slots=True, frozen=True)
class FaceModel:
    """The full face, captured at one instant.

    All values are immutable. Use the helper methods to build new models
    with a single field changed (this is what the renderer animates).
    """

    width: int = 240
    height: int = 240

    left_eye: Eye = field(default_factory=Eye)
    right_eye: Eye = field(default_factory=Eye)

    # Eyelids
    eyelids: Eyelids = field(default_factory=Eyelids)

    # Eyebrows (one per eye)
    left_eyebrow: Eyebrow = field(default_factory=Eyebrow)
    right_eyebrow: Eyebrow = field(default_factory=Eyebrow)

    # Mouth
    mouth: Mouth = field(default_factory=Mouth)

    # Cheeks
    cheeks: Cheeks = field(default_factory=Cheeks)

    # Overlays
    overlay: Overlay = field(default_factory=Overlay)

    # Persistent accessories
    accessory: Accessory = field(default_factory=Accessory)

    # Colour palette (themes override this)
    palette: FacePalette = field(default_factory=FacePalette)

    # Subtle bounce / squash & stretch (in normalised units)
    bounce: float = 0.0  # -1..1 vertical translation
    squash: float = 1.0  # 0..2 horizontal scale (1 = neutral)

    # Body-language hint proposed by the EmotionEngine
    body_hint: BodyLanguageHint = field(default_factory=BodyLanguageHint)

    # ------------------------------------------------------------------
    # Convenience builders (return a new model with one field changed)
    # ------------------------------------------------------------------
    def with_eyes(
        self,
        left_eye: Eye | None = None,
        right_eye: Eye | None = None,
    ) -> FaceModel:
        return replace(
            self, left_eye=left_eye or self.left_eye, right_eye=right_eye or self.right_eye
        )

    def with_eyelids(self, eyelids: Eyelids) -> FaceModel:
        return replace(self, eyelids=eyelids)

    def with_eyebrows(
        self,
        left: Eyebrow | None = None,
        right: Eyebrow | None = None,
    ) -> FaceModel:
        return replace(
            self, left_eyebrow=left or self.left_eyebrow, right_eyebrow=right or self.right_eyebrow
        )

    def with_mouth(self, mouth: Mouth) -> FaceModel:
        return replace(self, mouth=mouth)

    def with_cheeks(self, cheeks: Cheeks) -> FaceModel:
        return replace(self, cheeks=cheeks)

    def with_overlay(self, overlay: Overlay) -> FaceModel:
        return replace(self, overlay=overlay)

    def with_accessory(self, accessory: Accessory) -> FaceModel:
        return replace(self, accessory=accessory)

    def with_palette(self, palette: FacePalette) -> FaceModel:
        return replace(self, palette=palette)

    def with_transform(self, bounce: float | None = None, squash: float | None = None) -> FaceModel:
        return replace(
            self,
            bounce=self.bounce if bounce is None else bounce,
            squash=self.squash if squash is None else squash,
        )

    def with_body_hint(self, body_hint: BodyLanguageHint) -> FaceModel:
        return replace(self, body_hint=body_hint)

accessory = field(default_factory=Accessory) class-attribute instance-attribute

body_hint = field(default_factory=BodyLanguageHint) class-attribute instance-attribute

bounce = 0.0 class-attribute instance-attribute

cheeks = field(default_factory=Cheeks) class-attribute instance-attribute

eyelids = field(default_factory=Eyelids) class-attribute instance-attribute

height = 240 class-attribute instance-attribute

left_eye = field(default_factory=Eye) class-attribute instance-attribute

left_eyebrow = field(default_factory=Eyebrow) class-attribute instance-attribute

mouth = field(default_factory=Mouth) class-attribute instance-attribute

overlay = field(default_factory=Overlay) class-attribute instance-attribute

palette = field(default_factory=FacePalette) class-attribute instance-attribute

right_eye = field(default_factory=Eye) class-attribute instance-attribute

right_eyebrow = field(default_factory=Eyebrow) class-attribute instance-attribute

squash = 1.0 class-attribute instance-attribute

width = 240 class-attribute instance-attribute

__init__(width=240, height=240, left_eye=Eye(), right_eye=Eye(), eyelids=Eyelids(), left_eyebrow=Eyebrow(), right_eyebrow=Eyebrow(), mouth=Mouth(), cheeks=Cheeks(), overlay=Overlay(), accessory=Accessory(), palette=FacePalette(), bounce=0.0, squash=1.0, body_hint=BodyLanguageHint())

with_accessory(accessory)

Source code in src/robot/face/model.py
def with_accessory(self, accessory: Accessory) -> FaceModel:
    return replace(self, accessory=accessory)

with_body_hint(body_hint)

Source code in src/robot/face/model.py
def with_body_hint(self, body_hint: BodyLanguageHint) -> FaceModel:
    return replace(self, body_hint=body_hint)

with_cheeks(cheeks)

Source code in src/robot/face/model.py
def with_cheeks(self, cheeks: Cheeks) -> FaceModel:
    return replace(self, cheeks=cheeks)

with_eyebrows(left=None, right=None)

Source code in src/robot/face/model.py
def with_eyebrows(
    self,
    left: Eyebrow | None = None,
    right: Eyebrow | None = None,
) -> FaceModel:
    return replace(
        self, left_eyebrow=left or self.left_eyebrow, right_eyebrow=right or self.right_eyebrow
    )

with_eyelids(eyelids)

Source code in src/robot/face/model.py
def with_eyelids(self, eyelids: Eyelids) -> FaceModel:
    return replace(self, eyelids=eyelids)

with_eyes(left_eye=None, right_eye=None)

Source code in src/robot/face/model.py
def with_eyes(
    self,
    left_eye: Eye | None = None,
    right_eye: Eye | None = None,
) -> FaceModel:
    return replace(
        self, left_eye=left_eye or self.left_eye, right_eye=right_eye or self.right_eye
    )

with_mouth(mouth)

Source code in src/robot/face/model.py
def with_mouth(self, mouth: Mouth) -> FaceModel:
    return replace(self, mouth=mouth)

with_overlay(overlay)

Source code in src/robot/face/model.py
def with_overlay(self, overlay: Overlay) -> FaceModel:
    return replace(self, overlay=overlay)

with_palette(palette)

Source code in src/robot/face/model.py
def with_palette(self, palette: FacePalette) -> FaceModel:
    return replace(self, palette=palette)

with_transform(bounce=None, squash=None)

Source code in src/robot/face/model.py
def with_transform(self, bounce: float | None = None, squash: float | None = None) -> FaceModel:
    return replace(
        self,
        bounce=self.bounce if bounce is None else bounce,
        squash=self.squash if squash is None else squash,
    )

FacePalette dataclass

All colours the renderer can use. Themes override these.

mode selects a renderer rendering style. The default "face" draws the full eye stack (sclera + iris + pupil + highlight + eyelids + eyebrows + mouth). The "vector" mode draws two filled rounded-squares for eyes and a thin horizontal bar for the mouth - the Anki Vector 2.0 minimalist look.

Source code in src/robot/face/components.py
@dataclass(slots=True, frozen=True)
class FacePalette:
    """All colours the renderer can use. Themes override these.

    ``mode`` selects a renderer rendering style. The default ``"face"``
    draws the full eye stack (sclera + iris + pupil + highlight +
    eyelids + eyebrows + mouth). The ``"vector"`` mode draws two
    filled rounded-squares for eyes and a thin horizontal bar for
    the mouth - the Anki Vector 2.0 minimalist look.
    """

    background: tuple[int, int, int] = (10, 10, 20)
    sclera: tuple[int, int, int] = (245, 245, 235)
    iris: tuple[int, int, int] = (40, 110, 200)
    pupil: tuple[int, int, int] = (10, 10, 20)
    eyelid: tuple[int, int, int] = (20, 20, 30)
    eyebrow: tuple[int, int, int] = (40, 30, 30)
    mouth: tuple[int, int, int] = (180, 60, 80)
    cheek: tuple[int, int, int] = (255, 130, 130)
    blush: tuple[int, int, int] = (255, 90, 90)
    outline: tuple[int, int, int] = (10, 10, 10)
    highlight: tuple[int, int, int] = (255, 255, 255)
    mode: str = PALETTE_MODE_FACE

background = (10, 10, 20) class-attribute instance-attribute

blush = (255, 90, 90) class-attribute instance-attribute

cheek = (255, 130, 130) class-attribute instance-attribute

eyebrow = (40, 30, 30) class-attribute instance-attribute

eyelid = (20, 20, 30) class-attribute instance-attribute

highlight = (255, 255, 255) class-attribute instance-attribute

iris = (40, 110, 200) class-attribute instance-attribute

mode = PALETTE_MODE_FACE class-attribute instance-attribute

mouth = (180, 60, 80) class-attribute instance-attribute

outline = (10, 10, 10) class-attribute instance-attribute

pupil = (10, 10, 20) class-attribute instance-attribute

sclera = (245, 245, 235) class-attribute instance-attribute

__init__(background=(10, 10, 20), sclera=(245, 245, 235), iris=(40, 110, 200), pupil=(10, 10, 20), eyelid=(20, 20, 30), eyebrow=(40, 30, 30), mouth=(180, 60, 80), cheek=(255, 130, 130), blush=(255, 90, 90), outline=(10, 10, 10), highlight=(255, 255, 255), mode=PALETTE_MODE_FACE)

HeadTilt

Bases: Enum

Discrete head-tilt hints the body-language engine understands.

Source code in src/robot/face/model.py
class HeadTilt(Enum):
    """Discrete head-tilt hints the body-language engine understands."""

    NEUTRAL = "neutral"
    CURIOUS = "curious"  # slight tilt
    THINKING = "thinking"  # small side-to-side nod
    SLEEPY = "sleepy"  # droop
    SAD = "sad"  # downward
    EXCITED = "excited"  # quick tilt

CURIOUS = 'curious' class-attribute instance-attribute

EXCITED = 'excited' class-attribute instance-attribute

NEUTRAL = 'neutral' class-attribute instance-attribute

SAD = 'sad' class-attribute instance-attribute

SLEEPY = 'sleepy' class-attribute instance-attribute

THINKING = 'thinking' class-attribute instance-attribute

Mouth dataclass

The mouth, parameterised.

Source code in src/robot/face/components.py
@dataclass(slots=True, frozen=True)
class Mouth:
    """The mouth, parameterised."""

    shape: MouthShape = MouthShape.NEUTRAL
    openness: float = 0.0  # 0.0 = closed, 1.0 = wide open
    width: float = 0.5  # 0.0 = small, 1.0 = wide
    asymmetry: float = 0.0  # -1..1 (left side higher = smirk)

asymmetry = 0.0 class-attribute instance-attribute

openness = 0.0 class-attribute instance-attribute

shape = MouthShape.NEUTRAL class-attribute instance-attribute

width = 0.5 class-attribute instance-attribute

__init__(shape=MouthShape.NEUTRAL, openness=0.0, width=0.5, asymmetry=0.0)

Overlay dataclass

A floating symbol rendered on top of the face.

Source code in src/robot/face/components.py
@dataclass(slots=True, frozen=True)
class Overlay:
    """A floating symbol rendered on top of the face."""

    kind: OverlayKind = OverlayKind.NONE
    position: Point = field(default_factory=lambda: Point(0.0, -0.5))
    size: float = 0.3  # 0..1 fraction of the face radius
    rotation: float = 0.0  # radians
    color: tuple[int, int, int] = (255, 255, 255)

color = (255, 255, 255) class-attribute instance-attribute

kind = OverlayKind.NONE class-attribute instance-attribute

position = field(default_factory=lambda: Point(0.0, -0.5)) class-attribute instance-attribute

rotation = 0.0 class-attribute instance-attribute

size = 0.3 class-attribute instance-attribute

__init__(kind=OverlayKind.NONE, position=(lambda: Point(0.0, -0.5))(), size=0.3, rotation=0.0, color=(255, 255, 255))

Components

robot.face.components

Reusable face components.

A face is a composition of small, independent components. Each component is an immutable value type so the :class:FaceModel itself is also immutable - that makes the renderer deterministic and unit-testable.

The components live at three levels:

  • eyes (left/right) - gaze vector, openness, pupil dilation, etc.
  • face features - eyebrows, mouth, cheeks, all parameterised.
  • overlays - sparkles, hearts, tears, sweat drop, blush, accessories. They are off-screen by default and turned on by the :class:EmotionEngine when an emotion needs them.

PALETTE_MODE_FACE = 'face' module-attribute

PALETTE_MODE_VECTOR = 'vector' module-attribute

__all__ = ['PALETTE_MODE_FACE', 'PALETTE_MODE_VECTOR', 'Accessory', 'AccessoryKind', 'CheekState', 'Cheeks', 'Eye', 'Eyebrow', 'EyebrowShape', 'Eyelids', 'FacePalette', 'Gaze', 'Mouth', 'MouthShape', 'Overlay', 'OverlayKind', 'Point'] module-attribute

Accessory dataclass

A persistent decoration (vs. an :class:Overlay which is transient).

Source code in src/robot/face/components.py
@dataclass(slots=True, frozen=True)
class Accessory:
    """A persistent decoration (vs. an :class:`Overlay` which is transient)."""

    kind: AccessoryKind = AccessoryKind.NONE
    color: tuple[int, int, int] = (255, 255, 255)
    opacity: float = 1.0  # 0..1

color = (255, 255, 255) class-attribute instance-attribute

kind = AccessoryKind.NONE class-attribute instance-attribute

opacity = 1.0 class-attribute instance-attribute

__init__(kind=AccessoryKind.NONE, color=(255, 255, 255), opacity=1.0)

AccessoryKind

Bases: str, Enum

Source code in src/robot/face/components.py
class AccessoryKind(str, Enum):
    NONE = "none"
    GLASSES = "glasses"
    SUNGLASSES = "sunglasses"
    MUSTACHE = "mustache"
    BOW_TIE = "bow_tie"
    HAT = "hat"
    CROWN = "crown"
    BANDAGE = "bandage"
    HEART_EYES = "heart_eyes"  # per-eye decoration (overrides pupil)

BANDAGE = 'bandage' class-attribute instance-attribute

BOW_TIE = 'bow_tie' class-attribute instance-attribute

CROWN = 'crown' class-attribute instance-attribute

GLASSES = 'glasses' class-attribute instance-attribute

HAT = 'hat' class-attribute instance-attribute

HEART_EYES = 'heart_eyes' class-attribute instance-attribute

MUSTACHE = 'mustache' class-attribute instance-attribute

NONE = 'none' class-attribute instance-attribute

SUNGLASSES = 'sunglasses' class-attribute instance-attribute

CheekState

Bases: str, Enum

Source code in src/robot/face/components.py
class CheekState(str, Enum):
    NONE = "none"
    SOFT = "soft"  # neutral happy
    BRIGHT = "bright"  # very happy / embarrassed
    COLD = "cold"  # sad / cold

BRIGHT = 'bright' class-attribute instance-attribute

COLD = 'cold' class-attribute instance-attribute

NONE = 'none' class-attribute instance-attribute

SOFT = 'soft' class-attribute instance-attribute

Cheeks dataclass

Cheek rendering - base + accent colour, intensity.

Source code in src/robot/face/components.py
@dataclass(slots=True, frozen=True)
class Cheeks:
    """Cheek rendering - base + accent colour, intensity."""

    state: CheekState = CheekState.NONE
    intensity: float = 0.0  # 0..1

intensity = 0.0 class-attribute instance-attribute

state = CheekState.NONE class-attribute instance-attribute

__init__(state=CheekState.NONE, intensity=0.0)

Eye dataclass

A single eye. The face has two of them.

Source code in src/robot/face/components.py
@dataclass(slots=True, frozen=True)
class Eye:
    """A single eye. The face has two of them."""

    gaze: Gaze = field(default_factory=Gaze)
    openness: float = 1.0  # 0.0 = closed, 1.0 = wide
    pupil_dilation: float = 0.5  # 0.0 = constricted, 1.0 = dilated
    highlight: Gaze = field(default_factory=lambda: Gaze(0.3, 0.3))
    asymmetric: bool = False  # for character expressions

asymmetric = False class-attribute instance-attribute

gaze = field(default_factory=Gaze) class-attribute instance-attribute

highlight = field(default_factory=lambda: Gaze(0.3, 0.3)) class-attribute instance-attribute

openness = 1.0 class-attribute instance-attribute

pupil_dilation = 0.5 class-attribute instance-attribute

__init__(gaze=Gaze(), openness=1.0, pupil_dilation=0.5, highlight=(lambda: Gaze(0.3, 0.3))(), asymmetric=False)

Eyebrow dataclass

A single eyebrow.

Source code in src/robot/face/components.py
@dataclass(slots=True, frozen=True)
class Eyebrow:
    """A single eyebrow."""

    shape: EyebrowShape = EyebrowShape.NEUTRAL
    raise_amount: float = 0.0  # 0..1 vertical raise (additive on top of shape)
    angle: float = 0.0  # -1..1 tilt (angry < 0, worried > 0)

angle = 0.0 class-attribute instance-attribute

raise_amount = 0.0 class-attribute instance-attribute

shape = EyebrowShape.NEUTRAL class-attribute instance-attribute

__init__(shape=EyebrowShape.NEUTRAL, raise_amount=0.0, angle=0.0)

EyebrowShape

Bases: str, Enum

Source code in src/robot/face/components.py
class EyebrowShape(str, Enum):
    NEUTRAL = "neutral"
    RAISED = "raised"
    ANGRY = "angry"
    WORRIED = "worried"
    SLEEPY = "sleepy"
    SAD = "sad"

ANGRY = 'angry' class-attribute instance-attribute

NEUTRAL = 'neutral' class-attribute instance-attribute

RAISED = 'raised' class-attribute instance-attribute

SAD = 'sad' class-attribute instance-attribute

SLEEPY = 'sleepy' class-attribute instance-attribute

WORRIED = 'worried' class-attribute instance-attribute

Eyelids dataclass

Vertical eyelid positions, 0.0 = retracted, 1.0 = fully closed.

Source code in src/robot/face/components.py
@dataclass(slots=True, frozen=True)
class Eyelids:
    """Vertical eyelid positions, ``0.0`` = retracted, ``1.0`` = fully closed."""

    top: float = 0.0
    bottom: float = 0.0

bottom = 0.0 class-attribute instance-attribute

top = 0.0 class-attribute instance-attribute

__init__(top=0.0, bottom=0.0)

FacePalette dataclass

All colours the renderer can use. Themes override these.

mode selects a renderer rendering style. The default "face" draws the full eye stack (sclera + iris + pupil + highlight + eyelids + eyebrows + mouth). The "vector" mode draws two filled rounded-squares for eyes and a thin horizontal bar for the mouth - the Anki Vector 2.0 minimalist look.

Source code in src/robot/face/components.py
@dataclass(slots=True, frozen=True)
class FacePalette:
    """All colours the renderer can use. Themes override these.

    ``mode`` selects a renderer rendering style. The default ``"face"``
    draws the full eye stack (sclera + iris + pupil + highlight +
    eyelids + eyebrows + mouth). The ``"vector"`` mode draws two
    filled rounded-squares for eyes and a thin horizontal bar for
    the mouth - the Anki Vector 2.0 minimalist look.
    """

    background: tuple[int, int, int] = (10, 10, 20)
    sclera: tuple[int, int, int] = (245, 245, 235)
    iris: tuple[int, int, int] = (40, 110, 200)
    pupil: tuple[int, int, int] = (10, 10, 20)
    eyelid: tuple[int, int, int] = (20, 20, 30)
    eyebrow: tuple[int, int, int] = (40, 30, 30)
    mouth: tuple[int, int, int] = (180, 60, 80)
    cheek: tuple[int, int, int] = (255, 130, 130)
    blush: tuple[int, int, int] = (255, 90, 90)
    outline: tuple[int, int, int] = (10, 10, 10)
    highlight: tuple[int, int, int] = (255, 255, 255)
    mode: str = PALETTE_MODE_FACE

background = (10, 10, 20) class-attribute instance-attribute

blush = (255, 90, 90) class-attribute instance-attribute

cheek = (255, 130, 130) class-attribute instance-attribute

eyebrow = (40, 30, 30) class-attribute instance-attribute

eyelid = (20, 20, 30) class-attribute instance-attribute

highlight = (255, 255, 255) class-attribute instance-attribute

iris = (40, 110, 200) class-attribute instance-attribute

mode = PALETTE_MODE_FACE class-attribute instance-attribute

mouth = (180, 60, 80) class-attribute instance-attribute

outline = (10, 10, 10) class-attribute instance-attribute

pupil = (10, 10, 20) class-attribute instance-attribute

sclera = (245, 245, 235) class-attribute instance-attribute

__init__(background=(10, 10, 20), sclera=(245, 245, 235), iris=(40, 110, 200), pupil=(10, 10, 20), eyelid=(20, 20, 30), eyebrow=(40, 30, 30), mouth=(180, 60, 80), cheek=(255, 130, 130), blush=(255, 90, 90), outline=(10, 10, 10), highlight=(255, 255, 255), mode=PALETTE_MODE_FACE)

Gaze dataclass

2D gaze target normalised in [-1, 1].

Source code in src/robot/face/components.py
@dataclass(slots=True, frozen=True)
class Gaze:
    """2D gaze target normalised in ``[-1, 1]``."""

    x: float = 0.0
    y: float = 0.0

    def clamped(self) -> Gaze:
        return Gaze(
            x=max(-1.0, min(1.0, self.x)),
            y=max(-1.0, min(1.0, self.y)),
        )

x = 0.0 class-attribute instance-attribute

y = 0.0 class-attribute instance-attribute

__init__(x=0.0, y=0.0)

clamped()

Source code in src/robot/face/components.py
def clamped(self) -> Gaze:
    return Gaze(
        x=max(-1.0, min(1.0, self.x)),
        y=max(-1.0, min(1.0, self.y)),
    )

Mouth dataclass

The mouth, parameterised.

Source code in src/robot/face/components.py
@dataclass(slots=True, frozen=True)
class Mouth:
    """The mouth, parameterised."""

    shape: MouthShape = MouthShape.NEUTRAL
    openness: float = 0.0  # 0.0 = closed, 1.0 = wide open
    width: float = 0.5  # 0.0 = small, 1.0 = wide
    asymmetry: float = 0.0  # -1..1 (left side higher = smirk)

asymmetry = 0.0 class-attribute instance-attribute

openness = 0.0 class-attribute instance-attribute

shape = MouthShape.NEUTRAL class-attribute instance-attribute

width = 0.5 class-attribute instance-attribute

__init__(shape=MouthShape.NEUTRAL, openness=0.0, width=0.5, asymmetry=0.0)

MouthShape

Bases: str, Enum

Source code in src/robot/face/components.py
class MouthShape(str, Enum):
    CLOSED = "closed"
    NEUTRAL = "neutral"
    SMILE = "smile"
    GRIN = "grin"
    FROWN = "frown"
    OPEN = "open"  # small "oh"
    WIDE_OPEN = "wide_open"  # gasp / surprise
    TONGUE = "tongue"  # playful
    SMILE_OPEN = "smile_open"  # laughing

CLOSED = 'closed' class-attribute instance-attribute

FROWN = 'frown' class-attribute instance-attribute

GRIN = 'grin' class-attribute instance-attribute

NEUTRAL = 'neutral' class-attribute instance-attribute

OPEN = 'open' class-attribute instance-attribute

SMILE = 'smile' class-attribute instance-attribute

SMILE_OPEN = 'smile_open' class-attribute instance-attribute

TONGUE = 'tongue' class-attribute instance-attribute

WIDE_OPEN = 'wide_open' class-attribute instance-attribute

Overlay dataclass

A floating symbol rendered on top of the face.

Source code in src/robot/face/components.py
@dataclass(slots=True, frozen=True)
class Overlay:
    """A floating symbol rendered on top of the face."""

    kind: OverlayKind = OverlayKind.NONE
    position: Point = field(default_factory=lambda: Point(0.0, -0.5))
    size: float = 0.3  # 0..1 fraction of the face radius
    rotation: float = 0.0  # radians
    color: tuple[int, int, int] = (255, 255, 255)

color = (255, 255, 255) class-attribute instance-attribute

kind = OverlayKind.NONE class-attribute instance-attribute

position = field(default_factory=lambda: Point(0.0, -0.5)) class-attribute instance-attribute

rotation = 0.0 class-attribute instance-attribute

size = 0.3 class-attribute instance-attribute

__init__(kind=OverlayKind.NONE, position=(lambda: Point(0.0, -0.5))(), size=0.3, rotation=0.0, color=(255, 255, 255))

OverlayKind

Bases: str, Enum

Source code in src/robot/face/components.py
class OverlayKind(str, Enum):
    NONE = "none"
    SPARKLE = "sparkle"
    HEART = "heart"
    TEAR = "tear"
    SWEAT = "sweat"
    ANGER = "anger"  # vein symbol
    QUESTION = "question"  # "?" mark
    EXCLAIM = "exclaim"  # "!" mark
    MUSIC = "music"  # note
    STAR = "star"

ANGER = 'anger' class-attribute instance-attribute

EXCLAIM = 'exclaim' class-attribute instance-attribute

HEART = 'heart' class-attribute instance-attribute

MUSIC = 'music' class-attribute instance-attribute

NONE = 'none' class-attribute instance-attribute

QUESTION = 'question' class-attribute instance-attribute

SPARKLE = 'sparkle' class-attribute instance-attribute

STAR = 'star' class-attribute instance-attribute

SWEAT = 'sweat' class-attribute instance-attribute

TEAR = 'tear' class-attribute instance-attribute

Point dataclass

A 2D point in the face's local frame, in pixels.

Source code in src/robot/face/components.py
@dataclass(slots=True, frozen=True)
class Point:
    """A 2D point in the face's local frame, in pixels."""

    x: float
    y: float

x instance-attribute

y instance-attribute

__init__(x, y)

Renderer

robot.face.renderer

The :class:FaceRenderer - display-agnostic pixel art.

The renderer takes a :class:FaceModel and produces an :class:EyeFrame (an RGB888 buffer). It knows nothing about displays, themes, or animation - it just rasterises the model it is given.

The drawing layers (z-order, back to front) are:

  1. Background - solid colour from the palette.
  2. Bounce / squash transform - translate / scale the entire face based on the model's bounce and squash fields.
  3. Cheeks - soft circular blush patches.
  4. Sclera (eyes) - filled circles clipped to the panel.
  5. Eyelids - horizontal bands that cover the eyes.
  6. Iris - coloured discs shifted by gaze offset.
  7. Pupil - dark discs on top of the iris.
  8. Eye highlight - small catch-light.
  9. Eyebrows - short bars above each eye.
  10. Mouth - the mouth shape as a small filled curve.
  11. Overlay - sparkles, hearts, tears, sweat, etc.
  12. Accessory - glasses, hat, etc.

PALETTE_MODE_VECTOR = 'vector' module-attribute

__all__ = ['FaceRenderer'] module-attribute

AccessoryKind

Bases: str, Enum

Source code in src/robot/face/components.py
class AccessoryKind(str, Enum):
    NONE = "none"
    GLASSES = "glasses"
    SUNGLASSES = "sunglasses"
    MUSTACHE = "mustache"
    BOW_TIE = "bow_tie"
    HAT = "hat"
    CROWN = "crown"
    BANDAGE = "bandage"
    HEART_EYES = "heart_eyes"  # per-eye decoration (overrides pupil)

BANDAGE = 'bandage' class-attribute instance-attribute

BOW_TIE = 'bow_tie' class-attribute instance-attribute

CROWN = 'crown' class-attribute instance-attribute

GLASSES = 'glasses' class-attribute instance-attribute

HAT = 'hat' class-attribute instance-attribute

HEART_EYES = 'heart_eyes' class-attribute instance-attribute

MUSTACHE = 'mustache' class-attribute instance-attribute

NONE = 'none' class-attribute instance-attribute

SUNGLASSES = 'sunglasses' class-attribute instance-attribute

CheekState

Bases: str, Enum

Source code in src/robot/face/components.py
class CheekState(str, Enum):
    NONE = "none"
    SOFT = "soft"  # neutral happy
    BRIGHT = "bright"  # very happy / embarrassed
    COLD = "cold"  # sad / cold

BRIGHT = 'bright' class-attribute instance-attribute

COLD = 'cold' class-attribute instance-attribute

NONE = 'none' class-attribute instance-attribute

SOFT = 'soft' class-attribute instance-attribute

EyeFrame dataclass

An RGB888 image to push to the display.

Attributes

width, height: Pixel dimensions. pixels: Row-major RGB888 buffer of length width * height * 3.

Source code in src/robot/interfaces/display.py
@dataclass(slots=True, frozen=True)
class EyeFrame:
    """An RGB888 image to push to the display.

    Attributes
    ----------
    width, height:
        Pixel dimensions.
    pixels:
        Row-major RGB888 buffer of length ``width * height * 3``.
    """

    width: int
    height: int
    pixels: bytes

height instance-attribute

pixels instance-attribute

width instance-attribute

__init__(width, height, pixels)

EyebrowShape

Bases: str, Enum

Source code in src/robot/face/components.py
class EyebrowShape(str, Enum):
    NEUTRAL = "neutral"
    RAISED = "raised"
    ANGRY = "angry"
    WORRIED = "worried"
    SLEEPY = "sleepy"
    SAD = "sad"

ANGRY = 'angry' class-attribute instance-attribute

NEUTRAL = 'neutral' class-attribute instance-attribute

RAISED = 'raised' class-attribute instance-attribute

SAD = 'sad' class-attribute instance-attribute

SLEEPY = 'sleepy' class-attribute instance-attribute

WORRIED = 'worried' class-attribute instance-attribute

FaceModel dataclass

The full face, captured at one instant.

All values are immutable. Use the helper methods to build new models with a single field changed (this is what the renderer animates).

Source code in src/robot/face/model.py
@dataclass(slots=True, frozen=True)
class FaceModel:
    """The full face, captured at one instant.

    All values are immutable. Use the helper methods to build new models
    with a single field changed (this is what the renderer animates).
    """

    width: int = 240
    height: int = 240

    left_eye: Eye = field(default_factory=Eye)
    right_eye: Eye = field(default_factory=Eye)

    # Eyelids
    eyelids: Eyelids = field(default_factory=Eyelids)

    # Eyebrows (one per eye)
    left_eyebrow: Eyebrow = field(default_factory=Eyebrow)
    right_eyebrow: Eyebrow = field(default_factory=Eyebrow)

    # Mouth
    mouth: Mouth = field(default_factory=Mouth)

    # Cheeks
    cheeks: Cheeks = field(default_factory=Cheeks)

    # Overlays
    overlay: Overlay = field(default_factory=Overlay)

    # Persistent accessories
    accessory: Accessory = field(default_factory=Accessory)

    # Colour palette (themes override this)
    palette: FacePalette = field(default_factory=FacePalette)

    # Subtle bounce / squash & stretch (in normalised units)
    bounce: float = 0.0  # -1..1 vertical translation
    squash: float = 1.0  # 0..2 horizontal scale (1 = neutral)

    # Body-language hint proposed by the EmotionEngine
    body_hint: BodyLanguageHint = field(default_factory=BodyLanguageHint)

    # ------------------------------------------------------------------
    # Convenience builders (return a new model with one field changed)
    # ------------------------------------------------------------------
    def with_eyes(
        self,
        left_eye: Eye | None = None,
        right_eye: Eye | None = None,
    ) -> FaceModel:
        return replace(
            self, left_eye=left_eye or self.left_eye, right_eye=right_eye or self.right_eye
        )

    def with_eyelids(self, eyelids: Eyelids) -> FaceModel:
        return replace(self, eyelids=eyelids)

    def with_eyebrows(
        self,
        left: Eyebrow | None = None,
        right: Eyebrow | None = None,
    ) -> FaceModel:
        return replace(
            self, left_eyebrow=left or self.left_eyebrow, right_eyebrow=right or self.right_eyebrow
        )

    def with_mouth(self, mouth: Mouth) -> FaceModel:
        return replace(self, mouth=mouth)

    def with_cheeks(self, cheeks: Cheeks) -> FaceModel:
        return replace(self, cheeks=cheeks)

    def with_overlay(self, overlay: Overlay) -> FaceModel:
        return replace(self, overlay=overlay)

    def with_accessory(self, accessory: Accessory) -> FaceModel:
        return replace(self, accessory=accessory)

    def with_palette(self, palette: FacePalette) -> FaceModel:
        return replace(self, palette=palette)

    def with_transform(self, bounce: float | None = None, squash: float | None = None) -> FaceModel:
        return replace(
            self,
            bounce=self.bounce if bounce is None else bounce,
            squash=self.squash if squash is None else squash,
        )

    def with_body_hint(self, body_hint: BodyLanguageHint) -> FaceModel:
        return replace(self, body_hint=body_hint)

accessory = field(default_factory=Accessory) class-attribute instance-attribute

body_hint = field(default_factory=BodyLanguageHint) class-attribute instance-attribute

bounce = 0.0 class-attribute instance-attribute

cheeks = field(default_factory=Cheeks) class-attribute instance-attribute

eyelids = field(default_factory=Eyelids) class-attribute instance-attribute

height = 240 class-attribute instance-attribute

left_eye = field(default_factory=Eye) class-attribute instance-attribute

left_eyebrow = field(default_factory=Eyebrow) class-attribute instance-attribute

mouth = field(default_factory=Mouth) class-attribute instance-attribute

overlay = field(default_factory=Overlay) class-attribute instance-attribute

palette = field(default_factory=FacePalette) class-attribute instance-attribute

right_eye = field(default_factory=Eye) class-attribute instance-attribute

right_eyebrow = field(default_factory=Eyebrow) class-attribute instance-attribute

squash = 1.0 class-attribute instance-attribute

width = 240 class-attribute instance-attribute

__init__(width=240, height=240, left_eye=Eye(), right_eye=Eye(), eyelids=Eyelids(), left_eyebrow=Eyebrow(), right_eyebrow=Eyebrow(), mouth=Mouth(), cheeks=Cheeks(), overlay=Overlay(), accessory=Accessory(), palette=FacePalette(), bounce=0.0, squash=1.0, body_hint=BodyLanguageHint())

with_accessory(accessory)

Source code in src/robot/face/model.py
def with_accessory(self, accessory: Accessory) -> FaceModel:
    return replace(self, accessory=accessory)

with_body_hint(body_hint)

Source code in src/robot/face/model.py
def with_body_hint(self, body_hint: BodyLanguageHint) -> FaceModel:
    return replace(self, body_hint=body_hint)

with_cheeks(cheeks)

Source code in src/robot/face/model.py
def with_cheeks(self, cheeks: Cheeks) -> FaceModel:
    return replace(self, cheeks=cheeks)

with_eyebrows(left=None, right=None)

Source code in src/robot/face/model.py
def with_eyebrows(
    self,
    left: Eyebrow | None = None,
    right: Eyebrow | None = None,
) -> FaceModel:
    return replace(
        self, left_eyebrow=left or self.left_eyebrow, right_eyebrow=right or self.right_eyebrow
    )

with_eyelids(eyelids)

Source code in src/robot/face/model.py
def with_eyelids(self, eyelids: Eyelids) -> FaceModel:
    return replace(self, eyelids=eyelids)

with_eyes(left_eye=None, right_eye=None)

Source code in src/robot/face/model.py
def with_eyes(
    self,
    left_eye: Eye | None = None,
    right_eye: Eye | None = None,
) -> FaceModel:
    return replace(
        self, left_eye=left_eye or self.left_eye, right_eye=right_eye or self.right_eye
    )

with_mouth(mouth)

Source code in src/robot/face/model.py
def with_mouth(self, mouth: Mouth) -> FaceModel:
    return replace(self, mouth=mouth)

with_overlay(overlay)

Source code in src/robot/face/model.py
def with_overlay(self, overlay: Overlay) -> FaceModel:
    return replace(self, overlay=overlay)

with_palette(palette)

Source code in src/robot/face/model.py
def with_palette(self, palette: FacePalette) -> FaceModel:
    return replace(self, palette=palette)

with_transform(bounce=None, squash=None)

Source code in src/robot/face/model.py
def with_transform(self, bounce: float | None = None, squash: float | None = None) -> FaceModel:
    return replace(
        self,
        bounce=self.bounce if bounce is None else bounce,
        squash=self.squash if squash is None else squash,
    )

FaceRenderer

Render a :class:FaceModel to an RGB888 frame.

Source code in src/robot/face/renderer.py
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 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
 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
class FaceRenderer:
    """Render a :class:`FaceModel` to an RGB888 frame."""

    def __init__(self, width: int = 240, height: int = 240) -> None:
        if width <= 0 or height <= 0:
            raise ValueError("width and height must be > 0")
        self._width = width
        self._height = height

    @property
    def width(self) -> int:
        return self._width

    @property
    def height(self) -> int:
        return self._height

    # ------------------------------------------------------------------ public
    def render(self, model: FaceModel) -> EyeFrame:
        """Render ``model`` into a new RGB888 frame."""
        if model.width != self._width or model.height != self._height:
            raise ValueError(
                f"model is {model.width}x{model.height}, renderer is {self._width}x{self._height}"
            )
        raster = self._new_raster()
        # Vector mode bypasses the full face stack and renders only the
        # minimalist "two glowing squares + a horizontal line" used by the
        # Anki Vector 2.0 face. Cheeks/eyebrows/iris/sclera are skipped
        # because the Vector palette does not use them.
        if model.palette.mode == PALETTE_MODE_VECTOR:
            self._draw_background(raster, model)
            self._draw_vector_eyes(raster, model)
            self._draw_vector_mouth(raster, model)
            return EyeFrame(width=self._width, height=self._height, pixels=bytes(raster.pixels))
        self._draw_background(raster, model)
        self._draw_cheeks(raster, model)
        self._draw_sclera(raster, model)
        self._draw_eyelids(raster, model)
        self._draw_iris(raster, model)
        self._draw_pupil(raster, model)
        self._draw_highlight(raster, model)
        self._draw_eyebrows(raster, model)
        self._draw_mouth(raster, model)
        self._draw_overlay(raster, model)
        self._draw_accessory(raster, model)
        return EyeFrame(width=self._width, height=self._height, pixels=bytes(raster.pixels))

    # ------------------------------------------------------------------ vector mode
    def _draw_vector_eyes(self, raster: _Raster, model: FaceModel) -> None:
        """Draw two glowing rounded-squares for the eyes (Vector style).

        Each eye follows the model's gaze position so drift and look
        commands produce visible movement.  The mouth still animates
        independently.
        """
        cx, cy, face_radius, _, _ = self._face_geometry(model)
        # Vector eyes sit a bit above the panel centre, like the Anki robot.
        eye_radius = face_radius * 0.18
        eye_y = cy - face_radius * 0.30
        eye_offset_x = face_radius * 0.45
        # Gaze offset - both eyes share the same gaze direction.
        # A multiplier of 0.35 produces a visible (~3-5 px) shift on a
        # 240 px face so that drift and look commands are perceptible.
        gaze_shift_x = face_radius * 0.35 * model.left_eye.gaze.x
        gaze_shift_y = face_radius * 0.35 * model.left_eye.gaze.y
        for sx in (-1, 1):
            ex = cx + sx * eye_offset_x + gaze_shift_x
            ey = eye_y + gaze_shift_y
            self._fill_rounded_square(
                raster,
                ex - eye_radius,
                ey - eye_radius,
                eye_radius * 2,
                eye_radius * 2,
                eye_radius * 0.25,
                model.palette.iris,
            )

    def _draw_vector_mouth(self, raster: _Raster, model: FaceModel) -> None:
        """Draw a thin horizontal bar mouth that morphs with the mouth shape.

        Shape -> visual:
          NEUTRAL / CLOSED  -> straight horizontal bar
          SMILE / GRIN      -> bar curves up at the ends
          FROWN             -> bar curves down at the ends
          OPEN / WIDE_OPEN  -> bar with a gap in the middle (small "o")
          TONGUE            -> bar with a small dot below
        """
        cx, cy, face_radius, _, _ = self._face_geometry(model)
        bar_y = cy + face_radius * 0.45
        bar_half_w = face_radius * 0.32
        bar_thickness = max(2, int(face_radius * 0.08))
        shape = model.mouth.shape
        openness = model.mouth.openness
        color = model.palette.mouth
        if shape in (MouthShape.SMILE, MouthShape.GRIN, MouthShape.SMILE_OPEN, MouthShape.TONGUE):
            # Curve the ends upward (smile).
            curve = -face_radius * 0.18 * (1.0 + openness)
            self._draw_arc(raster, cx, bar_y, bar_half_w, curve, color, bar_thickness)
            if shape is MouthShape.TONGUE:
                # A tiny tongue dot below the mouth line.
                self._fill_circle(
                    raster,
                    cx,
                    bar_y - face_radius * 0.06,
                    face_radius * 0.06,
                    (255, 130, 180),
                )
        elif shape is MouthShape.FROWN:
            # Curve the ends downward.
            curve = face_radius * 0.18
            self._draw_arc(raster, cx, bar_y, bar_half_w, curve, color, bar_thickness)
        elif shape in (MouthShape.OPEN, MouthShape.WIDE_OPEN):
            # Two short bars with a gap = a small "o" shape.
            r = face_radius * (0.04 + 0.06 * openness) * (1.0 if shape is MouthShape.OPEN else 1.6)
            self._fill_circle(raster, cx, bar_y, r, color)
            if shape is MouthShape.WIDE_OPEN:
                self._fill_circle(raster, cx, bar_y, r * 0.6, model.palette.background)
        else:  # NEUTRAL / CLOSED
            self._draw_thick_line(
                raster,
                cx - bar_half_w,
                bar_y,
                cx + bar_half_w,
                bar_y,
                bar_thickness,
                color,
            )

    def _fill_rounded_square(
        self,
        raster: _Raster,
        x0: float,
        y0: float,
        w: float,
        h: float,
        radius: float,
        color: tuple[int, int, int],
    ) -> None:
        """Fill a rounded-square between ``(x0, y0)`` and ``(x0+w, y0+h)``.

        Used for the Vector-style eye. The corners are rounded by
        ``radius`` pixels (clamped to half the smaller side).
        """
        r = max(0.0, min(radius, min(w, h) / 2.0))
        x1 = x0 + w
        y1 = y0 + h
        col = bytes(color) * raster.width
        # Top + bottom strips + middle strips + corner arcs.
        for y in range(round(y0), round(y1)):
            if y < y0 + r or y >= y1 - r:
                # Top/bottom strip between the corners
                self._fill_rect_row(raster, round(x0 + r), y, round(x1 - r) - 1, col)
            else:
                # Full-width row in the middle
                self._fill_rect_row(raster, round(x0), y, round(x1) - 1, col)
        # Quadrant corner fills (4 circles for the rounded corners)
        cr = max(1, round(r))
        for cx_corner, cy_corner in (
            (x0 + r, y0 + r),
            (x1 - r, y0 + r),
            (x0 + r, y1 - r),
            (x1 - r, y1 - r),
        ):
            # Use the existing _fill_circle for each corner quadrant.
            # We restrict to the inside of the square so the result is a
            # smooth rounded corner rather than a full disc.
            self._fill_corner_quadrant(
                raster,
                round(cx_corner),
                round(cy_corner),
                cr,
                color,
                is_top_left=(cx_corner <= x0 + r and cy_corner <= y0 + r),
                is_top_right=(cx_corner >= x1 - r and cy_corner <= y0 + r),
                is_bottom_left=(cx_corner <= x0 + r and cy_corner >= y1 - r),
                is_bottom_right=(cx_corner >= x1 - r and cy_corner >= y1 - r),
            )

    def _fill_rect_row(self, raster: _Raster, x0: int, y: int, x1: int, color_bytes: bytes) -> None:
        """Fill a horizontal strip from ``(x0, y)`` to ``(x1, y)`` inclusive."""
        if x1 < x0 or y < 0 or y >= raster.height:
            return
        x0 = max(0, x0)
        x1 = min(raster.width - 1, x1)
        if x1 < x0:
            return
        start = (y * raster.width + x0) * 3
        end = (y * raster.width + x1 + 1) * 3
        # Write the 3-byte color (r, g, b) for every pixel in the row.
        i = start
        while i + 3 <= end:
            raster.pixels[i : i + 3] = bytes(color_bytes[:3])
            i += 3

    def _fill_corner_quadrant(
        self,
        raster: _Raster,
        cx: int,
        cy: int,
        r: int,
        color: tuple[int, int, int],
        *,
        is_top_left: bool,
        is_top_right: bool,
        is_bottom_left: bool,
        is_bottom_right: bool,
    ) -> None:
        """Fill the inside-quadrant of a circle of radius ``r`` at (cx, cy).

        Used to round the corners of :meth:`_fill_rounded_square`.
        """
        for dy in range(-r, r + 1):
            for dx in range(-r, r + 1):
                if dx * dx + dy * dy > r * r:
                    continue
                px = cx + dx
                py = cy + dy
                # Only write inside the square.
                inside = True
                if is_top_left and (dx > 0 or dy > 0):
                    inside = False
                if is_top_right and (dx < 0 or dy > 0):
                    inside = False
                if is_bottom_left and (dx > 0 or dy < 0):
                    inside = False
                if is_bottom_right and (dx < 0 or dy < 0):
                    inside = False
                if not inside:
                    continue
                if 0 <= px < raster.width and 0 <= py < raster.height:
                    i = (py * raster.width + px) * 3
                    raster.pixels[i : i + 3] = bytes(color)

    # ------------------------------------------------------------------ helpers
    def _new_raster(self) -> _Raster:
        return _Raster(width=self._width, height=self._height)

    # The model is drawn around a logical centre (cx, cy). The bounce and
    # squash fields are applied here so every layer sees the transformed
    # coordinates.
    def _face_geometry(self, model: FaceModel) -> tuple[float, float, float, float, float]:
        """Return (cx, cy, face_radius, eye_radius, mouth_y) in pixels."""
        cx = self._width / 2.0
        cy = self._height / 2.0
        # Vertical bounce: -1..1 -> -face_radius..+face_radius
        face_radius = min(self._width, self._height) * 0.45
        cy = cy + model.bounce * face_radius * 0.10
        # Horizontal squash: 1.0 = normal, 0.5 = squashed, 1.5 = stretched
        # We model squash as a uniform scale of the face radius (used by
        # sub-elements that respect a "horizontal scale" hint).
        face_radius *= 1.0
        eye_radius = face_radius * 0.30
        mouth_y = cy + face_radius * 0.55
        return cx, cy, face_radius, eye_radius, mouth_y

    def _sclera_radius(self, openness: float, eye_radius: float) -> tuple[float, float]:
        rx = eye_radius
        ry = max(eye_radius * 0.05, eye_radius * openness)
        return rx, ry

    # ------------------------------------------------------------------ layers
    def _draw_background(self, raster: _Raster, model: FaceModel) -> None:
        r, g, b = model.palette.background
        pixel = bytes((r, g, b)) * (raster.width * raster.height)
        raster.pixels[:] = pixel

    def _draw_cheeks(self, raster: _Raster, model: FaceModel) -> None:
        if model.cheeks.state is CheekState.NONE or model.cheeks.intensity <= 0.0:
            return
        cx, cy, face_radius, _, _ = self._face_geometry(model)
        # Cheek positions: left/right of mouth, below eyes
        for sx in (-1, 1):
            x = cx + sx * face_radius * 0.55
            y = cy + face_radius * 0.15
            color = (
                model.palette.blush
                if model.cheeks.state is CheekState.BRIGHT
                else model.palette.cheek
            )
            self._fill_circle_blend(raster, x, y, face_radius * 0.22, color, model.cheeks.intensity)

    def _draw_sclera(self, raster: _Raster, model: FaceModel) -> None:
        cx, cy, face_radius, eye_radius, _ = self._face_geometry(model)
        # Two eyes side by side
        for sx, eye in ((-1, model.left_eye), (1, model.right_eye)):
            ex = cx + sx * face_radius * 0.40
            ey = cy - face_radius * 0.18
            rx, ry = self._sclera_radius(eye.openness, eye_radius)
            self._fill_ellipse(raster, ex, ey, rx, ry, model.palette.sclera)
            if model.palette.outline != model.palette.sclera:
                self._draw_ellipse_outline(
                    raster,
                    ex,
                    ey,
                    rx,
                    ry,
                    model.palette.outline,
                    1,
                )

    def _draw_eyelids(self, raster: _Raster, model: FaceModel) -> None:
        if model.eyelids.top <= 0.0 and model.eyelids.bottom <= 0.0:
            return
        cx, cy, face_radius, eye_radius, _ = self._face_geometry(model)
        for sx in (-1, 1):
            ex = cx + sx * face_radius * 0.40
            ey = cy - face_radius * 0.18
            rx, ry = self._sclera_radius(1.0, eye_radius)
            if model.eyelids.top > 0.0:
                self._draw_horizontal_band(
                    raster,
                    ey - ry,
                    ey - ry + 2 * ry * model.eyelids.top,
                    ex,
                    rx,
                    model.palette.eyelid,
                )
            if model.eyelids.bottom > 0.0:
                self._draw_horizontal_band(
                    raster,
                    ey + ry - 2 * ry * model.eyelids.bottom,
                    ey + ry,
                    ex,
                    rx,
                    model.palette.eyelid,
                )

    def _draw_iris(self, raster: _Raster, model: FaceModel) -> None:
        cx, cy, face_radius, eye_radius, _ = self._face_geometry(model)
        for sx, eye in ((-1, model.left_eye), (1, model.right_eye)):
            ex = cx + sx * face_radius * 0.40
            ey = cy - face_radius * 0.18
            rx, ry = self._sclera_radius(eye.openness, eye_radius)
            if ry <= 1.0:
                continue
            gaze = eye.gaze.clamped()
            ox = gaze.x * self._width * 0.06
            oy = gaze.y * self._height * 0.06
            iris_cx = ex + ox
            iris_cy = ey + oy
            iris_rx = eye_radius * 0.55
            iris_ry = eye_radius * 0.55 * min(1.0, ry / rx) if rx > 0.0 else 0.0
            self._fill_ellipse(raster, iris_cx, iris_cy, iris_rx, iris_ry, model.palette.iris)
            self._draw_ellipse_outline(
                raster,
                iris_cx,
                iris_cy,
                iris_rx,
                iris_ry,
                model.palette.outline,
                1,
            )

    def _draw_pupil(self, raster: _Raster, model: FaceModel) -> None:
        cx, cy, face_radius, eye_radius, _ = self._face_geometry(model)
        for sx, eye in ((-1, model.left_eye), (1, model.right_eye)):
            ex = cx + sx * face_radius * 0.40
            ey = cy - face_radius * 0.18
            _rx, ry = self._sclera_radius(eye.openness, eye_radius)
            if ry <= 1.0:
                continue
            gaze = eye.gaze.clamped()
            ox = gaze.x * self._width * 0.06
            oy = gaze.y * self._height * 0.06
            iris_cx = ex + ox
            iris_cy = ey + oy
            base = eye_radius * 0.55 * 0.55
            pupil_r = base * (0.6 + 0.6 * eye.pupil_dilation)
            self._fill_circle(raster, iris_cx, iris_cy, pupil_r, model.palette.pupil)

    def _draw_highlight(self, raster: _Raster, model: FaceModel) -> None:
        cx, cy, face_radius, eye_radius, _ = self._face_geometry(model)
        for sx, eye in ((-1, model.left_eye), (1, model.right_eye)):
            ex = cx + sx * face_radius * 0.40
            ey = cy - face_radius * 0.18
            _rx, ry = self._sclera_radius(eye.openness, eye_radius)
            if ry <= 1.0:
                continue
            gaze = eye.gaze.clamped()
            ox = gaze.x * self._width * 0.06
            oy = gaze.y * self._height * 0.06
            iris_cx = ex + ox
            iris_cy = ey + oy
            hx = iris_cx + eye.highlight.x * eye_radius * 0.30
            hy = iris_cy + eye.highlight.y * eye_radius * 0.30
            self._fill_circle(raster, hx, hy, max(1.0, eye_radius * 0.08), model.palette.highlight)

    def _draw_eyebrows(self, raster: _Raster, model: FaceModel) -> None:
        cx, cy, face_radius, eye_radius, _ = self._face_geometry(model)
        for sx, brow in ((-1, model.left_eyebrow), (1, model.right_eyebrow)):
            ex = cx + sx * face_radius * 0.40
            ey = cy - face_radius * 0.18
            base_y = ey - eye_radius * (1.05 + brow.raise_amount)
            # Shape -> vertical offset
            if brow.shape is EyebrowShape.ANGRY:
                outer_y = base_y - 0.05 * face_radius
                inner_y = base_y + 0.10 * face_radius
            elif brow.shape is EyebrowShape.WORRIED:
                outer_y = base_y + 0.05 * face_radius
                inner_y = base_y - 0.10 * face_radius
            elif brow.shape is EyebrowShape.SAD:
                outer_y = base_y + 0.15 * face_radius
                inner_y = base_y - 0.05 * face_radius
            elif brow.shape is EyebrowShape.SLEEPY:
                outer_y = base_y - 0.10 * face_radius
                inner_y = base_y - 0.10 * face_radius
            else:  # NEUTRAL or RAISED
                outer_y = base_y
                inner_y = base_y

            # Add the angle tilt
            tilt = brow.angle * eye_radius * 0.4
            outer_y -= tilt
            inner_y += tilt

            thickness = max(1, int(eye_radius * 0.18))
            length = eye_radius * 0.95
            self._draw_thick_line(
                raster,
                ex - length / 2,
                outer_y,
                ex + length / 2,
                inner_y,
                thickness,
                model.palette.eyebrow,
            )

    def _draw_mouth(self, raster: _Raster, model: FaceModel) -> None:
        cx, _cy, face_radius, _, mouth_y = self._face_geometry(model)
        width = face_radius * 0.45
        shape = model.mouth.shape
        openness = model.mouth.openness
        width_scale = model.mouth.width
        actual_width = width * width_scale
        # Base line at mouth_y
        if shape is MouthShape.SMILE or shape is MouthShape.GRIN:
            curve = -face_radius * 0.10 * (1.0 + openness)
            self._draw_arc(raster, cx, mouth_y, actual_width, curve, model.palette.mouth, 3)
        elif shape is MouthShape.SMILE_OPEN:
            self._draw_arc(
                raster, cx, mouth_y, actual_width, -face_radius * 0.12, model.palette.mouth, 3
            )
            self._fill_circle(
                raster,
                cx,
                mouth_y - face_radius * 0.04,
                face_radius * 0.08 * openness,
                model.palette.background,
            )
        elif shape is MouthShape.FROWN:
            self._draw_arc(
                raster, cx, mouth_y, actual_width, face_radius * 0.10, model.palette.mouth, 3
            )
        elif shape is MouthShape.OPEN or shape is MouthShape.WIDE_OPEN:
            r = face_radius * (0.05 + 0.10 * openness) * (1.0 if shape is MouthShape.OPEN else 1.6)
            self._fill_circle(raster, cx, mouth_y, r, model.palette.mouth)
            if shape is MouthShape.WIDE_OPEN:
                # Inner dark
                self._fill_circle(raster, cx, mouth_y, r * 0.6, model.palette.background)
        elif shape is MouthShape.TONGUE:
            self._draw_arc(
                raster, cx, mouth_y, actual_width, -face_radius * 0.05, model.palette.mouth, 3
            )
            # Pink tongue
            self._fill_circle(
                raster, cx, mouth_y - face_radius * 0.01, face_radius * 0.06, (255, 130, 180)
            )
        else:  # CLOSED or NEUTRAL
            self._draw_arc(raster, cx, mouth_y, actual_width, 0.0, model.palette.mouth, 2)
        if model.mouth.asymmetry != 0.0:
            skew = model.mouth.asymmetry * actual_width * 0.3
            self._draw_arc(raster, cx + skew, mouth_y, actual_width, 0.0, model.palette.mouth, 2)

    def _draw_overlay(self, raster: _Raster, model: FaceModel) -> None:
        ov = model.overlay
        if ov.kind is OverlayKind.NONE:
            return
        cx, cy, face_radius, _, _ = self._face_geometry(model)
        # Position is in normalised face coordinates (-1..1) -> pixels
        x = cx + ov.position.x * face_radius
        y = cy + ov.position.y * face_radius
        size = max(2, int(face_radius * ov.size))
        if ov.kind is OverlayKind.SPARKLE or ov.kind is OverlayKind.STAR:
            # 4-pointed star: a small filled diamond
            self._fill_diamond(raster, x, y, size, ov.color)
        elif ov.kind is OverlayKind.HEART:
            self._fill_heart(raster, x, y, size, ov.color)
        elif ov.kind is OverlayKind.TEAR:
            self._fill_teardrop(raster, x, y, size, (80, 150, 255))
        elif ov.kind is OverlayKind.SWEAT:
            self._fill_teardrop(raster, x, y, size, (130, 200, 255))
        elif ov.kind is OverlayKind.ANGER:
            self._fill_diamond(raster, x, y, size, (255, 50, 50))
        elif ov.kind is OverlayKind.QUESTION:
            self._fill_circle(raster, x, y, size * 0.6, (255, 220, 60))
        elif ov.kind is OverlayKind.EXCLAIM:
            self._fill_circle(raster, x, y, size * 0.6, (255, 80, 80))
        elif ov.kind is OverlayKind.MUSIC:
            self._fill_circle(raster, x, y, size * 0.5, (60, 200, 255))

    def _draw_accessory(self, raster: _Raster, model: FaceModel) -> None:
        acc = model.accessory
        if acc.kind is AccessoryKind.NONE:
            return
        cx, cy, face_radius, eye_radius, _ = self._face_geometry(model)
        if acc.kind is AccessoryKind.GLASSES:
            # Two round rims
            for sx in (-1, 1):
                ex = cx + sx * face_radius * 0.40
                ey = cy - face_radius * 0.18
                self._draw_ellipse_outline(
                    raster, ex, ey, eye_radius * 0.85, eye_radius * 0.65, acc.color, 2
                )
            # Bridge
            self._draw_horizontal_band(
                raster,
                cy - face_radius * 0.20,
                cy - face_radius * 0.16,
                cx,
                face_radius * 0.20,
                acc.color,
            )
        elif acc.kind is AccessoryKind.SUNGLASSES:
            for sx in (-1, 1):
                ex = cx + sx * face_radius * 0.40
                ey = cy - face_radius * 0.18
                self._fill_ellipse(raster, ex, ey, eye_radius * 0.85, eye_radius * 0.55, acc.color)
        elif acc.kind is AccessoryKind.MUSTACHE:
            self._draw_mustache(raster, cx, cy + face_radius * 0.30, face_radius * 0.5, acc.color)
        elif acc.kind is AccessoryKind.BOW_TIE:
            self._draw_bow_tie(
                raster, cx, self._height - face_radius * 0.20, face_radius * 0.4, acc.color
            )
        elif acc.kind is AccessoryKind.HAT:
            # A simple band + brim
            self._draw_horizontal_band(
                raster,
                cy - face_radius,
                cy - face_radius * 0.7,
                cx,
                face_radius,
                acc.color,
            )
            self._draw_horizontal_band(
                raster,
                cy - face_radius * 0.7,
                cy - face_radius * 0.55,
                cx,
                face_radius * 1.1,
                acc.color,
            )
        elif acc.kind is AccessoryKind.CROWN:
            self._draw_crown(raster, cx, cy - face_radius * 0.85, face_radius * 0.9, acc.color)
        elif acc.kind is AccessoryKind.BANDAGE:
            self._draw_horizontal_band(
                raster,
                cy - face_radius * 0.6,
                cy - face_radius * 0.30,
                cx,
                face_radius * 0.9,
                (200, 200, 200),
            )
        elif acc.kind is AccessoryKind.HEART_EYES:
            for sx in (-1, 1):
                ex = cx + sx * face_radius * 0.40
                ey = cy - face_radius * 0.18
                self._fill_heart(raster, ex, ey, eye_radius * 0.7, (255, 80, 120))

    # ------------------------------------------------------------------ primitive stubs
    # (Detailed pixel-art primitives live below.)

    def _fill_circle(
        self,
        raster: _Raster,
        cx: float,
        cy: float,
        r: float,
        color: tuple[int, int, int],
    ) -> None:
        if r <= 0:
            return
        self._fill_ellipse(raster, cx, cy, r, r, color)

    def _fill_circle_blend(
        self,
        raster: _Raster,
        cx: float,
        cy: float,
        r: float,
        color: tuple[int, int, int],
        alpha: float,
    ) -> None:
        """Fill a circle with alpha-blending onto the background."""
        if r <= 0 or alpha <= 0.0:
            return
        alpha = max(0.0, min(1.0, alpha))
        w, h = raster.width, raster.height
        pr, pg, pb = color
        x0 = max(0, math.floor(cx - r))
        x1 = min(w - 1, math.ceil(cx + r))
        y0 = max(0, math.floor(cy - r))
        y1 = min(h - 1, math.ceil(cy + r))
        r2 = r * r
        for y in range(y0, y1 + 1):
            dy = y - cy
            row = (y * w) * 3
            for x in range(x0, x1 + 1):
                dx = x - cx
                if dx * dx + dy * dy > r2:
                    continue
                idx = row + x * 3
                # Soft falloff at the edge
                edge = 1.0 - (dx * dx + dy * dy) / r2 if r2 > 0.0 else 0.0
                local_alpha = alpha * (0.4 + 0.6 * edge)
                br = raster.pixels[idx]
                bg = raster.pixels[idx + 1]
                bb = raster.pixels[idx + 2]
                raster.pixels[idx] = int(br * (1 - local_alpha) + pr * local_alpha)
                raster.pixels[idx + 1] = int(bg * (1 - local_alpha) + pg * local_alpha)
                raster.pixels[idx + 2] = int(bb * (1 - local_alpha) + pb * local_alpha)

    def _fill_ellipse(
        self,
        raster: _Raster,
        cx: float,
        cy: float,
        rx: float,
        ry: float,
        color: tuple[int, int, int],
    ) -> None:
        if rx <= 0 or ry <= 0:
            return
        pr, pg, pb = color
        w, h = raster.width, raster.height
        x0 = max(0, math.floor(cx - rx))
        x1 = min(w - 1, math.ceil(cx + rx))
        y0 = max(0, math.floor(cy - ry))
        y1 = min(h - 1, math.ceil(cy + ry))
        if rx == ry:
            r2 = rx * rx
            for y in range(y0, y1 + 1):
                dy = y - cy
                row = (y * w) * 3
                for x in range(x0, x1 + 1):
                    dx = x - cx
                    if dx * dx + dy * dy <= r2:
                        idx = row + x * 3
                        raster.pixels[idx] = pr
                        raster.pixels[idx + 1] = pg
                        raster.pixels[idx + 2] = pb
            return
        inv_rx2 = 1.0 / (rx * rx) if rx > 0.0 else 0.0
        inv_ry2 = 1.0 / (ry * ry) if ry > 0.0 else 0.0
        for y in range(y0, y1 + 1):
            dy = y - cy
            row = (y * w) * 3
            for x in range(x0, x1 + 1):
                dx = x - cx
                if dx * dx * inv_rx2 + dy * dy * inv_ry2 <= 1.0:
                    idx = row + x * 3
                    raster.pixels[idx] = pr
                    raster.pixels[idx + 1] = pg
                    raster.pixels[idx + 2] = pb

    def _draw_ellipse_outline(
        self,
        raster: _Raster,
        cx: float,
        cy: float,
        rx: float,
        ry: float,
        color: tuple[int, int, int],
        width: int,
    ) -> None:
        if rx <= 0 or ry <= 0 or width <= 0:
            return
        for w in range(width):
            self._draw_ellipse(raster, cx, cy, max(0.0, rx - w), max(0.0, ry - w), color)

    def _draw_ellipse(
        self,
        raster: _Raster,
        cx: float,
        cy: float,
        rx: float,
        ry: float,
        color: tuple[int, int, int],
    ) -> None:
        if rx == ry:
            self._draw_circle(raster, cx, cy, rx, color)
            return
        pr, pg, pb = color
        w, h = raster.width, raster.height

        def put(px: int, py: int) -> None:
            if 0 <= px < w and 0 <= py < h:
                idx = (py * w + px) * 3
                raster.pixels[idx] = pr
                raster.pixels[idx + 1] = pg
                raster.pixels[idx + 2] = pb

        rx2 = rx * rx
        ry2 = ry * ry
        x = 0.0
        y = ry
        px = 0.0
        py = 2 * rx2 * y
        d1 = ry2 - rx2 * ry + 0.25 * rx2
        while px < py:
            put(int(cx + x), int(cy + y))
            put(int(cx - x), int(cy + y))
            put(int(cx + x), int(cy - y))
            put(int(cx - x), int(cy - y))
            x += 1
            px += 2 * ry2
            if d1 < 0:
                d1 += ry2 + px
            else:
                y -= 1
                py -= 2 * rx2
                d1 += ry2 + px - py
        d2 = ry2 * (x + 0.5) * (x + 0.5) + rx2 * (y - 1) * (y - 1) - rx2 * ry2
        while y > 0:
            put(int(cx + x), int(cy + y))
            put(int(cx - x), int(cy + y))
            put(int(cx + x), int(cy - y))
            put(int(cx - x), int(cy - y))
            y -= 1
            py -= 2 * rx2
            if d2 > 0:
                d2 += rx2 - py
            else:
                x += 1
                px += 2 * ry2
                d2 += rx2 - py + px

    def _draw_circle(
        self,
        raster: _Raster,
        cx: float,
        cy: float,
        r: float,
        color: tuple[int, int, int],
    ) -> None:
        if r <= 0:
            return
        pr, pg, pb = color
        w, h = raster.width, raster.height

        def put(px: int, py: int) -> None:
            if 0 <= px < w and 0 <= py < h:
                idx = (py * w + px) * 3
                raster.pixels[idx] = pr
                raster.pixels[idx + 1] = pg
                raster.pixels[idx + 2] = pb

        x = round(r)
        y = 0
        err = 0
        icx, icy = round(cx), round(cy)
        while x >= y:
            put(icx + x, icy + y)
            put(icx + y, icy + x)
            put(icx - y, icy + x)
            put(icx - x, icy + y)
            put(icx - x, icy - y)
            put(icx - y, icy - x)
            put(icx + y, icy - x)
            put(icx + x, icy - y)
            y += 1
            err += 1 + 2 * y
            if 2 * (err - x) + 1 > 0:
                x -= 1
                err += 1 - 2 * x

    def _draw_horizontal_band(
        self,
        raster: _Raster,
        y_top: float,
        y_bottom: float,
        cx: float,
        rx: float,
        color: tuple[int, int, int],
    ) -> None:
        pr, pg, pb = color
        w, h = raster.width, raster.height
        x0 = max(0, math.floor(cx - rx))
        x1 = min(w - 1, math.ceil(cx + rx))
        y0 = max(0, math.ceil(y_top))
        y1 = min(h - 1, math.floor(y_bottom))
        rx2 = rx * rx
        band_cy = (y_top + y_bottom) / 2.0
        for y in range(y0, y1 + 1):
            dy = y - band_cy
            row = (y * w) * 3
            for x in range(x0, x1 + 1):
                dx = x - cx
                if dx * dx + dy * dy > rx2:
                    continue
                idx = row + x * 3
                raster.pixels[idx] = pr
                raster.pixels[idx + 1] = pg
                raster.pixels[idx + 2] = pb

    def _draw_arc(
        self,
        raster: _Raster,
        cx: float,
        cy: float,
        width: float,
        curve: float,
        color: tuple[int, int, int],
        thickness: int,
    ) -> None:
        """Draw a smile/frown arc as a thin filled strip.

        ``curve`` is positive for a frown, negative for a smile. The
        arc is sampled at many x positions and a small vertical strip
        of ``thickness`` pixels is drawn.
        """
        if abs(curve) < 0.5:
            # Treat as a horizontal line
            y = int(cy)
            for x in range(int(cx - width / 2), int(cx + width / 2) + 1):
                for t in range(thickness):
                    py = y - thickness // 2 + t
                    if 0 <= x < raster.width and 0 <= py < raster.height:
                        idx = (py * raster.width + x) * 3
                        raster.pixels[idx] = color[0]
                        raster.pixels[idx + 1] = color[1]
                        raster.pixels[idx + 2] = color[2]
            return
        # Parametric arc: y = cy + curve * (1 - ((x-cx) / (width/2)) ** 2)
        steps: int = max(8, round(width))
        half: float = width / 2.0
        if half <= 0.0:
            return
        cx_f: float = float(cx)
        cy_f: float = float(cy)
        curve_f: float = float(curve)
        for i in range(steps + 1):
            x_f: float = cx_f - half + (i / steps) * width
            t_f: float = (x_f - cx_f) / half
            y_f: float = cy_f - curve_f * (1 - t_f * t_f)
            for k in range(-thickness // 2, thickness // 2 + 1):
                px, py = round(x_f), round(y_f + k)
                if 0 <= px < raster.width and 0 <= py < raster.height:
                    idx = (py * raster.width + px) * 3
                    raster.pixels[idx] = color[0]
                    raster.pixels[idx + 1] = color[1]
                    raster.pixels[idx + 2] = color[2]

    def _draw_thick_line(
        self,
        raster: _Raster,
        x0: float,
        y0: float,
        x1: float,
        y1: float,
        thickness: int,
        color: tuple[int, int, int],
    ) -> None:
        # Bresenham with a brush
        steps = max(2, int(max(abs(x1 - x0), abs(y1 - y0)) * 2))
        for i in range(steps + 1):
            t = i / steps
            x = x0 + (x1 - x0) * t
            y = y0 + (y1 - y0) * t
            for dx in range(-thickness // 2, thickness // 2 + 1):
                for dy in range(-thickness // 2, thickness // 2 + 1):
                    px, py = round(x + dx), round(y + dy)
                    if 0 <= px < raster.width and 0 <= py < raster.height:
                        idx = (py * raster.width + px) * 3
                        raster.pixels[idx] = color[0]
                        raster.pixels[idx + 1] = color[1]
                        raster.pixels[idx + 2] = color[2]

    def _fill_diamond(
        self,
        raster: _Raster,
        cx: float,
        cy: float,
        size: float,
        color: tuple[int, int, int],
    ) -> None:
        self._fill_ellipse(raster, cx, cy, size * 0.45, size, color)

    def _fill_heart(
        self,
        raster: _Raster,
        cx: float,
        cy: float,
        size: float,
        color: tuple[int, int, int],
    ) -> None:
        # Two small circles + a downward triangle
        r = size * 0.45
        self._fill_circle(raster, cx - r * 0.6, cy - r * 0.3, r, color)
        self._fill_circle(raster, cx + r * 0.6, cy - r * 0.3, r, color)
        # Triangle (approximated with a rotated square)
        for y in range(int(cy - r * 0.3), int(cy + size * 0.7) + 1):
            t = (y - (cy - r * 0.3)) / (size + 0.2 * r)
            t = max(0.0, min(1.0, t))
            half = size * 0.6 * (1.0 - t)
            for x in range(int(cx - half), int(cx + half) + 1):
                if 0 <= x < raster.width and 0 <= y < raster.height:
                    idx = (y * raster.width + x) * 3
                    raster.pixels[idx] = color[0]
                    raster.pixels[idx + 1] = color[1]
                    raster.pixels[idx + 2] = color[2]

    def _fill_teardrop(
        self,
        raster: _Raster,
        cx: float,
        cy: float,
        size: float,
        color: tuple[int, int, int],
    ) -> None:
        # Circle + triangle pointing down
        r = size * 0.4
        self._fill_circle(raster, cx, cy - size * 0.3, r, color)
        for y in range(int(cy - size * 0.3), int(cy + size * 0.6) + 1):
            t = (y - (cy - size * 0.3)) / (size * 0.9)
            t = max(0.0, min(1.0, t))
            half = size * 0.4 * (1.0 - t)
            for x in range(int(cx - half), int(cx + half) + 1):
                if 0 <= x < raster.width and 0 <= y < raster.height:
                    idx = (y * raster.width + x) * 3
                    raster.pixels[idx] = color[0]
                    raster.pixels[idx + 1] = color[1]
                    raster.pixels[idx + 2] = color[2]

    def _draw_mustache(
        self,
        raster: _Raster,
        cx: float,
        cy: float,
        length: float,
        color: tuple[int, int, int],
    ) -> None:
        # Two curves meeting in the middle
        for sx in (-1, 1):
            self._draw_arc(
                raster,
                cx + sx * length * 0.30,
                cy - sx * length * 0.05,
                length * 0.6,
                -length * 0.10 * sx,
                color,
                3,
            )

    def _draw_bow_tie(
        self,
        raster: _Raster,
        cx: float,
        cy: float,
        size: float,
        color: tuple[int, int, int],
    ) -> None:
        # Two triangles
        for sx in (-1, 1):
            for y in range(int(cy - size / 2), int(cy + size / 2) + 1):
                t = (y - (cy - size / 2)) / size
                half = size * 0.4 * (1.0 - abs(t - 0.5) * 2)
                x_start = cx + sx * size * 0.05
                x_end = x_start + sx * half
                for x in range(int(min(x_start, x_end)), int(max(x_start, x_end)) + 1):
                    if 0 <= x < raster.width and 0 <= y < raster.height:
                        idx = (y * raster.width + x) * 3
                        raster.pixels[idx] = color[0]
                        raster.pixels[idx + 1] = color[1]
                        raster.pixels[idx + 2] = color[2]

    def _draw_crown(
        self,
        raster: _Raster,
        cx: float,
        cy: float,
        length: float,
        color: tuple[int, int, int],
    ) -> None:
        # Three triangles
        points = [
            (cx - length / 2, cy),
            (cx - length / 4, cy - length / 3),
            (cx, cy),
            (cx + length / 4, cy - length / 3),
            (cx + length / 2, cy),
            (cx + length / 2, cy + length / 6),
            (cx - length / 2, cy + length / 6),
        ]
        for i in range(len(points) - 1):
            self._draw_thick_line(
                raster,
                points[i][0],
                points[i][1],
                points[i + 1][0],
                points[i + 1][1],
                2,
                color,
            )

height property

width property

__init__(width=240, height=240)

Source code in src/robot/face/renderer.py
def __init__(self, width: int = 240, height: int = 240) -> None:
    if width <= 0 or height <= 0:
        raise ValueError("width and height must be > 0")
    self._width = width
    self._height = height

render(model)

Render model into a new RGB888 frame.

Source code in src/robot/face/renderer.py
def render(self, model: FaceModel) -> EyeFrame:
    """Render ``model`` into a new RGB888 frame."""
    if model.width != self._width or model.height != self._height:
        raise ValueError(
            f"model is {model.width}x{model.height}, renderer is {self._width}x{self._height}"
        )
    raster = self._new_raster()
    # Vector mode bypasses the full face stack and renders only the
    # minimalist "two glowing squares + a horizontal line" used by the
    # Anki Vector 2.0 face. Cheeks/eyebrows/iris/sclera are skipped
    # because the Vector palette does not use them.
    if model.palette.mode == PALETTE_MODE_VECTOR:
        self._draw_background(raster, model)
        self._draw_vector_eyes(raster, model)
        self._draw_vector_mouth(raster, model)
        return EyeFrame(width=self._width, height=self._height, pixels=bytes(raster.pixels))
    self._draw_background(raster, model)
    self._draw_cheeks(raster, model)
    self._draw_sclera(raster, model)
    self._draw_eyelids(raster, model)
    self._draw_iris(raster, model)
    self._draw_pupil(raster, model)
    self._draw_highlight(raster, model)
    self._draw_eyebrows(raster, model)
    self._draw_mouth(raster, model)
    self._draw_overlay(raster, model)
    self._draw_accessory(raster, model)
    return EyeFrame(width=self._width, height=self._height, pixels=bytes(raster.pixels))

MouthShape

Bases: str, Enum

Source code in src/robot/face/components.py
class MouthShape(str, Enum):
    CLOSED = "closed"
    NEUTRAL = "neutral"
    SMILE = "smile"
    GRIN = "grin"
    FROWN = "frown"
    OPEN = "open"  # small "oh"
    WIDE_OPEN = "wide_open"  # gasp / surprise
    TONGUE = "tongue"  # playful
    SMILE_OPEN = "smile_open"  # laughing

CLOSED = 'closed' class-attribute instance-attribute

FROWN = 'frown' class-attribute instance-attribute

GRIN = 'grin' class-attribute instance-attribute

NEUTRAL = 'neutral' class-attribute instance-attribute

OPEN = 'open' class-attribute instance-attribute

SMILE = 'smile' class-attribute instance-attribute

SMILE_OPEN = 'smile_open' class-attribute instance-attribute

TONGUE = 'tongue' class-attribute instance-attribute

WIDE_OPEN = 'wide_open' class-attribute instance-attribute

OverlayKind

Bases: str, Enum

Source code in src/robot/face/components.py
class OverlayKind(str, Enum):
    NONE = "none"
    SPARKLE = "sparkle"
    HEART = "heart"
    TEAR = "tear"
    SWEAT = "sweat"
    ANGER = "anger"  # vein symbol
    QUESTION = "question"  # "?" mark
    EXCLAIM = "exclaim"  # "!" mark
    MUSIC = "music"  # note
    STAR = "star"

ANGER = 'anger' class-attribute instance-attribute

EXCLAIM = 'exclaim' class-attribute instance-attribute

HEART = 'heart' class-attribute instance-attribute

MUSIC = 'music' class-attribute instance-attribute

NONE = 'none' class-attribute instance-attribute

QUESTION = 'question' class-attribute instance-attribute

SPARKLE = 'sparkle' class-attribute instance-attribute

STAR = 'star' class-attribute instance-attribute

SWEAT = 'sweat' class-attribute instance-attribute

TEAR = 'tear' class-attribute instance-attribute

_Raster dataclass

A mutable RGB888 image buffer.

Source code in src/robot/face/renderer.py
@dataclass(slots=True)
class _Raster:
    """A mutable RGB888 image buffer."""

    width: int
    height: int
    pixels: bytearray = field(default_factory=bytearray)

    def __post_init__(self) -> None:
        if self.width <= 0 or self.height <= 0:
            raise ValueError("width and height must be > 0")
        if not self.pixels:
            self.pixels = bytearray(self.width * self.height * 3)

height instance-attribute

pixels = field(default_factory=bytearray) class-attribute instance-attribute

width instance-attribute

__init__(width, height, pixels=bytearray())

__post_init__()

Source code in src/robot/face/renderer.py
def __post_init__(self) -> None:
    if self.width <= 0 or self.height <= 0:
        raise ValueError("width and height must be > 0")
    if not self.pixels:
        self.pixels = bytearray(self.width * self.height * 3)

Animator

robot.face.animator

The :class:FaceAnimator - drives the face at 30 FPS.

This is the high-level component the application boots. It owns:

  • the per-eye :class:EyeAnimator (the existing state machine),
  • a :class:FaceRenderer,
  • a single :class:Display (one circular TFT),
  • the active :class:Theme.

It runs at 30 FPS (configurable), produces one :class:FaceModel per frame, applies the theme, renders to an :class:EyeFrame, and pushes it to the display.

Animations are driven by timelines built on the existing :mod:robot.animation framework (easing + parallel + queue + easing). The animator exposes small explicit commands (blink, smile, …) and each command internally composes a :class:Timeline that drives the intermediate :class:FaceModel snapshots.

__all__ = ['FaceAnimator'] module-attribute

_log = get_logger('face.animator') module-attribute

Cheeks dataclass

Cheek rendering - base + accent colour, intensity.

Source code in src/robot/face/components.py
@dataclass(slots=True, frozen=True)
class Cheeks:
    """Cheek rendering - base + accent colour, intensity."""

    state: CheekState = CheekState.NONE
    intensity: float = 0.0  # 0..1

intensity = 0.0 class-attribute instance-attribute

state = CheekState.NONE class-attribute instance-attribute

__init__(state=CheekState.NONE, intensity=0.0)

Clock

Bases: Protocol

Minimal time abstraction.

Source code in src/robot/utils/clock.py
class Clock(Protocol):
    """Minimal time abstraction."""

    def now(self) -> datetime:
        """Return the current wall-clock time (UTC)."""

    def monotonic(self) -> float:
        """Return a strictly monotonic time in seconds."""

    async def sleep(self, seconds: float) -> None:
        """Sleep for the given number of seconds."""

monotonic()

Return a strictly monotonic time in seconds.

Source code in src/robot/utils/clock.py
def monotonic(self) -> float:
    """Return a strictly monotonic time in seconds."""

now()

Return the current wall-clock time (UTC).

Source code in src/robot/utils/clock.py
def now(self) -> datetime:
    """Return the current wall-clock time (UTC)."""

sleep(seconds) async

Sleep for the given number of seconds.

Source code in src/robot/utils/clock.py
async def sleep(self, seconds: float) -> None:
    """Sleep for the given number of seconds."""

Display

Bases: Protocol

A single display the eye engine can render to.

Source code in src/robot/interfaces/display.py
@runtime_checkable
class Display(Protocol):
    """A single display the eye engine can render to."""

    @property
    def width(self) -> int:
        """Width of the framebuffer in pixels."""

    @property
    def height(self) -> int:
        """Height of the framebuffer in pixels."""

    async def show(self, frame: EyeFrame) -> None:
        """Push a frame to the panel."""

    async def fill(self, color: tuple[int, int, int]) -> None:
        """Fill the entire panel with a single RGB color."""

    async def clear(self) -> None:
        """Reset the panel to black."""

    async def close(self) -> None:
        """Release hardware resources."""

height property

Height of the framebuffer in pixels.

width property

Width of the framebuffer in pixels.

clear() async

Reset the panel to black.

Source code in src/robot/interfaces/display.py
async def clear(self) -> None:
    """Reset the panel to black."""

close() async

Release hardware resources.

Source code in src/robot/interfaces/display.py
async def close(self) -> None:
    """Release hardware resources."""

fill(color) async

Fill the entire panel with a single RGB color.

Source code in src/robot/interfaces/display.py
async def fill(self, color: tuple[int, int, int]) -> None:
    """Fill the entire panel with a single RGB color."""

show(frame) async

Push a frame to the panel.

Source code in src/robot/interfaces/display.py
async def show(self, frame: EyeFrame) -> None:
    """Push a frame to the panel."""

EmotionEngine

Produces :class:FaceModel + :class:BodyLanguageHint from an emotion.

Source code in src/robot/face/emotions.py
class EmotionEngine:
    """Produces :class:`FaceModel` + :class:`BodyLanguageHint` from an emotion."""

    def __init__(
        self, palette: FacePalette | None = None, width: int = 240, height: int = 240
    ) -> None:
        self._palette = palette or FacePalette()
        self._width = width
        self._height = height

    def set_dimensions(self, width: int, height: int) -> None:
        self._width = width
        self._height = height

    def available(self) -> list[str]:
        return list(EMOTION_DEFS.keys())

    def get(self, name: str) -> _EmotionDef:
        try:
            return EMOTION_DEFS[name]
        except KeyError as exc:
            raise KeyError(
                f"unknown emotion {name!r}; available: {sorted(EMOTION_DEFS.keys())}"
            ) from exc

    def build(self, name: str) -> FaceModel:
        """Build the :class:`FaceModel` for ``name`` with default geometry."""
        d = self.get(name)
        left_eye, right_eye = d.eyes
        left_brow, right_brow = d.eyebrows
        return FaceModel(
            width=self._width,
            height=self._height,
            left_eye=left_eye,
            right_eye=right_eye,
            eyelids=d.eyelids,
            left_eyebrow=left_brow,
            right_eyebrow=right_brow,
            mouth=d.mouth,
            cheeks=d.cheeks,
            overlay=d.overlay,
            palette=self._palette,
            body_hint=d.body_hint,
        )

    def register(self, name: str, definition: _EmotionDef) -> None:
        """Register a new emotion or override an existing one."""
        EMOTION_DEFS[name] = definition

__init__(palette=None, width=240, height=240)

Source code in src/robot/face/emotions.py
def __init__(
    self, palette: FacePalette | None = None, width: int = 240, height: int = 240
) -> None:
    self._palette = palette or FacePalette()
    self._width = width
    self._height = height

available()

Source code in src/robot/face/emotions.py
def available(self) -> list[str]:
    return list(EMOTION_DEFS.keys())

build(name)

Build the :class:FaceModel for name with default geometry.

Source code in src/robot/face/emotions.py
def build(self, name: str) -> FaceModel:
    """Build the :class:`FaceModel` for ``name`` with default geometry."""
    d = self.get(name)
    left_eye, right_eye = d.eyes
    left_brow, right_brow = d.eyebrows
    return FaceModel(
        width=self._width,
        height=self._height,
        left_eye=left_eye,
        right_eye=right_eye,
        eyelids=d.eyelids,
        left_eyebrow=left_brow,
        right_eyebrow=right_brow,
        mouth=d.mouth,
        cheeks=d.cheeks,
        overlay=d.overlay,
        palette=self._palette,
        body_hint=d.body_hint,
    )

get(name)

Source code in src/robot/face/emotions.py
def get(self, name: str) -> _EmotionDef:
    try:
        return EMOTION_DEFS[name]
    except KeyError as exc:
        raise KeyError(
            f"unknown emotion {name!r}; available: {sorted(EMOTION_DEFS.keys())}"
        ) from exc

register(name, definition)

Register a new emotion or override an existing one.

Source code in src/robot/face/emotions.py
def register(self, name: str, definition: _EmotionDef) -> None:
    """Register a new emotion or override an existing one."""
    EMOTION_DEFS[name] = definition

set_dimensions(width, height)

Source code in src/robot/face/emotions.py
def set_dimensions(self, width: int, height: int) -> None:
    self._width = width
    self._height = height

Eye dataclass

A single eye. The face has two of them.

Source code in src/robot/face/components.py
@dataclass(slots=True, frozen=True)
class Eye:
    """A single eye. The face has two of them."""

    gaze: Gaze = field(default_factory=Gaze)
    openness: float = 1.0  # 0.0 = closed, 1.0 = wide
    pupil_dilation: float = 0.5  # 0.0 = constricted, 1.0 = dilated
    highlight: Gaze = field(default_factory=lambda: Gaze(0.3, 0.3))
    asymmetric: bool = False  # for character expressions

asymmetric = False class-attribute instance-attribute

gaze = field(default_factory=Gaze) class-attribute instance-attribute

highlight = field(default_factory=lambda: Gaze(0.3, 0.3)) class-attribute instance-attribute

openness = 1.0 class-attribute instance-attribute

pupil_dilation = 0.5 class-attribute instance-attribute

__init__(gaze=Gaze(), openness=1.0, pupil_dilation=0.5, highlight=(lambda: Gaze(0.3, 0.3))(), asymmetric=False)

EyeAnimator

State machine that produces :class:EyeRenderState for one eye.

The animator exposes a small, explicit API. Every method that changes state is a "command" - the actual movement happens over the next several frames, interpolated smoothly.

Use :meth:step to advance one frame; the caller (a :class:DualEyeAnimator or a test) decides the frame interval.

Source code in src/robot/eye_engine/animation.py
class EyeAnimator:
    """State machine that produces :class:`EyeRenderState` for one eye.

    The animator exposes a small, explicit API. Every method that changes
    state is a "command" - the actual movement happens over the next
    several frames, interpolated smoothly.

    Use :meth:`step` to advance one frame; the caller (a
    :class:`DualEyeAnimator` or a test) decides the frame interval.
    """

    DEFAULT_FPS: Final[int] = 30

    def __init__(
        self,
        side: EyeSide,
        width: int = 240,
        height: int = 240,
        fps: int = DEFAULT_FPS,
    ) -> None:
        if fps <= 0:
            raise ValueError("fps must be > 0")
        self.side = side
        self._width = width
        self._height = height
        self._fps = fps
        self._frame_interval = 1.0 / fps
        self._eye_radius = float(min(width, height)) * 0.42

        # Current / target state
        self._gaze_x = 0.0
        self._gaze_y = 0.0
        self._gaze_target = _GazeTarget(0.0, 0.0, 0.0)
        self._openness = 1.0
        self._pupil_dilation = 0.5
        self._lid_top = 0.0
        self._lid_bottom = 0.0
        self._highlight_x = 0.3
        self._highlight_y = 0.3
        self._emotion: EmotionName = EmotionName.NEUTRAL
        self._intensity: float = 1.0

        # Animation state
        self._kind: _AnimKind = _AnimKind.IDLE
        self._anim_time: float = 0.0  # seconds since the animation started
        self._just_completed: bool = False  # set when an animation finishes this frame
        self._blink_def: _BlinkDef = _BlinkDef()
        self._pending_double_blink: bool = False
        self._gaze_origin: tuple[float, float] = (0.0, 0.0)
        self._gaze_duration: float = 0.0
        # Wink uses lid_top/lid_bottom driven from "wink" without affecting gaze
        self._wink_time: float = 0.0
        self._wink_duration: float = 0.0
        # Frame count + last render for diagnostics
        self._frame_count: int = 0

    # ------------------------------------------------------------------ properties
    @property
    def emotion(self) -> EmotionName:
        return self._emotion

    @property
    def openness(self) -> float:
        return self._openness

    @property
    def frame_count(self) -> int:
        return self._frame_count

    @property
    def width(self) -> int:
        return self._width

    @property
    def height(self) -> int:
        return self._height

    # ------------------------------------------------------------------ public commands
    def blink(self) -> None:
        """Trigger a single blink (interrupts any current blink)."""
        self._kind = _AnimKind.BLINK
        self._anim_time = 0.0
        self._blink_def = _BlinkDef()
        self._pending_double_blink = False

    def double_blink(self) -> None:
        """Trigger two quick blinks in succession."""
        self._kind = _AnimKind.DOUBLE_BLINK
        self._anim_time = 0.0
        self._blink_def = _BlinkDef(closing_s=0.05, closed_s=0.015, opening_s=0.08)
        self._pending_double_blink = True

    def wink(self) -> None:
        """Close this eye briefly while the other eye stays open (independent mode)."""
        self._kind = _AnimKind.WINK
        self._wink_time = 0.0
        self._wink_duration = 0.30

    def look(self, x: float, y: float, duration_s: float = 0.25) -> None:
        """Smoothly move the gaze to ``(x, y)`` over ``duration_s`` seconds.

        ``x`` and ``y`` are in ``[-1, 1]``.
        """
        x = max(-1.0, min(1.0, x))
        y = max(-1.0, min(1.0, y))
        self._gaze_origin = (self._gaze_x, self._gaze_y)
        self._gaze_duration = max(0.0, duration_s)
        self._gaze_target = _GazeTarget(x, y, duration_s)
        self._kind = _AnimKind.LOOK
        self._anim_time = 0.0

    def look_left(self, duration_s: float = 0.25) -> None:
        self.look(-1.0, 0.0, duration_s)

    def look_right(self, duration_s: float = 0.25) -> None:
        self.look(1.0, 0.0, duration_s)

    def look_up(self, duration_s: float = 0.25) -> None:
        self.look(0.0, -1.0, duration_s)

    def look_down(self, duration_s: float = 0.25) -> None:
        self.look(0.0, 1.0, duration_s)

    def look_center(self, duration_s: float = 0.25) -> None:
        self.look(0.0, 0.0, duration_s)

    def set_emotion(self, emotion: EmotionName, intensity: float = 1.0) -> None:
        """Set the resting emotion (overrides eyelid/iris defaults)."""
        self._emotion = emotion
        self._intensity = max(0.0, min(1.0, intensity))
        d = emotion_def(emotion)
        # Snap the resting values to the emotion
        self._openness = d.openness
        self._pupil_dilation = d.pupil_dilation
        self._lid_top = d.lid_top
        self._lid_bottom = d.lid_bottom
        self._highlight_x = d.highlight[0]
        self._highlight_y = d.highlight[1]
        # A non-blink/gaze animation can stay running; the next step will
        # ease gaze back to the emotion default.
        if self._kind not in (_AnimKind.BLINK, _AnimKind.DOUBLE_BLINK, _AnimKind.WINK):
            self.look(d.gaze[0], d.gaze[1], duration_s=0.4)

    def drift(self, amplitude: float = 0.15, speed: float = 0.6) -> None:
        """Apply a slow, smooth gaze drift.

        Call this once per frame from the caller; it advances an internal
        phase. The drift is sinusoidal and looks like an idle glance
        around the current gaze target.
        """
        phase = self._frame_count * speed * self._frame_interval
        # Lissajous-ish figure-eight for a "looking around" feel
        ox = math.sin(phase) * amplitude
        oy = math.sin(phase * 1.7) * amplitude * 0.6
        # Read the current gaze target from the last LOOK command
        tx, ty = self._gaze_target.x, self._gaze_target.y
        # Drift around the target but clamp
        x = max(-1.0, min(1.0, tx + ox))
        y = max(-1.0, min(1.0, ty + oy))
        # Drift is non-interrupting - we don't change _kind.
        self._gaze_x = x
        self._gaze_y = y

    def reset(self) -> None:
        """Stop any running animation and return to the neutral state."""
        self._kind = _AnimKind.IDLE
        self._anim_time = 0.0
        self._pending_double_blink = False
        self._wink_time = 0.0
        self._just_completed = False
        self._emotion = EmotionName.NEUTRAL
        self._intensity = 1.0
        d = _EMOTIONS[EmotionName.NEUTRAL]
        self._gaze_x = d.gaze[0]
        self._gaze_y = d.gaze[1]
        self._openness = d.openness
        self._pupil_dilation = d.pupil_dilation
        self._lid_top = d.lid_top
        self._lid_bottom = d.lid_bottom
        self._highlight_x = d.highlight[0]
        self._highlight_y = d.highlight[1]

    # ------------------------------------------------------------------ step / render
    def step(self) -> EyeRenderState:
        """Advance one frame and return the current render state."""
        dt = self._frame_interval
        self._frame_count += 1

        if self._kind is _AnimKind.BLINK:
            self._advance_blink(dt, double=False)
        elif self._kind is _AnimKind.DOUBLE_BLINK:
            self._advance_blink(dt, double=True)
        elif self._kind is _AnimKind.LOOK:
            self._advance_look(dt)
        elif self._kind is _AnimKind.WINK:
            self._advance_wink(dt)

        # If no gaze animation is running, ease gaze gently toward the
        # emotion default so the eye settles after a Look command.
        # If no gaze animation is running, ease gaze gently toward the
        # emotion default so the eye settles after a Look command - but
        # not on the frame the look just completed (otherwise the target
        # would be partially undone immediately).
        just_finished = self._just_completed
        self._just_completed = False
        if self._kind is not _AnimKind.LOOK and not just_finished:
            d = emotion_def(self._emotion)
            self._gaze_x = self._lerp(self._gaze_x, d.gaze[0], 0.05)
            self._gaze_y = self._lerp(self._gaze_y, d.gaze[1], 0.05)

        return self.render_state()

    def render_state(self) -> EyeRenderState:
        """Return the current :class:`EyeRenderState` without advancing."""
        return EyeRenderState(
            cx=self._width / 2.0,
            cy=self._height / 2.0,
            eye_radius=self._eye_radius,
            openness=self._openness,
            lid_top=self._lid_top,
            lid_bottom=self._lid_bottom,
            gaze_x=self._gaze_x,
            gaze_y=self._gaze_y,
            pupil_dilation=self._pupil_dilation,
            highlight_x=self._highlight_x,
            highlight_y=self._highlight_y,
        )

    # ------------------------------------------------------------------ internal
    def _advance_blink(self, dt: float, *, double: bool) -> None:
        bd = self._blink_def
        total = bd.closing_s + bd.closed_s + bd.opening_s
        if double:
            total = 2 * total + 0.05  # gap between the two blinks
        self._anim_time += dt
        t = self._anim_time

        if double:
            # Split the timeline into two blinks with a small gap.
            blink_total = bd.closing_s + bd.closed_s + bd.opening_s
            cycle = blink_total + 0.05
            phase_t = t % cycle if t < cycle * 2 else t
            if phase_t < blink_total:
                self._openness = self._blink_curve(phase_t, bd)
            else:
                self._openness = 1.0  # gap
            if t >= 2 * blink_total + 0.05:
                self._kind = _AnimKind.IDLE
                self._anim_time = 0.0
                self._openness = 1.0
                self._just_completed = True
        elif t < bd.closing_s:
            p = t / bd.closing_s
            self._openness = 1.0 - p * p  # ease-in to 0
        elif t < bd.closing_s + bd.closed_s:
            self._openness = 0.0
        elif t < total:
            p = (t - bd.closing_s - bd.closed_s) / bd.opening_s
            self._openness = p * (2.0 - p)  # ease-out to 1
        else:
            self._openness = 1.0
            self._kind = _AnimKind.IDLE
            self._anim_time = 0.0
            self._just_completed = True

    @staticmethod
    def _blink_curve(t: float, bd: _BlinkDef) -> float:
        if t < bd.closing_s:
            p = t / bd.closing_s
            return 1.0 - p * p
        if t < bd.closing_s + bd.closed_s:
            return 0.0
        p = (t - bd.closing_s - bd.closed_s) / bd.opening_s
        return p * (2.0 - p)

    def _advance_look(self, dt: float) -> None:
        self._anim_time += dt
        if self._gaze_duration <= 0.0:
            self._gaze_x, self._gaze_y = self._gaze_target.x, self._gaze_target.y
            self._kind = _AnimKind.IDLE
            self._just_completed = True
            return
        t = min(1.0, self._anim_time / self._gaze_duration)
        # Smoothstep easing
        eased = t * t * (3.0 - 2.0 * t)
        ox, oy = self._gaze_origin
        self._gaze_x = ox + (self._gaze_target.x - ox) * eased
        self._gaze_y = oy + (self._gaze_target.y - oy) * eased
        if t >= 1.0:
            self._kind = _AnimKind.IDLE
            self._anim_time = 0.0
            self._just_completed = True

    def _advance_wink(self, dt: float) -> None:
        self._wink_time += dt
        total = self._wink_duration
        half = total / 2.0
        if self._wink_time < half:
            p = self._wink_time / half
            self._lid_top = 0.6 * p
        elif self._wink_time < total:
            p = (self._wink_time - half) / half
            self._lid_top = 0.6 * (1.0 - p)
        else:
            self._lid_top = 0.0
            self._kind = _AnimKind.IDLE
            self._just_completed = True

    @staticmethod
    def _lerp(a: float, b: float, t: float) -> float:
        return a + (b - a) * t

DEFAULT_FPS = 30 class-attribute instance-attribute

emotion property

frame_count property

height property

openness property

side = side instance-attribute

width property

__init__(side, width=240, height=240, fps=DEFAULT_FPS)

Source code in src/robot/eye_engine/animation.py
def __init__(
    self,
    side: EyeSide,
    width: int = 240,
    height: int = 240,
    fps: int = DEFAULT_FPS,
) -> None:
    if fps <= 0:
        raise ValueError("fps must be > 0")
    self.side = side
    self._width = width
    self._height = height
    self._fps = fps
    self._frame_interval = 1.0 / fps
    self._eye_radius = float(min(width, height)) * 0.42

    # Current / target state
    self._gaze_x = 0.0
    self._gaze_y = 0.0
    self._gaze_target = _GazeTarget(0.0, 0.0, 0.0)
    self._openness = 1.0
    self._pupil_dilation = 0.5
    self._lid_top = 0.0
    self._lid_bottom = 0.0
    self._highlight_x = 0.3
    self._highlight_y = 0.3
    self._emotion: EmotionName = EmotionName.NEUTRAL
    self._intensity: float = 1.0

    # Animation state
    self._kind: _AnimKind = _AnimKind.IDLE
    self._anim_time: float = 0.0  # seconds since the animation started
    self._just_completed: bool = False  # set when an animation finishes this frame
    self._blink_def: _BlinkDef = _BlinkDef()
    self._pending_double_blink: bool = False
    self._gaze_origin: tuple[float, float] = (0.0, 0.0)
    self._gaze_duration: float = 0.0
    # Wink uses lid_top/lid_bottom driven from "wink" without affecting gaze
    self._wink_time: float = 0.0
    self._wink_duration: float = 0.0
    # Frame count + last render for diagnostics
    self._frame_count: int = 0

Trigger a single blink (interrupts any current blink).

Source code in src/robot/eye_engine/animation.py
def blink(self) -> None:
    """Trigger a single blink (interrupts any current blink)."""
    self._kind = _AnimKind.BLINK
    self._anim_time = 0.0
    self._blink_def = _BlinkDef()
    self._pending_double_blink = False

Trigger two quick blinks in succession.

Source code in src/robot/eye_engine/animation.py
def double_blink(self) -> None:
    """Trigger two quick blinks in succession."""
    self._kind = _AnimKind.DOUBLE_BLINK
    self._anim_time = 0.0
    self._blink_def = _BlinkDef(closing_s=0.05, closed_s=0.015, opening_s=0.08)
    self._pending_double_blink = True

drift(amplitude=0.15, speed=0.6)

Apply a slow, smooth gaze drift.

Call this once per frame from the caller; it advances an internal phase. The drift is sinusoidal and looks like an idle glance around the current gaze target.

Source code in src/robot/eye_engine/animation.py
def drift(self, amplitude: float = 0.15, speed: float = 0.6) -> None:
    """Apply a slow, smooth gaze drift.

    Call this once per frame from the caller; it advances an internal
    phase. The drift is sinusoidal and looks like an idle glance
    around the current gaze target.
    """
    phase = self._frame_count * speed * self._frame_interval
    # Lissajous-ish figure-eight for a "looking around" feel
    ox = math.sin(phase) * amplitude
    oy = math.sin(phase * 1.7) * amplitude * 0.6
    # Read the current gaze target from the last LOOK command
    tx, ty = self._gaze_target.x, self._gaze_target.y
    # Drift around the target but clamp
    x = max(-1.0, min(1.0, tx + ox))
    y = max(-1.0, min(1.0, ty + oy))
    # Drift is non-interrupting - we don't change _kind.
    self._gaze_x = x
    self._gaze_y = y

look(x, y, duration_s=0.25)

Smoothly move the gaze to (x, y) over duration_s seconds.

x and y are in [-1, 1].

Source code in src/robot/eye_engine/animation.py
def look(self, x: float, y: float, duration_s: float = 0.25) -> None:
    """Smoothly move the gaze to ``(x, y)`` over ``duration_s`` seconds.

    ``x`` and ``y`` are in ``[-1, 1]``.
    """
    x = max(-1.0, min(1.0, x))
    y = max(-1.0, min(1.0, y))
    self._gaze_origin = (self._gaze_x, self._gaze_y)
    self._gaze_duration = max(0.0, duration_s)
    self._gaze_target = _GazeTarget(x, y, duration_s)
    self._kind = _AnimKind.LOOK
    self._anim_time = 0.0

look_center(duration_s=0.25)

Source code in src/robot/eye_engine/animation.py
def look_center(self, duration_s: float = 0.25) -> None:
    self.look(0.0, 0.0, duration_s)

look_down(duration_s=0.25)

Source code in src/robot/eye_engine/animation.py
def look_down(self, duration_s: float = 0.25) -> None:
    self.look(0.0, 1.0, duration_s)

look_left(duration_s=0.25)

Source code in src/robot/eye_engine/animation.py
def look_left(self, duration_s: float = 0.25) -> None:
    self.look(-1.0, 0.0, duration_s)

look_right(duration_s=0.25)

Source code in src/robot/eye_engine/animation.py
def look_right(self, duration_s: float = 0.25) -> None:
    self.look(1.0, 0.0, duration_s)

look_up(duration_s=0.25)

Source code in src/robot/eye_engine/animation.py
def look_up(self, duration_s: float = 0.25) -> None:
    self.look(0.0, -1.0, duration_s)

render_state()

Return the current :class:EyeRenderState without advancing.

Source code in src/robot/eye_engine/animation.py
def render_state(self) -> EyeRenderState:
    """Return the current :class:`EyeRenderState` without advancing."""
    return EyeRenderState(
        cx=self._width / 2.0,
        cy=self._height / 2.0,
        eye_radius=self._eye_radius,
        openness=self._openness,
        lid_top=self._lid_top,
        lid_bottom=self._lid_bottom,
        gaze_x=self._gaze_x,
        gaze_y=self._gaze_y,
        pupil_dilation=self._pupil_dilation,
        highlight_x=self._highlight_x,
        highlight_y=self._highlight_y,
    )

reset()

Stop any running animation and return to the neutral state.

Source code in src/robot/eye_engine/animation.py
def reset(self) -> None:
    """Stop any running animation and return to the neutral state."""
    self._kind = _AnimKind.IDLE
    self._anim_time = 0.0
    self._pending_double_blink = False
    self._wink_time = 0.0
    self._just_completed = False
    self._emotion = EmotionName.NEUTRAL
    self._intensity = 1.0
    d = _EMOTIONS[EmotionName.NEUTRAL]
    self._gaze_x = d.gaze[0]
    self._gaze_y = d.gaze[1]
    self._openness = d.openness
    self._pupil_dilation = d.pupil_dilation
    self._lid_top = d.lid_top
    self._lid_bottom = d.lid_bottom
    self._highlight_x = d.highlight[0]
    self._highlight_y = d.highlight[1]

set_emotion(emotion, intensity=1.0)

Set the resting emotion (overrides eyelid/iris defaults).

Source code in src/robot/eye_engine/animation.py
def set_emotion(self, emotion: EmotionName, intensity: float = 1.0) -> None:
    """Set the resting emotion (overrides eyelid/iris defaults)."""
    self._emotion = emotion
    self._intensity = max(0.0, min(1.0, intensity))
    d = emotion_def(emotion)
    # Snap the resting values to the emotion
    self._openness = d.openness
    self._pupil_dilation = d.pupil_dilation
    self._lid_top = d.lid_top
    self._lid_bottom = d.lid_bottom
    self._highlight_x = d.highlight[0]
    self._highlight_y = d.highlight[1]
    # A non-blink/gaze animation can stay running; the next step will
    # ease gaze back to the emotion default.
    if self._kind not in (_AnimKind.BLINK, _AnimKind.DOUBLE_BLINK, _AnimKind.WINK):
        self.look(d.gaze[0], d.gaze[1], duration_s=0.4)

step()

Advance one frame and return the current render state.

Source code in src/robot/eye_engine/animation.py
def step(self) -> EyeRenderState:
    """Advance one frame and return the current render state."""
    dt = self._frame_interval
    self._frame_count += 1

    if self._kind is _AnimKind.BLINK:
        self._advance_blink(dt, double=False)
    elif self._kind is _AnimKind.DOUBLE_BLINK:
        self._advance_blink(dt, double=True)
    elif self._kind is _AnimKind.LOOK:
        self._advance_look(dt)
    elif self._kind is _AnimKind.WINK:
        self._advance_wink(dt)

    # If no gaze animation is running, ease gaze gently toward the
    # emotion default so the eye settles after a Look command.
    # If no gaze animation is running, ease gaze gently toward the
    # emotion default so the eye settles after a Look command - but
    # not on the frame the look just completed (otherwise the target
    # would be partially undone immediately).
    just_finished = self._just_completed
    self._just_completed = False
    if self._kind is not _AnimKind.LOOK and not just_finished:
        d = emotion_def(self._emotion)
        self._gaze_x = self._lerp(self._gaze_x, d.gaze[0], 0.05)
        self._gaze_y = self._lerp(self._gaze_y, d.gaze[1], 0.05)

    return self.render_state()

wink()

Close this eye briefly while the other eye stays open (independent mode).

Source code in src/robot/eye_engine/animation.py
def wink(self) -> None:
    """Close this eye briefly while the other eye stays open (independent mode)."""
    self._kind = _AnimKind.WINK
    self._wink_time = 0.0
    self._wink_duration = 0.30

EyeFrame dataclass

An RGB888 image to push to the display.

Attributes

width, height: Pixel dimensions. pixels: Row-major RGB888 buffer of length width * height * 3.

Source code in src/robot/interfaces/display.py
@dataclass(slots=True, frozen=True)
class EyeFrame:
    """An RGB888 image to push to the display.

    Attributes
    ----------
    width, height:
        Pixel dimensions.
    pixels:
        Row-major RGB888 buffer of length ``width * height * 3``.
    """

    width: int
    height: int
    pixels: bytes

height instance-attribute

pixels instance-attribute

width instance-attribute

__init__(width, height, pixels)

EyeSide

Bases: str, Enum

Which physical eye the animator drives.

Source code in src/robot/eye_engine/animation.py
class EyeSide(str, enum.Enum):
    """Which physical eye the animator drives."""

    LEFT = "left"
    RIGHT = "right"
    BOTH = "both"

BOTH = 'both' class-attribute instance-attribute

LEFT = 'left' class-attribute instance-attribute

RIGHT = 'right' class-attribute instance-attribute

Eyebrow dataclass

A single eyebrow.

Source code in src/robot/face/components.py
@dataclass(slots=True, frozen=True)
class Eyebrow:
    """A single eyebrow."""

    shape: EyebrowShape = EyebrowShape.NEUTRAL
    raise_amount: float = 0.0  # 0..1 vertical raise (additive on top of shape)
    angle: float = 0.0  # -1..1 tilt (angry < 0, worried > 0)

angle = 0.0 class-attribute instance-attribute

raise_amount = 0.0 class-attribute instance-attribute

shape = EyebrowShape.NEUTRAL class-attribute instance-attribute

__init__(shape=EyebrowShape.NEUTRAL, raise_amount=0.0, angle=0.0)

EyebrowShape

Bases: str, Enum

Source code in src/robot/face/components.py
class EyebrowShape(str, Enum):
    NEUTRAL = "neutral"
    RAISED = "raised"
    ANGRY = "angry"
    WORRIED = "worried"
    SLEEPY = "sleepy"
    SAD = "sad"

ANGRY = 'angry' class-attribute instance-attribute

NEUTRAL = 'neutral' class-attribute instance-attribute

RAISED = 'raised' class-attribute instance-attribute

SAD = 'sad' class-attribute instance-attribute

SLEEPY = 'sleepy' class-attribute instance-attribute

WORRIED = 'worried' class-attribute instance-attribute

Eyelids dataclass

Vertical eyelid positions, 0.0 = retracted, 1.0 = fully closed.

Source code in src/robot/face/components.py
@dataclass(slots=True, frozen=True)
class Eyelids:
    """Vertical eyelid positions, ``0.0`` = retracted, ``1.0`` = fully closed."""

    top: float = 0.0
    bottom: float = 0.0

bottom = 0.0 class-attribute instance-attribute

top = 0.0 class-attribute instance-attribute

__init__(top=0.0, bottom=0.0)

FaceAnimator dataclass

Drive a single circular face display at 30 FPS.

Source code in src/robot/face/animator.py
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
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
@dataclass(slots=True)
class FaceAnimator:
    """Drive a single circular face display at 30 FPS."""

    DEFAULT_FPS: ClassVar[int] = 30

    renderer: FaceRenderer
    display: Display
    clock: Clock
    emotions: EmotionEngine
    theme: Theme
    fps: int = DEFAULT_FPS
    bus: InMemoryEventBus | None = None
    width: int = 240
    height: int = 240

    _current: FaceModel = field(init=False)
    _target: FaceModel = field(init=False)
    _eye: EyeAnimator = field(init=False)
    _stopped: bool = field(default=True, init=False)
    _frame_count: int = field(default=0, init=False)
    _anim_time: float = field(default=0.0, init=False)
    _timeline: Timeline | None = field(default=None, init=False)
    _timeline_t: float = field(default=0.0, init=False)
    _timeline_total: float = field(default=0.0, init=False)
    _speaking_animation: SpeakingAnimation | None = field(default=None, init=False)
    _thinking_animation: ThinkingDotsAnimation | None = field(default=None, init=False)
    _wake_animation: WakeAnimation | None = field(default=None, init=False)
    _frame_profiler: FrameProfiler | None = field(default=None, init=False, repr=False)

    def __post_init__(self) -> None:
        if self.fps <= 0:
            raise ValueError("fps must be > 0")
        if self.width <= 0 or self.height <= 0:
            raise ValueError("width and height must be > 0")
        self._eye = EyeAnimator(
            side=EyeSide.LEFT,
            width=self.width,
            height=self.height,
            fps=self.fps,
        )
        self._current = self.emotions.build("neutral")
        self._target = self._current
        if self.bus is not None:
            from robot.events.events import (
                BlinkRequested,
                EmotionChanged,
                LookRequested,
            )

            self.bus.subscribe(EmotionChanged, self._on_emotion)
            self.bus.subscribe(BlinkRequested, self._on_blink)
            self.bus.subscribe(LookRequested, self._on_look)

    # ------------------------------------------------------------------ properties
    @property
    def current(self) -> FaceModel:
        return self._current

    @property
    def frame_count(self) -> int:
        return self._frame_count

    @property
    def is_running(self) -> bool:
        return not self._stopped

    # ------------------------------------------------------------------ public commands
    def set_emotion(self, name: str, intensity: float = 1.0) -> None:
        """Animate to the given emotion over ~0.3s.

        Calling this method clears any running speaking and thinking
        animations (they are interruptible).  The wake animation is
        *not* cleared -- it plays to completion.
        """
        # Clear interruptible animations on emotion change.
        self._speaking_animation = None
        self._thinking_animation = None
        target = self.emotions.build(name)
        # Apply intensity: scale the change in openness, mouth, etc.
        self._timeline = self._build_emotion_timeline(self._current, target, duration_s=0.3)
        self._target = target

    def blink(self) -> None:
        self._eye.blink()

    def double_blink(self) -> None:
        self._eye.double_blink()

    def wink(self) -> None:
        self._eye.wink()

    def look(self, x: float, y: float, duration_s: float = 0.25) -> None:
        self._eye.look(x, y, duration_s)

    def look_left(self, duration_s: float = 0.25) -> None:
        self._eye.look_left(duration_s)

    def look_right(self, duration_s: float = 0.25) -> None:
        self._eye.look_right(duration_s)

    def look_up(self, duration_s: float = 0.25) -> None:
        self._eye.look_up(duration_s)

    def look_down(self, duration_s: float = 0.25) -> None:
        self._eye.look_down(duration_s)

    def look_center(self, duration_s: float = 0.25) -> None:
        self._eye.look_center(duration_s)

    def drift(self, amplitude: float = 0.10, speed: float = 0.6) -> None:
        self._eye.drift(amplitude=amplitude, speed=speed)

    def bounce(self) -> None:
        """Run a one-shot bounce animation (squash & stretch)."""
        tl = self._build_bounce_timeline()
        self._timeline = tl

    def smile_grow(self) -> None:
        """Animate the mouth from NEUTRAL to SMILE over 0.4s."""
        target = self._current.with_mouth(Mouth(shape=MouthShape.SMILE, openness=0.4, width=0.7))
        self._timeline = self._build_mouth_timeline(self._current, target, 0.4)

    def mouth_open(self, duration_s: float = 0.3) -> None:
        target = self._current.with_mouth(Mouth(shape=MouthShape.OPEN, openness=0.6, width=0.6))
        self._start_timeline(self._build_mouth_timeline(self._current, target, duration_s))

    def eyebrow_raise(self, amount: float = 0.6) -> None:
        target = self._current.with_eyebrows(
            left=Eyebrow(shape=EyebrowShape.RAISED, raise_amount=amount),
            right=Eyebrow(shape=EyebrowShape.RAISED, raise_amount=amount),
        )
        self._timeline = self._build_eyebrow_timeline(self._current, target, 0.3)

    # ------------------------------------------------------------------ animation slots
    def set_speaking_animation(self, animation: SpeakingAnimation | None) -> None:
        """Set (or clear) the speaking animation that drives mouth shapes."""
        self._speaking_animation = animation

    def set_thinking_animation(self, animation: ThinkingDotsAnimation | None) -> None:
        """Set (or clear) the thinking animation that drives gaze shifts."""
        self._thinking_animation = animation

    def set_wake_animation(self, animation: WakeAnimation | None) -> None:
        """Set (or clear) the wake animation (highest priority override)."""
        self._wake_animation = animation

    def reset(self) -> None:
        self._current = self.emotions.build("neutral")
        self._target = self._current
        self._timeline = None
        self._speaking_animation = None
        self._thinking_animation = None
        self._wake_animation = None
        self._eye.reset()

    # ------------------------------------------------------------------ bus
    async def _on_emotion(self, event: object) -> None:
        name = getattr(event, "current", None)
        if name is None:
            return
        # The event's ``current`` can be either an ``EmotionName`` enum or
        # a plain string; normalise to a string before looking it up.
        if hasattr(name, "value"):
            name = name.value
        elif not isinstance(name, str):
            return
        self.set_emotion(name)

    async def _on_blink(self, event: object) -> None:
        self.blink()

    async def _on_look(self, event: object) -> None:
        self.look(
            float(getattr(event, "x", 0.0)),
            float(getattr(event, "y", 0.0)),
            duration_s=float(getattr(event, "duration_s", 0.25)),
        )

    # ------------------------------------------------------------------ frame loop
    def step(self, drift: bool = True) -> EyeFrame:
        """Advance one frame and push to the display.

        The rendering pipeline applies overrides in priority order:

        1. Eye drift + blink state (from :class:`EyeAnimator`).
        2. Thinking animation gaze override.
        3. Timeline-based emotion interpolation.
        4. Speaking animation mouth override.
        5. Wake animation full override (highest priority).
        """
        dt = 1.0 / self.fps
        self._frame_count += 1

        if drift:
            self._eye.drift(amplitude=0.10, speed=0.6)
        # Eye state: pull current gaze from the eye animator
        eye_state = self._eye.step()
        # Translate the eye's (gaze, openness) into left/right Eye components
        new_eyes = self._eyes_from_eye_state(eye_state)

        # Thinking animation: override gaze when active.
        if self._thinking_animation is not None:
            gaze = self._thinking_animation.step(dt)
            new_eyes = (
                Eye(
                    gaze=gaze,
                    openness=new_eyes[0].openness,
                    pupil_dilation=new_eyes[0].pupil_dilation,
                    highlight=new_eyes[0].highlight,
                ),
                Eye(
                    gaze=gaze,
                    openness=new_eyes[1].openness,
                    pupil_dilation=new_eyes[1].pupil_dilation,
                    highlight=new_eyes[1].highlight,
                ),
            )

        # Apply timeline (smile, eyebrows, bounce, …) if any
        if self._timeline is not None:
            self._timeline_t += dt
            progress = min(1.0, self._timeline_t / max(0.001, self._timeline_total))
            # Invoke the on_update callbacks directly. Each builder
            # registered a single tween whose callback writes to
            # ``self._current`` (interpolation, bounce, …).
            for animation in self._timeline._items:
                if hasattr(animation, "on_update"):
                    animation.on_update(progress)
            if progress >= 1.0:
                self._timeline = None
                self._timeline_t = 0.0
        # Merge eye state + current body
        merged = self._current.with_eyes(left_eye=new_eyes[0], right_eye=new_eyes[1])
        # Update the current model so a.current reflects the rendered state.
        self._current = merged

        # Speaking animation: override mouth when active.
        if self._speaking_animation is not None:
            viseme = self._speaking_animation.step(dt)
            mouth_shape = MouthShape.OPEN if viseme.openness > 0.1 else MouthShape.NEUTRAL
            self._current = self._current.with_mouth(
                Mouth(shape=mouth_shape, openness=viseme.openness, width=viseme.width)
            )
            if not self._speaking_animation.has_frames:
                self._speaking_animation = None

        # Wake animation: full override (highest priority).
        if self._wake_animation is not None:
            wake_frame = self._wake_animation.step(dt)
            self._current = self._apply_wake_frame(self._current, wake_frame)
            if self._wake_animation.done:
                self._wake_animation = None

        # Apply theme
        themed = self.theme.apply(self._current)
        return self.renderer.render(themed)

    async def _step_async(self, drift: bool = True) -> EyeFrame:
        frame = self.step(drift=drift)
        await self._push(frame)
        return frame

    async def _push(self, frame: EyeFrame) -> None:
        try:
            await self.display.show(frame)
        except Exception:
            _log.exception("face.animator.display_failed")
        if self.bus is not None:
            from robot.events.events import DisplayUpdated

            with contextlib.suppress(Exception):
                await self.bus.publish(DisplayUpdated(display="face"))

    async def run_forever(self) -> None:
        self._stopped = False
        frame_interval = 1.0 / self.fps
        try:
            while not self._stopped:
                start = time.monotonic()
                await self._step_async(drift=True)
                end = time.monotonic()
                if self._frame_profiler is not None and getattr(
                    self._frame_profiler, "enabled", False
                ):
                    self._frame_profiler.record_frame(start, end)
                await self.clock.sleep(frame_interval)
        finally:
            self._stopped = True

    def stop(self) -> None:
        self._stopped = True

    # ------------------------------------------------------------------ timeline helpers
    def _start_timeline(self, timeline: Timeline) -> None:
        self._timeline = timeline
        self._timeline_t = 0.0
        # _timeline_total is set by the builder (so the builder can also do its own work)

    def _build_emotion_timeline(
        self, start: FaceModel, end: FaceModel, duration_s: float
    ) -> Timeline:
        """Build a timeline that interpolates between two FaceModels.

        We don't yet have a generic FaceModel interpolator, so we use a
        sequence of tween callbacks to lerp scalar fields. The
        renderer is what makes the result look smooth.
        """
        tl = Timeline()
        # Tween the mouth shape change discretely (mid-way)
        tl.tween(
            from_value=0.0,
            to_value=1.0,
            duration_s=duration_s,
            on_update=lambda t: self._set_interp(start, end, t),
        )
        self._timeline_total = duration_s
        return tl

    def _build_mouth_timeline(
        self, start: FaceModel, end: FaceModel, duration_s: float
    ) -> Timeline:
        tl = Timeline()
        tl.tween(
            from_value=0.0,
            to_value=1.0,
            duration_s=duration_s,
            on_update=lambda t: self._set_interp(start, end, t),
        )
        self._timeline_total = duration_s
        return tl

    def _build_eyebrow_timeline(
        self, start: FaceModel, end: FaceModel, duration_s: float
    ) -> Timeline:
        tl = Timeline()
        tl.tween(
            from_value=0.0,
            to_value=1.0,
            duration_s=duration_s,
            on_update=lambda t: self._set_interp(start, end, t),
        )
        self._timeline_total = duration_s
        return tl

    def _build_bounce_timeline(self) -> Timeline:
        """One-shot bounce: bounce up, squash on landing, settle.

        Uses the model's ``bounce`` and ``squash`` fields and writes a
        per-frame value through a single tween.
        """
        # Build a sequence of keyframes as a list of (t, bounce, squash)
        keyframes: list[tuple[float, float, float]] = [
            (0.00, 0.0, 1.00),
            (0.10, 0.50, 0.92),  # anticipation squash
            (0.30, 0.85, 1.10),  # jump stretch
            (0.55, 0.00, 0.95),  # impact squash
            (0.75, 0.30, 1.04),  # small bounce
            (1.00, 0.0, 1.00),  # settle
        ]
        duration = 0.6

        class _Bounce:
            def __init__(self) -> None:
                pass

        # Use a simple Tween + linear interp through keyframes
        def _sample(t: float) -> tuple[float, float]:
            for i in range(len(keyframes) - 1):
                t0, b0, s0 = keyframes[i]
                t1, b1, s1 = keyframes[i + 1]
                if t0 <= t <= t1:
                    local = (t - t0) / max(1e-6, t1 - t0)
                    local = _ease_in_out(local)
                    return (b0 + (b1 - b0) * local, s0 + (s1 - s0) * local)
            return keyframes[-1][1], keyframes[-1][2]

        def _apply(t: float) -> None:
            bounce, squash = _sample(t)
            # Apply in-place: store the bounce/squash on the model.
            # We achieve this by replacing self._current with a new model
            # that has the transformed bounce/squash.
            self._current = self._current.with_transform(bounce=bounce, squash=squash)

        tl = Timeline()
        tl.tween(from_value=0.0, to_value=1.0, duration_s=duration, on_update=_apply)
        self._timeline_total = duration
        return tl

    def _apply_timeline_at(self, model: FaceModel, t: float) -> FaceModel:
        """Most timelines write to ``self._current`` directly via tween
        callbacks. This method is the fallback for any future timeline
        that wants to be queryable.
        """
        return model

    def _apply_wake_frame(self, model: FaceModel, frame: WakeFrame) -> FaceModel:
        """Apply a :class:`WakeFrame` override to the model.

        The wake animation has the highest priority and overrides
        eyes, eyelids, mouth, and eyebrows.
        """
        return (
            model.with_eyes(
                left_eye=Eye(
                    gaze=frame.gaze,
                    openness=frame.eye_openness,
                    pupil_dilation=model.left_eye.pupil_dilation,
                    highlight=model.left_eye.highlight,
                ),
                right_eye=Eye(
                    gaze=frame.gaze,
                    openness=frame.eye_openness,
                    pupil_dilation=model.right_eye.pupil_dilation,
                    highlight=model.right_eye.highlight,
                ),
            )
            .with_eyelids(Eyelids(top=frame.eyelid_top, bottom=0.0))
            .with_mouth(
                Mouth(
                    shape=frame.mouth_shape, openness=frame.mouth_openness, width=frame.mouth_width
                )
            )
            .with_eyebrows(
                left=Eyebrow(shape=frame.eyebrow_shape, raise_amount=frame.eyebrow_raise),
                right=Eyebrow(shape=frame.eyebrow_shape, raise_amount=frame.eyebrow_raise),
            )
        )

    def _set_interp(self, start: FaceModel, end: FaceModel, t: float) -> None:
        """Snap-interpolate scalar fields from start to end at progress t."""
        e = _ease_in_out(t)
        left_eye = _interp_eye(start.left_eye, end.left_eye, e)
        right_eye = _interp_eye(start.right_eye, end.right_eye, e)
        eyelids = _interp_eyelids(start.eyelids, end.eyelids, e)
        left_brow = _interp_eyebrow(start.left_eyebrow, end.left_eyebrow, e)
        right_brow = _interp_eyebrow(start.right_eyebrow, end.right_eyebrow, e)
        mouth = _interp_mouth(start.mouth, end.mouth, e)
        cheeks = _interp_cheeks(start.cheeks, end.cheeks, e)
        overlay = end.overlay if e > 0.5 else start.overlay
        body_hint = end.body_hint if e > 0.5 else start.body_hint
        self._current = FaceModel(
            width=start.width,
            height=start.height,
            left_eye=left_eye,
            right_eye=right_eye,
            eyelids=eyelids,
            left_eyebrow=left_brow,
            right_eyebrow=right_brow,
            mouth=mouth,
            cheeks=cheeks,
            overlay=overlay,
            accessory=start.accessory,
            palette=start.palette,
            bounce=start.bounce,
            squash=start.squash,
            body_hint=body_hint,
        )

    def _eyes_from_eye_state(self, state: object) -> tuple[Eye, Eye]:
        """Translate the eye render state into two :class:`Eye` components."""
        # The legacy EyeState has a ``gaze`` field; the new EyeRenderState
        # has separate ``gaze_x`` / ``gaze_y`` floats. Handle both.
        if hasattr(state, "gaze_x"):
            gaze = Gaze(float(getattr(state, "gaze_x", 0.0)), float(getattr(state, "gaze_y", 0.0)))
        else:
            g = getattr(state, "gaze", Gaze())
            gaze = Gaze(float(g.x), float(g.y))
        openness = float(getattr(state, "openness", 1.0))
        dilation = float(getattr(state, "pupil_dilation", 0.5))
        eye = Eye(gaze=gaze, openness=openness, pupil_dilation=dilation, highlight=Gaze(0.3, 0.3))
        return eye, eye

DEFAULT_FPS = 30 class-attribute

bus = None class-attribute instance-attribute

clock instance-attribute

current property

display instance-attribute

emotions instance-attribute

fps = DEFAULT_FPS class-attribute instance-attribute

frame_count property

height = 240 class-attribute instance-attribute

is_running property

renderer instance-attribute

theme instance-attribute

width = 240 class-attribute instance-attribute

__init__(renderer, display, clock, emotions, theme, fps=DEFAULT_FPS, bus=None, width=240, height=240)

__post_init__()

Source code in src/robot/face/animator.py
def __post_init__(self) -> None:
    if self.fps <= 0:
        raise ValueError("fps must be > 0")
    if self.width <= 0 or self.height <= 0:
        raise ValueError("width and height must be > 0")
    self._eye = EyeAnimator(
        side=EyeSide.LEFT,
        width=self.width,
        height=self.height,
        fps=self.fps,
    )
    self._current = self.emotions.build("neutral")
    self._target = self._current
    if self.bus is not None:
        from robot.events.events import (
            BlinkRequested,
            EmotionChanged,
            LookRequested,
        )

        self.bus.subscribe(EmotionChanged, self._on_emotion)
        self.bus.subscribe(BlinkRequested, self._on_blink)
        self.bus.subscribe(LookRequested, self._on_look)
Source code in src/robot/face/animator.py
def blink(self) -> None:
    self._eye.blink()

bounce()

Run a one-shot bounce animation (squash & stretch).

Source code in src/robot/face/animator.py
def bounce(self) -> None:
    """Run a one-shot bounce animation (squash & stretch)."""
    tl = self._build_bounce_timeline()
    self._timeline = tl
Source code in src/robot/face/animator.py
def double_blink(self) -> None:
    self._eye.double_blink()

drift(amplitude=0.1, speed=0.6)

Source code in src/robot/face/animator.py
def drift(self, amplitude: float = 0.10, speed: float = 0.6) -> None:
    self._eye.drift(amplitude=amplitude, speed=speed)

eyebrow_raise(amount=0.6)

Source code in src/robot/face/animator.py
def eyebrow_raise(self, amount: float = 0.6) -> None:
    target = self._current.with_eyebrows(
        left=Eyebrow(shape=EyebrowShape.RAISED, raise_amount=amount),
        right=Eyebrow(shape=EyebrowShape.RAISED, raise_amount=amount),
    )
    self._timeline = self._build_eyebrow_timeline(self._current, target, 0.3)

look(x, y, duration_s=0.25)

Source code in src/robot/face/animator.py
def look(self, x: float, y: float, duration_s: float = 0.25) -> None:
    self._eye.look(x, y, duration_s)

look_center(duration_s=0.25)

Source code in src/robot/face/animator.py
def look_center(self, duration_s: float = 0.25) -> None:
    self._eye.look_center(duration_s)

look_down(duration_s=0.25)

Source code in src/robot/face/animator.py
def look_down(self, duration_s: float = 0.25) -> None:
    self._eye.look_down(duration_s)

look_left(duration_s=0.25)

Source code in src/robot/face/animator.py
def look_left(self, duration_s: float = 0.25) -> None:
    self._eye.look_left(duration_s)

look_right(duration_s=0.25)

Source code in src/robot/face/animator.py
def look_right(self, duration_s: float = 0.25) -> None:
    self._eye.look_right(duration_s)

look_up(duration_s=0.25)

Source code in src/robot/face/animator.py
def look_up(self, duration_s: float = 0.25) -> None:
    self._eye.look_up(duration_s)

mouth_open(duration_s=0.3)

Source code in src/robot/face/animator.py
def mouth_open(self, duration_s: float = 0.3) -> None:
    target = self._current.with_mouth(Mouth(shape=MouthShape.OPEN, openness=0.6, width=0.6))
    self._start_timeline(self._build_mouth_timeline(self._current, target, duration_s))

reset()

Source code in src/robot/face/animator.py
def reset(self) -> None:
    self._current = self.emotions.build("neutral")
    self._target = self._current
    self._timeline = None
    self._speaking_animation = None
    self._thinking_animation = None
    self._wake_animation = None
    self._eye.reset()

run_forever() async

Source code in src/robot/face/animator.py
async def run_forever(self) -> None:
    self._stopped = False
    frame_interval = 1.0 / self.fps
    try:
        while not self._stopped:
            start = time.monotonic()
            await self._step_async(drift=True)
            end = time.monotonic()
            if self._frame_profiler is not None and getattr(
                self._frame_profiler, "enabled", False
            ):
                self._frame_profiler.record_frame(start, end)
            await self.clock.sleep(frame_interval)
    finally:
        self._stopped = True

set_emotion(name, intensity=1.0)

Animate to the given emotion over ~0.3s.

Calling this method clears any running speaking and thinking animations (they are interruptible). The wake animation is not cleared -- it plays to completion.

Source code in src/robot/face/animator.py
def set_emotion(self, name: str, intensity: float = 1.0) -> None:
    """Animate to the given emotion over ~0.3s.

    Calling this method clears any running speaking and thinking
    animations (they are interruptible).  The wake animation is
    *not* cleared -- it plays to completion.
    """
    # Clear interruptible animations on emotion change.
    self._speaking_animation = None
    self._thinking_animation = None
    target = self.emotions.build(name)
    # Apply intensity: scale the change in openness, mouth, etc.
    self._timeline = self._build_emotion_timeline(self._current, target, duration_s=0.3)
    self._target = target

set_speaking_animation(animation)

Set (or clear) the speaking animation that drives mouth shapes.

Source code in src/robot/face/animator.py
def set_speaking_animation(self, animation: SpeakingAnimation | None) -> None:
    """Set (or clear) the speaking animation that drives mouth shapes."""
    self._speaking_animation = animation

set_thinking_animation(animation)

Set (or clear) the thinking animation that drives gaze shifts.

Source code in src/robot/face/animator.py
def set_thinking_animation(self, animation: ThinkingDotsAnimation | None) -> None:
    """Set (or clear) the thinking animation that drives gaze shifts."""
    self._thinking_animation = animation

set_wake_animation(animation)

Set (or clear) the wake animation (highest priority override).

Source code in src/robot/face/animator.py
def set_wake_animation(self, animation: WakeAnimation | None) -> None:
    """Set (or clear) the wake animation (highest priority override)."""
    self._wake_animation = animation

smile_grow()

Animate the mouth from NEUTRAL to SMILE over 0.4s.

Source code in src/robot/face/animator.py
def smile_grow(self) -> None:
    """Animate the mouth from NEUTRAL to SMILE over 0.4s."""
    target = self._current.with_mouth(Mouth(shape=MouthShape.SMILE, openness=0.4, width=0.7))
    self._timeline = self._build_mouth_timeline(self._current, target, 0.4)

step(drift=True)

Advance one frame and push to the display.

The rendering pipeline applies overrides in priority order:

  1. Eye drift + blink state (from :class:EyeAnimator).
  2. Thinking animation gaze override.
  3. Timeline-based emotion interpolation.
  4. Speaking animation mouth override.
  5. Wake animation full override (highest priority).
Source code in src/robot/face/animator.py
def step(self, drift: bool = True) -> EyeFrame:
    """Advance one frame and push to the display.

    The rendering pipeline applies overrides in priority order:

    1. Eye drift + blink state (from :class:`EyeAnimator`).
    2. Thinking animation gaze override.
    3. Timeline-based emotion interpolation.
    4. Speaking animation mouth override.
    5. Wake animation full override (highest priority).
    """
    dt = 1.0 / self.fps
    self._frame_count += 1

    if drift:
        self._eye.drift(amplitude=0.10, speed=0.6)
    # Eye state: pull current gaze from the eye animator
    eye_state = self._eye.step()
    # Translate the eye's (gaze, openness) into left/right Eye components
    new_eyes = self._eyes_from_eye_state(eye_state)

    # Thinking animation: override gaze when active.
    if self._thinking_animation is not None:
        gaze = self._thinking_animation.step(dt)
        new_eyes = (
            Eye(
                gaze=gaze,
                openness=new_eyes[0].openness,
                pupil_dilation=new_eyes[0].pupil_dilation,
                highlight=new_eyes[0].highlight,
            ),
            Eye(
                gaze=gaze,
                openness=new_eyes[1].openness,
                pupil_dilation=new_eyes[1].pupil_dilation,
                highlight=new_eyes[1].highlight,
            ),
        )

    # Apply timeline (smile, eyebrows, bounce, …) if any
    if self._timeline is not None:
        self._timeline_t += dt
        progress = min(1.0, self._timeline_t / max(0.001, self._timeline_total))
        # Invoke the on_update callbacks directly. Each builder
        # registered a single tween whose callback writes to
        # ``self._current`` (interpolation, bounce, …).
        for animation in self._timeline._items:
            if hasattr(animation, "on_update"):
                animation.on_update(progress)
        if progress >= 1.0:
            self._timeline = None
            self._timeline_t = 0.0
    # Merge eye state + current body
    merged = self._current.with_eyes(left_eye=new_eyes[0], right_eye=new_eyes[1])
    # Update the current model so a.current reflects the rendered state.
    self._current = merged

    # Speaking animation: override mouth when active.
    if self._speaking_animation is not None:
        viseme = self._speaking_animation.step(dt)
        mouth_shape = MouthShape.OPEN if viseme.openness > 0.1 else MouthShape.NEUTRAL
        self._current = self._current.with_mouth(
            Mouth(shape=mouth_shape, openness=viseme.openness, width=viseme.width)
        )
        if not self._speaking_animation.has_frames:
            self._speaking_animation = None

    # Wake animation: full override (highest priority).
    if self._wake_animation is not None:
        wake_frame = self._wake_animation.step(dt)
        self._current = self._apply_wake_frame(self._current, wake_frame)
        if self._wake_animation.done:
            self._wake_animation = None

    # Apply theme
    themed = self.theme.apply(self._current)
    return self.renderer.render(themed)

stop()

Source code in src/robot/face/animator.py
def stop(self) -> None:
    self._stopped = True

wink()

Source code in src/robot/face/animator.py
def wink(self) -> None:
    self._eye.wink()

FaceModel dataclass

The full face, captured at one instant.

All values are immutable. Use the helper methods to build new models with a single field changed (this is what the renderer animates).

Source code in src/robot/face/model.py
@dataclass(slots=True, frozen=True)
class FaceModel:
    """The full face, captured at one instant.

    All values are immutable. Use the helper methods to build new models
    with a single field changed (this is what the renderer animates).
    """

    width: int = 240
    height: int = 240

    left_eye: Eye = field(default_factory=Eye)
    right_eye: Eye = field(default_factory=Eye)

    # Eyelids
    eyelids: Eyelids = field(default_factory=Eyelids)

    # Eyebrows (one per eye)
    left_eyebrow: Eyebrow = field(default_factory=Eyebrow)
    right_eyebrow: Eyebrow = field(default_factory=Eyebrow)

    # Mouth
    mouth: Mouth = field(default_factory=Mouth)

    # Cheeks
    cheeks: Cheeks = field(default_factory=Cheeks)

    # Overlays
    overlay: Overlay = field(default_factory=Overlay)

    # Persistent accessories
    accessory: Accessory = field(default_factory=Accessory)

    # Colour palette (themes override this)
    palette: FacePalette = field(default_factory=FacePalette)

    # Subtle bounce / squash & stretch (in normalised units)
    bounce: float = 0.0  # -1..1 vertical translation
    squash: float = 1.0  # 0..2 horizontal scale (1 = neutral)

    # Body-language hint proposed by the EmotionEngine
    body_hint: BodyLanguageHint = field(default_factory=BodyLanguageHint)

    # ------------------------------------------------------------------
    # Convenience builders (return a new model with one field changed)
    # ------------------------------------------------------------------
    def with_eyes(
        self,
        left_eye: Eye | None = None,
        right_eye: Eye | None = None,
    ) -> FaceModel:
        return replace(
            self, left_eye=left_eye or self.left_eye, right_eye=right_eye or self.right_eye
        )

    def with_eyelids(self, eyelids: Eyelids) -> FaceModel:
        return replace(self, eyelids=eyelids)

    def with_eyebrows(
        self,
        left: Eyebrow | None = None,
        right: Eyebrow | None = None,
    ) -> FaceModel:
        return replace(
            self, left_eyebrow=left or self.left_eyebrow, right_eyebrow=right or self.right_eyebrow
        )

    def with_mouth(self, mouth: Mouth) -> FaceModel:
        return replace(self, mouth=mouth)

    def with_cheeks(self, cheeks: Cheeks) -> FaceModel:
        return replace(self, cheeks=cheeks)

    def with_overlay(self, overlay: Overlay) -> FaceModel:
        return replace(self, overlay=overlay)

    def with_accessory(self, accessory: Accessory) -> FaceModel:
        return replace(self, accessory=accessory)

    def with_palette(self, palette: FacePalette) -> FaceModel:
        return replace(self, palette=palette)

    def with_transform(self, bounce: float | None = None, squash: float | None = None) -> FaceModel:
        return replace(
            self,
            bounce=self.bounce if bounce is None else bounce,
            squash=self.squash if squash is None else squash,
        )

    def with_body_hint(self, body_hint: BodyLanguageHint) -> FaceModel:
        return replace(self, body_hint=body_hint)

accessory = field(default_factory=Accessory) class-attribute instance-attribute

body_hint = field(default_factory=BodyLanguageHint) class-attribute instance-attribute

bounce = 0.0 class-attribute instance-attribute

cheeks = field(default_factory=Cheeks) class-attribute instance-attribute

eyelids = field(default_factory=Eyelids) class-attribute instance-attribute

height = 240 class-attribute instance-attribute

left_eye = field(default_factory=Eye) class-attribute instance-attribute

left_eyebrow = field(default_factory=Eyebrow) class-attribute instance-attribute

mouth = field(default_factory=Mouth) class-attribute instance-attribute

overlay = field(default_factory=Overlay) class-attribute instance-attribute

palette = field(default_factory=FacePalette) class-attribute instance-attribute

right_eye = field(default_factory=Eye) class-attribute instance-attribute

right_eyebrow = field(default_factory=Eyebrow) class-attribute instance-attribute

squash = 1.0 class-attribute instance-attribute

width = 240 class-attribute instance-attribute

__init__(width=240, height=240, left_eye=Eye(), right_eye=Eye(), eyelids=Eyelids(), left_eyebrow=Eyebrow(), right_eyebrow=Eyebrow(), mouth=Mouth(), cheeks=Cheeks(), overlay=Overlay(), accessory=Accessory(), palette=FacePalette(), bounce=0.0, squash=1.0, body_hint=BodyLanguageHint())

with_accessory(accessory)

Source code in src/robot/face/model.py
def with_accessory(self, accessory: Accessory) -> FaceModel:
    return replace(self, accessory=accessory)

with_body_hint(body_hint)

Source code in src/robot/face/model.py
def with_body_hint(self, body_hint: BodyLanguageHint) -> FaceModel:
    return replace(self, body_hint=body_hint)

with_cheeks(cheeks)

Source code in src/robot/face/model.py
def with_cheeks(self, cheeks: Cheeks) -> FaceModel:
    return replace(self, cheeks=cheeks)

with_eyebrows(left=None, right=None)

Source code in src/robot/face/model.py
def with_eyebrows(
    self,
    left: Eyebrow | None = None,
    right: Eyebrow | None = None,
) -> FaceModel:
    return replace(
        self, left_eyebrow=left or self.left_eyebrow, right_eyebrow=right or self.right_eyebrow
    )

with_eyelids(eyelids)

Source code in src/robot/face/model.py
def with_eyelids(self, eyelids: Eyelids) -> FaceModel:
    return replace(self, eyelids=eyelids)

with_eyes(left_eye=None, right_eye=None)

Source code in src/robot/face/model.py
def with_eyes(
    self,
    left_eye: Eye | None = None,
    right_eye: Eye | None = None,
) -> FaceModel:
    return replace(
        self, left_eye=left_eye or self.left_eye, right_eye=right_eye or self.right_eye
    )

with_mouth(mouth)

Source code in src/robot/face/model.py
def with_mouth(self, mouth: Mouth) -> FaceModel:
    return replace(self, mouth=mouth)

with_overlay(overlay)

Source code in src/robot/face/model.py
def with_overlay(self, overlay: Overlay) -> FaceModel:
    return replace(self, overlay=overlay)

with_palette(palette)

Source code in src/robot/face/model.py
def with_palette(self, palette: FacePalette) -> FaceModel:
    return replace(self, palette=palette)

with_transform(bounce=None, squash=None)

Source code in src/robot/face/model.py
def with_transform(self, bounce: float | None = None, squash: float | None = None) -> FaceModel:
    return replace(
        self,
        bounce=self.bounce if bounce is None else bounce,
        squash=self.squash if squash is None else squash,
    )

FaceRenderer

Render a :class:FaceModel to an RGB888 frame.

Source code in src/robot/face/renderer.py
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 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
 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
class FaceRenderer:
    """Render a :class:`FaceModel` to an RGB888 frame."""

    def __init__(self, width: int = 240, height: int = 240) -> None:
        if width <= 0 or height <= 0:
            raise ValueError("width and height must be > 0")
        self._width = width
        self._height = height

    @property
    def width(self) -> int:
        return self._width

    @property
    def height(self) -> int:
        return self._height

    # ------------------------------------------------------------------ public
    def render(self, model: FaceModel) -> EyeFrame:
        """Render ``model`` into a new RGB888 frame."""
        if model.width != self._width or model.height != self._height:
            raise ValueError(
                f"model is {model.width}x{model.height}, renderer is {self._width}x{self._height}"
            )
        raster = self._new_raster()
        # Vector mode bypasses the full face stack and renders only the
        # minimalist "two glowing squares + a horizontal line" used by the
        # Anki Vector 2.0 face. Cheeks/eyebrows/iris/sclera are skipped
        # because the Vector palette does not use them.
        if model.palette.mode == PALETTE_MODE_VECTOR:
            self._draw_background(raster, model)
            self._draw_vector_eyes(raster, model)
            self._draw_vector_mouth(raster, model)
            return EyeFrame(width=self._width, height=self._height, pixels=bytes(raster.pixels))
        self._draw_background(raster, model)
        self._draw_cheeks(raster, model)
        self._draw_sclera(raster, model)
        self._draw_eyelids(raster, model)
        self._draw_iris(raster, model)
        self._draw_pupil(raster, model)
        self._draw_highlight(raster, model)
        self._draw_eyebrows(raster, model)
        self._draw_mouth(raster, model)
        self._draw_overlay(raster, model)
        self._draw_accessory(raster, model)
        return EyeFrame(width=self._width, height=self._height, pixels=bytes(raster.pixels))

    # ------------------------------------------------------------------ vector mode
    def _draw_vector_eyes(self, raster: _Raster, model: FaceModel) -> None:
        """Draw two glowing rounded-squares for the eyes (Vector style).

        Each eye follows the model's gaze position so drift and look
        commands produce visible movement.  The mouth still animates
        independently.
        """
        cx, cy, face_radius, _, _ = self._face_geometry(model)
        # Vector eyes sit a bit above the panel centre, like the Anki robot.
        eye_radius = face_radius * 0.18
        eye_y = cy - face_radius * 0.30
        eye_offset_x = face_radius * 0.45
        # Gaze offset - both eyes share the same gaze direction.
        # A multiplier of 0.35 produces a visible (~3-5 px) shift on a
        # 240 px face so that drift and look commands are perceptible.
        gaze_shift_x = face_radius * 0.35 * model.left_eye.gaze.x
        gaze_shift_y = face_radius * 0.35 * model.left_eye.gaze.y
        for sx in (-1, 1):
            ex = cx + sx * eye_offset_x + gaze_shift_x
            ey = eye_y + gaze_shift_y
            self._fill_rounded_square(
                raster,
                ex - eye_radius,
                ey - eye_radius,
                eye_radius * 2,
                eye_radius * 2,
                eye_radius * 0.25,
                model.palette.iris,
            )

    def _draw_vector_mouth(self, raster: _Raster, model: FaceModel) -> None:
        """Draw a thin horizontal bar mouth that morphs with the mouth shape.

        Shape -> visual:
          NEUTRAL / CLOSED  -> straight horizontal bar
          SMILE / GRIN      -> bar curves up at the ends
          FROWN             -> bar curves down at the ends
          OPEN / WIDE_OPEN  -> bar with a gap in the middle (small "o")
          TONGUE            -> bar with a small dot below
        """
        cx, cy, face_radius, _, _ = self._face_geometry(model)
        bar_y = cy + face_radius * 0.45
        bar_half_w = face_radius * 0.32
        bar_thickness = max(2, int(face_radius * 0.08))
        shape = model.mouth.shape
        openness = model.mouth.openness
        color = model.palette.mouth
        if shape in (MouthShape.SMILE, MouthShape.GRIN, MouthShape.SMILE_OPEN, MouthShape.TONGUE):
            # Curve the ends upward (smile).
            curve = -face_radius * 0.18 * (1.0 + openness)
            self._draw_arc(raster, cx, bar_y, bar_half_w, curve, color, bar_thickness)
            if shape is MouthShape.TONGUE:
                # A tiny tongue dot below the mouth line.
                self._fill_circle(
                    raster,
                    cx,
                    bar_y - face_radius * 0.06,
                    face_radius * 0.06,
                    (255, 130, 180),
                )
        elif shape is MouthShape.FROWN:
            # Curve the ends downward.
            curve = face_radius * 0.18
            self._draw_arc(raster, cx, bar_y, bar_half_w, curve, color, bar_thickness)
        elif shape in (MouthShape.OPEN, MouthShape.WIDE_OPEN):
            # Two short bars with a gap = a small "o" shape.
            r = face_radius * (0.04 + 0.06 * openness) * (1.0 if shape is MouthShape.OPEN else 1.6)
            self._fill_circle(raster, cx, bar_y, r, color)
            if shape is MouthShape.WIDE_OPEN:
                self._fill_circle(raster, cx, bar_y, r * 0.6, model.palette.background)
        else:  # NEUTRAL / CLOSED
            self._draw_thick_line(
                raster,
                cx - bar_half_w,
                bar_y,
                cx + bar_half_w,
                bar_y,
                bar_thickness,
                color,
            )

    def _fill_rounded_square(
        self,
        raster: _Raster,
        x0: float,
        y0: float,
        w: float,
        h: float,
        radius: float,
        color: tuple[int, int, int],
    ) -> None:
        """Fill a rounded-square between ``(x0, y0)`` and ``(x0+w, y0+h)``.

        Used for the Vector-style eye. The corners are rounded by
        ``radius`` pixels (clamped to half the smaller side).
        """
        r = max(0.0, min(radius, min(w, h) / 2.0))
        x1 = x0 + w
        y1 = y0 + h
        col = bytes(color) * raster.width
        # Top + bottom strips + middle strips + corner arcs.
        for y in range(round(y0), round(y1)):
            if y < y0 + r or y >= y1 - r:
                # Top/bottom strip between the corners
                self._fill_rect_row(raster, round(x0 + r), y, round(x1 - r) - 1, col)
            else:
                # Full-width row in the middle
                self._fill_rect_row(raster, round(x0), y, round(x1) - 1, col)
        # Quadrant corner fills (4 circles for the rounded corners)
        cr = max(1, round(r))
        for cx_corner, cy_corner in (
            (x0 + r, y0 + r),
            (x1 - r, y0 + r),
            (x0 + r, y1 - r),
            (x1 - r, y1 - r),
        ):
            # Use the existing _fill_circle for each corner quadrant.
            # We restrict to the inside of the square so the result is a
            # smooth rounded corner rather than a full disc.
            self._fill_corner_quadrant(
                raster,
                round(cx_corner),
                round(cy_corner),
                cr,
                color,
                is_top_left=(cx_corner <= x0 + r and cy_corner <= y0 + r),
                is_top_right=(cx_corner >= x1 - r and cy_corner <= y0 + r),
                is_bottom_left=(cx_corner <= x0 + r and cy_corner >= y1 - r),
                is_bottom_right=(cx_corner >= x1 - r and cy_corner >= y1 - r),
            )

    def _fill_rect_row(self, raster: _Raster, x0: int, y: int, x1: int, color_bytes: bytes) -> None:
        """Fill a horizontal strip from ``(x0, y)`` to ``(x1, y)`` inclusive."""
        if x1 < x0 or y < 0 or y >= raster.height:
            return
        x0 = max(0, x0)
        x1 = min(raster.width - 1, x1)
        if x1 < x0:
            return
        start = (y * raster.width + x0) * 3
        end = (y * raster.width + x1 + 1) * 3
        # Write the 3-byte color (r, g, b) for every pixel in the row.
        i = start
        while i + 3 <= end:
            raster.pixels[i : i + 3] = bytes(color_bytes[:3])
            i += 3

    def _fill_corner_quadrant(
        self,
        raster: _Raster,
        cx: int,
        cy: int,
        r: int,
        color: tuple[int, int, int],
        *,
        is_top_left: bool,
        is_top_right: bool,
        is_bottom_left: bool,
        is_bottom_right: bool,
    ) -> None:
        """Fill the inside-quadrant of a circle of radius ``r`` at (cx, cy).

        Used to round the corners of :meth:`_fill_rounded_square`.
        """
        for dy in range(-r, r + 1):
            for dx in range(-r, r + 1):
                if dx * dx + dy * dy > r * r:
                    continue
                px = cx + dx
                py = cy + dy
                # Only write inside the square.
                inside = True
                if is_top_left and (dx > 0 or dy > 0):
                    inside = False
                if is_top_right and (dx < 0 or dy > 0):
                    inside = False
                if is_bottom_left and (dx > 0 or dy < 0):
                    inside = False
                if is_bottom_right and (dx < 0 or dy < 0):
                    inside = False
                if not inside:
                    continue
                if 0 <= px < raster.width and 0 <= py < raster.height:
                    i = (py * raster.width + px) * 3
                    raster.pixels[i : i + 3] = bytes(color)

    # ------------------------------------------------------------------ helpers
    def _new_raster(self) -> _Raster:
        return _Raster(width=self._width, height=self._height)

    # The model is drawn around a logical centre (cx, cy). The bounce and
    # squash fields are applied here so every layer sees the transformed
    # coordinates.
    def _face_geometry(self, model: FaceModel) -> tuple[float, float, float, float, float]:
        """Return (cx, cy, face_radius, eye_radius, mouth_y) in pixels."""
        cx = self._width / 2.0
        cy = self._height / 2.0
        # Vertical bounce: -1..1 -> -face_radius..+face_radius
        face_radius = min(self._width, self._height) * 0.45
        cy = cy + model.bounce * face_radius * 0.10
        # Horizontal squash: 1.0 = normal, 0.5 = squashed, 1.5 = stretched
        # We model squash as a uniform scale of the face radius (used by
        # sub-elements that respect a "horizontal scale" hint).
        face_radius *= 1.0
        eye_radius = face_radius * 0.30
        mouth_y = cy + face_radius * 0.55
        return cx, cy, face_radius, eye_radius, mouth_y

    def _sclera_radius(self, openness: float, eye_radius: float) -> tuple[float, float]:
        rx = eye_radius
        ry = max(eye_radius * 0.05, eye_radius * openness)
        return rx, ry

    # ------------------------------------------------------------------ layers
    def _draw_background(self, raster: _Raster, model: FaceModel) -> None:
        r, g, b = model.palette.background
        pixel = bytes((r, g, b)) * (raster.width * raster.height)
        raster.pixels[:] = pixel

    def _draw_cheeks(self, raster: _Raster, model: FaceModel) -> None:
        if model.cheeks.state is CheekState.NONE or model.cheeks.intensity <= 0.0:
            return
        cx, cy, face_radius, _, _ = self._face_geometry(model)
        # Cheek positions: left/right of mouth, below eyes
        for sx in (-1, 1):
            x = cx + sx * face_radius * 0.55
            y = cy + face_radius * 0.15
            color = (
                model.palette.blush
                if model.cheeks.state is CheekState.BRIGHT
                else model.palette.cheek
            )
            self._fill_circle_blend(raster, x, y, face_radius * 0.22, color, model.cheeks.intensity)

    def _draw_sclera(self, raster: _Raster, model: FaceModel) -> None:
        cx, cy, face_radius, eye_radius, _ = self._face_geometry(model)
        # Two eyes side by side
        for sx, eye in ((-1, model.left_eye), (1, model.right_eye)):
            ex = cx + sx * face_radius * 0.40
            ey = cy - face_radius * 0.18
            rx, ry = self._sclera_radius(eye.openness, eye_radius)
            self._fill_ellipse(raster, ex, ey, rx, ry, model.palette.sclera)
            if model.palette.outline != model.palette.sclera:
                self._draw_ellipse_outline(
                    raster,
                    ex,
                    ey,
                    rx,
                    ry,
                    model.palette.outline,
                    1,
                )

    def _draw_eyelids(self, raster: _Raster, model: FaceModel) -> None:
        if model.eyelids.top <= 0.0 and model.eyelids.bottom <= 0.0:
            return
        cx, cy, face_radius, eye_radius, _ = self._face_geometry(model)
        for sx in (-1, 1):
            ex = cx + sx * face_radius * 0.40
            ey = cy - face_radius * 0.18
            rx, ry = self._sclera_radius(1.0, eye_radius)
            if model.eyelids.top > 0.0:
                self._draw_horizontal_band(
                    raster,
                    ey - ry,
                    ey - ry + 2 * ry * model.eyelids.top,
                    ex,
                    rx,
                    model.palette.eyelid,
                )
            if model.eyelids.bottom > 0.0:
                self._draw_horizontal_band(
                    raster,
                    ey + ry - 2 * ry * model.eyelids.bottom,
                    ey + ry,
                    ex,
                    rx,
                    model.palette.eyelid,
                )

    def _draw_iris(self, raster: _Raster, model: FaceModel) -> None:
        cx, cy, face_radius, eye_radius, _ = self._face_geometry(model)
        for sx, eye in ((-1, model.left_eye), (1, model.right_eye)):
            ex = cx + sx * face_radius * 0.40
            ey = cy - face_radius * 0.18
            rx, ry = self._sclera_radius(eye.openness, eye_radius)
            if ry <= 1.0:
                continue
            gaze = eye.gaze.clamped()
            ox = gaze.x * self._width * 0.06
            oy = gaze.y * self._height * 0.06
            iris_cx = ex + ox
            iris_cy = ey + oy
            iris_rx = eye_radius * 0.55
            iris_ry = eye_radius * 0.55 * min(1.0, ry / rx) if rx > 0.0 else 0.0
            self._fill_ellipse(raster, iris_cx, iris_cy, iris_rx, iris_ry, model.palette.iris)
            self._draw_ellipse_outline(
                raster,
                iris_cx,
                iris_cy,
                iris_rx,
                iris_ry,
                model.palette.outline,
                1,
            )

    def _draw_pupil(self, raster: _Raster, model: FaceModel) -> None:
        cx, cy, face_radius, eye_radius, _ = self._face_geometry(model)
        for sx, eye in ((-1, model.left_eye), (1, model.right_eye)):
            ex = cx + sx * face_radius * 0.40
            ey = cy - face_radius * 0.18
            _rx, ry = self._sclera_radius(eye.openness, eye_radius)
            if ry <= 1.0:
                continue
            gaze = eye.gaze.clamped()
            ox = gaze.x * self._width * 0.06
            oy = gaze.y * self._height * 0.06
            iris_cx = ex + ox
            iris_cy = ey + oy
            base = eye_radius * 0.55 * 0.55
            pupil_r = base * (0.6 + 0.6 * eye.pupil_dilation)
            self._fill_circle(raster, iris_cx, iris_cy, pupil_r, model.palette.pupil)

    def _draw_highlight(self, raster: _Raster, model: FaceModel) -> None:
        cx, cy, face_radius, eye_radius, _ = self._face_geometry(model)
        for sx, eye in ((-1, model.left_eye), (1, model.right_eye)):
            ex = cx + sx * face_radius * 0.40
            ey = cy - face_radius * 0.18
            _rx, ry = self._sclera_radius(eye.openness, eye_radius)
            if ry <= 1.0:
                continue
            gaze = eye.gaze.clamped()
            ox = gaze.x * self._width * 0.06
            oy = gaze.y * self._height * 0.06
            iris_cx = ex + ox
            iris_cy = ey + oy
            hx = iris_cx + eye.highlight.x * eye_radius * 0.30
            hy = iris_cy + eye.highlight.y * eye_radius * 0.30
            self._fill_circle(raster, hx, hy, max(1.0, eye_radius * 0.08), model.palette.highlight)

    def _draw_eyebrows(self, raster: _Raster, model: FaceModel) -> None:
        cx, cy, face_radius, eye_radius, _ = self._face_geometry(model)
        for sx, brow in ((-1, model.left_eyebrow), (1, model.right_eyebrow)):
            ex = cx + sx * face_radius * 0.40
            ey = cy - face_radius * 0.18
            base_y = ey - eye_radius * (1.05 + brow.raise_amount)
            # Shape -> vertical offset
            if brow.shape is EyebrowShape.ANGRY:
                outer_y = base_y - 0.05 * face_radius
                inner_y = base_y + 0.10 * face_radius
            elif brow.shape is EyebrowShape.WORRIED:
                outer_y = base_y + 0.05 * face_radius
                inner_y = base_y - 0.10 * face_radius
            elif brow.shape is EyebrowShape.SAD:
                outer_y = base_y + 0.15 * face_radius
                inner_y = base_y - 0.05 * face_radius
            elif brow.shape is EyebrowShape.SLEEPY:
                outer_y = base_y - 0.10 * face_radius
                inner_y = base_y - 0.10 * face_radius
            else:  # NEUTRAL or RAISED
                outer_y = base_y
                inner_y = base_y

            # Add the angle tilt
            tilt = brow.angle * eye_radius * 0.4
            outer_y -= tilt
            inner_y += tilt

            thickness = max(1, int(eye_radius * 0.18))
            length = eye_radius * 0.95
            self._draw_thick_line(
                raster,
                ex - length / 2,
                outer_y,
                ex + length / 2,
                inner_y,
                thickness,
                model.palette.eyebrow,
            )

    def _draw_mouth(self, raster: _Raster, model: FaceModel) -> None:
        cx, _cy, face_radius, _, mouth_y = self._face_geometry(model)
        width = face_radius * 0.45
        shape = model.mouth.shape
        openness = model.mouth.openness
        width_scale = model.mouth.width
        actual_width = width * width_scale
        # Base line at mouth_y
        if shape is MouthShape.SMILE or shape is MouthShape.GRIN:
            curve = -face_radius * 0.10 * (1.0 + openness)
            self._draw_arc(raster, cx, mouth_y, actual_width, curve, model.palette.mouth, 3)
        elif shape is MouthShape.SMILE_OPEN:
            self._draw_arc(
                raster, cx, mouth_y, actual_width, -face_radius * 0.12, model.palette.mouth, 3
            )
            self._fill_circle(
                raster,
                cx,
                mouth_y - face_radius * 0.04,
                face_radius * 0.08 * openness,
                model.palette.background,
            )
        elif shape is MouthShape.FROWN:
            self._draw_arc(
                raster, cx, mouth_y, actual_width, face_radius * 0.10, model.palette.mouth, 3
            )
        elif shape is MouthShape.OPEN or shape is MouthShape.WIDE_OPEN:
            r = face_radius * (0.05 + 0.10 * openness) * (1.0 if shape is MouthShape.OPEN else 1.6)
            self._fill_circle(raster, cx, mouth_y, r, model.palette.mouth)
            if shape is MouthShape.WIDE_OPEN:
                # Inner dark
                self._fill_circle(raster, cx, mouth_y, r * 0.6, model.palette.background)
        elif shape is MouthShape.TONGUE:
            self._draw_arc(
                raster, cx, mouth_y, actual_width, -face_radius * 0.05, model.palette.mouth, 3
            )
            # Pink tongue
            self._fill_circle(
                raster, cx, mouth_y - face_radius * 0.01, face_radius * 0.06, (255, 130, 180)
            )
        else:  # CLOSED or NEUTRAL
            self._draw_arc(raster, cx, mouth_y, actual_width, 0.0, model.palette.mouth, 2)
        if model.mouth.asymmetry != 0.0:
            skew = model.mouth.asymmetry * actual_width * 0.3
            self._draw_arc(raster, cx + skew, mouth_y, actual_width, 0.0, model.palette.mouth, 2)

    def _draw_overlay(self, raster: _Raster, model: FaceModel) -> None:
        ov = model.overlay
        if ov.kind is OverlayKind.NONE:
            return
        cx, cy, face_radius, _, _ = self._face_geometry(model)
        # Position is in normalised face coordinates (-1..1) -> pixels
        x = cx + ov.position.x * face_radius
        y = cy + ov.position.y * face_radius
        size = max(2, int(face_radius * ov.size))
        if ov.kind is OverlayKind.SPARKLE or ov.kind is OverlayKind.STAR:
            # 4-pointed star: a small filled diamond
            self._fill_diamond(raster, x, y, size, ov.color)
        elif ov.kind is OverlayKind.HEART:
            self._fill_heart(raster, x, y, size, ov.color)
        elif ov.kind is OverlayKind.TEAR:
            self._fill_teardrop(raster, x, y, size, (80, 150, 255))
        elif ov.kind is OverlayKind.SWEAT:
            self._fill_teardrop(raster, x, y, size, (130, 200, 255))
        elif ov.kind is OverlayKind.ANGER:
            self._fill_diamond(raster, x, y, size, (255, 50, 50))
        elif ov.kind is OverlayKind.QUESTION:
            self._fill_circle(raster, x, y, size * 0.6, (255, 220, 60))
        elif ov.kind is OverlayKind.EXCLAIM:
            self._fill_circle(raster, x, y, size * 0.6, (255, 80, 80))
        elif ov.kind is OverlayKind.MUSIC:
            self._fill_circle(raster, x, y, size * 0.5, (60, 200, 255))

    def _draw_accessory(self, raster: _Raster, model: FaceModel) -> None:
        acc = model.accessory
        if acc.kind is AccessoryKind.NONE:
            return
        cx, cy, face_radius, eye_radius, _ = self._face_geometry(model)
        if acc.kind is AccessoryKind.GLASSES:
            # Two round rims
            for sx in (-1, 1):
                ex = cx + sx * face_radius * 0.40
                ey = cy - face_radius * 0.18
                self._draw_ellipse_outline(
                    raster, ex, ey, eye_radius * 0.85, eye_radius * 0.65, acc.color, 2
                )
            # Bridge
            self._draw_horizontal_band(
                raster,
                cy - face_radius * 0.20,
                cy - face_radius * 0.16,
                cx,
                face_radius * 0.20,
                acc.color,
            )
        elif acc.kind is AccessoryKind.SUNGLASSES:
            for sx in (-1, 1):
                ex = cx + sx * face_radius * 0.40
                ey = cy - face_radius * 0.18
                self._fill_ellipse(raster, ex, ey, eye_radius * 0.85, eye_radius * 0.55, acc.color)
        elif acc.kind is AccessoryKind.MUSTACHE:
            self._draw_mustache(raster, cx, cy + face_radius * 0.30, face_radius * 0.5, acc.color)
        elif acc.kind is AccessoryKind.BOW_TIE:
            self._draw_bow_tie(
                raster, cx, self._height - face_radius * 0.20, face_radius * 0.4, acc.color
            )
        elif acc.kind is AccessoryKind.HAT:
            # A simple band + brim
            self._draw_horizontal_band(
                raster,
                cy - face_radius,
                cy - face_radius * 0.7,
                cx,
                face_radius,
                acc.color,
            )
            self._draw_horizontal_band(
                raster,
                cy - face_radius * 0.7,
                cy - face_radius * 0.55,
                cx,
                face_radius * 1.1,
                acc.color,
            )
        elif acc.kind is AccessoryKind.CROWN:
            self._draw_crown(raster, cx, cy - face_radius * 0.85, face_radius * 0.9, acc.color)
        elif acc.kind is AccessoryKind.BANDAGE:
            self._draw_horizontal_band(
                raster,
                cy - face_radius * 0.6,
                cy - face_radius * 0.30,
                cx,
                face_radius * 0.9,
                (200, 200, 200),
            )
        elif acc.kind is AccessoryKind.HEART_EYES:
            for sx in (-1, 1):
                ex = cx + sx * face_radius * 0.40
                ey = cy - face_radius * 0.18
                self._fill_heart(raster, ex, ey, eye_radius * 0.7, (255, 80, 120))

    # ------------------------------------------------------------------ primitive stubs
    # (Detailed pixel-art primitives live below.)

    def _fill_circle(
        self,
        raster: _Raster,
        cx: float,
        cy: float,
        r: float,
        color: tuple[int, int, int],
    ) -> None:
        if r <= 0:
            return
        self._fill_ellipse(raster, cx, cy, r, r, color)

    def _fill_circle_blend(
        self,
        raster: _Raster,
        cx: float,
        cy: float,
        r: float,
        color: tuple[int, int, int],
        alpha: float,
    ) -> None:
        """Fill a circle with alpha-blending onto the background."""
        if r <= 0 or alpha <= 0.0:
            return
        alpha = max(0.0, min(1.0, alpha))
        w, h = raster.width, raster.height
        pr, pg, pb = color
        x0 = max(0, math.floor(cx - r))
        x1 = min(w - 1, math.ceil(cx + r))
        y0 = max(0, math.floor(cy - r))
        y1 = min(h - 1, math.ceil(cy + r))
        r2 = r * r
        for y in range(y0, y1 + 1):
            dy = y - cy
            row = (y * w) * 3
            for x in range(x0, x1 + 1):
                dx = x - cx
                if dx * dx + dy * dy > r2:
                    continue
                idx = row + x * 3
                # Soft falloff at the edge
                edge = 1.0 - (dx * dx + dy * dy) / r2 if r2 > 0.0 else 0.0
                local_alpha = alpha * (0.4 + 0.6 * edge)
                br = raster.pixels[idx]
                bg = raster.pixels[idx + 1]
                bb = raster.pixels[idx + 2]
                raster.pixels[idx] = int(br * (1 - local_alpha) + pr * local_alpha)
                raster.pixels[idx + 1] = int(bg * (1 - local_alpha) + pg * local_alpha)
                raster.pixels[idx + 2] = int(bb * (1 - local_alpha) + pb * local_alpha)

    def _fill_ellipse(
        self,
        raster: _Raster,
        cx: float,
        cy: float,
        rx: float,
        ry: float,
        color: tuple[int, int, int],
    ) -> None:
        if rx <= 0 or ry <= 0:
            return
        pr, pg, pb = color
        w, h = raster.width, raster.height
        x0 = max(0, math.floor(cx - rx))
        x1 = min(w - 1, math.ceil(cx + rx))
        y0 = max(0, math.floor(cy - ry))
        y1 = min(h - 1, math.ceil(cy + ry))
        if rx == ry:
            r2 = rx * rx
            for y in range(y0, y1 + 1):
                dy = y - cy
                row = (y * w) * 3
                for x in range(x0, x1 + 1):
                    dx = x - cx
                    if dx * dx + dy * dy <= r2:
                        idx = row + x * 3
                        raster.pixels[idx] = pr
                        raster.pixels[idx + 1] = pg
                        raster.pixels[idx + 2] = pb
            return
        inv_rx2 = 1.0 / (rx * rx) if rx > 0.0 else 0.0
        inv_ry2 = 1.0 / (ry * ry) if ry > 0.0 else 0.0
        for y in range(y0, y1 + 1):
            dy = y - cy
            row = (y * w) * 3
            for x in range(x0, x1 + 1):
                dx = x - cx
                if dx * dx * inv_rx2 + dy * dy * inv_ry2 <= 1.0:
                    idx = row + x * 3
                    raster.pixels[idx] = pr
                    raster.pixels[idx + 1] = pg
                    raster.pixels[idx + 2] = pb

    def _draw_ellipse_outline(
        self,
        raster: _Raster,
        cx: float,
        cy: float,
        rx: float,
        ry: float,
        color: tuple[int, int, int],
        width: int,
    ) -> None:
        if rx <= 0 or ry <= 0 or width <= 0:
            return
        for w in range(width):
            self._draw_ellipse(raster, cx, cy, max(0.0, rx - w), max(0.0, ry - w), color)

    def _draw_ellipse(
        self,
        raster: _Raster,
        cx: float,
        cy: float,
        rx: float,
        ry: float,
        color: tuple[int, int, int],
    ) -> None:
        if rx == ry:
            self._draw_circle(raster, cx, cy, rx, color)
            return
        pr, pg, pb = color
        w, h = raster.width, raster.height

        def put(px: int, py: int) -> None:
            if 0 <= px < w and 0 <= py < h:
                idx = (py * w + px) * 3
                raster.pixels[idx] = pr
                raster.pixels[idx + 1] = pg
                raster.pixels[idx + 2] = pb

        rx2 = rx * rx
        ry2 = ry * ry
        x = 0.0
        y = ry
        px = 0.0
        py = 2 * rx2 * y
        d1 = ry2 - rx2 * ry + 0.25 * rx2
        while px < py:
            put(int(cx + x), int(cy + y))
            put(int(cx - x), int(cy + y))
            put(int(cx + x), int(cy - y))
            put(int(cx - x), int(cy - y))
            x += 1
            px += 2 * ry2
            if d1 < 0:
                d1 += ry2 + px
            else:
                y -= 1
                py -= 2 * rx2
                d1 += ry2 + px - py
        d2 = ry2 * (x + 0.5) * (x + 0.5) + rx2 * (y - 1) * (y - 1) - rx2 * ry2
        while y > 0:
            put(int(cx + x), int(cy + y))
            put(int(cx - x), int(cy + y))
            put(int(cx + x), int(cy - y))
            put(int(cx - x), int(cy - y))
            y -= 1
            py -= 2 * rx2
            if d2 > 0:
                d2 += rx2 - py
            else:
                x += 1
                px += 2 * ry2
                d2 += rx2 - py + px

    def _draw_circle(
        self,
        raster: _Raster,
        cx: float,
        cy: float,
        r: float,
        color: tuple[int, int, int],
    ) -> None:
        if r <= 0:
            return
        pr, pg, pb = color
        w, h = raster.width, raster.height

        def put(px: int, py: int) -> None:
            if 0 <= px < w and 0 <= py < h:
                idx = (py * w + px) * 3
                raster.pixels[idx] = pr
                raster.pixels[idx + 1] = pg
                raster.pixels[idx + 2] = pb

        x = round(r)
        y = 0
        err = 0
        icx, icy = round(cx), round(cy)
        while x >= y:
            put(icx + x, icy + y)
            put(icx + y, icy + x)
            put(icx - y, icy + x)
            put(icx - x, icy + y)
            put(icx - x, icy - y)
            put(icx - y, icy - x)
            put(icx + y, icy - x)
            put(icx + x, icy - y)
            y += 1
            err += 1 + 2 * y
            if 2 * (err - x) + 1 > 0:
                x -= 1
                err += 1 - 2 * x

    def _draw_horizontal_band(
        self,
        raster: _Raster,
        y_top: float,
        y_bottom: float,
        cx: float,
        rx: float,
        color: tuple[int, int, int],
    ) -> None:
        pr, pg, pb = color
        w, h = raster.width, raster.height
        x0 = max(0, math.floor(cx - rx))
        x1 = min(w - 1, math.ceil(cx + rx))
        y0 = max(0, math.ceil(y_top))
        y1 = min(h - 1, math.floor(y_bottom))
        rx2 = rx * rx
        band_cy = (y_top + y_bottom) / 2.0
        for y in range(y0, y1 + 1):
            dy = y - band_cy
            row = (y * w) * 3
            for x in range(x0, x1 + 1):
                dx = x - cx
                if dx * dx + dy * dy > rx2:
                    continue
                idx = row + x * 3
                raster.pixels[idx] = pr
                raster.pixels[idx + 1] = pg
                raster.pixels[idx + 2] = pb

    def _draw_arc(
        self,
        raster: _Raster,
        cx: float,
        cy: float,
        width: float,
        curve: float,
        color: tuple[int, int, int],
        thickness: int,
    ) -> None:
        """Draw a smile/frown arc as a thin filled strip.

        ``curve`` is positive for a frown, negative for a smile. The
        arc is sampled at many x positions and a small vertical strip
        of ``thickness`` pixels is drawn.
        """
        if abs(curve) < 0.5:
            # Treat as a horizontal line
            y = int(cy)
            for x in range(int(cx - width / 2), int(cx + width / 2) + 1):
                for t in range(thickness):
                    py = y - thickness // 2 + t
                    if 0 <= x < raster.width and 0 <= py < raster.height:
                        idx = (py * raster.width + x) * 3
                        raster.pixels[idx] = color[0]
                        raster.pixels[idx + 1] = color[1]
                        raster.pixels[idx + 2] = color[2]
            return
        # Parametric arc: y = cy + curve * (1 - ((x-cx) / (width/2)) ** 2)
        steps: int = max(8, round(width))
        half: float = width / 2.0
        if half <= 0.0:
            return
        cx_f: float = float(cx)
        cy_f: float = float(cy)
        curve_f: float = float(curve)
        for i in range(steps + 1):
            x_f: float = cx_f - half + (i / steps) * width
            t_f: float = (x_f - cx_f) / half
            y_f: float = cy_f - curve_f * (1 - t_f * t_f)
            for k in range(-thickness // 2, thickness // 2 + 1):
                px, py = round(x_f), round(y_f + k)
                if 0 <= px < raster.width and 0 <= py < raster.height:
                    idx = (py * raster.width + px) * 3
                    raster.pixels[idx] = color[0]
                    raster.pixels[idx + 1] = color[1]
                    raster.pixels[idx + 2] = color[2]

    def _draw_thick_line(
        self,
        raster: _Raster,
        x0: float,
        y0: float,
        x1: float,
        y1: float,
        thickness: int,
        color: tuple[int, int, int],
    ) -> None:
        # Bresenham with a brush
        steps = max(2, int(max(abs(x1 - x0), abs(y1 - y0)) * 2))
        for i in range(steps + 1):
            t = i / steps
            x = x0 + (x1 - x0) * t
            y = y0 + (y1 - y0) * t
            for dx in range(-thickness // 2, thickness // 2 + 1):
                for dy in range(-thickness // 2, thickness // 2 + 1):
                    px, py = round(x + dx), round(y + dy)
                    if 0 <= px < raster.width and 0 <= py < raster.height:
                        idx = (py * raster.width + px) * 3
                        raster.pixels[idx] = color[0]
                        raster.pixels[idx + 1] = color[1]
                        raster.pixels[idx + 2] = color[2]

    def _fill_diamond(
        self,
        raster: _Raster,
        cx: float,
        cy: float,
        size: float,
        color: tuple[int, int, int],
    ) -> None:
        self._fill_ellipse(raster, cx, cy, size * 0.45, size, color)

    def _fill_heart(
        self,
        raster: _Raster,
        cx: float,
        cy: float,
        size: float,
        color: tuple[int, int, int],
    ) -> None:
        # Two small circles + a downward triangle
        r = size * 0.45
        self._fill_circle(raster, cx - r * 0.6, cy - r * 0.3, r, color)
        self._fill_circle(raster, cx + r * 0.6, cy - r * 0.3, r, color)
        # Triangle (approximated with a rotated square)
        for y in range(int(cy - r * 0.3), int(cy + size * 0.7) + 1):
            t = (y - (cy - r * 0.3)) / (size + 0.2 * r)
            t = max(0.0, min(1.0, t))
            half = size * 0.6 * (1.0 - t)
            for x in range(int(cx - half), int(cx + half) + 1):
                if 0 <= x < raster.width and 0 <= y < raster.height:
                    idx = (y * raster.width + x) * 3
                    raster.pixels[idx] = color[0]
                    raster.pixels[idx + 1] = color[1]
                    raster.pixels[idx + 2] = color[2]

    def _fill_teardrop(
        self,
        raster: _Raster,
        cx: float,
        cy: float,
        size: float,
        color: tuple[int, int, int],
    ) -> None:
        # Circle + triangle pointing down
        r = size * 0.4
        self._fill_circle(raster, cx, cy - size * 0.3, r, color)
        for y in range(int(cy - size * 0.3), int(cy + size * 0.6) + 1):
            t = (y - (cy - size * 0.3)) / (size * 0.9)
            t = max(0.0, min(1.0, t))
            half = size * 0.4 * (1.0 - t)
            for x in range(int(cx - half), int(cx + half) + 1):
                if 0 <= x < raster.width and 0 <= y < raster.height:
                    idx = (y * raster.width + x) * 3
                    raster.pixels[idx] = color[0]
                    raster.pixels[idx + 1] = color[1]
                    raster.pixels[idx + 2] = color[2]

    def _draw_mustache(
        self,
        raster: _Raster,
        cx: float,
        cy: float,
        length: float,
        color: tuple[int, int, int],
    ) -> None:
        # Two curves meeting in the middle
        for sx in (-1, 1):
            self._draw_arc(
                raster,
                cx + sx * length * 0.30,
                cy - sx * length * 0.05,
                length * 0.6,
                -length * 0.10 * sx,
                color,
                3,
            )

    def _draw_bow_tie(
        self,
        raster: _Raster,
        cx: float,
        cy: float,
        size: float,
        color: tuple[int, int, int],
    ) -> None:
        # Two triangles
        for sx in (-1, 1):
            for y in range(int(cy - size / 2), int(cy + size / 2) + 1):
                t = (y - (cy - size / 2)) / size
                half = size * 0.4 * (1.0 - abs(t - 0.5) * 2)
                x_start = cx + sx * size * 0.05
                x_end = x_start + sx * half
                for x in range(int(min(x_start, x_end)), int(max(x_start, x_end)) + 1):
                    if 0 <= x < raster.width and 0 <= y < raster.height:
                        idx = (y * raster.width + x) * 3
                        raster.pixels[idx] = color[0]
                        raster.pixels[idx + 1] = color[1]
                        raster.pixels[idx + 2] = color[2]

    def _draw_crown(
        self,
        raster: _Raster,
        cx: float,
        cy: float,
        length: float,
        color: tuple[int, int, int],
    ) -> None:
        # Three triangles
        points = [
            (cx - length / 2, cy),
            (cx - length / 4, cy - length / 3),
            (cx, cy),
            (cx + length / 4, cy - length / 3),
            (cx + length / 2, cy),
            (cx + length / 2, cy + length / 6),
            (cx - length / 2, cy + length / 6),
        ]
        for i in range(len(points) - 1):
            self._draw_thick_line(
                raster,
                points[i][0],
                points[i][1],
                points[i + 1][0],
                points[i + 1][1],
                2,
                color,
            )

height property

width property

__init__(width=240, height=240)

Source code in src/robot/face/renderer.py
def __init__(self, width: int = 240, height: int = 240) -> None:
    if width <= 0 or height <= 0:
        raise ValueError("width and height must be > 0")
    self._width = width
    self._height = height

render(model)

Render model into a new RGB888 frame.

Source code in src/robot/face/renderer.py
def render(self, model: FaceModel) -> EyeFrame:
    """Render ``model`` into a new RGB888 frame."""
    if model.width != self._width or model.height != self._height:
        raise ValueError(
            f"model is {model.width}x{model.height}, renderer is {self._width}x{self._height}"
        )
    raster = self._new_raster()
    # Vector mode bypasses the full face stack and renders only the
    # minimalist "two glowing squares + a horizontal line" used by the
    # Anki Vector 2.0 face. Cheeks/eyebrows/iris/sclera are skipped
    # because the Vector palette does not use them.
    if model.palette.mode == PALETTE_MODE_VECTOR:
        self._draw_background(raster, model)
        self._draw_vector_eyes(raster, model)
        self._draw_vector_mouth(raster, model)
        return EyeFrame(width=self._width, height=self._height, pixels=bytes(raster.pixels))
    self._draw_background(raster, model)
    self._draw_cheeks(raster, model)
    self._draw_sclera(raster, model)
    self._draw_eyelids(raster, model)
    self._draw_iris(raster, model)
    self._draw_pupil(raster, model)
    self._draw_highlight(raster, model)
    self._draw_eyebrows(raster, model)
    self._draw_mouth(raster, model)
    self._draw_overlay(raster, model)
    self._draw_accessory(raster, model)
    return EyeFrame(width=self._width, height=self._height, pixels=bytes(raster.pixels))

FrameProfiler

Measures frame rendering performance and reports budget compliance.

Parameters

target_fps: The desired frame rate used to compute the per-frame budget. window: Rolling window size (number of recent frames kept for statistics). report_interval: Publish a :class:FrameStatsReport event every this many frames. Set to 0 to disable periodic reports. bus: Optional event bus for publishing :class:FrameStatsReport events. enabled: When False, :meth:record_frame is a no-op.

Source code in src/robot/performance/frame_profiler.py
class FrameProfiler:
    """Measures frame rendering performance and reports budget compliance.

    Parameters
    ----------
    target_fps:
        The desired frame rate used to compute the per-frame budget.
    window:
        Rolling window size (number of recent frames kept for statistics).
    report_interval:
        Publish a :class:`FrameStatsReport` event every this many frames.
        Set to ``0`` to disable periodic reports.
    bus:
        Optional event bus for publishing :class:`FrameStatsReport` events.
    enabled:
        When ``False``, :meth:`record_frame` is a no-op.
    """

    def __init__(
        self,
        target_fps: int = 30,
        window: int = 100,
        report_interval: int = 100,
        bus: InMemoryEventBus | None = None,
        enabled: bool = True,
    ) -> None:
        if target_fps <= 0:
            raise ValueError("target_fps must be > 0")
        if window <= 0:
            raise ValueError("window must be > 0")

        self._target_fps = target_fps
        self._window = window
        self._report_interval = report_interval
        self._bus = bus
        self.enabled = enabled

        self._frame_times_ms: list[float] = []
        self._total_frames: int = 0
        self._dropped_frames: int = 0
        self._budget_ms: float = 1000.0 / target_fps

    # ------------------------------------------------------------------ public API
    def record_frame(self, start: float, end: float) -> None:
        """Record the timing of a single frame.

        *start* and *end* must be monotonic timestamps
        (``time.monotonic()`` values). This method is a fast no-op when
        ``self.enabled`` is ``False``.
        """
        if not self.enabled:
            return

        frame_time_ms = (end - start) * 1000.0
        self._frame_times_ms.append(frame_time_ms)
        self._total_frames += 1

        # Trim to rolling window
        if len(self._frame_times_ms) > self._window:
            self._frame_times_ms = self._frame_times_ms[-self._window :]

        # Track dropped frames
        if frame_time_ms > self._budget_ms:
            self._dropped_frames += 1
            _log.warning(
                "frame.budget_exceeded",
                frame_time_ms=round(frame_time_ms, 2),
                budget_ms=round(self._budget_ms, 2),
            )

        # Periodic report
        if (
            self._report_interval > 0
            and self._total_frames % self._report_interval == 0
            and self._bus is not None
        ):
            import asyncio

            report = FrameStatsReport(stats=self.stats())
            try:
                loop = asyncio.get_running_loop()
                _task = loop.create_task(self._bus.publish(report))  # noqa: RUF006
            except RuntimeError:
                # No running loop: publish synchronously is not safe;
                # the report will simply be skipped.
                pass

    def stats(self) -> FrameStats:
        """Return a snapshot of current frame performance statistics."""
        if not self._frame_times_ms:
            return FrameStats(
                target_fps=self._target_fps,
                actual_fps=0.0,
                avg_frame_time_ms=0.0,
                p50_frame_time_ms=0.0,
                p95_frame_time_ms=0.0,
                p99_frame_time_ms=0.0,
                dropped_frames=0,
                total_frames=0,
            )

        times = sorted(self._frame_times_ms)
        n = len(times)
        avg = sum(times) / n
        actual_fps = 1000.0 / avg if avg > 0 else 0.0

        return FrameStats(
            target_fps=self._target_fps,
            actual_fps=round(actual_fps, 2),
            avg_frame_time_ms=round(avg, 2),
            p50_frame_time_ms=round(self._percentile(times, 50), 2),
            p95_frame_time_ms=round(self._percentile(times, 95), 2),
            p99_frame_time_ms=round(self._percentile(times, 99), 2),
            dropped_frames=self._dropped_frames,
            total_frames=self._total_frames,
        )

    def reset(self) -> None:
        """Clear all recorded data."""
        self._frame_times_ms.clear()
        self._total_frames = 0
        self._dropped_frames = 0

    # ------------------------------------------------------------------ helpers
    @staticmethod
    def _percentile(sorted_data: list[float], pct: float) -> float:
        """Compute the *pct*-th percentile of sorted data."""
        if not sorted_data:
            return 0.0
        k = (pct / 100.0) * (len(sorted_data) - 1)
        f = int(k)
        c = f + 1
        if c >= len(sorted_data):
            return sorted_data[-1]
        return sorted_data[f] + (k - f) * (sorted_data[c] - sorted_data[f])

enabled = enabled instance-attribute

__init__(target_fps=30, window=100, report_interval=100, bus=None, enabled=True)

Source code in src/robot/performance/frame_profiler.py
def __init__(
    self,
    target_fps: int = 30,
    window: int = 100,
    report_interval: int = 100,
    bus: InMemoryEventBus | None = None,
    enabled: bool = True,
) -> None:
    if target_fps <= 0:
        raise ValueError("target_fps must be > 0")
    if window <= 0:
        raise ValueError("window must be > 0")

    self._target_fps = target_fps
    self._window = window
    self._report_interval = report_interval
    self._bus = bus
    self.enabled = enabled

    self._frame_times_ms: list[float] = []
    self._total_frames: int = 0
    self._dropped_frames: int = 0
    self._budget_ms: float = 1000.0 / target_fps

record_frame(start, end)

Record the timing of a single frame.

start and end must be monotonic timestamps (time.monotonic() values). This method is a fast no-op when self.enabled is False.

Source code in src/robot/performance/frame_profiler.py
def record_frame(self, start: float, end: float) -> None:
    """Record the timing of a single frame.

    *start* and *end* must be monotonic timestamps
    (``time.monotonic()`` values). This method is a fast no-op when
    ``self.enabled`` is ``False``.
    """
    if not self.enabled:
        return

    frame_time_ms = (end - start) * 1000.0
    self._frame_times_ms.append(frame_time_ms)
    self._total_frames += 1

    # Trim to rolling window
    if len(self._frame_times_ms) > self._window:
        self._frame_times_ms = self._frame_times_ms[-self._window :]

    # Track dropped frames
    if frame_time_ms > self._budget_ms:
        self._dropped_frames += 1
        _log.warning(
            "frame.budget_exceeded",
            frame_time_ms=round(frame_time_ms, 2),
            budget_ms=round(self._budget_ms, 2),
        )

    # Periodic report
    if (
        self._report_interval > 0
        and self._total_frames % self._report_interval == 0
        and self._bus is not None
    ):
        import asyncio

        report = FrameStatsReport(stats=self.stats())
        try:
            loop = asyncio.get_running_loop()
            _task = loop.create_task(self._bus.publish(report))  # noqa: RUF006
        except RuntimeError:
            # No running loop: publish synchronously is not safe;
            # the report will simply be skipped.
            pass

reset()

Clear all recorded data.

Source code in src/robot/performance/frame_profiler.py
def reset(self) -> None:
    """Clear all recorded data."""
    self._frame_times_ms.clear()
    self._total_frames = 0
    self._dropped_frames = 0

stats()

Return a snapshot of current frame performance statistics.

Source code in src/robot/performance/frame_profiler.py
def stats(self) -> FrameStats:
    """Return a snapshot of current frame performance statistics."""
    if not self._frame_times_ms:
        return FrameStats(
            target_fps=self._target_fps,
            actual_fps=0.0,
            avg_frame_time_ms=0.0,
            p50_frame_time_ms=0.0,
            p95_frame_time_ms=0.0,
            p99_frame_time_ms=0.0,
            dropped_frames=0,
            total_frames=0,
        )

    times = sorted(self._frame_times_ms)
    n = len(times)
    avg = sum(times) / n
    actual_fps = 1000.0 / avg if avg > 0 else 0.0

    return FrameStats(
        target_fps=self._target_fps,
        actual_fps=round(actual_fps, 2),
        avg_frame_time_ms=round(avg, 2),
        p50_frame_time_ms=round(self._percentile(times, 50), 2),
        p95_frame_time_ms=round(self._percentile(times, 95), 2),
        p99_frame_time_ms=round(self._percentile(times, 99), 2),
        dropped_frames=self._dropped_frames,
        total_frames=self._total_frames,
    )

Gaze dataclass

2D gaze target normalised in [-1, 1].

Source code in src/robot/face/components.py
@dataclass(slots=True, frozen=True)
class Gaze:
    """2D gaze target normalised in ``[-1, 1]``."""

    x: float = 0.0
    y: float = 0.0

    def clamped(self) -> Gaze:
        return Gaze(
            x=max(-1.0, min(1.0, self.x)),
            y=max(-1.0, min(1.0, self.y)),
        )

x = 0.0 class-attribute instance-attribute

y = 0.0 class-attribute instance-attribute

__init__(x=0.0, y=0.0)

clamped()

Source code in src/robot/face/components.py
def clamped(self) -> Gaze:
    return Gaze(
        x=max(-1.0, min(1.0, self.x)),
        y=max(-1.0, min(1.0, self.y)),
    )

InMemoryEventBus

An async pub/sub bus for in-process events with handler priority.

Critical handlers have their exceptions propagated; non-critical handlers have their exceptions logged and isolated.

Source code in src/robot/events/bus.py
class InMemoryEventBus:
    """An async pub/sub bus for in-process events with handler priority.

    Critical handlers have their exceptions propagated; non-critical
    handlers have their exceptions logged and isolated.
    """

    def __init__(self) -> None:
        self._subscribers: dict[type, list[_Subscription]] = defaultdict(list)
        self._lock = asyncio.Lock()
        self._sync_lock = threading.Lock()
        self._closed = False

    async def publish(self, event: object) -> None:
        """Publish an event to all subscribers."""
        if self._closed:
            return
        event_type = type(event)
        async with self._lock:
            subs = list(self._subscribers.get(event_type, []))
            if event_type is not object:
                subs.extend(self._subscribers.get(object, []))

        critical_subs = [s for s in subs if s.critical]
        non_critical_subs = [s for s in subs if not s.critical]

        critical_failures: list[HandlerFailedError] = []
        for sub in critical_subs:
            handler = sub.handler
            try:
                result = handler(event)
                if asyncio.iscoroutine(result):
                    await result
            except Exception as exc:
                hf = HandlerFailedError(
                    event_type=event_type.__name__,
                    handler=getattr(handler, "__qualname__", repr(handler)),
                    original=exc,
                )
                critical_failures.append(hf)
                _log.exception(
                    "events.critical_handler_failed",
                    event_type=event_type.__name__,
                    handler=hf.handler,
                )

        for sub in non_critical_subs:
            handler = sub.handler
            try:
                result = handler(event)
                if asyncio.iscoroutine(result):
                    await result
            except Exception:
                _log.exception(
                    "events.handler_failed",
                    event_type=event_type.__name__,
                    handler=getattr(handler, "__qualname__", repr(handler)),
                )

        if critical_failures:
            if len(critical_failures) > 1:
                _log.warning(
                    "events.suppressed_critical_failures",
                    count=len(critical_failures) - 1,
                )
            raise critical_failures[0]

    def subscribe(self, event_type: type, handler: EventHandler) -> None:
        """Subscribe a non-critical handler for events of ``event_type``."""
        sub = _Subscription(handler=handler, critical=False)
        with self._sync_lock:
            if sub in self._subscribers[event_type]:
                return
            self._subscribers[event_type].append(sub)
        _log.debug("events.subscribed", event_type=event_type.__name__, handler=handler.__name__)

    def subscribe_critical(self, event_type: type, handler: EventHandler) -> None:
        """Subscribe a critical handler for events of ``event_type``."""
        sub = _Subscription(handler=handler, critical=True)
        with self._sync_lock:
            self._subscribers[event_type].append(sub)
        _log.debug(
            "events.subscribed_critical",
            event_type=event_type.__name__,
            handler=handler.__name__,
        )

    def unsubscribe(self, event_type: type, handler: EventHandler) -> None:
        """Unsubscribe a previously-registered handler."""
        with self._sync_lock:
            self._subscribers[event_type] = [
                s for s in self._subscribers[event_type] if s.handler != handler
            ]

    async def close(self) -> None:
        self._closed = True
        self._subscribers.clear()

    def __repr__(self) -> str:
        total = sum(len(v) for v in self._subscribers.values())
        return f"InMemoryEventBus(subscribers={total}, closed={self._closed})"

__init__()

Source code in src/robot/events/bus.py
def __init__(self) -> None:
    self._subscribers: dict[type, list[_Subscription]] = defaultdict(list)
    self._lock = asyncio.Lock()
    self._sync_lock = threading.Lock()
    self._closed = False

__repr__()

Source code in src/robot/events/bus.py
def __repr__(self) -> str:
    total = sum(len(v) for v in self._subscribers.values())
    return f"InMemoryEventBus(subscribers={total}, closed={self._closed})"

close() async

Source code in src/robot/events/bus.py
async def close(self) -> None:
    self._closed = True
    self._subscribers.clear()

publish(event) async

Publish an event to all subscribers.

Source code in src/robot/events/bus.py
async def publish(self, event: object) -> None:
    """Publish an event to all subscribers."""
    if self._closed:
        return
    event_type = type(event)
    async with self._lock:
        subs = list(self._subscribers.get(event_type, []))
        if event_type is not object:
            subs.extend(self._subscribers.get(object, []))

    critical_subs = [s for s in subs if s.critical]
    non_critical_subs = [s for s in subs if not s.critical]

    critical_failures: list[HandlerFailedError] = []
    for sub in critical_subs:
        handler = sub.handler
        try:
            result = handler(event)
            if asyncio.iscoroutine(result):
                await result
        except Exception as exc:
            hf = HandlerFailedError(
                event_type=event_type.__name__,
                handler=getattr(handler, "__qualname__", repr(handler)),
                original=exc,
            )
            critical_failures.append(hf)
            _log.exception(
                "events.critical_handler_failed",
                event_type=event_type.__name__,
                handler=hf.handler,
            )

    for sub in non_critical_subs:
        handler = sub.handler
        try:
            result = handler(event)
            if asyncio.iscoroutine(result):
                await result
        except Exception:
            _log.exception(
                "events.handler_failed",
                event_type=event_type.__name__,
                handler=getattr(handler, "__qualname__", repr(handler)),
            )

    if critical_failures:
        if len(critical_failures) > 1:
            _log.warning(
                "events.suppressed_critical_failures",
                count=len(critical_failures) - 1,
            )
        raise critical_failures[0]

subscribe(event_type, handler)

Subscribe a non-critical handler for events of event_type.

Source code in src/robot/events/bus.py
def subscribe(self, event_type: type, handler: EventHandler) -> None:
    """Subscribe a non-critical handler for events of ``event_type``."""
    sub = _Subscription(handler=handler, critical=False)
    with self._sync_lock:
        if sub in self._subscribers[event_type]:
            return
        self._subscribers[event_type].append(sub)
    _log.debug("events.subscribed", event_type=event_type.__name__, handler=handler.__name__)

subscribe_critical(event_type, handler)

Subscribe a critical handler for events of event_type.

Source code in src/robot/events/bus.py
def subscribe_critical(self, event_type: type, handler: EventHandler) -> None:
    """Subscribe a critical handler for events of ``event_type``."""
    sub = _Subscription(handler=handler, critical=True)
    with self._sync_lock:
        self._subscribers[event_type].append(sub)
    _log.debug(
        "events.subscribed_critical",
        event_type=event_type.__name__,
        handler=handler.__name__,
    )

unsubscribe(event_type, handler)

Unsubscribe a previously-registered handler.

Source code in src/robot/events/bus.py
def unsubscribe(self, event_type: type, handler: EventHandler) -> None:
    """Unsubscribe a previously-registered handler."""
    with self._sync_lock:
        self._subscribers[event_type] = [
            s for s in self._subscribers[event_type] if s.handler != handler
        ]

Mouth dataclass

The mouth, parameterised.

Source code in src/robot/face/components.py
@dataclass(slots=True, frozen=True)
class Mouth:
    """The mouth, parameterised."""

    shape: MouthShape = MouthShape.NEUTRAL
    openness: float = 0.0  # 0.0 = closed, 1.0 = wide open
    width: float = 0.5  # 0.0 = small, 1.0 = wide
    asymmetry: float = 0.0  # -1..1 (left side higher = smirk)

asymmetry = 0.0 class-attribute instance-attribute

openness = 0.0 class-attribute instance-attribute

shape = MouthShape.NEUTRAL class-attribute instance-attribute

width = 0.5 class-attribute instance-attribute

__init__(shape=MouthShape.NEUTRAL, openness=0.0, width=0.5, asymmetry=0.0)

MouthShape

Bases: str, Enum

Source code in src/robot/face/components.py
class MouthShape(str, Enum):
    CLOSED = "closed"
    NEUTRAL = "neutral"
    SMILE = "smile"
    GRIN = "grin"
    FROWN = "frown"
    OPEN = "open"  # small "oh"
    WIDE_OPEN = "wide_open"  # gasp / surprise
    TONGUE = "tongue"  # playful
    SMILE_OPEN = "smile_open"  # laughing

CLOSED = 'closed' class-attribute instance-attribute

FROWN = 'frown' class-attribute instance-attribute

GRIN = 'grin' class-attribute instance-attribute

NEUTRAL = 'neutral' class-attribute instance-attribute

OPEN = 'open' class-attribute instance-attribute

SMILE = 'smile' class-attribute instance-attribute

SMILE_OPEN = 'smile_open' class-attribute instance-attribute

TONGUE = 'tongue' class-attribute instance-attribute

WIDE_OPEN = 'wide_open' class-attribute instance-attribute

SpeakingAnimation dataclass

Produces a sequence of mouth shapes for lip-synced speech.

The animation converts text into a sequence of :class:VisemeFrame objects, one per phoneme, with timing that approximates natural speech cadence.

Usage::

anim = SpeakingAnimation(text="Hello there!")
while anim.has_frames:
    frame = anim.step(dt=0.033)
    face_model = face_model.with_mouth(
        Mouth(shape=MouthShape.NEUTRAL, openness=frame.openness, width=frame.width)
    )
Source code in src/robot/face/animations/speaking.py
@dataclass(slots=True)
class SpeakingAnimation:
    """Produces a sequence of mouth shapes for lip-synced speech.

    The animation converts text into a sequence of :class:`VisemeFrame`
    objects, one per phoneme, with timing that approximates natural
    speech cadence.

    Usage::

        anim = SpeakingAnimation(text="Hello there!")
        while anim.has_frames:
            frame = anim.step(dt=0.033)
            face_model = face_model.with_mouth(
                Mouth(shape=MouthShape.NEUTRAL, openness=frame.openness, width=frame.width)
            )
    """

    text: str = ""
    # Default duration per phoneme in seconds. Real speech varies but
    # this gives a reasonable approximation for visual animation.
    default_phoneme_duration: float = 0.08
    # Duration for pauses (spaces, commas, periods).
    pause_duration: float = 0.15
    sentence_pause_duration: float = 0.25
    # Speed multiplier (1.0 = normal, 0.5 = half speed, 2.0 = double).
    speed: float = 1.0

    _frames: list[VisemeFrame] = field(default_factory=list, init=False)
    _index: int = field(default=0, init=False)
    _elapsed: float = field(default=0.0, init=False)

    def __post_init__(self) -> None:
        if self.text:
            self._frames = self._text_to_frames(self.text)

    @classmethod
    def from_visemes(
        cls,
        visemes: Sequence[tuple[Viseme, float]],
        speed: float = 1.0,
    ) -> SpeakingAnimation:
        """Create an animation from an explicit viseme sequence.

        Each tuple is ``(viseme, duration_s)``.
        """
        anim = cls(speed=speed)
        for viseme, duration in visemes:
            openness, width = _VISEME_TARGETS.get(viseme, (0.3, 0.5))
            anim._frames.append(
                VisemeFrame(
                    openness=openness,
                    width=width,
                    duration_s=duration / speed,
                    viseme=viseme,
                )
            )
        return anim

    def step(self, dt: float) -> VisemeFrame:
        """Advance the animation by ``dt`` seconds.

        Returns the current :class:`VisemeFrame`. If the animation has
        finished, returns :class:`Viseme.IDLE` frame.
        """
        if not self._frames or self._index >= len(self._frames):
            return VisemeFrame(openness=0.0, width=0.5, duration_s=0.0)

        self._elapsed += dt

        # Advance to the next frame when the current frame's duration
        # expires.  Unlike a simple ``elapsed + duration <= dt`` check,
        # we accumulate time across calls so that frames with durations
        # longer than a single ``dt`` are held for their full duration.
        while (
            self._index < len(self._frames)
            and self._elapsed >= self._frames[self._index].duration_s
        ):
            self._elapsed -= self._frames[self._index].duration_s
            self._index += 1

        if self._index >= len(self._frames):
            return VisemeFrame(openness=0.0, width=0.5, duration_s=0.0)

        return self._frames[self._index]

    @property
    def has_frames(self) -> bool:
        """Whether there are still frames to animate."""
        return self._index < len(self._frames)

    @property
    def total_duration(self) -> float:
        """Total animation duration in seconds."""
        return sum(f.duration_s for f in self._frames)

    def reset(self) -> None:
        """Reset the animation to the beginning."""
        self._index = 0
        self._elapsed = 0.0

    # ------------------------------------------------------------------ text->viseme
    def _text_to_frames(self, text: str) -> list[VisemeFrame]:
        """Convert text into a list of viseme frames."""
        frames: list[VisemeFrame] = []
        i = 0
        while i < len(text):
            ch = text[i].lower()

            # Handle punctuation as pauses.
            if ch in ".!?":
                frames.append(
                    VisemeFrame(
                        openness=0.0,
                        width=0.5,
                        duration_s=self.sentence_pause_duration / self.speed,
                    )
                )
                i += 1
                continue
            if ch in ",;:":
                frames.append(
                    VisemeFrame(
                        openness=0.0, width=0.5, duration_s=self.pause_duration / self.speed
                    )
                )
                i += 1
                continue
            if ch in " \n\t":
                frames.append(VisemeFrame(openness=0.0, width=0.5, duration_s=0.05 / self.speed))
                i += 1
                continue

            # Try two-character digraphs first.
            if i + 1 < len(text):
                digraph = text[i : i + 2].lower()
                if digraph in _CHAR_TO_VISEME:
                    viseme = _CHAR_TO_VISEME[digraph]
                    openness, width = _VISEME_TARGETS[viseme]
                    frames.append(
                        VisemeFrame(
                            openness=openness,
                            width=width,
                            duration_s=self.default_phoneme_duration / self.speed,
                            viseme=viseme,
                        )
                    )
                    i += 2
                    continue

            # Single character.
            viseme = _CHAR_TO_VISEME.get(ch, Viseme.IDLE)
            openness, width = _VISEME_TARGETS[viseme]
            frames.append(
                VisemeFrame(
                    openness=openness,
                    width=width,
                    duration_s=self.default_phoneme_duration / self.speed,
                    viseme=viseme,
                )
            )
            i += 1

        return frames

default_phoneme_duration = 0.08 class-attribute instance-attribute

has_frames property

Whether there are still frames to animate.

pause_duration = 0.15 class-attribute instance-attribute

sentence_pause_duration = 0.25 class-attribute instance-attribute

speed = 1.0 class-attribute instance-attribute

text = '' class-attribute instance-attribute

total_duration property

Total animation duration in seconds.

__init__(text='', default_phoneme_duration=0.08, pause_duration=0.15, sentence_pause_duration=0.25, speed=1.0)

__post_init__()

Source code in src/robot/face/animations/speaking.py
def __post_init__(self) -> None:
    if self.text:
        self._frames = self._text_to_frames(self.text)

from_visemes(visemes, speed=1.0) classmethod

Create an animation from an explicit viseme sequence.

Each tuple is (viseme, duration_s).

Source code in src/robot/face/animations/speaking.py
@classmethod
def from_visemes(
    cls,
    visemes: Sequence[tuple[Viseme, float]],
    speed: float = 1.0,
) -> SpeakingAnimation:
    """Create an animation from an explicit viseme sequence.

    Each tuple is ``(viseme, duration_s)``.
    """
    anim = cls(speed=speed)
    for viseme, duration in visemes:
        openness, width = _VISEME_TARGETS.get(viseme, (0.3, 0.5))
        anim._frames.append(
            VisemeFrame(
                openness=openness,
                width=width,
                duration_s=duration / speed,
                viseme=viseme,
            )
        )
    return anim

reset()

Reset the animation to the beginning.

Source code in src/robot/face/animations/speaking.py
def reset(self) -> None:
    """Reset the animation to the beginning."""
    self._index = 0
    self._elapsed = 0.0

step(dt)

Advance the animation by dt seconds.

Returns the current :class:VisemeFrame. If the animation has finished, returns :class:Viseme.IDLE frame.

Source code in src/robot/face/animations/speaking.py
def step(self, dt: float) -> VisemeFrame:
    """Advance the animation by ``dt`` seconds.

    Returns the current :class:`VisemeFrame`. If the animation has
    finished, returns :class:`Viseme.IDLE` frame.
    """
    if not self._frames or self._index >= len(self._frames):
        return VisemeFrame(openness=0.0, width=0.5, duration_s=0.0)

    self._elapsed += dt

    # Advance to the next frame when the current frame's duration
    # expires.  Unlike a simple ``elapsed + duration <= dt`` check,
    # we accumulate time across calls so that frames with durations
    # longer than a single ``dt`` are held for their full duration.
    while (
        self._index < len(self._frames)
        and self._elapsed >= self._frames[self._index].duration_s
    ):
        self._elapsed -= self._frames[self._index].duration_s
        self._index += 1

    if self._index >= len(self._frames):
        return VisemeFrame(openness=0.0, width=0.5, duration_s=0.0)

    return self._frames[self._index]

Theme

Bases: Protocol

A visual style applied to a :class:FaceModel.

Source code in src/robot/face/themes/base.py
@runtime_checkable
class Theme(Protocol):
    """A visual style applied to a :class:`FaceModel`."""

    @property
    def name(self) -> str:
        """Human-readable theme name."""

    @property
    def palette(self) -> FacePalette:
        """The colour palette the theme uses."""

    def apply(self, model: FaceModel) -> FaceModel:
        """Return ``model`` with the theme's visual style applied."""

name property

Human-readable theme name.

palette property

The colour palette the theme uses.

apply(model)

Return model with the theme's visual style applied.

Source code in src/robot/face/themes/base.py
def apply(self, model: FaceModel) -> FaceModel:
    """Return ``model`` with the theme's visual style applied."""

ThinkingDotsAnimation dataclass

Produces a sequence of gaze positions for the "thinking dots" effect.

The animation advances through keyframes each time :meth:step is called, returning the current gaze position. The caller is responsible for applying the gaze to the face model and publishing any events.

Source code in src/robot/face/animations/thinking_dots.py
@dataclass(slots=True)
class ThinkingDotsAnimation:
    """Produces a sequence of gaze positions for the "thinking dots" effect.

    The animation advances through keyframes each time :meth:`step`
    is called, returning the current gaze position. The caller is
    responsible for applying the gaze to the face model and publishing
    any events.
    """

    pattern: Sequence[tuple[float, float, float]] = _THINKING_PATTERN
    _index: int = 0
    _elapsed: float = 0.0

    def step(self, dt: float) -> Gaze:
        """Advance the animation by ``dt`` seconds and return the current gaze.

        Parameters
        ----------
        dt:
            Time elapsed since the last call, in seconds.
        """
        if not self.pattern:
            return Gaze(0.0, 0.0)

        self._elapsed += dt
        _, _, hold = self.pattern[self._index]

        # Advance to the next keyframe when the hold time expires.
        while self._elapsed >= hold:
            self._elapsed -= hold
            self._index = (self._index + 1) % len(self.pattern)
            _, _, hold = self.pattern[self._index]

        # Lerp between the current and next keyframe for smooth transitions.
        x, y, _ = self.pattern[self._index]
        next_idx = (self._index + 1) % len(self.pattern)
        nx, ny, _ = self.pattern[next_idx]

        # Transition ratio: how far we are into the hold period.
        transition_start = hold * 0.7  # start transitioning at 70% of hold
        if self._elapsed >= transition_start:
            t = (self._elapsed - transition_start) / max(0.001, hold - transition_start)
            t = max(0.0, min(1.0, t))
            # Smooth the transition.
            t = t * t * (3.0 - 2.0 * t)  # smoothstep
            x = x + (nx - x) * t
            y = y + (ny - y) * t

        return Gaze(x=x, y=y)

    def reset(self) -> None:
        """Reset the animation to the beginning."""
        self._index = 0
        self._elapsed = 0.0

    @property
    def current_position(self) -> tuple[float, float]:
        """Return the current gaze (x, y) without advancing."""
        if not self.pattern:
            return 0.0, 0.0
        x, y, _ = self.pattern[self._index]
        return x, y

current_position property

Return the current gaze (x, y) without advancing.

pattern = _THINKING_PATTERN class-attribute instance-attribute

__init__(pattern=_THINKING_PATTERN, _index=0, _elapsed=0.0)

reset()

Reset the animation to the beginning.

Source code in src/robot/face/animations/thinking_dots.py
def reset(self) -> None:
    """Reset the animation to the beginning."""
    self._index = 0
    self._elapsed = 0.0

step(dt)

Advance the animation by dt seconds and return the current gaze.

Parameters

dt: Time elapsed since the last call, in seconds.

Source code in src/robot/face/animations/thinking_dots.py
def step(self, dt: float) -> Gaze:
    """Advance the animation by ``dt`` seconds and return the current gaze.

    Parameters
    ----------
    dt:
        Time elapsed since the last call, in seconds.
    """
    if not self.pattern:
        return Gaze(0.0, 0.0)

    self._elapsed += dt
    _, _, hold = self.pattern[self._index]

    # Advance to the next keyframe when the hold time expires.
    while self._elapsed >= hold:
        self._elapsed -= hold
        self._index = (self._index + 1) % len(self.pattern)
        _, _, hold = self.pattern[self._index]

    # Lerp between the current and next keyframe for smooth transitions.
    x, y, _ = self.pattern[self._index]
    next_idx = (self._index + 1) % len(self.pattern)
    nx, ny, _ = self.pattern[next_idx]

    # Transition ratio: how far we are into the hold period.
    transition_start = hold * 0.7  # start transitioning at 70% of hold
    if self._elapsed >= transition_start:
        t = (self._elapsed - transition_start) / max(0.001, hold - transition_start)
        t = max(0.0, min(1.0, t))
        # Smooth the transition.
        t = t * t * (3.0 - 2.0 * t)  # smoothstep
        x = x + (nx - x) * t
        y = y + (ny - y) * t

    return Gaze(x=x, y=y)

Timeline

Builder-style helper for declaring animations.

Source code in src/robot/animation/timelines.py
class Timeline:
    """Builder-style helper for declaring animations."""

    def __init__(self, animations: list[Animation] | None = None) -> None:
        self._items: list[Animation] = list(animations or [])

    def tween(
        self,
        from_value: float,
        to_value: float,
        duration_s: float,
        easing: Easing = linear,
        on_update: Callback | None = None,
    ) -> Timeline:
        self._items.append(
            Tween(
                duration_s=duration_s,
                easing=easing,
                from_value=from_value,
                to_value=to_value,
                on_update=on_update if on_update is not None else (lambda _v: None),
            )
        )
        return self

    def wait(self, duration_s: float) -> Timeline:
        self._items.append(Wait(duration_s=duration_s))
        return self

    def parallel(self, *children: Animation) -> Timeline:
        max_dur = max((c.duration_s for c in children), default=0.0)
        self._items.append(Parallel(duration_s=max_dur, children=list(children)))
        return self

    def queue(self, *children: Animation) -> Timeline:
        total = sum(c.duration_s for c in children)
        self._items.append(Queue(duration_s=total, children=list(children)))
        return self

    def build(self) -> Queue:
        total = sum(c.duration_s for c in self._items)
        return Queue(duration_s=total, children=list(self._items))

    async def run(self) -> None:
        await self.build().run()

__init__(animations=None)

Source code in src/robot/animation/timelines.py
def __init__(self, animations: list[Animation] | None = None) -> None:
    self._items: list[Animation] = list(animations or [])

build()

Source code in src/robot/animation/timelines.py
def build(self) -> Queue:
    total = sum(c.duration_s for c in self._items)
    return Queue(duration_s=total, children=list(self._items))

parallel(*children)

Source code in src/robot/animation/timelines.py
def parallel(self, *children: Animation) -> Timeline:
    max_dur = max((c.duration_s for c in children), default=0.0)
    self._items.append(Parallel(duration_s=max_dur, children=list(children)))
    return self

queue(*children)

Source code in src/robot/animation/timelines.py
def queue(self, *children: Animation) -> Timeline:
    total = sum(c.duration_s for c in children)
    self._items.append(Queue(duration_s=total, children=list(children)))
    return self

run() async

Source code in src/robot/animation/timelines.py
async def run(self) -> None:
    await self.build().run()

tween(from_value, to_value, duration_s, easing=linear, on_update=None)

Source code in src/robot/animation/timelines.py
def tween(
    self,
    from_value: float,
    to_value: float,
    duration_s: float,
    easing: Easing = linear,
    on_update: Callback | None = None,
) -> Timeline:
    self._items.append(
        Tween(
            duration_s=duration_s,
            easing=easing,
            from_value=from_value,
            to_value=to_value,
            on_update=on_update if on_update is not None else (lambda _v: None),
        )
    )
    return self

wait(duration_s)

Source code in src/robot/animation/timelines.py
def wait(self, duration_s: float) -> Timeline:
    self._items.append(Wait(duration_s=duration_s))
    return self

WakeAnimation dataclass

Produces a sequence of :class:WakeFrame objects for the wake animation.

Usage::

anim = WakeAnimation()
while not anim.done:
    frame = anim.step(dt=0.033)
    # Apply frame to face model...
Source code in src/robot/face/animations/wake.py
@dataclass(slots=True)
class WakeAnimation:
    """Produces a sequence of :class:`WakeFrame` objects for the wake animation.

    Usage::

        anim = WakeAnimation()
        while not anim.done:
            frame = anim.step(dt=0.033)
            # Apply frame to face model...
    """

    _phase: WakePhase = WakePhase.EYES_OPEN
    _elapsed: float = 0.0

    def step(self, dt: float) -> WakeFrame:
        """Advance the animation by ``dt`` seconds and return the current frame."""
        if self._phase == WakePhase.DONE:
            return self._idle_frame()

        self._elapsed += dt
        phase_duration = _PHASE_DURATIONS.get(self._phase, 0.3)

        frame = self._frame_for_phase(self._phase)

        # Transition to next phase when duration expires.
        if self._elapsed >= phase_duration:
            self._elapsed -= phase_duration
            self._phase = self._next_phase(self._phase)

        return frame

    @property
    def done(self) -> bool:
        """Whether the animation has completed."""
        return self._phase == WakePhase.DONE

    def reset(self) -> None:
        """Reset the animation to the beginning."""
        self._phase = WakePhase.EYES_OPEN
        self._elapsed = 0.0

    def _next_phase(self, phase: WakePhase) -> WakePhase:
        order = [
            WakePhase.EYES_OPEN,
            WakePhase.DOUBLE_BLINK,
            WakePhase.MOUTH_SURPRISE,
            WakePhase.TRANSITION,
            WakePhase.DONE,
        ]
        idx = order.index(phase) if phase in order else 0
        next_idx = idx + 1
        if next_idx >= len(order):
            return WakePhase.DONE
        return order[next_idx]

    def _frame_for_phase(self, phase: WakePhase) -> WakeFrame:
        if phase == WakePhase.EYES_OPEN:
            return WakeFrame(
                gaze=Gaze(0.0, 0.0),
                eye_openness=1.2,
                eyelid_top=0.0,
                eyebrow_shape=EyebrowShape.RAISED,
                eyebrow_raise=0.8,
                phase=phase,
            )
        if phase == WakePhase.DOUBLE_BLINK:
            # The blink cycle happens within the 0.3s window.
            # First 0.15s: eyes closed. Next 0.15s: eyes open, then closed again.
            blink_t = self._elapsed / max(0.001, _PHASE_DURATIONS[WakePhase.DOUBLE_BLINK])
            if blink_t < 0.15:
                openness = max(0.1, 1.0 - blink_t * 6.0)
            elif blink_t < 0.30:
                openness = 0.1 + (blink_t - 0.15) * 6.0
            elif blink_t < 0.50:
                openness = max(0.1, 1.0 - (blink_t - 0.30) * 5.0)
            else:
                openness = 0.1 + (blink_t - 0.50) * 1.8
            openness = max(0.1, min(1.2, openness))
            return WakeFrame(
                gaze=Gaze(0.0, 0.05),
                eye_openness=openness,
                eyelid_top=1.0 - openness,
                mouth_shape=MouthShape.NEUTRAL,
                mouth_openness=0.1,
                phase=phase,
            )
        if phase == WakePhase.MOUTH_SURPRISE:
            return WakeFrame(
                gaze=Gaze(0.0, 0.05),
                eye_openness=1.1,
                eyelid_top=0.05,
                mouth_shape=MouthShape.WIDE_OPEN,
                mouth_openness=0.7,
                mouth_width=0.6,
                eyebrow_shape=EyebrowShape.RAISED,
                eyebrow_raise=0.6,
                phase=phase,
            )
        if phase == WakePhase.TRANSITION:
            # Smooth transition to "curious" look.
            return WakeFrame(
                gaze=Gaze(0.1, 0.1),
                eye_openness=1.0,
                eyelid_top=0.0,
                mouth_shape=MouthShape.OPEN,
                mouth_openness=0.2,
                mouth_width=0.4,
                eyebrow_shape=EyebrowShape.RAISED,
                eyebrow_raise=0.3,
                phase=phase,
            )
        return self._idle_frame()

    @staticmethod
    def _idle_frame() -> WakeFrame:
        return WakeFrame(gaze=Gaze(0.0, 0.0), phase=WakePhase.DONE)

done property

Whether the animation has completed.

__init__(_phase=WakePhase.EYES_OPEN, _elapsed=0.0)

reset()

Reset the animation to the beginning.

Source code in src/robot/face/animations/wake.py
def reset(self) -> None:
    """Reset the animation to the beginning."""
    self._phase = WakePhase.EYES_OPEN
    self._elapsed = 0.0

step(dt)

Advance the animation by dt seconds and return the current frame.

Source code in src/robot/face/animations/wake.py
def step(self, dt: float) -> WakeFrame:
    """Advance the animation by ``dt`` seconds and return the current frame."""
    if self._phase == WakePhase.DONE:
        return self._idle_frame()

    self._elapsed += dt
    phase_duration = _PHASE_DURATIONS.get(self._phase, 0.3)

    frame = self._frame_for_phase(self._phase)

    # Transition to next phase when duration expires.
    if self._elapsed >= phase_duration:
        self._elapsed -= phase_duration
        self._phase = self._next_phase(self._phase)

    return frame

WakeFrame dataclass

A single frame of the wake animation.

Provides target values for the face model at a given animation time. The caller interpolates between the current state and this target.

Source code in src/robot/face/animations/wake.py
@dataclass(slots=True, frozen=True)
class WakeFrame:
    """A single frame of the wake animation.

    Provides target values for the face model at a given animation
    time. The caller interpolates between the current state and
    this target.
    """

    gaze: Gaze
    eye_openness: float = 1.0
    eyelid_top: float = 0.0
    mouth_shape: MouthShape = MouthShape.NEUTRAL
    mouth_openness: float = 0.0
    mouth_width: float = 0.5
    eyebrow_shape: EyebrowShape = EyebrowShape.NEUTRAL
    eyebrow_raise: float = 0.0
    phase: WakePhase = WakePhase.IDLE

eye_openness = 1.0 class-attribute instance-attribute

eyebrow_raise = 0.0 class-attribute instance-attribute

eyebrow_shape = EyebrowShape.NEUTRAL class-attribute instance-attribute

eyelid_top = 0.0 class-attribute instance-attribute

gaze instance-attribute

mouth_openness = 0.0 class-attribute instance-attribute

mouth_shape = MouthShape.NEUTRAL class-attribute instance-attribute

mouth_width = 0.5 class-attribute instance-attribute

phase = WakePhase.IDLE class-attribute instance-attribute

__init__(gaze, eye_openness=1.0, eyelid_top=0.0, mouth_shape=MouthShape.NEUTRAL, mouth_openness=0.0, mouth_width=0.5, eyebrow_shape=EyebrowShape.NEUTRAL, eyebrow_raise=0.0, phase=WakePhase.IDLE)

_ease_in_out(t)

Source code in src/robot/face/animator.py
def _ease_in_out(t: float) -> float:
    return t * t * (3.0 - 2.0 * t)

_ease_out(t)

Source code in src/robot/face/animator.py
def _ease_out(t: float) -> float:
    return 1.0 - (1.0 - t) ** 2

_interp(a, b, t)

Source code in src/robot/face/animator.py
def _interp(a: float, b: float, t: float) -> float:
    return a + (b - a) * t

_interp_cheeks(a, b, t)

Source code in src/robot/face/animator.py
def _interp_cheeks(a: Cheeks, b: Cheeks, t: float) -> Cheeks:
    if a.state is b.state:
        return Cheeks(state=a.state, intensity=a.intensity + (b.intensity - a.intensity) * t)
    return b if t > 0.5 else a

_interp_eye(a, b, t)

Source code in src/robot/face/animator.py
def _interp_eye(a: Eye, b: Eye, t: float) -> Eye:
    return Eye(
        gaze=Gaze(
            a.gaze.x + (b.gaze.x - a.gaze.x) * t,
            a.gaze.y + (b.gaze.y - a.gaze.y) * t,
        ),
        openness=a.openness + (b.openness - a.openness) * t,
        pupil_dilation=a.pupil_dilation + (b.pupil_dilation - a.pupil_dilation) * t,
        highlight=Gaze(
            a.highlight.x + (b.highlight.x - a.highlight.x) * t,
            a.highlight.y + (b.highlight.y - a.highlight.y) * t,
        ),
        asymmetric=a.asymmetric or b.asymmetric,
    )

_interp_eyebrow(a, b, t)

Source code in src/robot/face/animator.py
def _interp_eyebrow(a: Eyebrow, b: Eyebrow, t: float) -> Eyebrow:
    # If both shapes are equal, just lerp params. Otherwise snap at t=0.5.
    if a.shape is b.shape:
        return Eyebrow(
            shape=a.shape,
            raise_amount=a.raise_amount + (b.raise_amount - a.raise_amount) * t,
            angle=a.angle + (b.angle - a.angle) * t,
        )
    return b if t > 0.5 else a

_interp_eyelids(a, b, t)

Source code in src/robot/face/animator.py
def _interp_eyelids(a: Eyelids, b: Eyelids, t: float) -> Eyelids:
    return Eyelids(
        top=a.top + (b.top - a.top) * t,
        bottom=a.bottom + (b.bottom - a.bottom) * t,
    )

_interp_mouth(a, b, t)

Source code in src/robot/face/animator.py
def _interp_mouth(a: Mouth, b: Mouth, t: float) -> Mouth:
    if a.shape is b.shape:
        return Mouth(
            shape=a.shape,
            openness=a.openness + (b.openness - a.openness) * t,
            width=a.width + (b.width - a.width) * t,
            asymmetry=a.asymmetry + (b.asymmetry - a.asymmetry) * t,
        )
    return b if t > 0.5 else a

get_logger(name)

Return a bound logger for the given module name.

The name is prefixed with robot. if it doesn't already start with it, so log records naturally form a hierarchy. The name is also bound into the event context as logger_name so :func:_capture_to_ring_buffer can record it; :func:_strip_logger_name removes it before rendering so the stdout JSON output stays unchanged.

Source code in src/robot/logging.py
def get_logger(name: str) -> structlog.stdlib.BoundLogger:
    """Return a bound logger for the given module name.

    The name is prefixed with ``robot.`` if it doesn't already start with it,
    so log records naturally form a hierarchy. The name is also bound into
    the event context as ``logger_name`` so :func:`_capture_to_ring_buffer`
    can record it; :func:`_strip_logger_name` removes it before rendering so
    the stdout JSON output stays unchanged.
    """
    if not name.startswith("robot."):
        name = f"robot.{name}"
    logger = structlog.get_logger(name).bind(logger_name=name)
    return cast("structlog.stdlib.BoundLogger", logger)

Emotions

robot.face.emotions

The :class:EmotionEngine - produces a :class:FaceModel from an emotion.

The engine is a pure function EmotionName -> (FaceModel, BodyLanguageHint). It never touches rendering, servos, displays, or animation state. This is the single source of truth for "what does emotion X look like?".

Emotions are built from a small set of reusable face component presets (eye defaults, mouth shape, eyebrow shape, …) so that adding a new emotion is a one-line change.

EMOTION_DEFS = {'neutral': _EmotionDef(eyes=NEUTRAL_EYES, eyelids=NEUTRAL_EYELIDS, eyebrows=NEUTRAL_EYEBROWS, mouth=NEUTRAL_MOUTH, cheeks=NEUTRAL_CHEEKS, overlay=NEUTRAL_OVERLAY, body_hint=NEUTRAL_HINT), 'happy': _EmotionDef(eyes=(Eye(gaze=Gaze(0.0, 0.05), openness=0.85), Eye(gaze=Gaze(0.0, 0.05), openness=0.85)), eyelids=Eyelids(top=0.05, bottom=0.25), eyebrows=(Eyebrow(shape=EyebrowShape.RAISED, raise_amount=0.3), Eyebrow(shape=EyebrowShape.RAISED, raise_amount=0.3)), mouth=Mouth(shape=MouthShape.SMILE, openness=0.3, width=0.6), cheeks=Cheeks(state=CheekState.SOFT, intensity=0.6), overlay=NEUTRAL_OVERLAY, body_hint=BodyLanguageHint(head_tilt=HeadTilt.CURIOUS, arm_pose=ArmPose.OPEN, intensity=0.7)), 'curious': _EmotionDef(eyes=(Eye(gaze=Gaze(0.2, 0.1), openness=1.0, highlight=Gaze(0.4, 0.4)), Eye(gaze=Gaze(0.2, 0.1), openness=1.0, highlight=Gaze(0.4, 0.4))), eyelids=NEUTRAL_EYELIDS, eyebrows=(Eyebrow(shape=EyebrowShape.RAISED, raise_amount=0.6), Eyebrow(shape=EyebrowShape.RAISED, raise_amount=0.6)), mouth=Mouth(shape=MouthShape.OPEN, openness=0.2, width=0.4), cheeks=NEUTRAL_CHEEKS, overlay=Overlay(kind=OverlayKind.QUESTION, position=Point(0.7, -0.5)), body_hint=BodyLanguageHint(head_tilt=HeadTilt.CURIOUS, arm_pose=ArmPose.POINT, intensity=0.6)), 'thinking': _EmotionDef(eyes=(Eye(gaze=Gaze(0.2, 0.3), openness=0.85), Eye(gaze=Gaze(0.2, 0.3), openness=0.85)), eyelids=NEUTRAL_EYELIDS, eyebrows=(Eyebrow(shape=EyebrowShape.WORRIED, raise_amount=0.2, angle=0.2), Eyebrow(shape=EyebrowShape.WORRIED, raise_amount=0.2, angle=-0.2)), mouth=Mouth(shape=MouthShape.NEUTRAL, openness=0.0, width=0.4), cheeks=NEUTRAL_CHEEKS, overlay=NEUTRAL_OVERLAY, body_hint=BodyLanguageHint(head_tilt=HeadTilt.THINKING, arm_pose=ArmPose.RELAXED, intensity=0.5)), 'sleepy': _EmotionDef(eyes=(Eye(gaze=Gaze(0.0, 0.0), openness=0.15), Eye(gaze=Gaze(0.0, 0.0), openness=0.15)), eyelids=Eyelids(top=0.65, bottom=0.0), eyebrows=(Eyebrow(shape=EyebrowShape.SLEEPY), Eyebrow(shape=EyebrowShape.SLEEPY)), mouth=Mouth(shape=MouthShape.OPEN, openness=0.1, width=0.4), cheeks=NEUTRAL_CHEEKS, overlay=NEUTRAL_OVERLAY, body_hint=BodyLanguageHint(head_tilt=HeadTilt.SLEEPY, arm_pose=ArmPose.DOWN, intensity=0.7)), 'embarrassed': _EmotionDef(eyes=(Eye(gaze=Gaze(0.0, -0.3), openness=0.7, highlight=Gaze(-0.3, -0.3)), Eye(gaze=Gaze(0.0, -0.3), openness=0.7, highlight=Gaze(-0.3, -0.3))), eyelids=Eyelids(top=0.1, bottom=0.05), eyebrows=(Eyebrow(shape=EyebrowShape.WORRIED, angle=0.3), Eyebrow(shape=EyebrowShape.WORRIED, angle=-0.3)), mouth=Mouth(shape=MouthShape.SMILE, openness=0.2, width=0.5, asymmetry=0.3), cheeks=Cheeks(state=CheekState.BRIGHT, intensity=0.9), overlay=NEUTRAL_OVERLAY, body_hint=BodyLanguageHint(head_tilt=HeadTilt.SAD, arm_pose=ArmPose.SHRUG, intensity=0.5)), 'excited': _EmotionDef(eyes=(Eye(gaze=Gaze(0.0, -0.1), openness=1.2, highlight=Gaze(0.0, 0.0)), Eye(gaze=Gaze(0.0, -0.1), openness=1.2, highlight=Gaze(0.0, 0.0))), eyelids=NEUTRAL_EYELIDS, eyebrows=(Eyebrow(shape=EyebrowShape.RAISED, raise_amount=0.8), Eyebrow(shape=EyebrowShape.RAISED, raise_amount=0.8)), mouth=Mouth(shape=MouthShape.SMILE_OPEN, openness=0.6, width=0.7), cheeks=Cheeks(state=CheekState.SOFT, intensity=0.4), overlay=Overlay(kind=OverlayKind.SPARKLE, position=Point(-0.5, -0.4), size=0.3), body_hint=BodyLanguageHint(head_tilt=HeadTilt.EXCITED, arm_pose=ArmPose.WIDE, intensity=1.0, gestures=('bounce',))), 'sad': _EmotionDef(eyes=(Eye(gaze=Gaze(0.0, -0.3), openness=0.65, pupil_dilation=0.7), Eye(gaze=Gaze(0.0, -0.3), openness=0.65, pupil_dilation=0.7)), eyelids=Eyelids(top=0.35, bottom=0.0), eyebrows=(Eyebrow(shape=EyebrowShape.SAD, angle=0.4), Eyebrow(shape=EyebrowShape.SAD, angle=-0.4)), mouth=Mouth(shape=MouthShape.FROWN, openness=0.0, width=0.5), cheeks=Cheeks(state=CheekState.COLD, intensity=0.4), overlay=Overlay(kind=OverlayKind.TEAR, position=Point(-0.3, 0.1), size=0.2), body_hint=BodyLanguageHint(head_tilt=HeadTilt.SAD, arm_pose=ArmPose.DOWN, intensity=0.7)), 'surprised': _EmotionDef(eyes=(Eye(gaze=Gaze(0.0, 0.0), openness=1.0, pupil_dilation=0.2), Eye(gaze=Gaze(0.0, 0.0), openness=1.0, pupil_dilation=0.2)), eyelids=NEUTRAL_EYELIDS, eyebrows=(Eyebrow(shape=EyebrowShape.RAISED, raise_amount=1.0), Eyebrow(shape=EyebrowShape.RAISED, raise_amount=1.0)), mouth=Mouth(shape=MouthShape.WIDE_OPEN, openness=0.9, width=0.6), cheeks=NEUTRAL_CHEEKS, overlay=Overlay(kind=OverlayKind.EXCLAIM, position=Point(0.6, -0.5), size=0.3), body_hint=BodyLanguageHint(head_tilt=HeadTilt.EXCITED, arm_pose=ArmPose.SHRUG, intensity=0.8, gestures=('bounce',))), 'angry': _EmotionDef(eyes=(Eye(gaze=Gaze(0.0, -0.1), openness=0.7, pupil_dilation=0.2), Eye(gaze=Gaze(0.0, -0.1), openness=0.7, pupil_dilation=0.2)), eyelids=Eyelids(top=0.3, bottom=0.0), eyebrows=(Eyebrow(shape=EyebrowShape.ANGRY, angle=0.7), Eyebrow(shape=EyebrowShape.ANGRY, angle=-0.7)), mouth=Mouth(shape=MouthShape.FROWN, openness=0.2, width=0.5), cheeks=Cheeks(state=CheekState.BRIGHT, intensity=0.5), overlay=Overlay(kind=OverlayKind.ANGER, position=Point(0.5, -0.5), size=0.3), body_hint=BodyLanguageHint(head_tilt=HeadTilt.NEUTRAL, arm_pose=ArmPose.SHRUG, intensity=0.7))} module-attribute

NEUTRAL_CHEEKS = Cheeks(state=CheekState.NONE, intensity=0.0) module-attribute

NEUTRAL_EYEBROWS = (Eyebrow(shape=EyebrowShape.NEUTRAL), Eyebrow(shape=EyebrowShape.NEUTRAL)) module-attribute

NEUTRAL_EYELIDS = Eyelids(top=0.0, bottom=0.0) module-attribute

NEUTRAL_EYES = (Eye(gaze=Gaze(0.0, 0.0)), Eye(gaze=Gaze(0.0, 0.0))) module-attribute

NEUTRAL_HINT = BodyLanguageHint(head_tilt=HeadTilt.NEUTRAL, arm_pose=ArmPose.RELAXED, intensity=0.5) module-attribute

NEUTRAL_MOUTH = Mouth(shape=MouthShape.NEUTRAL, openness=0.0, width=0.5, asymmetry=0.0) module-attribute

NEUTRAL_OVERLAY = Overlay(kind=OverlayKind.NONE) module-attribute

__all__ = ['EMOTION_DEFS', 'EmotionEngine'] module-attribute

ArmPose

Bases: Enum

Discrete arm-pose hints.

Source code in src/robot/face/model.py
class ArmPose(Enum):
    """Discrete arm-pose hints."""

    RELAXED = "relaxed"
    OPEN = "open"  # slightly raised
    WIDE = "wide"  # celebration
    WAVING = "waving"  # one arm up
    SHRUG = "shrug"  # both up
    DOWN = "down"  # rest
    POINT = "point"  # one arm forward

DOWN = 'down' class-attribute instance-attribute

OPEN = 'open' class-attribute instance-attribute

POINT = 'point' class-attribute instance-attribute

RELAXED = 'relaxed' class-attribute instance-attribute

SHRUG = 'shrug' class-attribute instance-attribute

WAVING = 'waving' class-attribute instance-attribute

WIDE = 'wide' class-attribute instance-attribute

BodyLanguageHint dataclass

A high-level body-language request produced by the EmotionEngine.

Source code in src/robot/face/model.py
@dataclass(slots=True, frozen=True)
class BodyLanguageHint:
    """A high-level body-language request produced by the EmotionEngine."""

    head_tilt: HeadTilt = HeadTilt.NEUTRAL
    arm_pose: ArmPose = ArmPose.RELAXED
    # Intensity scales how strongly the body-language engine applies the
    # pose (0.0 = ignore, 1.0 = full expression).
    intensity: float = 1.0
    # Special transient gestures the body-language engine should run once
    # (e.g. a wave). Empty tuple = "no transient gestures".
    gestures: tuple[str, ...] = ()

arm_pose = ArmPose.RELAXED class-attribute instance-attribute

gestures = () class-attribute instance-attribute

head_tilt = HeadTilt.NEUTRAL class-attribute instance-attribute

intensity = 1.0 class-attribute instance-attribute

__init__(head_tilt=HeadTilt.NEUTRAL, arm_pose=ArmPose.RELAXED, intensity=1.0, gestures=())

CheekState

Bases: str, Enum

Source code in src/robot/face/components.py
class CheekState(str, Enum):
    NONE = "none"
    SOFT = "soft"  # neutral happy
    BRIGHT = "bright"  # very happy / embarrassed
    COLD = "cold"  # sad / cold

BRIGHT = 'bright' class-attribute instance-attribute

COLD = 'cold' class-attribute instance-attribute

NONE = 'none' class-attribute instance-attribute

SOFT = 'soft' class-attribute instance-attribute

Cheeks dataclass

Cheek rendering - base + accent colour, intensity.

Source code in src/robot/face/components.py
@dataclass(slots=True, frozen=True)
class Cheeks:
    """Cheek rendering - base + accent colour, intensity."""

    state: CheekState = CheekState.NONE
    intensity: float = 0.0  # 0..1

intensity = 0.0 class-attribute instance-attribute

state = CheekState.NONE class-attribute instance-attribute

__init__(state=CheekState.NONE, intensity=0.0)

EmotionEngine

Produces :class:FaceModel + :class:BodyLanguageHint from an emotion.

Source code in src/robot/face/emotions.py
class EmotionEngine:
    """Produces :class:`FaceModel` + :class:`BodyLanguageHint` from an emotion."""

    def __init__(
        self, palette: FacePalette | None = None, width: int = 240, height: int = 240
    ) -> None:
        self._palette = palette or FacePalette()
        self._width = width
        self._height = height

    def set_dimensions(self, width: int, height: int) -> None:
        self._width = width
        self._height = height

    def available(self) -> list[str]:
        return list(EMOTION_DEFS.keys())

    def get(self, name: str) -> _EmotionDef:
        try:
            return EMOTION_DEFS[name]
        except KeyError as exc:
            raise KeyError(
                f"unknown emotion {name!r}; available: {sorted(EMOTION_DEFS.keys())}"
            ) from exc

    def build(self, name: str) -> FaceModel:
        """Build the :class:`FaceModel` for ``name`` with default geometry."""
        d = self.get(name)
        left_eye, right_eye = d.eyes
        left_brow, right_brow = d.eyebrows
        return FaceModel(
            width=self._width,
            height=self._height,
            left_eye=left_eye,
            right_eye=right_eye,
            eyelids=d.eyelids,
            left_eyebrow=left_brow,
            right_eyebrow=right_brow,
            mouth=d.mouth,
            cheeks=d.cheeks,
            overlay=d.overlay,
            palette=self._palette,
            body_hint=d.body_hint,
        )

    def register(self, name: str, definition: _EmotionDef) -> None:
        """Register a new emotion or override an existing one."""
        EMOTION_DEFS[name] = definition

__init__(palette=None, width=240, height=240)

Source code in src/robot/face/emotions.py
def __init__(
    self, palette: FacePalette | None = None, width: int = 240, height: int = 240
) -> None:
    self._palette = palette or FacePalette()
    self._width = width
    self._height = height

available()

Source code in src/robot/face/emotions.py
def available(self) -> list[str]:
    return list(EMOTION_DEFS.keys())

build(name)

Build the :class:FaceModel for name with default geometry.

Source code in src/robot/face/emotions.py
def build(self, name: str) -> FaceModel:
    """Build the :class:`FaceModel` for ``name`` with default geometry."""
    d = self.get(name)
    left_eye, right_eye = d.eyes
    left_brow, right_brow = d.eyebrows
    return FaceModel(
        width=self._width,
        height=self._height,
        left_eye=left_eye,
        right_eye=right_eye,
        eyelids=d.eyelids,
        left_eyebrow=left_brow,
        right_eyebrow=right_brow,
        mouth=d.mouth,
        cheeks=d.cheeks,
        overlay=d.overlay,
        palette=self._palette,
        body_hint=d.body_hint,
    )

get(name)

Source code in src/robot/face/emotions.py
def get(self, name: str) -> _EmotionDef:
    try:
        return EMOTION_DEFS[name]
    except KeyError as exc:
        raise KeyError(
            f"unknown emotion {name!r}; available: {sorted(EMOTION_DEFS.keys())}"
        ) from exc

register(name, definition)

Register a new emotion or override an existing one.

Source code in src/robot/face/emotions.py
def register(self, name: str, definition: _EmotionDef) -> None:
    """Register a new emotion or override an existing one."""
    EMOTION_DEFS[name] = definition

set_dimensions(width, height)

Source code in src/robot/face/emotions.py
def set_dimensions(self, width: int, height: int) -> None:
    self._width = width
    self._height = height

Eye dataclass

A single eye. The face has two of them.

Source code in src/robot/face/components.py
@dataclass(slots=True, frozen=True)
class Eye:
    """A single eye. The face has two of them."""

    gaze: Gaze = field(default_factory=Gaze)
    openness: float = 1.0  # 0.0 = closed, 1.0 = wide
    pupil_dilation: float = 0.5  # 0.0 = constricted, 1.0 = dilated
    highlight: Gaze = field(default_factory=lambda: Gaze(0.3, 0.3))
    asymmetric: bool = False  # for character expressions

asymmetric = False class-attribute instance-attribute

gaze = field(default_factory=Gaze) class-attribute instance-attribute

highlight = field(default_factory=lambda: Gaze(0.3, 0.3)) class-attribute instance-attribute

openness = 1.0 class-attribute instance-attribute

pupil_dilation = 0.5 class-attribute instance-attribute

__init__(gaze=Gaze(), openness=1.0, pupil_dilation=0.5, highlight=(lambda: Gaze(0.3, 0.3))(), asymmetric=False)

Eyebrow dataclass

A single eyebrow.

Source code in src/robot/face/components.py
@dataclass(slots=True, frozen=True)
class Eyebrow:
    """A single eyebrow."""

    shape: EyebrowShape = EyebrowShape.NEUTRAL
    raise_amount: float = 0.0  # 0..1 vertical raise (additive on top of shape)
    angle: float = 0.0  # -1..1 tilt (angry < 0, worried > 0)

angle = 0.0 class-attribute instance-attribute

raise_amount = 0.0 class-attribute instance-attribute

shape = EyebrowShape.NEUTRAL class-attribute instance-attribute

__init__(shape=EyebrowShape.NEUTRAL, raise_amount=0.0, angle=0.0)

EyebrowShape

Bases: str, Enum

Source code in src/robot/face/components.py
class EyebrowShape(str, Enum):
    NEUTRAL = "neutral"
    RAISED = "raised"
    ANGRY = "angry"
    WORRIED = "worried"
    SLEEPY = "sleepy"
    SAD = "sad"

ANGRY = 'angry' class-attribute instance-attribute

NEUTRAL = 'neutral' class-attribute instance-attribute

RAISED = 'raised' class-attribute instance-attribute

SAD = 'sad' class-attribute instance-attribute

SLEEPY = 'sleepy' class-attribute instance-attribute

WORRIED = 'worried' class-attribute instance-attribute

Eyelids dataclass

Vertical eyelid positions, 0.0 = retracted, 1.0 = fully closed.

Source code in src/robot/face/components.py
@dataclass(slots=True, frozen=True)
class Eyelids:
    """Vertical eyelid positions, ``0.0`` = retracted, ``1.0`` = fully closed."""

    top: float = 0.0
    bottom: float = 0.0

bottom = 0.0 class-attribute instance-attribute

top = 0.0 class-attribute instance-attribute

__init__(top=0.0, bottom=0.0)

FaceModel dataclass

The full face, captured at one instant.

All values are immutable. Use the helper methods to build new models with a single field changed (this is what the renderer animates).

Source code in src/robot/face/model.py
@dataclass(slots=True, frozen=True)
class FaceModel:
    """The full face, captured at one instant.

    All values are immutable. Use the helper methods to build new models
    with a single field changed (this is what the renderer animates).
    """

    width: int = 240
    height: int = 240

    left_eye: Eye = field(default_factory=Eye)
    right_eye: Eye = field(default_factory=Eye)

    # Eyelids
    eyelids: Eyelids = field(default_factory=Eyelids)

    # Eyebrows (one per eye)
    left_eyebrow: Eyebrow = field(default_factory=Eyebrow)
    right_eyebrow: Eyebrow = field(default_factory=Eyebrow)

    # Mouth
    mouth: Mouth = field(default_factory=Mouth)

    # Cheeks
    cheeks: Cheeks = field(default_factory=Cheeks)

    # Overlays
    overlay: Overlay = field(default_factory=Overlay)

    # Persistent accessories
    accessory: Accessory = field(default_factory=Accessory)

    # Colour palette (themes override this)
    palette: FacePalette = field(default_factory=FacePalette)

    # Subtle bounce / squash & stretch (in normalised units)
    bounce: float = 0.0  # -1..1 vertical translation
    squash: float = 1.0  # 0..2 horizontal scale (1 = neutral)

    # Body-language hint proposed by the EmotionEngine
    body_hint: BodyLanguageHint = field(default_factory=BodyLanguageHint)

    # ------------------------------------------------------------------
    # Convenience builders (return a new model with one field changed)
    # ------------------------------------------------------------------
    def with_eyes(
        self,
        left_eye: Eye | None = None,
        right_eye: Eye | None = None,
    ) -> FaceModel:
        return replace(
            self, left_eye=left_eye or self.left_eye, right_eye=right_eye or self.right_eye
        )

    def with_eyelids(self, eyelids: Eyelids) -> FaceModel:
        return replace(self, eyelids=eyelids)

    def with_eyebrows(
        self,
        left: Eyebrow | None = None,
        right: Eyebrow | None = None,
    ) -> FaceModel:
        return replace(
            self, left_eyebrow=left or self.left_eyebrow, right_eyebrow=right or self.right_eyebrow
        )

    def with_mouth(self, mouth: Mouth) -> FaceModel:
        return replace(self, mouth=mouth)

    def with_cheeks(self, cheeks: Cheeks) -> FaceModel:
        return replace(self, cheeks=cheeks)

    def with_overlay(self, overlay: Overlay) -> FaceModel:
        return replace(self, overlay=overlay)

    def with_accessory(self, accessory: Accessory) -> FaceModel:
        return replace(self, accessory=accessory)

    def with_palette(self, palette: FacePalette) -> FaceModel:
        return replace(self, palette=palette)

    def with_transform(self, bounce: float | None = None, squash: float | None = None) -> FaceModel:
        return replace(
            self,
            bounce=self.bounce if bounce is None else bounce,
            squash=self.squash if squash is None else squash,
        )

    def with_body_hint(self, body_hint: BodyLanguageHint) -> FaceModel:
        return replace(self, body_hint=body_hint)

accessory = field(default_factory=Accessory) class-attribute instance-attribute

body_hint = field(default_factory=BodyLanguageHint) class-attribute instance-attribute

bounce = 0.0 class-attribute instance-attribute

cheeks = field(default_factory=Cheeks) class-attribute instance-attribute

eyelids = field(default_factory=Eyelids) class-attribute instance-attribute

height = 240 class-attribute instance-attribute

left_eye = field(default_factory=Eye) class-attribute instance-attribute

left_eyebrow = field(default_factory=Eyebrow) class-attribute instance-attribute

mouth = field(default_factory=Mouth) class-attribute instance-attribute

overlay = field(default_factory=Overlay) class-attribute instance-attribute

palette = field(default_factory=FacePalette) class-attribute instance-attribute

right_eye = field(default_factory=Eye) class-attribute instance-attribute

right_eyebrow = field(default_factory=Eyebrow) class-attribute instance-attribute

squash = 1.0 class-attribute instance-attribute

width = 240 class-attribute instance-attribute

__init__(width=240, height=240, left_eye=Eye(), right_eye=Eye(), eyelids=Eyelids(), left_eyebrow=Eyebrow(), right_eyebrow=Eyebrow(), mouth=Mouth(), cheeks=Cheeks(), overlay=Overlay(), accessory=Accessory(), palette=FacePalette(), bounce=0.0, squash=1.0, body_hint=BodyLanguageHint())

with_accessory(accessory)

Source code in src/robot/face/model.py
def with_accessory(self, accessory: Accessory) -> FaceModel:
    return replace(self, accessory=accessory)

with_body_hint(body_hint)

Source code in src/robot/face/model.py
def with_body_hint(self, body_hint: BodyLanguageHint) -> FaceModel:
    return replace(self, body_hint=body_hint)

with_cheeks(cheeks)

Source code in src/robot/face/model.py
def with_cheeks(self, cheeks: Cheeks) -> FaceModel:
    return replace(self, cheeks=cheeks)

with_eyebrows(left=None, right=None)

Source code in src/robot/face/model.py
def with_eyebrows(
    self,
    left: Eyebrow | None = None,
    right: Eyebrow | None = None,
) -> FaceModel:
    return replace(
        self, left_eyebrow=left or self.left_eyebrow, right_eyebrow=right or self.right_eyebrow
    )

with_eyelids(eyelids)

Source code in src/robot/face/model.py
def with_eyelids(self, eyelids: Eyelids) -> FaceModel:
    return replace(self, eyelids=eyelids)

with_eyes(left_eye=None, right_eye=None)

Source code in src/robot/face/model.py
def with_eyes(
    self,
    left_eye: Eye | None = None,
    right_eye: Eye | None = None,
) -> FaceModel:
    return replace(
        self, left_eye=left_eye or self.left_eye, right_eye=right_eye or self.right_eye
    )

with_mouth(mouth)

Source code in src/robot/face/model.py
def with_mouth(self, mouth: Mouth) -> FaceModel:
    return replace(self, mouth=mouth)

with_overlay(overlay)

Source code in src/robot/face/model.py
def with_overlay(self, overlay: Overlay) -> FaceModel:
    return replace(self, overlay=overlay)

with_palette(palette)

Source code in src/robot/face/model.py
def with_palette(self, palette: FacePalette) -> FaceModel:
    return replace(self, palette=palette)

with_transform(bounce=None, squash=None)

Source code in src/robot/face/model.py
def with_transform(self, bounce: float | None = None, squash: float | None = None) -> FaceModel:
    return replace(
        self,
        bounce=self.bounce if bounce is None else bounce,
        squash=self.squash if squash is None else squash,
    )

FacePalette dataclass

All colours the renderer can use. Themes override these.

mode selects a renderer rendering style. The default "face" draws the full eye stack (sclera + iris + pupil + highlight + eyelids + eyebrows + mouth). The "vector" mode draws two filled rounded-squares for eyes and a thin horizontal bar for the mouth - the Anki Vector 2.0 minimalist look.

Source code in src/robot/face/components.py
@dataclass(slots=True, frozen=True)
class FacePalette:
    """All colours the renderer can use. Themes override these.

    ``mode`` selects a renderer rendering style. The default ``"face"``
    draws the full eye stack (sclera + iris + pupil + highlight +
    eyelids + eyebrows + mouth). The ``"vector"`` mode draws two
    filled rounded-squares for eyes and a thin horizontal bar for
    the mouth - the Anki Vector 2.0 minimalist look.
    """

    background: tuple[int, int, int] = (10, 10, 20)
    sclera: tuple[int, int, int] = (245, 245, 235)
    iris: tuple[int, int, int] = (40, 110, 200)
    pupil: tuple[int, int, int] = (10, 10, 20)
    eyelid: tuple[int, int, int] = (20, 20, 30)
    eyebrow: tuple[int, int, int] = (40, 30, 30)
    mouth: tuple[int, int, int] = (180, 60, 80)
    cheek: tuple[int, int, int] = (255, 130, 130)
    blush: tuple[int, int, int] = (255, 90, 90)
    outline: tuple[int, int, int] = (10, 10, 10)
    highlight: tuple[int, int, int] = (255, 255, 255)
    mode: str = PALETTE_MODE_FACE

background = (10, 10, 20) class-attribute instance-attribute

blush = (255, 90, 90) class-attribute instance-attribute

cheek = (255, 130, 130) class-attribute instance-attribute

eyebrow = (40, 30, 30) class-attribute instance-attribute

eyelid = (20, 20, 30) class-attribute instance-attribute

highlight = (255, 255, 255) class-attribute instance-attribute

iris = (40, 110, 200) class-attribute instance-attribute

mode = PALETTE_MODE_FACE class-attribute instance-attribute

mouth = (180, 60, 80) class-attribute instance-attribute

outline = (10, 10, 10) class-attribute instance-attribute

pupil = (10, 10, 20) class-attribute instance-attribute

sclera = (245, 245, 235) class-attribute instance-attribute

__init__(background=(10, 10, 20), sclera=(245, 245, 235), iris=(40, 110, 200), pupil=(10, 10, 20), eyelid=(20, 20, 30), eyebrow=(40, 30, 30), mouth=(180, 60, 80), cheek=(255, 130, 130), blush=(255, 90, 90), outline=(10, 10, 10), highlight=(255, 255, 255), mode=PALETTE_MODE_FACE)

Gaze dataclass

2D gaze target normalised in [-1, 1].

Source code in src/robot/face/components.py
@dataclass(slots=True, frozen=True)
class Gaze:
    """2D gaze target normalised in ``[-1, 1]``."""

    x: float = 0.0
    y: float = 0.0

    def clamped(self) -> Gaze:
        return Gaze(
            x=max(-1.0, min(1.0, self.x)),
            y=max(-1.0, min(1.0, self.y)),
        )

x = 0.0 class-attribute instance-attribute

y = 0.0 class-attribute instance-attribute

__init__(x=0.0, y=0.0)

clamped()

Source code in src/robot/face/components.py
def clamped(self) -> Gaze:
    return Gaze(
        x=max(-1.0, min(1.0, self.x)),
        y=max(-1.0, min(1.0, self.y)),
    )

HeadTilt

Bases: Enum

Discrete head-tilt hints the body-language engine understands.

Source code in src/robot/face/model.py
class HeadTilt(Enum):
    """Discrete head-tilt hints the body-language engine understands."""

    NEUTRAL = "neutral"
    CURIOUS = "curious"  # slight tilt
    THINKING = "thinking"  # small side-to-side nod
    SLEEPY = "sleepy"  # droop
    SAD = "sad"  # downward
    EXCITED = "excited"  # quick tilt

CURIOUS = 'curious' class-attribute instance-attribute

EXCITED = 'excited' class-attribute instance-attribute

NEUTRAL = 'neutral' class-attribute instance-attribute

SAD = 'sad' class-attribute instance-attribute

SLEEPY = 'sleepy' class-attribute instance-attribute

THINKING = 'thinking' class-attribute instance-attribute

Mouth dataclass

The mouth, parameterised.

Source code in src/robot/face/components.py
@dataclass(slots=True, frozen=True)
class Mouth:
    """The mouth, parameterised."""

    shape: MouthShape = MouthShape.NEUTRAL
    openness: float = 0.0  # 0.0 = closed, 1.0 = wide open
    width: float = 0.5  # 0.0 = small, 1.0 = wide
    asymmetry: float = 0.0  # -1..1 (left side higher = smirk)

asymmetry = 0.0 class-attribute instance-attribute

openness = 0.0 class-attribute instance-attribute

shape = MouthShape.NEUTRAL class-attribute instance-attribute

width = 0.5 class-attribute instance-attribute

__init__(shape=MouthShape.NEUTRAL, openness=0.0, width=0.5, asymmetry=0.0)

MouthShape

Bases: str, Enum

Source code in src/robot/face/components.py
class MouthShape(str, Enum):
    CLOSED = "closed"
    NEUTRAL = "neutral"
    SMILE = "smile"
    GRIN = "grin"
    FROWN = "frown"
    OPEN = "open"  # small "oh"
    WIDE_OPEN = "wide_open"  # gasp / surprise
    TONGUE = "tongue"  # playful
    SMILE_OPEN = "smile_open"  # laughing

CLOSED = 'closed' class-attribute instance-attribute

FROWN = 'frown' class-attribute instance-attribute

GRIN = 'grin' class-attribute instance-attribute

NEUTRAL = 'neutral' class-attribute instance-attribute

OPEN = 'open' class-attribute instance-attribute

SMILE = 'smile' class-attribute instance-attribute

SMILE_OPEN = 'smile_open' class-attribute instance-attribute

TONGUE = 'tongue' class-attribute instance-attribute

WIDE_OPEN = 'wide_open' class-attribute instance-attribute

Overlay dataclass

A floating symbol rendered on top of the face.

Source code in src/robot/face/components.py
@dataclass(slots=True, frozen=True)
class Overlay:
    """A floating symbol rendered on top of the face."""

    kind: OverlayKind = OverlayKind.NONE
    position: Point = field(default_factory=lambda: Point(0.0, -0.5))
    size: float = 0.3  # 0..1 fraction of the face radius
    rotation: float = 0.0  # radians
    color: tuple[int, int, int] = (255, 255, 255)

color = (255, 255, 255) class-attribute instance-attribute

kind = OverlayKind.NONE class-attribute instance-attribute

position = field(default_factory=lambda: Point(0.0, -0.5)) class-attribute instance-attribute

rotation = 0.0 class-attribute instance-attribute

size = 0.3 class-attribute instance-attribute

__init__(kind=OverlayKind.NONE, position=(lambda: Point(0.0, -0.5))(), size=0.3, rotation=0.0, color=(255, 255, 255))

OverlayKind

Bases: str, Enum

Source code in src/robot/face/components.py
class OverlayKind(str, Enum):
    NONE = "none"
    SPARKLE = "sparkle"
    HEART = "heart"
    TEAR = "tear"
    SWEAT = "sweat"
    ANGER = "anger"  # vein symbol
    QUESTION = "question"  # "?" mark
    EXCLAIM = "exclaim"  # "!" mark
    MUSIC = "music"  # note
    STAR = "star"

ANGER = 'anger' class-attribute instance-attribute

EXCLAIM = 'exclaim' class-attribute instance-attribute

HEART = 'heart' class-attribute instance-attribute

MUSIC = 'music' class-attribute instance-attribute

NONE = 'none' class-attribute instance-attribute

QUESTION = 'question' class-attribute instance-attribute

SPARKLE = 'sparkle' class-attribute instance-attribute

STAR = 'star' class-attribute instance-attribute

SWEAT = 'sweat' class-attribute instance-attribute

TEAR = 'tear' class-attribute instance-attribute

Point dataclass

A 2D point in the face's local frame, in pixels.

Source code in src/robot/face/components.py
@dataclass(slots=True, frozen=True)
class Point:
    """A 2D point in the face's local frame, in pixels."""

    x: float
    y: float

x instance-attribute

y instance-attribute

__init__(x, y)

_EmotionDef dataclass

A complete emotional expression: face presets + body hint.

Source code in src/robot/face/emotions.py
@dataclass(slots=True, frozen=True)
class _EmotionDef:
    """A complete emotional expression: face presets + body hint."""

    eyes: tuple[Eye, Eye]  # left, right
    eyelids: Eyelids
    eyebrows: tuple[Eyebrow, Eyebrow]  # left, right
    mouth: Mouth
    cheeks: Cheeks
    overlay: Overlay
    body_hint: BodyLanguageHint

body_hint instance-attribute

cheeks instance-attribute

eyebrows instance-attribute

eyelids instance-attribute

eyes instance-attribute

mouth instance-attribute

overlay instance-attribute

__init__(eyes, eyelids, eyebrows, mouth, cheeks, overlay, body_hint)