feat(integration): Complete feature rewrite with pipeline architecture, effects system, and display improvements

Major changes:
- Pipeline architecture with capability-based dependency resolution
- Effects plugin system with performance monitoring
- Display abstraction with multiple backends (terminal, null, websocket)
- Camera system for viewport scrolling
- Sensor framework for real-time input
- Command-and-control system via ntfy
- WebSocket display backend for browser clients
- Comprehensive test suite and documentation

Issue #48: ADR for preset scripting language included

This commit consolidates 110 individual commits into a single
feature integration that can be reviewed and tested before
further refinement.
This commit is contained in:
2026-03-20 04:41:23 -07:00
parent 42aa6f16cc
commit ef98add0c5
179 changed files with 27649 additions and 6552 deletions

View File

@@ -0,0 +1,38 @@
from pathlib import Path
PLUGIN_DIR = Path(__file__).parent
def discover_plugins():
from engine.effects.registry import get_registry
from engine.effects.types import EffectPlugin
registry = get_registry()
imported = {}
for file_path in PLUGIN_DIR.glob("*.py"):
if file_path.name.startswith("_"):
continue
module_name = file_path.stem
if module_name in ("base", "types"):
continue
try:
module = __import__(f"engine.effects.plugins.{module_name}", fromlist=[""])
for attr_name in dir(module):
attr = getattr(module, attr_name)
if (
isinstance(attr, type)
and issubclass(attr, EffectPlugin)
and attr is not EffectPlugin
and attr_name.endswith("Effect")
):
plugin = attr()
if not isinstance(plugin, EffectPlugin):
continue
registry.register(plugin)
imported[plugin.name] = plugin
except Exception:
pass
return imported

View File

@@ -0,0 +1,122 @@
"""Afterimage effect using previous frame."""
from engine.effects.types import EffectConfig, EffectContext, EffectPlugin
class AfterimageEffect(EffectPlugin):
"""Show a faint ghost of the previous frame.
This effect requires a FrameBufferStage to be present in the pipeline.
It shows a dimmed version of the previous frame super-imposed on the
current frame.
Attributes:
name: "afterimage"
config: EffectConfig with intensity parameter (0.0-1.0)
param_bindings: Optional sensor bindings for intensity modulation
Example:
>>> effect = AfterimageEffect()
>>> effect.configure(EffectConfig(intensity=0.3))
>>> result = effect.process(buffer, ctx)
"""
name = "afterimage"
config: EffectConfig = EffectConfig(enabled=True, intensity=0.3)
param_bindings: dict[str, dict[str, str | float]] = {}
supports_partial_updates = False
def process(self, buf: list[str], ctx: EffectContext) -> list[str]:
"""Apply afterimage effect using the previous frame.
Args:
buf: Current text buffer (list of strings)
ctx: Effect context with access to framebuffer history
Returns:
Buffer with ghost of previous frame overlaid
"""
if not buf:
return buf
# Get framebuffer history from context
history = None
for key in ctx.state:
if key.startswith("framebuffer.") and key.endswith(".history"):
history = ctx.state[key]
break
if not history or len(history) < 1:
# No previous frame available
return buf
# Get intensity from config
intensity = self.config.params.get("intensity", self.config.intensity)
intensity = max(0.0, min(1.0, intensity))
if intensity <= 0.0:
return buf
# Get the previous frame (index 1, since index 0 is current)
prev_frame = history[1] if len(history) > 1 else None
if not prev_frame:
return buf
# Blend current and previous frames
viewport_height = ctx.terminal_height - ctx.ticker_height
result = []
for row in range(len(buf)):
if row >= viewport_height:
result.append(buf[row])
continue
current_line = buf[row]
prev_line = prev_frame[row] if row < len(prev_frame) else ""
if not prev_line:
result.append(current_line)
continue
# Apply dimming effect by reducing ANSI color intensity or adding transparency
# For a simple text version, we'll use a blend strategy
blended = self._blend_lines(current_line, prev_line, intensity)
result.append(blended)
return result
def _blend_lines(self, current: str, previous: str, intensity: float) -> str:
"""Blend current and previous line with given intensity.
For text with ANSI codes, true blending is complex. This is a simplified
version that uses color averaging when possible.
A more sophisticated implementation would:
1. Parse ANSI color codes from both lines
2. Blend RGB values based on intensity
3. Reconstruct the line with blended colors
For now, we'll use a heuristic: if lines are similar, return current.
If they differ, we alternate or use the previous as a faint overlay.
"""
if current == previous:
return current
# Simple blending: intensity determines mix
# intensity=1.0 => fully current
# intensity=0.3 => 70% previous ghost, 30% current
if intensity > 0.7:
return current
elif intensity < 0.3:
# Show previous but dimmed (simulate by adding faint color/gray)
return previous # Would need to dim ANSI colors
else:
# For medium intensity, alternate based on character pattern
# This is a placeholder for proper blending
return current
def configure(self, config: EffectConfig) -> None:
"""Configure the effect."""
self.config = config

