Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
191 changes: 191 additions & 0 deletions ports/zephyr-cp/tests/test_displayio_colorconverter.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,191 @@
# SPDX-FileCopyrightText: 2026 Mikey Sklar for Adafruit Industries
#
# SPDX-License-Identifier: MIT

"""Bitmaps of 8 bits or fewer drawn through a ColorConverter, on both displayio compositors.

The LVGL compositor draws these as indexed images, with a table of the color the converter
gives each value. The expected frame is computed here from the same description. Only fully
saturated colors are used so the result doesn't depend on the display's pixel format: value 255
in RGB888, and a full 5 bit channel in the RGB555 and BGR555 colorspaces. Bitmaps of 4 bits or
fewer can't reach a saturated color, so their light pixels are a transparent value over the
green background instead.
"""

import pytest
from PIL import Image

BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)

_SETUP = """\
import board
import displayio
import time

display = board.DISPLAY
display.auto_refresh = False
CS = displayio.Colorspace

group = displayio.Group()
background = displayio.Palette(1)
background[0] = 0x00FF00
group.append(displayio.TileGrid(displayio.Bitmap(display.width, display.height, 1),
pixel_shader=background))


def bitmap(value_count, value_at):
b = displayio.Bitmap(20, 10, value_count)
for y in range(10):
for x in range(20):
b[x, y] = value_at(x, y)
return b


def converter(colorspace, transparent=None):
c = displayio.ColorConverter(input_colorspace=colorspace)
if transparent is not None:
c.make_transparent(transparent)
return c

"""

RENDER_CODE = (
_SETUP
+ """\
# 8 bit bitmaps in three colorspaces.
group.append(displayio.TileGrid(bitmap(256, lambda x, y: 255 if x < 10 else 0),
pixel_shader=converter(CS.RGB888), x=10, y=10))
group.append(displayio.TileGrid(bitmap(256, lambda x, y: 0x7C if y < 5 else 0),
pixel_shader=converter(CS.RGB555_SWAPPED), x=40, y=10))
group.append(displayio.TileGrid(bitmap(256, lambda x, y: 31 if (x // 2) % 2 else 0),
pixel_shader=converter(CS.BGR555), x=70, y=10))

# An 8 bit bitmap in a scaled group.
small = displayio.Bitmap(10, 5, 256)
for y in range(5):
for x in range(10):
small[x, y] = 31 if x < 5 else 0
scaled = displayio.Group(scale=2, x=100, y=10)
scaled.append(displayio.TileGrid(small, pixel_shader=converter(CS.RGB555)))
group.append(scaled)

# 1, 2 and 4 bit bitmaps whose top value is transparent.
for i, bits in enumerate((1, 2, 4)):
top = (1 << bits) - 1
group.append(displayio.TileGrid(bitmap(1 << bits, lambda x, y: top if x < 10 else 0),
pixel_shader=converter(CS.RGB565, transparent=top), x=10 + 30 * i, y=40))

# An 8 bit bitmap with a transparent value.
group.append(displayio.TileGrid(bitmap(256, lambda x, y: 5 if x < 10 else 255),
pixel_shader=converter(CS.RGB888, transparent=5), x=100, y=40))

display.root_group = group
display.refresh()
print("shown")
time.sleep(30)
"""
)

CHANGE_CODE = (
_SETUP
+ """\
blue_left = lambda x, y: 255 if x < 10 else 0
made_transparent = converter(CS.RGB888)
group.append(displayio.TileGrid(bitmap(256, blue_left), pixel_shader=made_transparent,
x=10, y=10))
made_opaque = converter(CS.RGB888, transparent=255)
group.append(displayio.TileGrid(bitmap(256, blue_left), pixel_shader=made_opaque,
x=40, y=10))

display.root_group = group
display.refresh()
print("first")
time.sleep(10)

made_transparent.make_transparent(255)
made_opaque.make_opaque(255)
display.refresh()
print("second")
time.sleep(20)
"""
)


def _frame(width, height):
return [[GREEN] * width for _ in range(height)]


def _fill(frame, x0, y0, color_at, width=20, height=10):
for y in range(height):
for x in range(width):
if 0 <= y0 + y < len(frame) and 0 <= x0 + x < len(frame[0]):
frame[y0 + y][x0 + x] = color_at(x, y)


