1 # SPDX-FileCopyrightText: 2020 Melissa LeBlanc-Williams for Adafruit Industries
3 # SPDX-License-Identifier: MIT
6 `vectorio._vectorshape`
7 ================================================================================
11 **Software and Dependencies:**
14 https://github.com/adafruit/Adafruit_Blinka/releases
16 * Author(s): Melissa LeBlanc-Williams
21 from typing import Union, Tuple
22 from circuitpython_typing import WriteableBuffer
23 from displayio._colorconverter import ColorConverter
24 from displayio._colorspace import Colorspace
25 from displayio._palette import Palette
26 from displayio._area import Area
27 from displayio._structs import null_transform, InputPixelStruct, OutputPixelStruct
29 __version__ = "0.0.0+auto.0"
30 __repo__ = "https://github.com/adafruit/Adafruit_Blinka_displayio.git"
36 pixel_shader: Union[ColorConverter, Palette],
42 self._pixel_shader = pixel_shader
44 self._current_area_dirty = True
45 self._current_area = Area(0, 0, 0, 0)
46 self._ephemeral_dirty_area = Area(0, 0, 0, 0)
47 self._absolute_transform = null_transform
48 self._get_screen_area(self._current_area)
52 """X position of the center point of the circle in the parent."""
56 def x(self, value: int) -> None:
60 self._shape_set_dirty()
64 """Y position of the center point of the circle in the parent."""
68 def y(self, value: int) -> None:
72 self._shape_set_dirty()
75 def hidden(self) -> bool:
76 """Hide the circle or not."""
80 def hidden(self, value: bool) -> None:
82 self._shape_set_dirty()
85 def location(self) -> Tuple[int, int]:
86 """(X,Y) position of the center point of the circle in the parent."""
87 return (self._x, self._y)
90 def location(self, value: Tuple[int, int]) -> None:
92 raise ValueError("location must be a list or tuple with exactly 2 integers")
103 self._shape_set_dirty()
106 def pixel_shader(self) -> Union[ColorConverter, Palette]:
107 """The pixel shader of the circle."""
108 return self._pixel_shader
111 def pixel_shader(self, value: Union[ColorConverter, Palette]) -> None:
112 self._pixel_shader = value
114 def _get_area(self, _out_area: Area) -> Area:
115 raise NotImplementedError("Subclass must implement _get_area")
117 def _get_pixel(self, _x: int, _y: int) -> int:
118 raise NotImplementedError("Subclass must implement _get_pixel")
120 def _shape_set_dirty(self) -> None:
121 current_area = Area()
122 self._get_screen_area(current_area)
123 moved = current_area != self._current_area
125 self._current_area.union(
126 self._ephemeral_dirty_area, self._ephemeral_dirty_area
128 # Dirty area tracks the shape's footprint between draws. It's reset on refresh finish.
129 current_area.copy_into(self._current_area)
130 self._current_area_dirty = True
132 def _get_dirty_area(self, out_area: Area) -> Area:
133 out_area.x1 = out_area.x2
134 self._ephemeral_dirty_area.union(self._current_area, out_area)
135 return True # For now just always redraw.
137 def _get_screen_area(self, out_area) -> Area:
138 self._get_area(out_area)
139 if self._absolute_transform.transpose_xy:
140 x = self._absolute_transform.x + self._absolute_transform.dx * self._y
141 y = self._absolute_transform.y + self._absolute_transform.dy * self._x
142 if self._absolute_transform.dx < 1:
143 out_area.y1 = out_area.y1 * -1 + 1
144 out_area.y2 = out_area.y2 * -1 + 1
145 if self._absolute_transform.dy < 1:
146 out_area.x1 = out_area.x1 * -1 + 1
147 out_area.x2 = out_area.x2 * -1 + 1
148 self._area_transpose(out_area)
150 x = self._absolute_transform.x + self._absolute_transform.dx * self._x
151 y = self._absolute_transform.y + self._absolute_transform.dy * self._y
152 if self._absolute_transform.dx < 1:
153 out_area.x1 = out_area.x1 * -1 + 1
154 out_area.x2 = out_area.x2 * -1 + 1
155 if self._absolute_transform.dy < 1:
156 out_area.y1 = out_area.y1 * -1 + 1
157 out_area.y2 = out_area.y2 * -1 + 1
162 def _area_transpose(to_transpose: Area) -> Area:
163 to_transpose.x1, to_transpose.y1 = to_transpose.y1, to_transpose.x1
164 to_transpose.x2, to_transpose.y2 = to_transpose.y2, to_transpose.x2
166 def _screen_to_shape_coordinates(self, x: int, y: int) -> Tuple[int, int]:
167 """Get the target pixel based on the shape's coordinate space"""
168 if self._absolute_transform.transpose_xy:
170 y - self._absolute_transform.y - self._absolute_transform.dy * self._x
173 x - self._absolute_transform.x - self._absolute_transform.dx * self._y
176 if self._absolute_transform.dx < 1:
178 if self._absolute_transform.dy < 1:
182 x - self._absolute_transform.x - self._absolute_transform.dx * self._x
185 y - self._absolute_transform.y - self._absolute_transform.dy * self._y
188 if self._absolute_transform.dx < 1:
190 if self._absolute_transform.dy < 1:
193 # It's mirrored via dx. Maybe we need to add support for also separately mirroring?
194 # if self.absolute_transform.mirror_x:
196 # (shape_area.x2 - shape_area.x1)
197 # - (pixel_to_get_x - shape_area.x1)
201 # if self.absolute_transform.mirror_y:
203 # (shape_area.y2 - shape_area.y1)
204 # - (pixel_to_get_y - shape_area.y1)
209 return out_shape_x, out_shape_y
211 def _shape_contains(self, x: int, y: int) -> bool:
212 shape_x, shape_y = self._screen_to_shape_coordinates(x, y)
213 return self._get_pixel(shape_x, shape_y) != 0
217 colorspace: Colorspace,
219 mask: WriteableBuffer,
220 buffer: WriteableBuffer,
222 # pylint: disable=too-many-locals,too-many-branches,too-many-statements
227 if not area.compute_overlap(self._current_area, overlap):
230 full_coverage = area == overlap
231 pixels_per_byte = 8 // colorspace.depth
232 linestride_px = area.width()
233 line_dirty_offset_px = (overlap.y1 - area.y1) * linestride_px
234 column_dirty_offset_px = overlap.x1 - area.x1
236 input_pixel = InputPixelStruct()
237 output_pixel = OutputPixelStruct()
240 self._get_area(shape_area)
242 mask_start_px = line_dirty_offset_px
244 for input_pixel.y in range(overlap.y1, overlap.y2):
245 mask_start_px += column_dirty_offset_px
246 for input_pixel.x in range(overlap.x1, overlap.x2):
247 # Check the mask first to see if the pixel has already been set.
248 pixel_index = mask_start_px + (input_pixel.x - overlap.x1)
249 mask_doubleword = mask[pixel_index // 32]
250 mask_bit = pixel_index % 32
251 if (mask_doubleword & (1 << mask_bit)) != 0:
253 output_pixel.pixel = 0
255 # Cast input screen coordinates to shape coordinates to pick the pixel to draw
256 pixel_to_get_x, pixel_to_get_y = self._screen_to_shape_coordinates(
257 input_pixel.x, input_pixel.y
259 input_pixel.pixel = self._get_pixel(pixel_to_get_x, pixel_to_get_y)
261 # vectorio shapes use 0 to mean "area is not covered."
262 # We can skip all the rest of the work for this pixel
263 # if it's not currently covered by the shape.
264 if input_pixel.pixel == 0:
265 full_coverage = False
267 # Pixel is not transparent. Let's pull the pixel value index down
268 # to 0-base for more error-resistant palettes.
269 input_pixel.pixel -= 1
270 output_pixel.opaque = True
271 if self._pixel_shader is None:
272 output_pixel.pixel = input_pixel.pixel
273 elif isinstance(self._pixel_shader, Palette):
274 self._pixel_shader._get_color( # pylint: disable=protected-access
275 colorspace, input_pixel, output_pixel
277 elif isinstance(self._pixel_shader, ColorConverter):
278 self._pixel_shader._convert( # pylint: disable=protected-access
279 colorspace, input_pixel, output_pixel
282 if not output_pixel.opaque:
283 full_coverage = False
285 mask[pixel_index // 32] |= 1 << (pixel_index % 32)
286 if colorspace.depth == 16:
293 elif colorspace.depth == 32:
300 elif colorspace.depth == 8:
301 buffer.cast("B")[pixel_index] = output_pixel.pixel & 0xFF
302 elif colorspace.depth < 8:
303 # Reorder the offsets to pack multiple rows into
304 # a byte (meaning they share a column).
305 if not colorspace.pixels_in_byte_share_row:
306 row = pixel_index // linestride_px
307 col = pixel_index % linestride_px
308 # Dividing by pixels_per_byte does truncated division
309 # even if we multiply it back out
311 col * pixels_per_byte
312 + (row // pixels_per_byte)
315 + (row % pixels_per_byte)
317 shift = (pixel_index % pixels_per_byte) * colorspace.depth
318 if colorspace.reverse_pixels_in_byte:
319 # Reverse the shift by subtracting it from the leftmost shift
320 shift = (pixels_per_byte - 1) * colorspace.depth - shift
321 buffer.cast("B")[pixel_index // pixels_per_byte] |= (
322 output_pixel.pixel << shift
324 mask_start_px += linestride_px - column_dirty_offset_px
328 def _finish_refresh(self) -> None:
329 if self._ephemeral_dirty_area.empty() and not self._current_area_dirty:
331 # Reset dirty area to nothing
332 self._ephemeral_dirty_area.x1 = self._ephemeral_dirty_area.x2
333 self._current_area_dirty = False
335 if isinstance(self._pixel_shader, (Palette, ColorConverter)):
336 self._pixel_shader._finish_refresh() # pylint: disable=protected-access
338 def _get_refresh_areas(self, areas: list[Area]) -> None:
339 if self._current_area_dirty or (
340 isinstance(self._pixel_shader, (Palette, ColorConverter))
341 and self._pixel_shader._needs_refresh # pylint: disable=protected-access
343 if not self._ephemeral_dirty_area.empty():
344 # Both are dirty, check if we should combine the areas or draw separately
345 # Draws as few pixels as possible both when animations move short distances
346 # and large distances. The display core implementation currently doesn't
347 # combine areas to reduce redrawing of masked areas. If it does, this could
348 # be simplified to just return the 2 possibly overlapping areas.
350 self._ephemeral_dirty_area.compute_overlap(
351 self._current_area, area_swap
353 overlap_size = area_swap.size()
354 self._ephemeral_dirty_area.union(self._current_area, area_swap)
355 union_size = area_swap.size()
356 current_size = self._current_area.size()
357 dirty_size = self._ephemeral_dirty_area.size()
359 if union_size - dirty_size - current_size + overlap_size <= min(
360 dirty_size, current_size
362 # The excluded / non-overlapping area from the disjoint dirty and current
363 # areas is smaller than the smallest area we need to draw. Redrawing the
364 # overlapping area would cost more than just drawing the union disjoint
366 area_swap.copy_into(self._ephemeral_dirty_area)
368 # The excluded area between the 2 dirty areas is larger than the smallest
369 # dirty area. It would be more costly to combine these areas than possibly
370 # redraw some overlap.
371 areas.append(self._current_area)
372 areas.append(self._ephemeral_dirty_area)
374 areas.append(self._current_area)
375 elif not self._ephemeral_dirty_area.empty():
376 areas.append(self._ephemeral_dirty_area)
378 def _update_transform(self, group_transform) -> None:
379 self._absolute_transform = (
380 null_transform if group_transform is None else group_transform
382 self._shape_set_dirty()