View File

@@ -0,0 +1,105 @@
from engine.effects.types import EffectConfig, EffectContext, EffectPlugin
class BorderEffect(EffectPlugin):
"""Simple border effect for terminal display.
Draws a border around the buffer and optionally displays
performance metrics in the border corners.
Internally crops to display dimensions to ensure border fits.
"""
name = "border"
config = EffectConfig(enabled=True, intensity=1.0)
def process(self, buf: list[str], ctx: EffectContext) -> list[str]:
if not buf:
return buf
# Get actual display dimensions from context
display_w = ctx.terminal_width
display_h = ctx.terminal_height
# If dimensions are reasonable, crop first - use slightly smaller to ensure fit
if display_w >= 10 and display_h >= 3:
# Subtract 2 for border characters (left and right)
crop_w = display_w - 2
crop_h = display_h - 2
buf = self._crop_to_size(buf, crop_w, crop_h)
w = display_w
h = display_h
else:
# Use buffer dimensions
h = len(buf)
w = max(len(line) for line in buf) if buf else 0
if w < 3 or h < 3:
return buf
inner_w = w - 2
# Get metrics from context
fps = 0.0
frame_time = 0.0
metrics = ctx.get_state("metrics")
if metrics:
avg_ms = metrics.get("avg_ms")
frame_count = metrics.get("frame_count", 0)
if avg_ms and frame_count > 0:
fps = 1000.0 / avg_ms
frame_time = avg_ms
# Build borders
# Top border: ┌────────────────────┐ or with FPS
if fps > 0:
fps_str = f" FPS:{fps:.0f}"
if len(fps_str) < inner_w:
right_len = inner_w - len(fps_str)
top_border = "" + "" * right_len + fps_str + ""
else:
top_border = "" + "" * inner_w + ""
else:
top_border = "" + "" * inner_w + ""
# Bottom border: └────────────────────┘ or with frame time
if frame_time > 0:
ft_str = f" {frame_time:.1f}ms"
if len(ft_str) < inner_w:
right_len = inner_w - len(ft_str)
bottom_border = "" + "" * right_len + ft_str + ""
else:
bottom_border = "" + "" * inner_w + ""
else:
bottom_border = "" + "" * inner_w + ""
# Build result with left/right borders
result = [top_border]
for line in buf[: h - 2]:
if len(line) >= inner_w:
result.append("" + line[:inner_w] + "")
else:
result.append("" + line + " " * (inner_w - len(line)) + "")
result.append(bottom_border)
return result
def _crop_to_size(self, buf: list[str], w: int, h: int) -> list[str]:
"""Crop buffer to fit within w x h."""
result = []
for i in range(min(h, len(buf))):
line = buf[i]
if len(line) > w:
result.append(line[:w])
else:
result.append(line + " " * (w - len(line)))
# Pad with empty lines if needed (for border)
while len(result) < h:
result.append(" " * w)
return result
def configure(self, config: EffectConfig) -> None:
self.config = config

View File

@@ -0,0 +1,42 @@
from engine.effects.types import EffectConfig, EffectContext, EffectPlugin
class CropEffect(EffectPlugin):
"""Crop effect that crops the input buffer to fit the display.
This ensures the output buffer matches the actual display dimensions,
useful when the source produces a buffer larger than the viewport.
"""
name = "crop"
config = EffectConfig(enabled=True, intensity=1.0)
def process(self, buf: list[str], ctx: EffectContext) -> list[str]:
if not buf:
return buf
# Get actual display dimensions from context
w = (
ctx.terminal_width
if ctx.terminal_width > 0
else max(len(line) for line in buf)
)
h = ctx.terminal_height if ctx.terminal_height > 0 else len(buf)
# Crop buffer to fit
result = []
for i in range(min(h, len(buf))):
line = buf[i]
if len(line) > w:
result.append(line[:w])
else:
result.append(line + " " * (w - len(line)))
# Pad with empty lines if needed
while len(result) < h:
result.append(" " * w)
return result
def configure(self, config: EffectConfig) -> None:
self.config = config