def _render_expected(width, height):
frame = _frame(width, height)
_fill(frame, 10, 10, lambda x, y: BLUE if x < 10 else BLACK)
_fill(frame, 40, 10, lambda x, y: RED if y < 5 else BLACK)
_fill(frame, 70, 10, lambda x, y: RED if (x // 2) % 2 else BLACK)
_fill(frame, 100, 10, lambda x, y: BLUE if x < 10 else BLACK)
for i in range(3):
_fill(frame, 10 + 30 * i, 40, lambda x, y: GREEN if x < 10 else BLACK)
_fill(frame, 100, 40, lambda x, y: GREEN if x < 10 else BLUE)
return frame


def _change_expected(width, height, changed):
frame = _frame(width, height)
shown = (GREEN, BLUE) if changed else (BLUE, GREEN)
_fill(frame, 10, 10, lambda x, y: shown[0] if x < 10 else BLACK)
_fill(frame, 40, 10, lambda x, y: shown[1] if x < 10 else BLACK)
return frame


def _compare(path, expected_for):
with Image.open(path) as img:
rgb = img.convert("RGB")
expected = expected_for(rgb.width, rgb.height)
mismatches = []
for y in range(rgb.height):
for x in range(rgb.width):
actual = rgb.getpixel((x, y))
if actual != expected[y][x]:
mismatches.append((x, y, expected[y][x], actual))
assert not mismatches, f"{len(mismatches)} pixels differ, first: {mismatches[:8]}"


@pytest.mark.circuitpy_drive({"code.py": RENDER_CODE})
@pytest.mark.display(capture_times_ns=[8_000_000_000])
@pytest.mark.duration(12)
def test_colorconverter_render(circuitpython):
"""Low bit bitmaps draw through a ColorConverter the same way on both compositors."""
circuitpython.wait_until_done()
assert "shown" in circuitpython.serial.all_output
captures = circuitpython.display_capture_paths()
if not captures or not captures[0].exists():
pytest.skip("display capture was not produced")
_compare(captures[0], _render_expected)


# Legacy displayio doesn't redraw a TileGrid when only its ColorConverter changes.
@pytest.mark.parametrize(
"board", ["native_native_sim_lvgl", "native_native_sim_lvgl_asan"], indirect=True
)
@pytest.mark.circuitpy_drive({"code.py": CHANGE_CODE})
@pytest.mark.display(capture_times_ns=[8_000_000_000, 20_000_000_000])
@pytest.mark.duration(24)
def test_colorconverter_transparency_change(circuitpython):
"""make_transparent() and make_opaque() redraw a TileGrid that is already shown."""
circuitpython.wait_until_done()
output = circuitpython.serial.all_output
assert "first" in output
assert "second" in output
captures = circuitpython.display_capture_paths()
if len(captures) < 2 or not captures[1].exists():
pytest.skip("display capture was not produced")
_compare(captures[0], lambda w, h: _change_expected(w, h, changed=False))
_compare(captures[1], lambda w, h: _change_expected(w, h, changed=True))
3 changes: 3 additions & 0 deletions shared-module/displayio/lvgl/ColorConverter.c
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

#include "py/misc.h"
#include "py/runtime.h"
#include "shared-module/displayio/lvgl/Palette.h"

#define NO_TRANSPARENT_COLOR (0x1000000)

Expand Down Expand Up @@ -224,12 +225,14 @@ void common_hal_displayio_colorconverter_make_transparent(displayio_colorconvert
mp_raise_RuntimeError(MP_ERROR_TEXT("Only one color can be transparent at a time"));
}
self->transparent_color = transparent_color;
displayio_lvgl_shader_notify(MP_OBJ_FROM_PTR(self));
}

void common_hal_displayio_colorconverter_make_opaque(displayio_colorconverter_t *self, uint32_t transparent_color) {
(void)transparent_color;
// NO_TRANSPARENT_COLOR will never equal a valid color
self->transparent_color = NO_TRANSPARENT_COLOR;
displayio_lvgl_shader_notify(MP_OBJ_FROM_PTR(self));
}


Expand Down
48 changes: 36 additions & 12 deletions shared-module/displayio/lvgl/Palette.c
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
//
// SPDX-License-Identifier: MIT

#include "shared-bindings/displayio/ColorConverter.h"
#include "shared-bindings/displayio/Palette.h"

#include "py/gc.h"
Expand All @@ -20,15 +21,16 @@

// --- The shader registry -----------------------------------------------------
//
// Bitmaps keep their views in the Bitmap itself, but Palettes are shared and may be `const`,
// so whoever draws with one registers in this port-memory registry keyed by the
// shader object. A Palette change then walks the list and updates each mirror.
// Bitmaps keep their views in the Bitmap itself, but Palettes and ColorConverters are shared
// and Palettes may be `const`, so whoever draws with one registers in this port-memory
// registry keyed by the shader object. A shader change then walks the list and updates each
// mirror.

typedef struct {
void *shader; // displayio Palette or ColorConverter object.
displayio_lvgl_mirror_user_t *users;
// LVGL's view of a Palette's colors, shared by every image drawing with it. NULL for
// ColorConverters and until an indexed image needs it.
// LVGL's view of the shader's colors, shared by every indexed image drawing with it. NULL
// until an indexed image needs it.
lv_color32_t *colors;
struct displayio_lvgl_mirror_entry *next; // as displayio_lvgl_mirror_entry_t
} displayio_lvgl_mirror_entry_t;
Expand Down Expand Up @@ -104,15 +106,38 @@ void displayio_lvgl_shader_unregister_user(mp_obj_t pixel_shader, void *user) {
}
}

