Alpha Swatches¶

In the blend chapter this notebook generates the swatches for the Porter-Duff source-over derivation: a translucent red foreground, a translucent blue background, and the color that results from compositing one over the other. Each swatch is drawn over a checkerboard so the transparency is visible. The color channels are linear sRGB values. You can plug in your own colors to generate your own swatches.

In [ ]:
import json
from pathlib import Path

import brushcue

def find_repo_root():
    for directory in (Path.cwd(), *Path.cwd().parents):
        if (directory / "writing/graphics/chapters/blend").is_dir():
            return directory
    raise FileNotFoundError("Could not find the graphics book directory")

ctx = brushcue.Context()
OUTPUT_DIRECTORY = find_repo_root() / "writing/graphics/chapters/blend/assets/alpha-swatches"

SWATCH_DIAMETER = 256
CHECKER_SIZE = 32
CHECKER_LIGHT = (1, 1, 1)
CHECKER_DARK = (0.8, 0.8, 0.8)
STROKE_WIDTH = 2
output_color_profile = brushcue.ColorProfile.srgb()

# Linear sRGB colors with alpha.
FOREGROUND = (1, 0, 0, 0.6)
BACKGROUND = (0, 0, 1, 0.7)
In [ ]:
def porter_duff_over(foreground, background):
    """Porter-Duff source over for straight (non-premultiplied) alpha."""
    *foreground_rgb, foreground_alpha = foreground
    *background_rgb, background_alpha = background
    output_alpha = foreground_alpha + background_alpha * (1 - foreground_alpha)
    output_rgb = [
        (f * foreground_alpha + b * background_alpha * (1 - foreground_alpha)) / output_alpha
        for f, b in zip(foreground_rgb, background_rgb)
    ]
    return (*output_rgb, output_alpha)

OUTPUT = porter_duff_over(FOREGROUND, BACKGROUND)
OUTPUT
In [ ]:
CENTER = brushcue.Point2f.from_components(0, 0)
INSTANCES = brushcue.Transform2.identity().to_list()

def srgb(rgb):
    return brushcue.ProfiledColor.from_rgba_srgb(brushcue.RGBAColor.from_components(*rgb, 1))

def circle(render_style):
    painter = brushcue.Painter.new().add_ellipse_with_render_style(
        CENTER, brushcue.Vector2f.from_components(SWATCH_DIAMETER, SWATCH_DIAMETER), 0, render_style, INSTANCES
    )
    return brushcue.Composition.painter(painter)

def checkerboard():
    """A checkerboard of light and dark squares covering the swatch, clipped to the circle."""
    painter = brushcue.Painter.new()
    count = SWATCH_DIAMETER // CHECKER_SIZE
    start = -SWATCH_DIAMETER / 2 + CHECKER_SIZE / 2
    square = brushcue.Vector2f.from_components(CHECKER_SIZE, CHECKER_SIZE)
    for row in range(count):
        for column in range(count):
            shade = CHECKER_LIGHT if (row + column) % 2 == 0 else CHECKER_DARK
            center = brushcue.Point2f.from_components(start + column * CHECKER_SIZE, start + row * CHECKER_SIZE)
            style = brushcue.RenderStyle.fill_only(brushcue.Fill.solid(srgb(shade)))
            painter = painter.add_rectangle_with_render_style(center, square, 0, style, INSTANCES)
    squares = brushcue.Composition.painter(painter)
    # Stencil keeps the checkerboard's color but only where the circle is.
    mask = circle(brushcue.RenderStyle.fill_only(brushcue.Fill.solid(srgb((0, 0, 0)))))
    return mask.blend_stencil(squares)

def alpha_swatch(rgba):
    fill = circle(brushcue.RenderStyle.fill_only(
        brushcue.Fill.solid(brushcue.ProfiledColor.from_rgba_srgb_linear(brushcue.RGBAColor.from_components(*rgba)))
    ))
    outline = circle(brushcue.RenderStyle.brush_only(brushcue.Brush.solid(srgb((0, 0, 0)), STROKE_WIDTH)))
    return outline.blend_alpha(fill.blend_alpha(checkerboard())).color_convert(output_color_profile)
In [ ]:
from IPython.display import Image, display

def format_channel(value):
    return f"{value:.3f}".rstrip("0").rstrip(".")

OUTPUT_DIRECTORY.mkdir(parents=True, exist_ok=True)
for name, rgba in [("foreground", FOREGROUND), ("background", BACKGROUND), ("output", OUTPUT)]:
    image_bytes = bytes(alpha_swatch(rgba).execute(ctx).to_image_bytes(ctx))
    (OUTPUT_DIRECTORY / f"{name}.png").write_bytes(image_bytes)
    with open(OUTPUT_DIRECTORY / f"{name}.json", "w") as f:
        json.dump({"rgb": [format_channel(c) for c in rgba[:3]], "alpha": format_channel(rgba[3])}, f)
    display(Image(image_bytes))