View File

@@ -0,0 +1,58 @@
import random
from engine.effects.types import EffectConfig, EffectContext, EffectPlugin
class FadeEffect(EffectPlugin):
name = "fade"
config = EffectConfig(enabled=True, intensity=1.0, entropy=0.1)
def process(self, buf: list[str], ctx: EffectContext) -> list[str]:
if not ctx.ticker_height:
return buf
result = list(buf)
intensity = self.config.intensity
top_zone = max(1, int(ctx.ticker_height * 0.25))
bot_zone = max(1, int(ctx.ticker_height * 0.10))
for r in range(len(result)):
if r >= ctx.ticker_height:
continue
top_f = min(1.0, r / top_zone) if top_zone > 0 else 1.0
bot_f = (
min(1.0, (ctx.ticker_height - 1 - r) / bot_zone)
if bot_zone > 0
else 1.0
)
row_fade = min(top_f, bot_f) * intensity
if row_fade < 1.0 and result[r].strip():
result[r] = self._fade_line(result[r], row_fade)
return result
def _fade_line(self, s: str, fade: float) -> str:
if fade >= 1.0:
return s
if fade <= 0.0:
return s # Preserve original line length - don't return empty
result = []
i = 0
while i < len(s):
if s[i] == "\033" and i + 1 < len(s) and s[i + 1] == "[":
j = i + 2
while j < len(s) and not s[j].isalpha():
j += 1
result.append(s[i : j + 1])
i = j + 1
elif s[i] == " ":
result.append(" ")
i += 1
else:
result.append(s[i] if random.random() < fade else " ")
i += 1
return "".join(result)
def configure(self, config: EffectConfig) -> None:
self.config = config

View File

@@ -0,0 +1,72 @@
import random
from datetime import datetime
from engine import config
from engine.effects.types import EffectConfig, EffectContext, EffectPlugin
from engine.sources import FEEDS, POETRY_SOURCES
from engine.terminal import C_DIM, G_DIM, G_LO, RST, W_GHOST
class FirehoseEffect(EffectPlugin):
name = "firehose"
config = EffectConfig(enabled=True, intensity=1.0, entropy=0.9)
def process(self, buf: list[str], ctx: EffectContext) -> list[str]:
firehose_h = config.FIREHOSE_H if config.FIREHOSE else 0
if firehose_h <= 0 or not ctx.items:
return buf
result = list(buf)
intensity = self.config.intensity
h = ctx.terminal_height
for fr in range(firehose_h):
scr_row = h - firehose_h + fr + 1
fline = self._firehose_line(ctx.items, ctx.terminal_width, intensity)
result.append(f"\033[{scr_row};1H{fline}\033[K")
return result
def _firehose_line(self, items: list, w: int, intensity: float) -> str:
r = random.random()
if r < 0.35 * intensity:
title, src, ts = random.choice(items)
text = title[: w - 1]
color = random.choice([G_LO, G_DIM, W_GHOST, C_DIM])
return f"{color}{text}{RST}"
elif r < 0.55 * intensity:
d = random.choice([0.45, 0.55, 0.65, 0.75])
return "".join(
f"{random.choice([G_LO, G_DIM, C_DIM, W_GHOST])}"
f"{random.choice(config.GLITCH + config.KATA)}{RST}"
if random.random() < d
else " "
for _ in range(w)
)
elif r < 0.78 * intensity:
sources = FEEDS if config.MODE == "news" else POETRY_SOURCES
src = random.choice(list(sources.keys()))
msgs = [
f" SIGNAL :: {src} :: {datetime.now().strftime('%H:%M:%S.%f')[:-3]}",
f" ░░ FEED ACTIVE :: {src}",
f" >> DECODE 0x{random.randint(0x1000, 0xFFFF):04X} :: {src[:24]}",
f" ▒▒ ACQUIRE :: {random.choice(['TCP', 'UDP', 'RSS', 'ATOM', 'XML'])} :: {src}",
f" {''.join(random.choice(config.KATA) for _ in range(3))} STRM "
f"{random.randint(0, 255):02X}:{random.randint(0, 255):02X}",
]
text = random.choice(msgs)[: w - 1]
color = random.choice([G_LO, G_DIM, W_GHOST])
return f"{color}{text}{RST}"
else:
title, _, _ = random.choice(items)
start = random.randint(0, max(0, len(title) - 20))
frag = title[start : start + random.randint(10, 35)]
pad = random.randint(0, max(0, w - len(frag) - 8))
gp = "".join(
random.choice(config.GLITCH) for _ in range(random.randint(1, 3))
)
text = (" " * pad + gp + " " + frag)[: w - 1]
color = random.choice([G_LO, C_DIM, W_GHOST])
return f"{color}{text}{RST}"
def configure(self, config: EffectConfig) -> None:
self.config = config