// The colors a ColorConverter gives each value of a bitmap of 8 bits or fewer, as legacy
// displayio would draw them. The transparent value is fully transparent.
static void _colorconverter_fill(displayio_colorconverter_t *converter, lv_color32_t *colors,
uint32_t count) {
for (uint32_t value = 0; value < count; value++) {
if (value == converter->transparent_color) {
colors[value] = (lv_color32_t) {0};
continue;
}
uint32_t rgb888 = displayio_colorconverter_convert_pixel(converter->input_colorspace, value);
colors[value] = lv_color32_make((rgb888 >> 16) & 0xff, (rgb888 >> 8) & 0xff,
rgb888 & 0xff, LV_OPA_COVER);
}
}

static void _shader_fill(mp_obj_t pixel_shader, lv_color32_t *colors) {
uint32_t count = LV_COLOR_INDEXED_PALETTE_SIZE(LV_COLOR_FORMAT_I8);
if (mp_obj_is_type(pixel_shader, &displayio_palette_type)) {
displayio_lvgl_palette_fill(MP_OBJ_TO_PTR(pixel_shader), colors, count);
} else {
_colorconverter_fill(MP_OBJ_TO_PTR(pixel_shader), colors, count);
}
}

void displayio_lvgl_shader_notify(mp_obj_t pixel_shader) {
displayio_lvgl_mirror_entry_t *entry = _mirror_entry(MP_OBJ_TO_PTR(pixel_shader));
if (entry == NULL) {
return;
}
displayio_lvgl_lock();
if (entry->colors != NULL && mp_obj_is_type(pixel_shader, &displayio_palette_type)) {
displayio_lvgl_palette_fill(MP_OBJ_TO_PTR(pixel_shader), entry->colors,
LV_COLOR_INDEXED_PALETTE_SIZE(LV_COLOR_FORMAT_I8));
if (entry->colors != NULL) {
_shader_fill(pixel_shader, entry->colors);
}
for (displayio_lvgl_mirror_user_t *user = entry->users; user != NULL; user = user->next) {
switch (user->kind) {
Expand Down Expand Up @@ -164,18 +189,17 @@ void displayio_lvgl_palette_fill(displayio_palette_t *palette, lv_color32_t *col

const lv_color32_t *displayio_lvgl_shader_palette(mp_obj_t pixel_shader) {
displayio_lvgl_mirror_entry_t *entry = _mirror_entry(MP_OBJ_TO_PTR(pixel_shader));
if (entry == NULL || !mp_obj_is_type(pixel_shader, &displayio_palette_type)) {
if (entry == NULL) {
return NULL;
}
if (entry->colors == NULL) {
// 256 entries (the largest indexed palette) so the address stays stable when the
// same Palette is used with bitmaps of different depths.
// same shader is used with bitmaps of different depths.
entry->colors = lv_malloc(LV_COLOR_INDEXED_PALETTE_SIZE(LV_COLOR_FORMAT_I8) * sizeof(lv_color32_t));
if (entry->colors == NULL) {
return NULL;
}
displayio_lvgl_palette_fill(MP_OBJ_TO_PTR(pixel_shader), entry->colors,
LV_COLOR_INDEXED_PALETTE_SIZE(LV_COLOR_FORMAT_I8));
_shader_fill(pixel_shader, entry->colors);
}
return entry->colors;
}
Expand Down
9 changes: 5 additions & 4 deletions shared-module/displayio/lvgl/Palette.h
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,9 @@ void displayio_lvgl_mirror_gc(void);
void displayio_lvgl_palette_fill(displayio_palette_t *palette, lv_color32_t *colors,
uint32_t count);

// The shared LVGL palette of `pixel_shader`, allocated and filled on first use. It lives in
// the shader's registry entry, so it is shared by every image drawing with the Palette and
// released when the last of them unregisters. Returns NULL for a non-Palette shader or when
// there is no memory. Call after registering a user.
// The shared LVGL palette of `pixel_shader`, a Palette or a ColorConverter, allocated and
// filled on first use. It lives in the shader's registry entry, so it is shared by every
// image drawing with the shader and released when the last of them unregisters. Returns
// NULL when the shader has no registry entry or there is no memory. Call after registering
// a user.
const lv_color32_t *displayio_lvgl_shader_palette(mp_obj_t pixel_shader);
Loading
Loading