View File

@@ -0,0 +1,52 @@
import random
from engine.effects.types import EffectConfig, EffectContext, EffectPlugin
from engine.terminal import DIM, G_LO, RST
class GlitchEffect(EffectPlugin):
name = "glitch"
config = EffectConfig(enabled=True, intensity=1.0, entropy=0.8)
def process(self, buf: list[str], ctx: EffectContext) -> list[str]:
if not buf:
return buf
result = list(buf)
intensity = self.config.intensity
glitch_prob = 0.32 + min(0.9, ctx.mic_excess * 0.16)
glitch_prob = glitch_prob * intensity
n_hits = 4 + int(ctx.mic_excess / 2)
n_hits = int(n_hits * intensity)
if random.random() < glitch_prob:
# Store original visible lengths before any modifications
# Strip ANSI codes to get visible length
import re
ansi_pattern = re.compile(r"\x1b\[[0-9;]*[a-zA-Z]")
original_lengths = [len(ansi_pattern.sub("", line)) for line in result]
for _ in range(min(n_hits, len(result))):
gi = random.randint(0, len(result) - 1)
result[gi]
target_len = original_lengths[gi] # Use stored original length
glitch_bar = self._glitch_bar(target_len)
result[gi] = glitch_bar
return result
def _glitch_bar(self, target_len: int) -> str:
c = random.choice(["", "", "", "\xc2"])
n = random.randint(3, max(3, target_len // 2))
o = random.randint(0, max(0, target_len - n))
glitch_chars = c * n
trailing_spaces = target_len - o - n
trailing_spaces = max(0, trailing_spaces)
glitch_part = f"{G_LO}{DIM}" + glitch_chars + RST
result = " " * o + glitch_part + " " * trailing_spaces
return result
def configure(self, config: EffectConfig) -> None:
self.config = config

View File

@@ -0,0 +1,102 @@
from engine.effects.types import (
EffectConfig,
EffectContext,
EffectPlugin,
PartialUpdate,
)
class HudEffect(EffectPlugin):
name = "hud"
config = EffectConfig(enabled=True, intensity=1.0)
supports_partial_updates = True # Enable partial update optimization
# Cache last HUD content to detect changes
_last_hud_content: tuple | None = None
def process_partial(
self, buf: list[str], ctx: EffectContext, partial: PartialUpdate
) -> list[str]:
# If full buffer requested, process normally
if partial.full_buffer:
return self.process(buf, ctx)
# If HUD rows (0, 1, 2) aren't dirty, skip processing
if partial.dirty:
hud_rows = {0, 1, 2}
dirty_hud_rows = partial.dirty & hud_rows
if not dirty_hud_rows:
return buf # Nothing for HUD to do
# Proceed with full processing
return self.process(buf, ctx)
def process(self, buf: list[str], ctx: EffectContext) -> list[str]:
result = list(buf)
# Read metrics from pipeline context (first-class citizen)
# Falls back to global monitor for backwards compatibility
metrics = ctx.get_state("metrics")
if not metrics:
# Fallback to global monitor for backwards compatibility
from engine.effects.performance import get_monitor
monitor = get_monitor()
if monitor:
stats = monitor.get_stats()
if stats and "pipeline" in stats:
metrics = stats
fps = 0.0
frame_time = 0.0
if metrics:
if "error" in metrics:
pass # No metrics available yet
elif "pipeline" in metrics:
frame_time = metrics["pipeline"].get("avg_ms", 0.0)
frame_count = metrics.get("frame_count", 0)
if frame_count > 0 and frame_time > 0:
fps = 1000.0 / frame_time
elif "avg_ms" in metrics:
# Direct metrics format
frame_time = metrics.get("avg_ms", 0.0)
frame_count = metrics.get("frame_count", 0)
if frame_count > 0 and frame_time > 0:
fps = 1000.0 / frame_time
effect_name = self.config.params.get("display_effect", "none")
effect_intensity = self.config.params.get("display_intensity", 0.0)
hud_lines = []
hud_lines.append(
f"\033[1;1H\033[38;5;46mMAINLINE DEMO\033[0m \033[38;5;245m|\033[0m \033[38;5;39mFPS: {fps:.1f}\033[0m \033[38;5;245m|\033[0m \033[38;5;208m{frame_time:.1f}ms\033[0m"
)
bar_width = 20
filled = int(bar_width * effect_intensity)
bar = (
"\033[38;5;82m"
+ "" * filled
+ "\033[38;5;240m"
+ "" * (bar_width - filled)
+ "\033[0m"
)
hud_lines.append(
f"\033[2;1H\033[38;5;45mEFFECT:\033[0m \033[1;38;5;227m{effect_name:12s}\033[0m \033[38;5;245m|\033[0m {bar} \033[38;5;245m|\033[0m \033[38;5;219m{effect_intensity * 100:.0f}%\033[0m"
)
# Get pipeline order from context
pipeline_order = ctx.get_state("pipeline_order")
pipeline_str = ",".join(pipeline_order) if pipeline_order else "(none)"
hud_lines.append(f"\033[3;1H\033[38;5;44mPIPELINE:\033[0m {pipeline_str}")
for i, line in enumerate(hud_lines):
if i < len(result):
result[i] = line
else:
result.append(line)
return result
def configure(self, config: EffectConfig) -> None:
self.config = config

View File

@@ -0,0 +1,119 @@
"""Motion blur effect using frame history."""
from engine.effects.types import EffectConfig, EffectContext, EffectPlugin
class MotionBlurEffect(EffectPlugin):
"""Apply motion blur by blending current frame with previous frames.
This effect requires a FrameBufferStage to be present in the pipeline.
The framebuffer provides frame history which is blended with the current
frame based on intensity.
Attributes:
name: "motionblur"
config: EffectConfig with intensity parameter (0.0-1.0)
param_bindings: Optional sensor bindings for intensity modulation
Example:
>>> effect = MotionBlurEffect()
>>> effect.configure(EffectConfig(intensity=0.5))
>>> result = effect.process(buffer, ctx)
"""
name = "motionblur"
config: EffectConfig = EffectConfig(enabled=True, intensity=0.5)
param_bindings: dict[str, dict[str, str | float]] = {}
supports_partial_updates = False
def process(self, buf: list[str], ctx: EffectContext) -> list[str]:
"""Apply motion blur by blending with previous frames.
Args:
buf: Current text buffer (list of strings)
ctx: Effect context with access to framebuffer history
Returns:
Blended buffer with motion blur effect applied
"""
if not buf:
return buf
# Get framebuffer history from context
# We'll look for the first available framebuffer history
history = None
for key in ctx.state:
if key.startswith("framebuffer.") and key.endswith(".history"):
history = ctx.state[key]
break
if not history:
# No framebuffer available, return unchanged
return buf
# Get intensity from config
intensity = self.config.params.get("intensity", self.config.intensity)
intensity = max(0.0, min(1.0, intensity))
if intensity <= 0.0:
return buf
# Get decay factor (how quickly older frames fade)
decay = self.config.params.get("decay", 0.7)
# Build output buffer
result = []
viewport_height = ctx.terminal_height - ctx.ticker_height
# Determine how many frames to blend (up to history depth)
max_frames = min(len(history), 5) # Cap at 5 frames for performance
for row in range(len(buf)):
if row >= viewport_height:
# Beyond viewport, just copy
result.append(buf[row])
continue
# Start with current frame
blended = buf[row]
# Blend with historical frames
weight_sum = 1.0
if max_frames > 0 and intensity > 0:
for i in range(max_frames):
frame_weight = intensity * (decay**i)
if frame_weight < 0.01: # Skip negligible weights
break
hist_row = history[i][row] if row < len(history[i]) else ""
# Simple string blending: we'll concatenate with space
# For a proper effect, we'd need to blend ANSI colors
# This is a simplified version that just adds the frames
blended = self._blend_strings(blended, hist_row, frame_weight)
weight_sum += frame_weight
result.append(blended)
return result
def _blend_strings(self, current: str, historical: str, weight: float) -> str:
"""Blend two strings with given weight.
This is a simplified blending that works with ANSI codes.
For proper blending we'd need to parse colors, but for now
we use a heuristic: if strings are identical, return one.
If they differ, we alternate or concatenate based on weight.
"""
if current == historical:
return current
# If weight is high, show current; if low, show historical
if weight > 0.5:
return current
else:
return historical
def configure(self, config: EffectConfig) -> None:
"""Configure the effect."""
self.config = config

View File

@@ -0,0 +1,37 @@
import random
from engine import config
from engine.effects.types import EffectConfig, EffectContext, EffectPlugin
from engine.terminal import C_DIM, G_DIM, G_LO, RST, W_GHOST
class NoiseEffect(EffectPlugin):
name = "noise"
config = EffectConfig(enabled=True, intensity=0.15, entropy=0.4)
def process(self, buf: list[str], ctx: EffectContext) -> list[str]:
if not ctx.ticker_height:
return buf
result = list(buf)
intensity = self.config.intensity
probability = intensity * 0.15
for r in range(len(result)):
cy = ctx.scroll_cam + r
if random.random() < probability:
original_line = result[r]
result[r] = self._generate_noise(len(original_line), cy)
return result
def _generate_noise(self, w: int, cy: int) -> str:
d = random.choice([0.15, 0.25, 0.35, 0.12])
return "".join(
f"{random.choice([G_LO, G_DIM, C_DIM, W_GHOST])}"
f"{random.choice(config.GLITCH + config.KATA)}{RST}"
if random.random() < d
else " "
for _ in range(w)
)
def configure(self, config: EffectConfig) -> None:
self.config = config

View File

@@ -0,0 +1,99 @@
from engine.effects.types import EffectConfig, EffectContext, EffectPlugin
class TintEffect(EffectPlugin):
"""Tint effect that applies an RGB color overlay to the buffer.
Uses ANSI escape codes to tint text with the specified RGB values.
Supports transparency (0-100%) for blending.
Inlets:
- r: Red component (0-255)
- g: Green component (0-255)
- b: Blue component (0-255)
- a: Alpha/transparency (0.0-1.0, where 0.0 = fully transparent)
"""
name = "tint"
config = EffectConfig(enabled=True, intensity=1.0)
# Define inlet types for PureData-style typing
@property
def inlet_types(self) -> set:
from engine.pipeline.core import DataType
return {DataType.TEXT_BUFFER}
@property
def outlet_types(self) -> set:
from engine.pipeline.core import DataType
return {DataType.TEXT_BUFFER}
def process(self, buf: list[str], ctx: EffectContext) -> list[str]:
if not buf:
return buf
# Get tint values from effect params or sensors
r = self.config.params.get("r", 255)
g = self.config.params.get("g", 255)
b = self.config.params.get("b", 255)
a = self.config.params.get("a", 0.3) # Default 30% tint
# Clamp values
r = max(0, min(255, int(r)))
g = max(0, min(255, int(g)))
b = max(0, min(255, int(b)))
a = max(0.0, min(1.0, float(a)))
if a <= 0:
return buf
# Convert RGB to ANSI 256 color
ansi_color = self._rgb_to_ansi256(r, g, b)
# Apply tint with transparency effect
result = []
for line in buf:
if not line.strip():
result.append(line)
continue
# Check if line already has ANSI codes
if "\033[" in line:
# For lines with existing colors, wrap the whole line
result.append(f"\033[38;5;{ansi_color}m{line}\033[0m")
else:
# Apply tint to plain text lines
result.append(f"\033[38;5;{ansi_color}m{line}\033[0m")
return result
def _rgb_to_ansi256(self, r: int, g: int, b: int) -> int:
"""Convert RGB (0-255 each) to ANSI 256 color code."""
if r == g == b == 0:
return 16
if r == g == b == 255:
return 231
# Calculate grayscale
gray = int((0.299 * r + 0.587 * g + 0.114 * b) / 255 * 24) + 232
# Calculate color cube
ri = int(r / 51)
gi = int(g / 51)
bi = int(b / 51)
color = 16 + 36 * ri + 6 * gi + bi
# Use whichever is closer - gray or color
gray_dist = abs(r - gray)
color_dist = (
(r - ri * 51) ** 2 + (g - gi * 51) ** 2 + (b - bi * 51) ** 2
) ** 0.5
if gray_dist < color_dist:
return gray
return color
def configure(self, config: EffectConfig) -> None:
self.config = config