@geastack/engine 0.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +29 -0
  3. package/bitmap_font.cpp +165 -0
  4. package/canvas.cpp +4608 -0
  5. package/components/Button.d.ts +4 -0
  6. package/components/Button.tsx +32 -0
  7. package/components/Image.d.ts +3 -0
  8. package/components/Image.tsx +17 -0
  9. package/components/Text.d.ts +3 -0
  10. package/components/Text.tsx +9 -0
  11. package/components/View.d.ts +3 -0
  12. package/components/View.tsx +24 -0
  13. package/components/index.d.ts +8 -0
  14. package/components/index.ts +4 -0
  15. package/css/animation.h +252 -0
  16. package/css/declarative.h +131 -0
  17. package/css/easing.h +160 -0
  18. package/css/engine.h +223 -0
  19. package/css/interpolate.h +38 -0
  20. package/image_store.cpp +807 -0
  21. package/package.json +62 -0
  22. package/rasterized_font.cpp +570 -0
  23. package/touch_runtime.cpp +513 -0
  24. package/ui/absolute_leaf_refresh.cpp +279 -0
  25. package/ui/absolute_leaf_refresh.h +12 -0
  26. package/ui/canvas_element.cpp +2314 -0
  27. package/ui/canvas_element.h +353 -0
  28. package/ui/canvas_store.cpp +188 -0
  29. package/ui/canvas_store.h +59 -0
  30. package/ui/core.cpp +135 -0
  31. package/ui/css_atom.cpp +155 -0
  32. package/ui/css_atom.h +21 -0
  33. package/ui/dirty_regions.cpp +66 -0
  34. package/ui/dirty_regions.h +34 -0
  35. package/ui/display_invalidation.cpp +101 -0
  36. package/ui/display_invalidation.h +15 -0
  37. package/ui/document.cpp +356 -0
  38. package/ui/document.h +101 -0
  39. package/ui/image.h +16 -0
  40. package/ui/image_element.cpp +13 -0
  41. package/ui/image_node.cpp +165 -0
  42. package/ui/input.cpp +936 -0
  43. package/ui/input_render.cpp +213 -0
  44. package/ui/internal.h +567 -0
  45. package/ui/layout.cpp +2025 -0
  46. package/ui/layout_snapshot.cpp +82 -0
  47. package/ui/layout_snapshot.h +12 -0
  48. package/ui/mirror.h +25 -0
  49. package/ui/node.cpp +243 -0
  50. package/ui/node.h +154 -0
  51. package/ui/node_lifecycle.cpp +137 -0
  52. package/ui/node_lifecycle.h +13 -0
  53. package/ui/node_model.h +597 -0
  54. package/ui/refresh_perf.h +235 -0
  55. package/ui/refresh_trace.h +68 -0
  56. package/ui/render.cpp +12097 -0
  57. package/ui/root_scroll_refresh.cpp +859 -0
  58. package/ui/root_scroll_refresh.h +30 -0
  59. package/ui/state_init.h +21 -0
  60. package/ui/style.cpp +14994 -0
  61. package/ui/style.h +727 -0
  62. package/ui/style_values.h +31 -0
  63. package/ui/text.cpp +2010 -0
  64. package/ui/text.h +15 -0
  65. package/ui/text_element.cpp +15 -0
  66. package/ui/tree_events.cpp +621 -0
  67. package/ui/tree_events.h +69 -0
  68. package/ui/tree_internal.h +191 -0
  69. package/ui/tree_nodes.cpp +628 -0
  70. package/ui/tree_render.cpp +3138 -0
  71. package/ui/tree_scroll_mirror.cpp +101 -0
  72. package/ui/tree_state.cpp +574 -0
  73. package/ui/tree_state.h +235 -0
  74. package/ui/tree_style.cpp +698 -0
  75. package/ui/ui.h +9 -0
  76. package/ui/view.cpp +2232 -0
  77. package/ui/view.h +14 -0
  78. package/ui/view_element.cpp +13 -0
  79. package/ui/viewport_region.cpp +36 -0
  80. package/ui/viewport_region.h +12 -0
  81. package/ui/virtual_keyboard.cpp +908 -0
  82. package/ui/virtual_keyboard.h +59 -0
  83. package/vendor/AnimatedGIF/AnimatedGIF.c +982 -0
  84. package/vendor/AnimatedGIF/AnimatedGIF.h +216 -0
  85. package/vendor/stb/stb_image.h +7988 -0
  86. package/vendor/stb/stb_truetype.h +5079 -0
package/canvas.cpp ADDED
@@ -0,0 +1,4608 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ #include "canvas.h"
3
+ #include "display.h"
4
+ #include "graphics/font.h"
5
+ #include "pixel.h"
6
+
7
+ #include <algorithm>
8
+ #include <cmath>
9
+ #include <cstdio>
10
+ #include <cstdlib>
11
+ #include <cstring>
12
+ #include <vector>
13
+
14
+ // For the compile-gated GEA_EMBEDDED_TEXT_SPRITE_DIAG counters (see the diag
15
+ // block above Canvas::drawRasterizedText). Includes must stay at file scope.
16
+ #ifndef GEA_EMBEDDED_TEXT_SPRITE_DIAG
17
+ #define GEA_EMBEDDED_TEXT_SPRITE_DIAG 0
18
+ #endif
19
+ #if GEA_EMBEDDED_TEXT_SPRITE_DIAG
20
+ #ifdef ESP_PLATFORM
21
+ #include <esp_timer.h>
22
+ #include <esp_cpu.h>
23
+ #else
24
+ #include <chrono>
25
+ #endif
26
+ #endif
27
+
28
+ // For the text-sprite hot staging buffer (internal SRAM; see HotTextSprite).
29
+ #ifdef ESP_PLATFORM
30
+ #include <esp_heap_caps.h>
31
+ #endif
32
+
33
+ #if __has_include("freertos/FreeRTOS.h")
34
+ #include "freertos/FreeRTOS.h"
35
+ #include "freertos/task.h"
36
+ #define GEA_CANVAS_HAS_FREERTOS 1
37
+ #else
38
+ #define GEA_CANVAS_HAS_FREERTOS 0
39
+ #endif
40
+
41
+ #if __has_include("pico.h")
42
+ #include "pico.h" // provides get_core_num(); pico/platform.h can't be included directly
43
+ #define GEA_CANVAS_HAS_PICO 1
44
+ #else
45
+ #define GEA_CANVAS_HAS_PICO 0
46
+ #endif
47
+
48
+ namespace gea::framework::graphics {
49
+
50
+ namespace {
51
+ // Per-scanline coverage bitmask for fillTrianglesOpaqueOccluded. Bit x set = a
52
+ // nearer triangle already owns pixel x on that chunk-local row. Two banks so two
53
+ // Canvases on different cores can occlude concurrently (cross-core band raster).
54
+ constexpr int kOcclMaxRows = 48; // chunk-local rows (gea3d half-res chunk ≤ 40)
55
+ constexpr int kOcclWords = 8; // 256 px wide (half-res 205 fits; wider falls back)
56
+ std::uint32_t s_occlBits[2][kOcclMaxRows][kOcclWords];
57
+
58
+ inline int occlCoreBank()
59
+ {
60
+ #if GEA_CANVAS_HAS_FREERTOS
61
+ return xPortGetCoreID() & 1;
62
+ #elif GEA_CANVAS_HAS_PICO
63
+ // RP2350: the present splits each chunk across both M33 cores, which raster the
64
+ // same triangle batch into disjoint row bands concurrently — each needs its own
65
+ // coverage bank or they stomp each other's occlusion mask (dropped triangles).
66
+ return get_core_num() & 1;
67
+ #else
68
+ return 0;
69
+ #endif
70
+ }
71
+ } // namespace
72
+
73
+ constexpr int kBitmapFontWidth = BitmapFont8x16::kWidth;
74
+ constexpr int kBitmapFontHeight = BitmapFont8x16::kHeight;
75
+ int gAntialiasSamples = 0;
76
+ // DIAG: temporarily default-on to measure, with GEA_EMBEDDED_TEXT_SPRITE_DIAG
77
+ // counters, whether the sprite cache engages on device for the FPS badge. Revert
78
+ // to false (opt-in via Display.setTextRasterCache) before shipping.
79
+ bool gTextRasterCacheEnabled = true;
80
+
81
+ // Pre-packed glyph stamping (opt-in via Display.setTextSolidBackdrop): the app
82
+ // declares that text draws over ONE solid color, so each glyph is pre-blended
83
+ // against that backdrop ONCE — natively in 4-bit — and stored as packed 4bpp
84
+ // rows in both x-parities. Drawing a glyph becomes row memcpys with at most two
85
+ // edge RMW bytes: no per-pixel destination read, no blend. Valid because glyph
86
+ // boxes don't overlap (no kerning). Glyphs whose color EQUALS the backdrop
87
+ // (e.g. white text on an inverted row) skip the stamp and take the true blend.
88
+ //
89
+ // Deliberately 4bpp-ONLY, not generalised with the rest of the packed path: the
90
+ // cache stores one pre-packed copy per possible x-phase, so a 2bpp target would
91
+ // need FOUR copies of every glyph instead of two — double the RAM of the 4bpp
92
+ // cache on the part that has the least of it (the C3 e-reader has no PSRAM,
93
+ // which is why it is 2bpp in the first place). GRAY2 takes the ordinary
94
+ // per-pixel blend below; setTextSolidBackdrop is a no-op there.
95
+ #if GEA_PIXEL_STORAGE_PACKED_BITS == 4
96
+ bool gTextStampEnabled = false;
97
+ std::uint8_t gTextStampBackdrop = 15;
98
+ #endif
99
+
100
+ namespace {
101
+ int nextUtf8Codepoint(const char *&p); // defined below (same anon namespace); used by the text sprite cache
102
+ #if GEA_PIXEL_STORAGE_PACKED_BITS == 4
103
+ void glyphStampCacheReset(); // defined below (same anon namespace); used by setTextSolidBackdrop
104
+ #endif
105
+ }
106
+
107
+ // ---- Large-static-text sprite cache ----------------------------------------
108
+ //
109
+ // Big HUD/badge/clock text (e.g. a 26vmin FPS badge ≈ 106px tall) is *static*
110
+ // content — it changes a couple of times a second at most — yet the dirty-region
111
+ // replay re-rasterizes it on (nearly) every frame because moving foreground
112
+ // content keeps dirtying the chunks it sits in. Each re-raster walks the glyphs
113
+ // and, per pixel, does a scattered read into a large flash-resident font atlas
114
+ // (`RasterizedFont::coverage`), which thrashes the flash cache.
115
+ //
116
+ // This cache bakes a glyph-coverage sprite into a sequential heap buffer (PSRAM
117
+ // on ESP, where the global allocator is SPIRAM-preferred — kept board-independent
118
+ // by using plain malloc/realloc, no heap_caps here) once the same large text has
119
+ // been seen twice, then blits that sprite (sequential read + opaque-run fast
120
+ // fill) instead of re-running the rasterizer. Coverage is colour/position/
121
+ // global-alpha independent, so only the text content + font identity key it; the
122
+ // colour and pen position are applied at blit time. Small text (the common UI
123
+ // case) never enters the cache, so dynamic text pays nothing but a hash compare.
124
+ #ifndef GEA_EMBEDDED_TEXT_SPRITE_CACHE
125
+ #define GEA_EMBEDDED_TEXT_SPRITE_CACHE 1
126
+ #endif
127
+
128
+ #if GEA_EMBEDDED_TEXT_SPRITE_CACHE
129
+ namespace {
130
+
131
+ constexpr int kTextSpriteSlots = 4;
132
+ constexpr int kTextSpriteMaxLen = 63;
133
+ // Only cache genuinely large text. The per-frame re-raster of small UI text is
134
+ // cheap, and caching it would risk churn (alloc/blit overhead) on dynamic lists.
135
+ constexpr int kTextSpriteMinSizePx = 40;
136
+ // Skip caching anything whose sprite would be larger than this (a runaway title).
137
+ constexpr std::size_t kTextSpriteMaxBytes = 768u * 1024u;
138
+
139
+ struct TextSprite {
140
+ enum State { Empty, Seen, Cached };
141
+ char text[kTextSpriteMaxLen + 1] = {0};
142
+ const RasterizedFontData *fontData = nullptr;
143
+ int sizePx = -1;
144
+ State state = Empty;
145
+ int minLX = 0;
146
+ int minLY = 0;
147
+ int w = 0;
148
+ int h = 0;
149
+ std::uint8_t *cov = nullptr; // w*h coverage bytes
150
+ std::int16_t *rowX0 = nullptr; // per-row ink start (w if empty)
151
+ std::int16_t *rowX1 = nullptr; // per-row ink end (-1 if empty)
152
+ std::size_t covCap = 0;
153
+ int extCap = 0;
154
+ // Run-length-encoded coverage, derived from cov at build time. Each row r is
155
+ // the runs [rleRowStart[r], rleRowStart[r+1]); each run is (rleVal, rleLen)
156
+ // covering rleLen contiguous columns of value rleVal. Blitting from this reads
157
+ // a few thousand run entries instead of W*H coverage bytes out of PSRAM (the
158
+ // measured ~1ms/frame cost for a large badge), and zero-runs cost no per-pixel
159
+ // work at all. rleRowStart==nullptr means "no RLE" → blit falls back to cov.
160
+ std::uint8_t *rleVal = nullptr;
161
+ std::uint16_t *rleLen = nullptr;
162
+ std::int32_t *rleRowStart = nullptr;
163
+ std::size_t rleCap = 0; // capacity of rleVal/rleLen (in runs)
164
+ int rleRowCap = 0; // capacity of rleRowStart (in rows)
165
+ bool rleValid = false; // true only when the current sprite has a valid RLE
166
+ };
167
+
168
+ TextSprite gTextSprites[kTextSpriteSlots];
169
+
170
+ // Internal-SRAM staging for the sprite currently being blitted. The RLE blit walks
171
+ // rowX0/rowX1/rleRowStart/rleVal/rleLen several times per frame (once per DMA chunk
172
+ // the text spans under a fused chunked flush). Those arrays live in PSRAM, and the
173
+ // walk's short dependent reads ride a cache the frame's full-screen flush traffic
174
+ // keeps evicting — measured ~350ns per run entry on the ESP32-S3 amoled (TSDIAG:
175
+ // walk ≈ 200µs of a 474µs blit for a 375×81 badge, as slow as a full re-raster).
176
+ // Staging the on-screen sprite's arrays here makes the walk cache-cheap. Ownership
177
+ // follows the blit: the first blit of a non-owner sprite copies its arrays in
178
+ // (~8KB memcpy, once per text change), so a badge cycling a handful of cached
179
+ // strings always blits the hot copy. cov is not staged — the RLE path never reads
180
+ // it — and a sprite that doesn't fit simply keeps blitting from PSRAM.
181
+ #ifndef GEA_EMBEDDED_TEXT_SPRITE_HOT_STAGE_BYTES
182
+ #define GEA_EMBEDDED_TEXT_SPRITE_HOT_STAGE_BYTES (12 * 1024)
183
+ #endif
184
+ #if GEA_EMBEDDED_TEXT_SPRITE_HOT_STAGE_BYTES > 0
185
+ struct HotTextSprite {
186
+ const TextSprite *owner = nullptr;
187
+ const std::int16_t *rowX0 = nullptr;
188
+ const std::int16_t *rowX1 = nullptr;
189
+ const std::int32_t *rleRowStart = nullptr;
190
+ const std::uint8_t *rleVal = nullptr;
191
+ const std::uint16_t *rleLen = nullptr;
192
+ std::uint8_t *buf = nullptr; // lazily allocated; null = no internal headroom
193
+ bool allocFailed = false;
194
+ };
195
+ HotTextSprite gHotTextSprite;
196
+
197
+ void adoptHotTextSprite(const TextSprite &s)
198
+ {
199
+ HotTextSprite &hot = gHotTextSprite;
200
+ hot.owner = nullptr;
201
+ if (!s.rleValid || !s.rleRowStart || s.h <= 0) return;
202
+ if (!hot.buf) {
203
+ if (hot.allocFailed) return;
204
+ #ifdef ESP_PLATFORM
205
+ // MALLOC_CAP_8BIT is load-bearing: INTERNAL alone lets the allocator hand
206
+ // back IRAM (its most-constrained matching heap) on the classic ESP32, and
207
+ // IRAM only supports 32-bit access — the RLE blit's byte reads then panic
208
+ // with LoadStoreError (crashed the M5Paper e-reader whenever a >=40px
209
+ // cached sprite blitted through the hot stage). The S3, where this staging
210
+ // was built, has byte-accessible IRAM and never showed it.
211
+ hot.buf = static_cast<std::uint8_t *>(
212
+ heap_caps_malloc(GEA_EMBEDDED_TEXT_SPRITE_HOT_STAGE_BYTES, MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT));
213
+ #else
214
+ hot.buf = static_cast<std::uint8_t *>(std::malloc(GEA_EMBEDDED_TEXT_SPRITE_HOT_STAGE_BYTES));
215
+ #endif
216
+ if (!hot.buf) { hot.allocFailed = true; return; }
217
+ }
218
+ const std::size_t h = static_cast<std::size_t>(s.h);
219
+ const std::size_t runs = static_cast<std::size_t>(s.rleRowStart[s.h]);
220
+ // Packed in descending alignment: rleRowStart(4), rowX0/rowX1/rleLen(2), rleVal(1).
221
+ const std::size_t needStart = sizeof(std::int32_t) * (h + 1);
222
+ const std::size_t needX = sizeof(std::int16_t) * h;
223
+ const std::size_t needLen = sizeof(std::uint16_t) * runs;
224
+ if (needStart + needX * 2 + needLen + runs > static_cast<std::size_t>(GEA_EMBEDDED_TEXT_SPRITE_HOT_STAGE_BYTES))
225
+ return;
226
+ std::uint8_t *p = hot.buf;
227
+ auto place = [&p](const void *src, std::size_t bytes) -> const void * {
228
+ std::memcpy(p, src, bytes);
229
+ const void *out = p;
230
+ p += bytes;
231
+ return out;
232
+ };
233
+ hot.rleRowStart = static_cast<const std::int32_t *>(place(s.rleRowStart, needStart));
234
+ hot.rowX0 = static_cast<const std::int16_t *>(place(s.rowX0, needX));
235
+ hot.rowX1 = static_cast<const std::int16_t *>(place(s.rowX1, needX));
236
+ hot.rleLen = static_cast<const std::uint16_t *>(place(s.rleLen, needLen));
237
+ hot.rleVal = static_cast<const std::uint8_t *>(place(s.rleVal, runs));
238
+ hot.owner = &s;
239
+ }
240
+ #endif // GEA_EMBEDDED_TEXT_SPRITE_HOT_STAGE_BYTES > 0
241
+
242
+ std::uint32_t hashTextContent(const char *s)
243
+ {
244
+ std::uint32_t h = 2166136261u; // FNV-1a
245
+ for (; *s; ++s) {
246
+ h ^= static_cast<std::uint8_t>(*s);
247
+ h *= 16777619u;
248
+ }
249
+ return h;
250
+ }
251
+
252
+ // Rasterize `text` into `sprite`'s coverage buffer in text-relative coordinates
253
+ // (origin = pen position). Returns false (leaving the slot uncacheable) on an
254
+ // empty or too-large sprite, or on allocation failure.
255
+ bool buildTextSprite(TextSprite &sprite, const char *text, const RasterizedFont &font)
256
+ {
257
+ const int lineH = font.lineHeight();
258
+ const int ascender = font.ascender();
259
+ const int fallbackAdvance = font.sizePx() / 2;
260
+
261
+ // Pass 1: bbox of all glyph ink relative to the pen origin (0,0).
262
+ int penX = 0, penY = 0;
263
+ int minLX = 0x7fffffff, minLY = 0x7fffffff, maxLX = -0x7fffffff, maxLY = -0x7fffffff;
264
+ for (const char *p = text; *p;) {
265
+ const int cp = nextUtf8Codepoint(p);
266
+ if (cp == '\n') { penX = 0; penY += lineH; continue; }
267
+ Glyph glyph{};
268
+ if (!font.glyph(cp, &glyph)) { penX += fallbackAdvance; continue; }
269
+ if (glyph.width > 0 && glyph.height > 0) {
270
+ const int gx = penX + glyph.bearingX;
271
+ const int gy = penY + ascender - glyph.bearingY;
272
+ if (gx < minLX) minLX = gx;
273
+ if (gy < minLY) minLY = gy;
274
+ if (gx + glyph.width - 1 > maxLX) maxLX = gx + glyph.width - 1;
275
+ if (gy + glyph.height - 1 > maxLY) maxLY = gy + glyph.height - 1;
276
+ }
277
+ penX += glyph.advance;
278
+ }
279
+ if (maxLX < minLX || maxLY < minLY) return false; // no ink
280
+
281
+ const int W = maxLX - minLX + 1;
282
+ const int H = maxLY - minLY + 1;
283
+ const std::size_t need = static_cast<std::size_t>(W) * static_cast<std::size_t>(H);
284
+ if (need > kTextSpriteMaxBytes) return false;
285
+
286
+ if (need > sprite.covCap) {
287
+ std::uint8_t *grown = static_cast<std::uint8_t *>(std::realloc(sprite.cov, need));
288
+ if (!grown) return false;
289
+ sprite.cov = grown;
290
+ sprite.covCap = need;
291
+ }
292
+ if (H > sprite.extCap) {
293
+ std::int16_t *gx0 = static_cast<std::int16_t *>(std::realloc(sprite.rowX0, sizeof(std::int16_t) * H));
294
+ std::int16_t *gx1 = static_cast<std::int16_t *>(std::realloc(sprite.rowX1, sizeof(std::int16_t) * H));
295
+ if (!gx0 || !gx1) {
296
+ // Keep whichever grew; capacity tracks the smaller so we retry next time.
297
+ if (gx0) sprite.rowX0 = gx0;
298
+ if (gx1) sprite.rowX1 = gx1;
299
+ return false;
300
+ }
301
+ sprite.rowX0 = gx0;
302
+ sprite.rowX1 = gx1;
303
+ sprite.extCap = H;
304
+ }
305
+
306
+ std::memset(sprite.cov, 0, need);
307
+ for (int r = 0; r < H; r++) {
308
+ sprite.rowX0[r] = static_cast<std::int16_t>(W);
309
+ sprite.rowX1[r] = -1;
310
+ }
311
+
312
+ // Pass 2: write coverage + per-row ink extents.
313
+ penX = 0; penY = 0;
314
+ for (const char *p = text; *p;) {
315
+ const int cp = nextUtf8Codepoint(p);
316
+ if (cp == '\n') { penX = 0; penY += lineH; continue; }
317
+ Glyph glyph{};
318
+ if (!font.glyph(cp, &glyph)) { penX += fallbackAdvance; continue; }
319
+ const int gx = penX + glyph.bearingX;
320
+ const int gy = penY + ascender - glyph.bearingY;
321
+ for (int row = 0; row < glyph.height; row++) {
322
+ const int by = gy + row - minLY;
323
+ if (by < 0 || by >= H) continue;
324
+ std::uint8_t *covRow = sprite.cov + static_cast<std::size_t>(by) * W;
325
+ for (int col = 0; col < glyph.width; col++) {
326
+ const int bx = gx + col - minLX;
327
+ if (bx < 0 || bx >= W) continue;
328
+ const std::uint8_t a = font.coverage(glyph, row, col);
329
+ if (a == 0) continue;
330
+ if (a > covRow[bx]) covRow[bx] = a;
331
+ if (bx < sprite.rowX0[by]) sprite.rowX0[by] = static_cast<std::int16_t>(bx);
332
+ if (bx > sprite.rowX1[by]) sprite.rowX1[by] = static_cast<std::int16_t>(bx);
333
+ }
334
+ }
335
+ penX += glyph.advance;
336
+ }
337
+
338
+ sprite.minLX = minLX;
339
+ sprite.minLY = minLY;
340
+ sprite.w = W;
341
+ sprite.h = H;
342
+
343
+ // Pass 3: run-length-encode each row of cov over [0,W). The blit reads these
344
+ // runs instead of W*H PSRAM bytes. Count first, then size the buffers exactly.
345
+ sprite.rleValid = false;
346
+ std::size_t runCount = 0;
347
+ for (int r = 0; r < H; r++) {
348
+ const std::uint8_t *covRow = sprite.cov + static_cast<std::size_t>(r) * W;
349
+ int c = 0;
350
+ while (c < W) {
351
+ const std::uint8_t v = covRow[c];
352
+ while (c < W && covRow[c] == v) c++;
353
+ runCount++;
354
+ }
355
+ }
356
+ bool rleOk = runCount > 0;
357
+ if (rleOk && runCount > sprite.rleCap) {
358
+ std::uint8_t *nv = static_cast<std::uint8_t *>(std::realloc(sprite.rleVal, runCount));
359
+ std::uint16_t *nl = static_cast<std::uint16_t *>(std::realloc(sprite.rleLen, sizeof(std::uint16_t) * runCount));
360
+ if (nv) sprite.rleVal = nv;
361
+ if (nl) sprite.rleLen = nl;
362
+ if (nv && nl) sprite.rleCap = runCount; else rleOk = false;
363
+ }
364
+ if (rleOk && (H + 1) > sprite.rleRowCap) {
365
+ std::int32_t *nr = static_cast<std::int32_t *>(std::realloc(sprite.rleRowStart, sizeof(std::int32_t) * (H + 1)));
366
+ if (nr) { sprite.rleRowStart = nr; sprite.rleRowCap = H + 1; } else rleOk = false;
367
+ }
368
+ if (rleOk) {
369
+ std::size_t run = 0;
370
+ for (int r = 0; r < H; r++) {
371
+ sprite.rleRowStart[r] = static_cast<std::int32_t>(run);
372
+ const std::uint8_t *covRow = sprite.cov + static_cast<std::size_t>(r) * W;
373
+ int c = 0;
374
+ while (c < W) {
375
+ const std::uint8_t v = covRow[c];
376
+ const int s = c;
377
+ while (c < W && covRow[c] == v) c++;
378
+ sprite.rleVal[run] = v;
379
+ sprite.rleLen[run] = static_cast<std::uint16_t>(c - s);
380
+ run++;
381
+ }
382
+ }
383
+ sprite.rleRowStart[H] = static_cast<std::int32_t>(run);
384
+ sprite.rleValid = true;
385
+ #ifndef ESP_PLATFORM
386
+ // Host builds (native tests / WASM simulator): verify the RLE decodes back
387
+ // to cov exactly, so a pixel-correctness regression is caught off-device.
388
+ for (int r = 0; r < H; r++) {
389
+ const std::uint8_t *covRow = sprite.cov + static_cast<std::size_t>(r) * W;
390
+ int c = 0;
391
+ for (std::int32_t k = sprite.rleRowStart[r]; k < sprite.rleRowStart[r + 1]; k++) {
392
+ for (int n = 0; n < sprite.rleLen[k]; n++) {
393
+ if (covRow[c] != sprite.rleVal[k]) { std::abort(); }
394
+ c++;
395
+ }
396
+ }
397
+ if (c != W) { std::abort(); }
398
+ }
399
+ #endif
400
+ }
401
+ return true;
402
+ }
403
+
404
+ } // namespace
405
+ #endif // GEA_EMBEDDED_TEXT_SPRITE_CACHE
406
+
407
+ static inline int normalizeAntialiasSamples(int samples)
408
+ {
409
+ if (samples >= 4) return 4;
410
+ if (samples >= 2) return 2;
411
+ return 0;
412
+ }
413
+
414
+ static inline float antialiasKernelWidth(int samples)
415
+ {
416
+ (void)samples;
417
+ return 1.0f;
418
+ }
419
+
420
+ static inline float roundedRectAntialiasKernelWidth(int samples, int w, int h)
421
+ {
422
+ if (samples < 4) return 1.0f;
423
+ return std::min(w, h) >= 64 ? 2.0f : 1.0f;
424
+ }
425
+
426
+ static inline bool roundedRectIsCircleLike(int w, int h, int tl, int tr, int br, int bl)
427
+ {
428
+ const int minSide = std::min(w, h);
429
+ if (minSide < 16 || std::abs(w - h) > 1) return false;
430
+ const int halfMin = minSide / 2;
431
+ const int minRadius = std::max(1, halfMin - 1);
432
+ return tl >= minRadius && tr >= minRadius && br >= minRadius && bl >= minRadius;
433
+ }
434
+
435
+ static inline float roundedRectAntialiasKernelWidth(int samples, int w, int h, int tl, int tr, int br, int bl)
436
+ {
437
+ if (samples < 2) return 1.0f;
438
+ if (roundedRectIsCircleLike(w, h, tl, tr, br, bl)) {
439
+ return 1.0f;
440
+ }
441
+ if (samples < 4) return 1.0f;
442
+ return roundedRectAntialiasKernelWidth(samples, w, h);
443
+ }
444
+
445
+ static inline bool roundedRectShouldCoverageSampleFill(int w, int h)
446
+ {
447
+ return w > 0 && h > 0 && w * h <= 4096;
448
+ }
449
+
450
+ static inline float antialiasOffsetWithKernel(int sample, int samples, float width)
451
+ {
452
+ return (1.0f - width) * 0.5f +
453
+ (static_cast<float>(sample) + 0.5f) * width / static_cast<float>(samples);
454
+ }
455
+
456
+ static inline float antialiasOffset(int sample, int samples)
457
+ {
458
+ return antialiasOffsetWithKernel(sample, samples, antialiasKernelWidth(samples));
459
+ }
460
+
461
+ static inline int antialiasEdgePad(float kernelWidth)
462
+ {
463
+ if (kernelWidth <= 1.0f) return 1;
464
+ return static_cast<int>(std::ceil(kernelWidth * 0.5f)) + 1;
465
+ }
466
+
467
+ void Canvas::setAntialiasSamples(int samples)
468
+ {
469
+ gAntialiasSamples = normalizeAntialiasSamples(samples);
470
+ }
471
+
472
+ int Canvas::antialiasSamples()
473
+ {
474
+ return gAntialiasSamples;
475
+ }
476
+
477
+ void Canvas::setTextRasterCacheEnabled(bool enabled)
478
+ {
479
+ gTextRasterCacheEnabled = enabled;
480
+ }
481
+
482
+ bool Canvas::textRasterCacheEnabled()
483
+ {
484
+ return gTextRasterCacheEnabled;
485
+ }
486
+
487
+ void Canvas::setTextSolidBackdrop(int rrggbb)
488
+ {
489
+ #if GEA_PIXEL_STORAGE_PACKED_BITS == 4
490
+ if (rrggbb < 0) {
491
+ gTextStampEnabled = false;
492
+ return;
493
+ }
494
+ const std::uint8_t level = static_cast<std::uint8_t>(
495
+ pixel::nativeColor((rrggbb >> 16) & 0xFF, (rrggbb >> 8) & 0xFF, rrggbb & 0xFF) & 0x0F);
496
+ if (gTextStampEnabled && level == gTextStampBackdrop) return;
497
+ gTextStampBackdrop = level;
498
+ gTextStampEnabled = true;
499
+ // A backdrop change invalidates every pre-blended glyph.
500
+ glyphStampCacheReset();
501
+ #else
502
+ (void)rrggbb;
503
+ #endif
504
+ }
505
+
506
+ static inline bool roundedRectSampleContains(int x,
507
+ int y,
508
+ int w,
509
+ int h,
510
+ int tl,
511
+ int tr,
512
+ int br,
513
+ int bl,
514
+ float sx,
515
+ float sy)
516
+ {
517
+ const float left = static_cast<float>(x);
518
+ const float top = static_cast<float>(y);
519
+ const float right = left + static_cast<float>(w);
520
+ const float bottom = top + static_cast<float>(h);
521
+ if (sx < left || sy < top || sx >= right || sy >= bottom) return false;
522
+
523
+ auto cornerContains = [](float cx, float cy, float r, float px, float py) {
524
+ if (r <= 0.0f) return true;
525
+ const float dx = (px - cx) / r;
526
+ const float dy = (py - cy) / r;
527
+ return dx * dx + dy * dy <= 1.0f;
528
+ };
529
+
530
+ if (tl > 0 && sx < left + static_cast<float>(tl) && sy < top + static_cast<float>(tl))
531
+ return cornerContains(left + static_cast<float>(tl), top + static_cast<float>(tl), static_cast<float>(tl), sx, sy);
532
+ if (tr > 0 && sx >= right - static_cast<float>(tr) && sy < top + static_cast<float>(tr))
533
+ return cornerContains(right - static_cast<float>(tr), top + static_cast<float>(tr), static_cast<float>(tr), sx, sy);
534
+ if (br > 0 && sx >= right - static_cast<float>(br) && sy >= bottom - static_cast<float>(br))
535
+ return cornerContains(right - static_cast<float>(br), bottom - static_cast<float>(br), static_cast<float>(br), sx, sy);
536
+ if (bl > 0 && sx < left + static_cast<float>(bl) && sy >= bottom - static_cast<float>(bl))
537
+ return cornerContains(left + static_cast<float>(bl), bottom - static_cast<float>(bl), static_cast<float>(bl), sx, sy);
538
+ return true;
539
+ }
540
+
541
+ static inline int roundedRectCoverage(int x,
542
+ int y,
543
+ int w,
544
+ int h,
545
+ int tl,
546
+ int tr,
547
+ int br,
548
+ int bl,
549
+ int px,
550
+ int py,
551
+ int samples,
552
+ float kernelWidth)
553
+ {
554
+ int coverage = 0;
555
+ for (int iy = 0; iy < samples; ++iy) {
556
+ const float oy = antialiasOffsetWithKernel(iy, samples, kernelWidth);
557
+ for (int ix = 0; ix < samples; ++ix) {
558
+ const float ox = antialiasOffsetWithKernel(ix, samples, kernelWidth);
559
+ if (roundedRectSampleContains(x, y, w, h, tl, tr, br, bl,
560
+ static_cast<float>(px) + ox,
561
+ static_cast<float>(py) + oy))
562
+ ++coverage;
563
+ }
564
+ }
565
+ return coverage;
566
+ }
567
+
568
+ static inline int roundedRectStrokeCoverage(int x,
569
+ int y,
570
+ int w,
571
+ int h,
572
+ int tl,
573
+ int tr,
574
+ int br,
575
+ int bl,
576
+ int lineWidth,
577
+ int px,
578
+ int py,
579
+ int samples,
580
+ float kernelWidth)
581
+ {
582
+ const int innerX = x + lineWidth;
583
+ const int innerY = y + lineWidth;
584
+ const int innerW = w - lineWidth * 2;
585
+ const int innerH = h - lineWidth * 2;
586
+ const int innerTl = std::max(0, tl - lineWidth);
587
+ const int innerTr = std::max(0, tr - lineWidth);
588
+ const int innerBr = std::max(0, br - lineWidth);
589
+ const int innerBl = std::max(0, bl - lineWidth);
590
+ const bool hasInner = innerW > 0 && innerH > 0;
591
+ int coverage = 0;
592
+ for (int iy = 0; iy < samples; ++iy) {
593
+ const float oy = antialiasOffsetWithKernel(iy, samples, kernelWidth);
594
+ for (int ix = 0; ix < samples; ++ix) {
595
+ const float ox = antialiasOffsetWithKernel(ix, samples, kernelWidth);
596
+ const float sx = static_cast<float>(px) + ox;
597
+ const float sy = static_cast<float>(py) + oy;
598
+ if (!roundedRectSampleContains(x, y, w, h, tl, tr, br, bl, sx, sy)) continue;
599
+ if (hasInner &&
600
+ roundedRectSampleContains(innerX, innerY, innerW, innerH,
601
+ innerTl, innerTr, innerBr, innerBl,
602
+ sx, sy))
603
+ continue;
604
+ ++coverage;
605
+ }
606
+ }
607
+ return coverage;
608
+ }
609
+
610
+ static inline int coverageAlpha(int alpha, int coverage, int sampleCount)
611
+ {
612
+ if (alpha <= 0 || coverage <= 0) return 0;
613
+ if (coverage >= sampleCount) return alpha;
614
+ return (alpha * coverage + sampleCount / 2) / sampleCount;
615
+ }
616
+
617
+ static inline void addUnclippedSpan(int left, int right, int *x0, int *x1)
618
+ {
619
+ if (left > right) return;
620
+ if (left < *x0) *x0 = left;
621
+ if (right > *x1) *x1 = right;
622
+ }
623
+
624
+ static inline void roundedRectAnyCoverageSpan(int x,
625
+ int y,
626
+ int w,
627
+ int h,
628
+ int tl,
629
+ int tr,
630
+ int br,
631
+ int bl,
632
+ int py,
633
+ int samples,
634
+ float kernelWidth,
635
+ int *spanX0,
636
+ int *spanX1)
637
+ {
638
+ const int topR = tl > tr ? tl : tr;
639
+ const int bottomR = bl > br ? bl : br;
640
+ const float minSample = antialiasOffsetWithKernel(0, samples, kernelWidth);
641
+ const float maxSample = antialiasOffsetWithKernel(samples - 1, samples, kernelWidth);
642
+ const float rowMin = static_cast<float>(py) + minSample;
643
+ const float rowMax = static_cast<float>(py) + maxSample;
644
+ const float left = static_cast<float>(x);
645
+ const float top = static_cast<float>(y);
646
+ const float right = left + static_cast<float>(w);
647
+ const float bottom = top + static_cast<float>(h);
648
+
649
+ if (rowMax < top || rowMin >= bottom) return;
650
+
651
+ auto addRectSpan = [&](int sx0, int sx1, float sy0, float sy1) {
652
+ if (rowMax < sy0 || rowMin >= sy1) return;
653
+ addUnclippedSpan(sx0, sx1, spanX0, spanX1);
654
+ };
655
+ addRectSpan(x, x + w - 1, top + static_cast<float>(topR), bottom - static_cast<float>(bottomR));
656
+ addRectSpan(x + tl, x + w - tr - 1, top, top + static_cast<float>(topR));
657
+ addRectSpan(x + bl, x + w - br - 1, bottom - static_cast<float>(bottomR), bottom);
658
+ if (tl > 0 && tl < topR) addRectSpan(x, x + tl - 1, top + static_cast<float>(tl), top + static_cast<float>(topR));
659
+ if (tr > 0 && tr < topR) addRectSpan(x + w - tr, x + w - 1, top + static_cast<float>(tr), top + static_cast<float>(topR));
660
+ if (bl > 0 && bl < bottomR) addRectSpan(x, x + bl - 1, bottom - static_cast<float>(bottomR), bottom - static_cast<float>(bl));
661
+ if (br > 0 && br < bottomR) addRectSpan(x + w - br, x + w - 1, bottom - static_cast<float>(bottomR), bottom - static_cast<float>(br));
662
+
663
+ auto addCornerSpan = [&](int radius, float cx, float cy, bool leftCorner, bool topCorner) {
664
+ if (radius <= 0) return;
665
+ const float r = static_cast<float>(radius);
666
+ if (topCorner) {
667
+ if (rowMax < cy - r || rowMin >= cy) return;
668
+ } else {
669
+ if (rowMax < cy || rowMin >= cy + r) return;
670
+ }
671
+ float sampleY = cy;
672
+ if (sampleY < rowMin) sampleY = rowMin;
673
+ if (sampleY > rowMax) sampleY = rowMax;
674
+ const float dy = sampleY - cy;
675
+ const float dx2 = r * r - dy * dy;
676
+ if (dx2 < 0.0f) return;
677
+ const float dx = std::sqrt(dx2);
678
+ if (leftCorner) {
679
+ const int sx0 = static_cast<int>(std::ceil(cx - dx - maxSample));
680
+ const int sx1 = static_cast<int>(std::floor(cx - minSample));
681
+ addUnclippedSpan(sx0, sx1, spanX0, spanX1);
682
+ } else {
683
+ const int sx0 = static_cast<int>(std::ceil(cx - maxSample));
684
+ const int sx1 = static_cast<int>(std::floor(cx + dx - minSample));
685
+ addUnclippedSpan(sx0, sx1, spanX0, spanX1);
686
+ }
687
+ };
688
+
689
+ addCornerSpan(tl, left + static_cast<float>(tl), top + static_cast<float>(tl), true, true);
690
+ addCornerSpan(tr, right - static_cast<float>(tr), top + static_cast<float>(tr), false, true);
691
+ addCornerSpan(bl, left + static_cast<float>(bl), bottom - static_cast<float>(bl), true, false);
692
+ addCornerSpan(br, right - static_cast<float>(br), bottom - static_cast<float>(br), false, false);
693
+ }
694
+
695
+ namespace {
696
+
697
+ int nextUtf8Codepoint(const char *&p)
698
+ {
699
+ const unsigned char c0 = static_cast<unsigned char>(*p++);
700
+ if (c0 < 0x80) return c0;
701
+
702
+ const auto isContinuation = [](unsigned char c) {
703
+ return (c & 0xc0) == 0x80;
704
+ };
705
+ if ((c0 & 0xe0) == 0xc0) {
706
+ const unsigned char c1 = static_cast<unsigned char>(*p);
707
+ if (c1 && isContinuation(c1)) {
708
+ ++p;
709
+ return ((c0 & 0x1f) << 6) | (c1 & 0x3f);
710
+ }
711
+ return c0;
712
+ }
713
+ if ((c0 & 0xf0) == 0xe0) {
714
+ const unsigned char c1 = static_cast<unsigned char>(p[0]);
715
+ const unsigned char c2 = static_cast<unsigned char>(p[1]);
716
+ if (c1 && c2 && isContinuation(c1) && isContinuation(c2)) {
717
+ p += 2;
718
+ return ((c0 & 0x0f) << 12) | ((c1 & 0x3f) << 6) | (c2 & 0x3f);
719
+ }
720
+ return c0;
721
+ }
722
+ if ((c0 & 0xf8) == 0xf0) {
723
+ const unsigned char c1 = static_cast<unsigned char>(p[0]);
724
+ const unsigned char c2 = static_cast<unsigned char>(p[1]);
725
+ const unsigned char c3 = static_cast<unsigned char>(p[2]);
726
+ if (c1 && c2 && c3 && isContinuation(c1) && isContinuation(c2) && isContinuation(c3)) {
727
+ p += 3;
728
+ return ((c0 & 0x07) << 18) | ((c1 & 0x3f) << 12) | ((c2 & 0x3f) << 6) | (c3 & 0x3f);
729
+ }
730
+ }
731
+ return c0;
732
+ }
733
+
734
+ } // namespace
735
+
736
+ #ifdef GEA_EMBEDDED_HAS_GENERATED_FONTS
737
+ namespace {
738
+
739
+ struct SolidGlyphRow {
740
+ int row = 0;
741
+ int start = 0;
742
+ int width = 0;
743
+ int offset = 0;
744
+ };
745
+
746
+ struct SolidGlyphCacheEntry {
747
+ const RasterizedFontData *font = nullptr;
748
+ pixel::native_t color = 0;
749
+ pixel::native_t background = 0;
750
+ int codepoint = 0;
751
+ Glyph glyph{};
752
+ std::vector<SolidGlyphRow> rows;
753
+ std::vector<pixel::native_t> pixels;
754
+ std::uint32_t lastUsed = 0;
755
+ };
756
+
757
+ constexpr int kSolidGlyphCacheSize = 48;
758
+ SolidGlyphCacheEntry gSolidGlyphCache[kSolidGlyphCacheSize];
759
+ std::uint32_t gSolidGlyphClock = 1;
760
+
761
+ SolidGlyphCacheEntry *solidGlyphCacheEntry(const RasterizedFont &font,
762
+ pixel::native_t color,
763
+ pixel::native_t background,
764
+ int codepoint)
765
+ {
766
+ const RasterizedFontData *data = font.data();
767
+ if (!data) return nullptr;
768
+
769
+ for (auto &entry : gSolidGlyphCache) {
770
+ if (entry.font == data && entry.color == color && entry.background == background &&
771
+ entry.codepoint == codepoint) {
772
+ entry.lastUsed = ++gSolidGlyphClock;
773
+ return &entry;
774
+ }
775
+ }
776
+
777
+ Glyph glyph{};
778
+ if (!font.glyph(codepoint, &glyph)) return nullptr;
779
+
780
+ SolidGlyphCacheEntry *victim = &gSolidGlyphCache[0];
781
+ for (auto &entry : gSolidGlyphCache) {
782
+ if (!entry.font) {
783
+ victim = &entry;
784
+ break;
785
+ }
786
+ if (entry.lastUsed < victim->lastUsed) victim = &entry;
787
+ }
788
+
789
+ victim->font = data;
790
+ victim->color = color;
791
+ victim->background = background;
792
+ victim->codepoint = codepoint;
793
+ victim->glyph = glyph;
794
+ victim->rows.clear();
795
+ victim->pixels.clear();
796
+ victim->rows.reserve(static_cast<std::size_t>(std::max(0, glyph.height)));
797
+
798
+ for (int row = 0; row < glyph.height; row++) {
799
+ int first = glyph.width;
800
+ int last = -1;
801
+ for (int col = 0; col < glyph.width; col++) {
802
+ if (font.coverage(glyph, row, col) == 0) continue;
803
+ if (col < first) first = col;
804
+ last = col;
805
+ }
806
+ if (last < first) continue;
807
+
808
+ SolidGlyphRow span{};
809
+ span.row = row;
810
+ span.start = first;
811
+ span.width = last - first + 1;
812
+ span.offset = static_cast<int>(victim->pixels.size());
813
+ victim->rows.push_back(span);
814
+
815
+ for (int col = first; col <= last; col++) {
816
+ const int alpha = font.coverage(glyph, row, col);
817
+ if (alpha <= 0) {
818
+ victim->pixels.push_back(background);
819
+ } else if (alpha >= 255) {
820
+ victim->pixels.push_back(color);
821
+ } else {
822
+ victim->pixels.push_back(pixel::blendNative(color, background, alpha));
823
+ }
824
+ }
825
+ }
826
+
827
+ victim->lastUsed = ++gSolidGlyphClock;
828
+ return victim;
829
+ }
830
+
831
+ } // namespace
832
+ #endif
833
+
834
+ class CanvasMath {
835
+ public:
836
+ #ifndef GEA_EMBEDDED_CANVAS_CIRCLE_RADIUS_MAX
837
+ #define GEA_EMBEDDED_CANVAS_CIRCLE_RADIUS_MAX 63
838
+ #endif
839
+ #ifndef GEA_EMBEDDED_CANVAS_CIRCLE_BOX_SPAN_MAX
840
+ #define GEA_EMBEDDED_CANVAS_CIRCLE_BOX_SPAN_MAX 128
841
+ #endif
842
+ #ifndef GEA_EMBEDDED_CANVAS_CIRCLE_BOX_SPAN_SLOTS
843
+ #define GEA_EMBEDDED_CANVAS_CIRCLE_BOX_SPAN_SLOTS 16
844
+ #endif
845
+
846
+ static constexpr int kCircleSpanMax = 32;
847
+ static constexpr int kCircleSpanSlotCount = (kCircleSpanMax / 2) + 1;
848
+ static constexpr int kCircleRadiusMax = GEA_EMBEDDED_CANVAS_CIRCLE_RADIUS_MAX;
849
+ static constexpr int kCircleRadiusSpanRows = (kCircleRadiusMax * 2) + 1;
850
+ static constexpr int kCircleBoxSpanMax = GEA_EMBEDDED_CANVAS_CIRCLE_BOX_SPAN_MAX;
851
+ static constexpr int kCircleBoxSpanSlots = GEA_EMBEDDED_CANVAS_CIRCLE_BOX_SPAN_SLOTS;
852
+ static_assert(kCircleRadiusMax > 0 && kCircleRadiusMax < 64);
853
+ static_assert(kCircleBoxSpanMax > 0 && kCircleBoxSpanMax <= 255);
854
+ static_assert(kCircleBoxSpanSlots > 0);
855
+
856
+ static int min(int a, int b) { return a < b ? a : b; }
857
+
858
+ static int integerSqrt(int n)
859
+ {
860
+ if (n <= 0) return 0;
861
+ int x = n;
862
+ int y = (x + 1) / 2;
863
+ while (y < x) {
864
+ x = y;
865
+ y = (x + n / x) / 2;
866
+ }
867
+ return x;
868
+ }
869
+
870
+ const std::uint8_t (*circleSpans(int size))[2]
871
+ {
872
+ if (size <= 0 || size > kCircleSpanMax || (size & 1)) return nullptr;
873
+ int slot = size / 2;
874
+ std::uint32_t bit = 1u << slot;
875
+ if (!(circleSpanCacheReady_ & bit)) {
876
+ int radius2 = size * size;
877
+ for (int row = 0; row < size; row++) {
878
+ int dy2 = row * 2 + 1 - size;
879
+ int dx2 = integerSqrt(radius2 - dy2 * dy2);
880
+ circleSpanCache_[slot][row][0] = (std::uint8_t)((size - dx2) / 2);
881
+ circleSpanCache_[slot][row][1] = (std::uint8_t)((size + dx2 - 1) / 2);
882
+ }
883
+ circleSpanCacheReady_ |= bit;
884
+ }
885
+ return circleSpanCache_[slot];
886
+ }
887
+
888
+ const std::uint8_t (*circleBoxSpans(int size))[2]
889
+ {
890
+ if (size <= 0 || size > kCircleBoxSpanMax) return nullptr;
891
+ for (int slot = 0; slot < kCircleBoxSpanSlots; ++slot) {
892
+ if (circleBoxSpanSize_[slot] == size)
893
+ return circleBoxSpanCache_[slot];
894
+ }
895
+ const int slot = circleBoxSpanNext_;
896
+ circleBoxSpanNext_ = (circleBoxSpanNext_ + 1) % kCircleBoxSpanSlots;
897
+ const long long ss = static_cast<long long>(size) * static_cast<long long>(size);
898
+ for (int row = 0; row < size; row++) {
899
+ const long long dy2 = static_cast<long long>(row * 2 + 1 - size);
900
+ long long inside = ss - dy2 * dy2;
901
+ if (inside < 0) inside = 0;
902
+ const int dx2 = integerSqrt(static_cast<int>(inside));
903
+ int sx0 = (size - dx2) / 2;
904
+ int sx1 = (size + dx2 - 1) / 2;
905
+ if (sx0 < 0) sx0 = 0;
906
+ if (sx1 >= size) sx1 = size - 1;
907
+ circleBoxSpanCache_[slot][row][0] = static_cast<std::uint8_t>(sx0);
908
+ circleBoxSpanCache_[slot][row][1] = static_cast<std::uint8_t>(sx1);
909
+ }
910
+ circleBoxSpanSize_[slot] = size;
911
+ return circleBoxSpanCache_[slot];
912
+ }
913
+
914
+ const std::uint8_t (*circleRadiusSpans(int radius))[2]
915
+ {
916
+ if (radius <= 0 || radius > kCircleRadiusMax) return nullptr;
917
+ std::uint64_t bit = 1ull << radius;
918
+ if (!(circleRadiusSpanCacheReady_ & bit)) {
919
+ const int diameter = radius * 2 + 1;
920
+ const int rr = radius * radius;
921
+ for (int row = 0; row < diameter; row++) {
922
+ const int dy = row - radius;
923
+ const int dx = integerSqrt(rr - dy * dy);
924
+ circleRadiusSpanCache_[radius][row][0] = (std::uint8_t)(radius - dx);
925
+ circleRadiusSpanCache_[radius][row][1] = (std::uint8_t)(radius + dx);
926
+ }
927
+ circleRadiusSpanCacheReady_ |= bit;
928
+ }
929
+ return circleRadiusSpanCache_[radius];
930
+ }
931
+
932
+ static CanvasMath &instance()
933
+ {
934
+ static CanvasMath math;
935
+ return math;
936
+ }
937
+
938
+ private:
939
+ std::uint8_t circleSpanCache_[kCircleSpanSlotCount][kCircleSpanMax][2]{};
940
+ std::uint32_t circleSpanCacheReady_ = 0;
941
+ std::uint8_t circleRadiusSpanCache_[kCircleRadiusMax + 1][kCircleRadiusSpanRows][2]{};
942
+ std::uint64_t circleRadiusSpanCacheReady_ = 0;
943
+ std::uint8_t circleBoxSpanCache_[kCircleBoxSpanSlots][kCircleBoxSpanMax][2]{};
944
+ std::uint8_t circleBoxSpanSize_[kCircleBoxSpanSlots]{};
945
+ int circleBoxSpanNext_ = 0;
946
+ };
947
+
948
+ void Canvas::writePixelNative(int x, int y, pixel::native_t c)
949
+ {
950
+ if (!pixels_) return;
951
+ if (x < 0 || x >= width_ || y < 0 || y >= height_) return;
952
+ if (x < clipStack_[clipDepth_].x0 || x > clipStack_[clipDepth_].x1 ||
953
+ y < clipStack_[clipDepth_].y0 || y > clipStack_[clipDepth_].y1)
954
+ return;
955
+ #if GEA_EMBEDDED_DISPLAY_ROTATE_LANDSCAPE
956
+ if (landscapeRot_) {
957
+ if (globalAlpha_ == 255) rotSet(x, y, c);
958
+ else if (globalAlpha_ != 0) rotBlend(x, y, c, globalAlpha_);
959
+ return;
960
+ }
961
+ #endif
962
+ #if GEA_PIXEL_STORAGE_PACKED
963
+ std::uint8_t *row = packedRow(rowToPhysical(y));
964
+ if (globalAlpha_ == 255)
965
+ pixel::packed::set(row, x, c);
966
+ else if (globalAlpha_ != 0)
967
+ pixel::packed::blendPixel(row, x, c, globalAlpha_);
968
+ #else
969
+ pixel::native_t *p = &pixels_[rowToPhysical(y) * stride_ + x];
970
+ if (globalAlpha_ == 255) {
971
+ *p = c;
972
+ } else if (globalAlpha_ != 0) {
973
+ *p = pixel::blendNative(c, *p, globalAlpha_);
974
+ }
975
+ #endif
976
+ }
977
+
978
+ void Canvas::writePixelNativeAlpha(int x, int y, pixel::native_t c, std::uint8_t alpha)
979
+ {
980
+ if (!pixels_) return;
981
+ if (alpha == 0 || globalAlpha_ == 0) return;
982
+ if (alpha == 255) {
983
+ writePixelNative(x, y, c);
984
+ return;
985
+ }
986
+ if (x < 0 || x >= width_ || y < 0 || y >= height_) return;
987
+ if (x < clipStack_[clipDepth_].x0 || x > clipStack_[clipDepth_].x1 ||
988
+ y < clipStack_[clipDepth_].y0 || y > clipStack_[clipDepth_].y1)
989
+ return;
990
+ int a = globalAlpha_ == 255 ? alpha : (alpha * globalAlpha_) / 255;
991
+ if (a <= 0) return;
992
+ #if GEA_EMBEDDED_DISPLAY_ROTATE_LANDSCAPE
993
+ if (landscapeRot_) {
994
+ if (a >= 255) rotSet(x, y, c);
995
+ else rotBlend(x, y, c, a);
996
+ return;
997
+ }
998
+ #endif
999
+ #if GEA_PIXEL_STORAGE_PACKED
1000
+ pixel::packed::blendPixel(packedRow(rowToPhysical(y)), x, c, a);
1001
+ #else
1002
+ pixel::native_t *p = &pixels_[rowToPhysical(y) * stride_ + x];
1003
+ *p = (a >= 255) ? c : pixel::blendNative(c, *p, a);
1004
+ #endif
1005
+ }
1006
+
1007
+ void Canvas::writePixel(int x, int y, pixel::native_t fg)
1008
+ {
1009
+ writePixelNative(x, y, fg);
1010
+ }
1011
+
1012
+ void Canvas::writePixelAlpha(int x, int y, pixel::native_t fg, std::uint8_t alpha)
1013
+ {
1014
+ writePixelNativeAlpha(x, y, fg, alpha);
1015
+ }
1016
+
1017
+ // Fill a horizontal span at physical row `phys` with a colour (converted once
1018
+ // to the native pixel). Native fill — no per-pixel conversion, no branch.
1019
+ void Canvas::fillSpanColor(int phys, int x0, int count, pixel::native_t color)
1020
+ {
1021
+ #if GEA_EMBEDDED_DISPLAY_ROTATE_LANDSCAPE
1022
+ // Rotated: `phys` is the logical row == physical COLUMN; the logical horizontal
1023
+ // span [x0, x0+count) becomes a physical vertical run (one write per row).
1024
+ if (landscapeRot_) {
1025
+ const int ly = phys;
1026
+ for (int i = 0; i < count; ++i) rotSet(x0 + i, ly, color);
1027
+ return;
1028
+ }
1029
+ #endif
1030
+ #if GEA_PIXEL_STORAGE_PACKED
1031
+ pixel::packed::fillSpan(packedRow(phys), x0, count, color);
1032
+ #else
1033
+ pixel::fillNative(&pixels_[phys * stride_ + x0], count, color);
1034
+ #endif
1035
+ }
1036
+
1037
+ void Canvas::fillSpanGlobalAlpha(int phys, int x0, int count, pixel::native_t color)
1038
+ {
1039
+ if (count <= 0) return;
1040
+ if (globalAlpha_ == 255) {
1041
+ fillSpanColor(phys, x0, count, color);
1042
+ return;
1043
+ }
1044
+ if (globalAlpha_ == 0) return;
1045
+ const int a = globalAlpha_;
1046
+ const pixel::native_t c = color;
1047
+ #if GEA_EMBEDDED_DISPLAY_ROTATE_LANDSCAPE
1048
+ if (landscapeRot_) {
1049
+ const int ly = phys;
1050
+ for (int i = 0; i < count; i++) rotBlend(x0 + i, ly, c, a);
1051
+ return;
1052
+ }
1053
+ #endif
1054
+ #if GEA_PIXEL_STORAGE_PACKED
1055
+ std::uint8_t *row = packedRow(phys);
1056
+ for (int i = 0; i < count; i++) pixel::packed::blendPixel(row, x0 + i, c, a);
1057
+ #else
1058
+ pixel::native_t *dst = &pixels_[phys * stride_ + x0];
1059
+ for (int i = 0; i < count; i++) dst[i] = pixel::blendNative(c, dst[i], a);
1060
+ #endif
1061
+ }
1062
+
1063
+ void Canvas::bindPixels(pixel::native_t *pixels, int width, int height)
1064
+ {
1065
+ bindPixels(pixels, width, height, width);
1066
+ }
1067
+
1068
+ void Canvas::bindPixels(pixel::native_t *pixels, int width, int height, int stridePixels)
1069
+ {
1070
+ width_ = width;
1071
+ height_ = height;
1072
+ stride_ = stridePixels > 0 ? stridePixels : width;
1073
+ #if GEA_PIXEL_STORAGE_PACKED
1074
+ // Framebuffer packs kPxPerByte pixels per byte (2 on GRAY4, 4 on GRAY2), so a
1075
+ // physical row is that many bytes, rounded up for a partial trailing byte.
1076
+ strideBytes_ = stride_ > 0 ? pixel::packed::rowBytes(stride_) : 0;
1077
+ #else
1078
+ strideBytes_ = stride_ > 0 ? stride_ * (int)sizeof(pixel::native_t) : 0;
1079
+ #endif
1080
+ regionY_ = 0;
1081
+ regionH_ = 0;
1082
+ scrollOffsetY_ = 0;
1083
+ pixels_ = pixels;
1084
+ globalAlpha_ = 255;
1085
+ #if GEA_EMBEDDED_DISPLAY_ROTATE_LANDSCAPE
1086
+ landscapeRot_ = false;
1087
+ #endif
1088
+ resetDirty();
1089
+ resetClip();
1090
+ }
1091
+
1092
+ #if GEA_EMBEDDED_DISPLAY_ROTATE_LANDSCAPE
1093
+ void Canvas::bindPixelsRotatedLandscape(pixel::native_t *physPixels, int logicalWidth, int logicalHeight)
1094
+ {
1095
+ // Present a LOGICAL portrait coordinate system (width_ x height_) while the
1096
+ // backing store is the PHYSICAL landscape buffer (logicalHeight x logicalWidth).
1097
+ // strideBytes_ is the PHYSICAL row stride (rowBytes(physicalWidth) =
1098
+ // rowBytes(logicalHeight)); packedRow(physRow) then steps whole physical rows
1099
+ // and rotSet/rotBlend/rotGet index the physical column. See the transform note
1100
+ // on the helpers in canvas.h.
1101
+ width_ = logicalWidth;
1102
+ height_ = logicalHeight;
1103
+ stride_ = logicalHeight;
1104
+ #if GEA_PIXEL_STORAGE_PACKED
1105
+ strideBytes_ = logicalHeight > 0 ? pixel::packed::rowBytes(logicalHeight) : 0;
1106
+ #else
1107
+ strideBytes_ = logicalHeight > 0 ? logicalHeight * static_cast<int>(sizeof(pixel::native_t)) : 0;
1108
+ #endif
1109
+ regionY_ = 0;
1110
+ regionH_ = 0;
1111
+ scrollOffsetY_ = 0;
1112
+ pixels_ = physPixels;
1113
+ globalAlpha_ = 255;
1114
+ landscapeRot_ = true;
1115
+ resetDirty();
1116
+ resetClip();
1117
+ }
1118
+ #endif
1119
+
1120
+ void Canvas::setScrollRegion(int regionY, int regionH, int scrollOffsetY)
1121
+ {
1122
+ if (regionH <= 0 || height_ <= 0) {
1123
+ regionY_ = 0;
1124
+ regionH_ = 0;
1125
+ scrollOffsetY_ = 0;
1126
+ return;
1127
+ }
1128
+ regionY_ = regionY;
1129
+ regionH_ = regionH;
1130
+ int o = scrollOffsetY % regionH;
1131
+ if (o < 0) o += regionH;
1132
+ scrollOffsetY_ = o;
1133
+ }
1134
+
1135
+ pixel::native_t *Canvas::pixels() { return pixels_; }
1136
+ const pixel::native_t *Canvas::pixels() const { return pixels_; }
1137
+ int Canvas::width() const { return width_; }
1138
+ int Canvas::height() const { return height_; }
1139
+ int Canvas::strideBytes() const { return strideBytes_; }
1140
+
1141
+ void Canvas::resetDirty()
1142
+ {
1143
+ dirtyX0_ = width_;
1144
+ dirtyY0_ = height_;
1145
+ dirtyX1_ = -1;
1146
+ dirtyY1_ = -1;
1147
+ dirtyRectCount_ = 0;
1148
+ }
1149
+
1150
+ void Canvas::addDirtyRect(int x0, int y0, int x1, int y1)
1151
+ {
1152
+ if (x0 > x1 || y0 > y1) return;
1153
+ CanvasDirtyRect rect{x0, y0, x1, y1};
1154
+
1155
+ for (int i = 0; i < dirtyRectCount_; i++) {
1156
+ CanvasDirtyRect &existing = dirtyRects_[i];
1157
+ if (existing.x0 <= rect.x1 + 1 && existing.x1 + 1 >= rect.x0 &&
1158
+ existing.y0 <= rect.y1 + 1 && existing.y1 + 1 >= rect.y0) {
1159
+ if (rect.x0 < existing.x0) existing.x0 = rect.x0;
1160
+ if (rect.y0 < existing.y0) existing.y0 = rect.y0;
1161
+ if (rect.x1 > existing.x1) existing.x1 = rect.x1;
1162
+ if (rect.y1 > existing.y1) existing.y1 = rect.y1;
1163
+ return;
1164
+ }
1165
+ }
1166
+
1167
+ if (dirtyRectCount_ < kMaxDirtyRects) {
1168
+ dirtyRects_[dirtyRectCount_++] = rect;
1169
+ return;
1170
+ }
1171
+
1172
+ int best = 0;
1173
+ int bestCost = 0x7fffffff;
1174
+ for (int i = 0; i < dirtyRectCount_; i++) {
1175
+ const CanvasDirtyRect &existing = dirtyRects_[i];
1176
+ const int ux0 = existing.x0 < rect.x0 ? existing.x0 : rect.x0;
1177
+ const int uy0 = existing.y0 < rect.y0 ? existing.y0 : rect.y0;
1178
+ const int ux1 = existing.x1 > rect.x1 ? existing.x1 : rect.x1;
1179
+ const int uy1 = existing.y1 > rect.y1 ? existing.y1 : rect.y1;
1180
+ const int existingArea = (existing.x1 - existing.x0 + 1) * (existing.y1 - existing.y0 + 1);
1181
+ const int mergedArea = (ux1 - ux0 + 1) * (uy1 - uy0 + 1);
1182
+ const int cost = mergedArea - existingArea;
1183
+ if (cost < bestCost) {
1184
+ bestCost = cost;
1185
+ best = i;
1186
+ }
1187
+ }
1188
+
1189
+ CanvasDirtyRect &existing = dirtyRects_[best];
1190
+ if (rect.x0 < existing.x0) existing.x0 = rect.x0;
1191
+ if (rect.y0 < existing.y0) existing.y0 = rect.y0;
1192
+ if (rect.x1 > existing.x1) existing.x1 = rect.x1;
1193
+ if (rect.y1 > existing.y1) existing.y1 = rect.y1;
1194
+ }
1195
+
1196
+ void Canvas::markDirty(int x0, int y0, int x1, int y1)
1197
+ {
1198
+ if (width_ <= 0 || height_ <= 0) return;
1199
+ if (x0 < 0) x0 = 0;
1200
+ if (y0 < 0) y0 = 0;
1201
+ if (x1 >= width_) x1 = width_ - 1;
1202
+ if (y1 >= height_) y1 = height_ - 1;
1203
+ if (x0 > x1 || y0 > y1) return;
1204
+ if (x0 < dirtyX0_) dirtyX0_ = x0;
1205
+ if (y0 < dirtyY0_) dirtyY0_ = y0;
1206
+ if (x1 > dirtyX1_) dirtyX1_ = x1;
1207
+ if (y1 > dirtyY1_) dirtyY1_ = y1;
1208
+ addDirtyRect(x0, y0, x1, y1);
1209
+ }
1210
+
1211
+ void Canvas::markDirtyClipped(int x0, int y0, int x1, int y1)
1212
+ {
1213
+ const ClipRect *clip = &clipStack_[clipDepth_];
1214
+ if (x0 < clip->x0) x0 = clip->x0;
1215
+ if (y0 < clip->y0) y0 = clip->y0;
1216
+ if (x1 > clip->x1) x1 = clip->x1;
1217
+ if (y1 > clip->y1) y1 = clip->y1;
1218
+ markDirty(x0, y0, x1, y1);
1219
+ }
1220
+
1221
+ bool Canvas::dirty(int *x0, int *y0, int *x1, int *y1) const
1222
+ {
1223
+ if (dirtyX0_ > dirtyX1_ || dirtyY0_ > dirtyY1_) return false;
1224
+ if (x0) *x0 = dirtyX0_;
1225
+ if (y0) *y0 = dirtyY0_;
1226
+ if (x1) *x1 = dirtyX1_;
1227
+ if (y1) *y1 = dirtyY1_;
1228
+ return true;
1229
+ }
1230
+
1231
+ int Canvas::dirtyRects(CanvasDirtyRect *rects, int capacity) const
1232
+ {
1233
+ if (!rects || capacity <= 0 || dirtyRectCount_ <= 0) return 0;
1234
+ int count = dirtyRectCount_;
1235
+ if (count > capacity) count = capacity;
1236
+ for (int i = 0; i < count; i++) rects[i] = dirtyRects_[i];
1237
+ return count;
1238
+ }
1239
+
1240
+ void Canvas::resetClip()
1241
+ {
1242
+ clipDepth_ = 0;
1243
+ clipStack_[0].x0 = 0;
1244
+ clipStack_[0].y0 = 0;
1245
+ clipStack_[0].x1 = width_ > 0 ? width_ - 1 : 0;
1246
+ clipStack_[0].y1 = height_ > 0 ? height_ - 1 : 0;
1247
+ }
1248
+
1249
+ void Canvas::pushClip(int x, int y, int w, int h)
1250
+ {
1251
+ int nx0 = x, ny0 = y, nx1 = x + w - 1, ny1 = y + h - 1;
1252
+ const ClipRect *current = &clipStack_[clipDepth_];
1253
+ if (nx0 < current->x0) nx0 = current->x0;
1254
+ if (ny0 < current->y0) ny0 = current->y0;
1255
+ if (nx1 > current->x1) nx1 = current->x1;
1256
+ if (ny1 > current->y1) ny1 = current->y1;
1257
+ if (clipDepth_ < Canvas::kMaxClipDepth - 1) clipDepth_++;
1258
+ clipStack_[clipDepth_].x0 = nx0;
1259
+ clipStack_[clipDepth_].y0 = ny0;
1260
+ clipStack_[clipDepth_].x1 = nx1;
1261
+ clipStack_[clipDepth_].y1 = ny1;
1262
+ }
1263
+
1264
+ void Canvas::popClip()
1265
+ {
1266
+ if (clipDepth_ > 0) clipDepth_--;
1267
+ }
1268
+
1269
+ void Canvas::currentClip(int *x0, int *y0, int *x1, int *y1) const
1270
+ {
1271
+ const ClipRect *c = &clipStack_[clipDepth_];
1272
+ if (x0) *x0 = c->x0;
1273
+ if (y0) *y0 = c->y0;
1274
+ if (x1) *x1 = c->x1;
1275
+ if (y1) *y1 = c->y1;
1276
+ }
1277
+
1278
+ void Canvas::setGlobalAlpha(std::uint8_t alpha)
1279
+ {
1280
+ globalAlpha_ = alpha;
1281
+ }
1282
+
1283
+ std::uint8_t Canvas::globalAlpha() const
1284
+ {
1285
+ return globalAlpha_;
1286
+ }
1287
+
1288
+ void Canvas::clear(pixel::native_t color)
1289
+ {
1290
+ if (!pixels_) return;
1291
+ #if GEA_PIXEL_STORAGE_PACKED
1292
+ const std::uint8_t rep = pixel::packed::replicate(static_cast<std::uint8_t>(color));
1293
+ // A solid replicated byte fills every nibble identically, so a rotated buffer
1294
+ // needs no per-pixel transform — only the correct byte count. The physical
1295
+ // landscape buffer is (strideBytes_ x width_), NOT (strideBytes_ x height_).
1296
+ std::size_t clearBytes = static_cast<std::size_t>(strideBytes_) * height_;
1297
+ #if GEA_EMBEDDED_DISPLAY_ROTATE_LANDSCAPE
1298
+ if (landscapeRot_) clearBytes = static_cast<std::size_t>(strideBytes_) * width_;
1299
+ #endif
1300
+ std::memset(reinterpret_cast<std::uint8_t *>(pixels_), rep, clearBytes);
1301
+ #else
1302
+ std::size_t clearPixels = static_cast<std::size_t>(stride_) * height_;
1303
+ #if GEA_EMBEDDED_DISPLAY_ROTATE_LANDSCAPE
1304
+ if (landscapeRot_) clearPixels = static_cast<std::size_t>(stride_) * width_;
1305
+ #endif
1306
+ std::fill_n(pixels_, clearPixels, color);
1307
+ #endif
1308
+ markDirty(0, 0, width_ - 1, height_ - 1);
1309
+ }
1310
+
1311
+ void Canvas::clearRect(int x, int y, int w, int h)
1312
+ {
1313
+ std::uint8_t previousAlpha = globalAlpha_;
1314
+ globalAlpha_ = 255;
1315
+ fillRect(x, y, w, h, 0);
1316
+ globalAlpha_ = previousAlpha;
1317
+ }
1318
+
1319
+ void Canvas::scrollRect(int x, int y, int w, int h, int dx, int dy)
1320
+ {
1321
+ if (!pixels_ || (dx == 0 && dy == 0) || w <= 0 || h <= 0) return;
1322
+
1323
+ const ClipRect *clip = &clipStack_[clipDepth_];
1324
+ int x0 = x, y0 = y, x1 = x + w - 1, y1 = y + h - 1;
1325
+
1326
+ if (x0 < clip->x0) x0 = clip->x0;
1327
+ if (y0 < clip->y0) y0 = clip->y0;
1328
+ if (x1 > clip->x1) x1 = clip->x1;
1329
+ if (y1 > clip->y1) y1 = clip->y1;
1330
+ if (x0 < 0) x0 = 0;
1331
+ if (y0 < 0) y0 = 0;
1332
+ if (x1 >= width_) x1 = width_ - 1;
1333
+ if (y1 >= height_) y1 = height_ - 1;
1334
+ if (x0 > x1 || y0 > y1) return;
1335
+
1336
+ int rect_w = x1 - x0 + 1;
1337
+ int rect_h = y1 - y0 + 1;
1338
+ if (dx <= -rect_w || dx >= rect_w) return;
1339
+ if (dy <= -rect_h || dy >= rect_h) return;
1340
+
1341
+ // Choose row iteration order so that we never overwrite a source row before reading it:
1342
+ // dy > 0 (move down): iterate rows bottom-up
1343
+ // dy <= 0 (move up or pure horizontal): iterate rows top-down
1344
+ int row_start, row_end, row_step;
1345
+ if (dy > 0) {
1346
+ row_start = y1; row_end = y0 - 1; row_step = -1;
1347
+ } else {
1348
+ row_start = y0; row_end = y1 + 1; row_step = 1;
1349
+ }
1350
+
1351
+ for (int row = row_start; row != row_end; row += row_step) {
1352
+ // Source row is row - dy if shifting down (dy>0), or row + |dy| if shifting up.
1353
+ int src_row = row - dy;
1354
+ if (src_row < y0 || src_row > y1) continue;
1355
+
1356
+ #if GEA_EMBEDDED_DISPLAY_ROTATE_LANDSCAPE
1357
+ // Rotated: copy per pixel through the transform. When dy==0 (row==src_row)
1358
+ // the shift aliases the same physical column, so pick the iteration
1359
+ // direction that reads each source before it is overwritten.
1360
+ if (landscapeRot_) {
1361
+ if (dx > 0) {
1362
+ for (int i = rect_w - dx - 1; i >= 0; --i) rotSet(x0 + dx + i, row, rotGet(x0 + i, src_row));
1363
+ } else if (dx < 0) {
1364
+ const int n = rect_w + dx;
1365
+ for (int i = 0; i < n; ++i) rotSet(x0 + i, row, rotGet(x0 - dx + i, src_row));
1366
+ } else {
1367
+ for (int i = 0; i < rect_w; ++i) rotSet(x0 + i, row, rotGet(x0 + i, src_row));
1368
+ }
1369
+ continue;
1370
+ }
1371
+ #endif
1372
+ // Within-row horizontal shift by dx pixels; overlap handled internally.
1373
+ #if GEA_PIXEL_STORAGE_PACKED
1374
+ std::uint8_t *dstRow = packedRow(rowToPhysical(row));
1375
+ const std::uint8_t *srcRow = packedRow(rowToPhysical(src_row));
1376
+ if (dx > 0) {
1377
+ pixel::packed::copyPacked(dstRow, x0 + dx, srcRow, x0, rect_w - dx);
1378
+ } else if (dx < 0) {
1379
+ pixel::packed::copyPacked(dstRow, x0, srcRow, x0 - dx, rect_w + dx);
1380
+ } else {
1381
+ pixel::packed::copyPacked(dstRow, x0, srcRow, x0, rect_w);
1382
+ }
1383
+ #else
1384
+ pixel::native_t *dst = &pixels_[rowToPhysical(row) * stride_ + x0];
1385
+ pixel::native_t *src = &pixels_[rowToPhysical(src_row) * stride_ + x0];
1386
+ if (dx > 0) {
1387
+ memmove(dst + dx, src, (size_t)(rect_w - dx) * sizeof(pixel::native_t));
1388
+ } else if (dx < 0) {
1389
+ memmove(dst, src - dx, (size_t)(rect_w + dx) * sizeof(pixel::native_t));
1390
+ } else {
1391
+ memmove(dst, src, (size_t)rect_w * sizeof(pixel::native_t));
1392
+ }
1393
+ #endif
1394
+ }
1395
+
1396
+ markDirty(x0, y0, x1, y1);
1397
+ }
1398
+
1399
+ void Canvas::fillRect(int x, int y, int w, int h, pixel::native_t color)
1400
+ {
1401
+ if (!pixels_) return;
1402
+
1403
+ const ClipRect *clip = &clipStack_[clipDepth_];
1404
+ int x0 = x, y0 = y, x1 = x + w - 1, y1 = y + h - 1;
1405
+
1406
+ if (x0 < clip->x0) x0 = clip->x0;
1407
+ if (y0 < clip->y0) y0 = clip->y0;
1408
+ if (x1 > clip->x1) x1 = clip->x1;
1409
+ if (y1 > clip->y1) y1 = clip->y1;
1410
+ if (x0 < 0) x0 = 0;
1411
+ if (y0 < 0) y0 = 0;
1412
+ if (x1 >= width_) x1 = width_ - 1;
1413
+ if (y1 >= height_) y1 = height_ - 1;
1414
+ if (x0 > x1 || y0 > y1) return;
1415
+
1416
+ const pixel::native_t c = color;
1417
+ if (globalAlpha_ == 255) {
1418
+ const int count = x1 - x0 + 1;
1419
+ #if GEA_EMBEDDED_DISPLAY_ROTATE_LANDSCAPE
1420
+ // Rotated: a logical row is a physical column, so the byte/word occlusion
1421
+ // scan below (which assumes contiguous packed bytes) does not apply. Walk
1422
+ // logical columns instead: each one is a contiguous native framebuffer row.
1423
+ // This avoids turning a small logical fill into one PSRAM cache miss per pixel.
1424
+ if (landscapeRot_) {
1425
+ #if GEA_PIXEL_STORAGE_PACKED
1426
+ for (int col = x0; col <= x1; ++col)
1427
+ for (int row = y0; row <= y1; ++row) rotSet(col, row, c);
1428
+ #else
1429
+ for (int col = x0; col <= x1; ++col)
1430
+ pixel::fillNative(&pixels_[rotPhysRow(col) * stride_ + y0], y1 - y0 + 1, c);
1431
+ #endif
1432
+ markDirty(x0, y0, x1, y1);
1433
+ return;
1434
+ }
1435
+ #endif
1436
+ #if !GEA_PIXEL_STORAGE_PACKED
1437
+ // Large opaque fills (e.g. a full-screen page/paper background) skip the
1438
+ // per-pixel occlusion scan below. That scan READS every pixel just to
1439
+ // minimize the dirty rect — worth it for a small changed region, but pure
1440
+ // overhead for a page-sized fill that gets repainted wholesale anyway. Here
1441
+ // we memset each row (fillSpanColor) and mark the whole rect dirty once.
1442
+ // (Packed targets take the word-scan below for EVERY size: on e-paper the
1443
+ // erase fill repaints a mostly-unchanged page, and skipping the matching
1444
+ // words costs one sequential read instead of a full write-allocate pass —
1445
+ // measured 42→~25 ms for the 540×960 page-turn eraser.)
1446
+ if (static_cast<long long>(count) * (y1 - y0 + 1) >= static_cast<long long>(width_) * height_ / 4) {
1447
+ for (int row = y0; row <= y1; row++) fillSpanColor(rowToPhysical(row), x0, count, c);
1448
+ markDirty(x0, y0, x1, y1);
1449
+ return;
1450
+ }
1451
+ #endif
1452
+ for (int row = y0; row <= y1; row++) {
1453
+ #if GEA_PIXEL_STORAGE_PACKED
1454
+ // Byte/word-wise occlusion scan: a packed byte holds kPxPerByte pixels,
1455
+ // so comparing whole bytes against the replicated value (and aligned
1456
+ // 32-bit words against it ×4) skips already-correct spans without
1457
+ // per-pixel bit work. Only differing bytes are rewritten and marked
1458
+ // dirty (kPxPerByte-px run granularity). The per-pixel version of this
1459
+ // scan read the whole rect one pixel at a time from PSRAM and dominated
1460
+ // an e-reader page turn (~200 ms of the frame).
1461
+ constexpr int kPxPerByte = pixel::packed::kPxPerByte;
1462
+ std::uint8_t *dstRow = packedRow(rowToPhysical(row));
1463
+ const std::uint8_t lvl = static_cast<std::uint8_t>(c & pixel::packed::kMask);
1464
+ const std::uint8_t rep = pixel::packed::replicate(lvl);
1465
+ const std::uint32_t rep4 = 0x01010101u * rep;
1466
+ int runStart = -1; // pixel coords; runs close inside this branch
1467
+ int xs = x0, xe = x1;
1468
+ // Leading pixels that share their byte with pixels BEFORE the span.
1469
+ while (xs <= xe && (xs % kPxPerByte) != 0) {
1470
+ if (pixel::packed::get(dstRow, xs) != lvl) {
1471
+ pixel::packed::set(dstRow, xs, lvl);
1472
+ markDirty(xs, row, xs, row);
1473
+ }
1474
+ xs++;
1475
+ }
1476
+ // Trailing pixels that share their byte with pixels AFTER the span.
1477
+ while (xe >= xs && (xe % kPxPerByte) != kPxPerByte - 1) {
1478
+ if (pixel::packed::get(dstRow, xe) != lvl) {
1479
+ pixel::packed::set(dstRow, xe, lvl);
1480
+ markDirty(xe, row, xe, row);
1481
+ }
1482
+ xe--;
1483
+ }
1484
+ // Whole-byte middle. Guarded because the trims above can consume the
1485
+ // entire span, and an empty [xs, xe] must not touch a byte.
1486
+ if (xs <= xe) {
1487
+ const int bEnd = xe / kPxPerByte; // inclusive whole-byte range
1488
+ for (int bi = xs / kPxPerByte; bi <= bEnd;) {
1489
+ if (bi + 3 <= bEnd &&
1490
+ (reinterpret_cast<std::uintptr_t>(dstRow + bi) & 3u) == 0 &&
1491
+ *reinterpret_cast<const std::uint32_t *>(dstRow + bi) == rep4) {
1492
+ if (runStart >= 0) {
1493
+ markDirty(runStart, row, bi * kPxPerByte - 1, row);
1494
+ runStart = -1;
1495
+ }
1496
+ bi += 4;
1497
+ continue;
1498
+ }
1499
+ if (dstRow[bi] == rep) {
1500
+ if (runStart >= 0) {
1501
+ markDirty(runStart, row, bi * kPxPerByte - 1, row);
1502
+ runStart = -1;
1503
+ }
1504
+ } else {
1505
+ if (runStart < 0) runStart = bi * kPxPerByte;
1506
+ dstRow[bi] = rep;
1507
+ }
1508
+ bi++;
1509
+ }
1510
+ }
1511
+ if (runStart >= 0) {
1512
+ markDirty(runStart, row, xe, row);
1513
+ runStart = -1; // keep the shared tail below a no-op
1514
+ }
1515
+ #else
1516
+ pixel::native_t *dst = &pixels_[rowToPhysical(row) * stride_ + x0];
1517
+ int runStart = -1;
1518
+ for (int i = 0; i < count; i++) {
1519
+ if (dst[i] == c) {
1520
+ if (runStart >= 0) {
1521
+ markDirty(x0 + runStart, row, x0 + i - 1, row);
1522
+ runStart = -1;
1523
+ }
1524
+ continue;
1525
+ }
1526
+ if (runStart < 0) runStart = i;
1527
+ dst[i] = c;
1528
+ }
1529
+ #endif
1530
+ if (runStart >= 0) markDirty(x0 + runStart, row, x1, row);
1531
+ }
1532
+ } else if (globalAlpha_ != 0) {
1533
+ const int a = globalAlpha_;
1534
+ #if GEA_EMBEDDED_DISPLAY_ROTATE_LANDSCAPE
1535
+ if (landscapeRot_) {
1536
+ #if GEA_PIXEL_STORAGE_PACKED
1537
+ for (int col = x0; col <= x1; ++col)
1538
+ for (int row = y0; row <= y1; ++row) rotBlend(col, row, c, a);
1539
+ #else
1540
+ for (int col = x0; col <= x1; ++col) {
1541
+ pixel::native_t *dst = &pixels_[rotPhysRow(col) * stride_ + y0];
1542
+ for (int row = y0; row <= y1; ++row, ++dst)
1543
+ *dst = pixel::blendNative(c, *dst, a);
1544
+ }
1545
+ #endif
1546
+ markDirty(x0, y0, x1, y1);
1547
+ return;
1548
+ }
1549
+ #endif
1550
+ for (int row = y0; row <= y1; row++) {
1551
+ #if GEA_PIXEL_STORAGE_PACKED
1552
+ std::uint8_t *dstRow = packedRow(rowToPhysical(row));
1553
+ for (int col = x0; col <= x1; col++) pixel::packed::blendPixel(dstRow, col, c, a);
1554
+ #else
1555
+ pixel::native_t *dst = &pixels_[rowToPhysical(row) * stride_ + x0];
1556
+ for (int col = x0; col <= x1; col++, dst++) {
1557
+ *dst = pixel::blendNative(c, *dst, a);
1558
+ }
1559
+ #endif
1560
+ }
1561
+ markDirty(x0, y0, x1, y1);
1562
+ }
1563
+ }
1564
+
1565
+ void Canvas::fillRectOpaque(int x, int y, int w, int h, pixel::native_t color)
1566
+ {
1567
+ if (!pixels_) return;
1568
+
1569
+ const ClipRect *clip = &clipStack_[clipDepth_];
1570
+ int x0 = x, y0 = y, x1 = x + w - 1, y1 = y + h - 1;
1571
+
1572
+ if (x0 < clip->x0) x0 = clip->x0;
1573
+ if (y0 < clip->y0) y0 = clip->y0;
1574
+ if (x1 > clip->x1) x1 = clip->x1;
1575
+ if (y1 > clip->y1) y1 = clip->y1;
1576
+ if (x0 < 0) x0 = 0;
1577
+ if (y0 < 0) y0 = 0;
1578
+ if (x1 >= width_) x1 = width_ - 1;
1579
+ if (y1 >= height_) y1 = height_ - 1;
1580
+ if (x0 > x1 || y0 > y1) return;
1581
+
1582
+ #if GEA_EMBEDDED_DISPLAY_ROTATE_LANDSCAPE
1583
+ if (landscapeRot_) {
1584
+ #if GEA_PIXEL_STORAGE_PACKED
1585
+ for (int col = x0; col <= x1; ++col)
1586
+ for (int row = y0; row <= y1; ++row) rotSet(col, row, color);
1587
+ #else
1588
+ for (int col = x0; col <= x1; ++col)
1589
+ pixel::fillNative(&pixels_[rotPhysRow(col) * stride_ + y0], y1 - y0 + 1, color);
1590
+ #endif
1591
+ markDirty(x0, y0, x1, y1);
1592
+ return;
1593
+ }
1594
+ #endif
1595
+
1596
+ const int count = x1 - x0 + 1;
1597
+ for (int row = y0; row <= y1; row++) {
1598
+ fillSpanColor(rowToPhysical(row), x0, count, color);
1599
+ }
1600
+ markDirty(x0, y0, x1, y1);
1601
+ }
1602
+
1603
+ void Canvas::strokeRect(int x, int y, int w, int h, pixel::native_t color)
1604
+ {
1605
+ if (w <= 0 || h <= 0) return;
1606
+ fillRect(x, y, w, 1, color);
1607
+ fillRect(x, y + h - 1, w, 1, color);
1608
+ if (h > 2) {
1609
+ fillRect(x, y + 1, 1, h - 2, color);
1610
+ fillRect(x + w - 1, y + 1, 1, h - 2, color);
1611
+ }
1612
+ }
1613
+
1614
+ void Canvas::fillCircle(int cx, int cy, int r, pixel::native_t color)
1615
+ {
1616
+ if (fillCircleNoDirty(cx, cy, r, color)) {
1617
+ markDirtyClipped(cx - r, cy - r, cx + r, cy + r);
1618
+ }
1619
+ }
1620
+
1621
+ bool Canvas::fillCircleNoDirty(int cx, int cy, int r, pixel::native_t color)
1622
+ {
1623
+ if (!pixels_ || r <= 0) return false;
1624
+ const ClipRect *clip = &clipStack_[clipDepth_];
1625
+ if (cx + r < clip->x0 || cx - r > clip->x1 || cy + r < clip->y0 || cy - r > clip->y1) return false;
1626
+
1627
+ const std::uint8_t (*spans)[2] = CanvasMath::instance().circleRadiusSpans(r);
1628
+ if (!spans) {
1629
+ const int rr = r * r;
1630
+ int dy0 = -r;
1631
+ int dy1 = r;
1632
+ if (cy + dy0 < clip->y0) dy0 = clip->y0 - cy;
1633
+ if (cy + dy1 > clip->y1) dy1 = clip->y1 - cy;
1634
+ if (cy + dy0 < 0) dy0 = -cy;
1635
+ if (cy + dy1 >= height_) dy1 = height_ - 1 - cy;
1636
+ if (dy0 > dy1) return false;
1637
+ for (int dy = dy0; dy <= dy1; dy++) {
1638
+ int py = cy + dy;
1639
+ int dx = CanvasMath::integerSqrt(rr - dy * dy);
1640
+ int x0 = cx - dx;
1641
+ int x1 = cx + dx;
1642
+ if (x0 < clip->x0) x0 = clip->x0;
1643
+ if (x1 > clip->x1) x1 = clip->x1;
1644
+ if (x0 < 0) x0 = 0;
1645
+ if (x1 >= width_) x1 = width_ - 1;
1646
+ if (x0 > x1) continue;
1647
+
1648
+ fillSpanGlobalAlpha(rowToPhysical(py), x0, x1 - x0 + 1, color);
1649
+ }
1650
+ return true;
1651
+ }
1652
+
1653
+ const int x = cx - r;
1654
+ const int y = cy - r;
1655
+ const int diameter = r * 2 + 1;
1656
+ int row0 = 0;
1657
+ int row1 = diameter - 1;
1658
+ if (y + row0 < clip->y0) row0 = clip->y0 - y;
1659
+ if (y + row1 > clip->y1) row1 = clip->y1 - y;
1660
+ if (y + row0 < 0) row0 = -y;
1661
+ if (y + row1 >= height_) row1 = height_ - 1 - y;
1662
+ if (row0 > row1) return false;
1663
+ for (int row = row0; row <= row1; row++) {
1664
+ int py = y + row;
1665
+ int x0 = x + spans[row][0];
1666
+ int x1 = x + spans[row][1];
1667
+ if (x0 < clip->x0) x0 = clip->x0;
1668
+ if (x1 > clip->x1) x1 = clip->x1;
1669
+ if (x0 < 0) x0 = 0;
1670
+ if (x1 >= width_) x1 = width_ - 1;
1671
+ if (x0 > x1) continue;
1672
+
1673
+ fillSpanGlobalAlpha(rowToPhysical(py), x0, x1 - x0 + 1, color);
1674
+ }
1675
+ return true;
1676
+ }
1677
+
1678
+ void Canvas::fillCirclesRgb565(const std::uint16_t *xs,
1679
+ const std::uint16_t *ys,
1680
+ int count,
1681
+ int r,
1682
+ const pixel::native_t *colors)
1683
+ {
1684
+ if (!pixels_ || !xs || !ys || !colors || count <= 0 || r <= 0) return;
1685
+ const ClipRect *clip = &clipStack_[clipDepth_];
1686
+ int dirtyX0 = width_;
1687
+ int dirtyY0 = height_;
1688
+ int dirtyX1 = -1;
1689
+ int dirtyY1 = -1;
1690
+
1691
+ for (int i = 0; i < count; i++) {
1692
+ const int cx = xs[i];
1693
+ const int cy = ys[i];
1694
+ int x0 = cx - r;
1695
+ int y0 = cy - r;
1696
+ int x1 = cx + r;
1697
+ int y1 = cy + r;
1698
+ if (x1 < clip->x0 || x0 > clip->x1 || y1 < clip->y0 || y0 > clip->y1) continue;
1699
+ if (x0 < clip->x0) x0 = clip->x0;
1700
+ if (y0 < clip->y0) y0 = clip->y0;
1701
+ if (x1 > clip->x1) x1 = clip->x1;
1702
+ if (y1 > clip->y1) y1 = clip->y1;
1703
+ if (x0 < 0) x0 = 0;
1704
+ if (y0 < 0) y0 = 0;
1705
+ if (x1 >= width_) x1 = width_ - 1;
1706
+ if (y1 >= height_) y1 = height_ - 1;
1707
+ if (x0 > x1 || y0 > y1) continue;
1708
+ if (x0 < dirtyX0) dirtyX0 = x0;
1709
+ if (y0 < dirtyY0) dirtyY0 = y0;
1710
+ if (x1 > dirtyX1) dirtyX1 = x1;
1711
+ if (y1 > dirtyY1) dirtyY1 = y1;
1712
+ fillCircleNoDirty(cx, cy, r, colors[i]);
1713
+ }
1714
+
1715
+ markDirty(dirtyX0, dirtyY0, dirtyX1, dirtyY1);
1716
+ }
1717
+
1718
+ void Canvas::fillCirclesRgb565Uniform(const std::uint16_t *xs,
1719
+ const std::uint16_t *ys,
1720
+ int count,
1721
+ int r,
1722
+ pixel::native_t color)
1723
+ {
1724
+ if (!pixels_ || !xs || !ys || count <= 0 || r <= 0) return;
1725
+ const ClipRect *clip = &clipStack_[clipDepth_];
1726
+ int dirtyX0 = width_;
1727
+ int dirtyY0 = height_;
1728
+ int dirtyX1 = -1;
1729
+ int dirtyY1 = -1;
1730
+
1731
+ for (int i = 0; i < count; i++) {
1732
+ const int cx = xs[i];
1733
+ const int cy = ys[i];
1734
+ int x0 = cx - r;
1735
+ int y0 = cy - r;
1736
+ int x1 = cx + r;
1737
+ int y1 = cy + r;
1738
+ if (x1 < clip->x0 || x0 > clip->x1 || y1 < clip->y0 || y0 > clip->y1) continue;
1739
+ if (x0 < clip->x0) x0 = clip->x0;
1740
+ if (y0 < clip->y0) y0 = clip->y0;
1741
+ if (x1 > clip->x1) x1 = clip->x1;
1742
+ if (y1 > clip->y1) y1 = clip->y1;
1743
+ if (x0 < 0) x0 = 0;
1744
+ if (y0 < 0) y0 = 0;
1745
+ if (x1 >= width_) x1 = width_ - 1;
1746
+ if (y1 >= height_) y1 = height_ - 1;
1747
+ if (x0 > x1 || y0 > y1) continue;
1748
+ if (x0 < dirtyX0) dirtyX0 = x0;
1749
+ if (y0 < dirtyY0) dirtyY0 = y0;
1750
+ if (x1 > dirtyX1) dirtyX1 = x1;
1751
+ if (y1 > dirtyY1) dirtyY1 = y1;
1752
+ fillCircleNoDirty(cx, cy, r, color);
1753
+ }
1754
+
1755
+ markDirty(dirtyX0, dirtyY0, dirtyX1, dirtyY1);
1756
+ }
1757
+
1758
+ // Batched fill optimized for the per-chunk rasterizer:
1759
+ // * Inputs are in WORLD coordinates; xOffset/yOffset are subtracted to
1760
+ // produce canvas-local positions.
1761
+ // * ys must be sorted ascending — skip leading circles whose bottom edge
1762
+ // is before yBandMinWorld, break once the top edge passes
1763
+ // yBandMaxWorld, so the iteration only touches in-band circles.
1764
+ // * Chunk Canvas instances are fresh: no scroll region, alpha=255, clip
1765
+ // == full canvas. We inline fillCircleNoDirty's hot path here and skip
1766
+ // every per-circle clip-stack / globalAlpha / rowToPhysical lookup.
1767
+ void Canvas::fillCirclesRgb565WorldYSorted(const CircleEntry *circles,
1768
+ int count,
1769
+ int r,
1770
+ int yBandMinWorld,
1771
+ int yBandMaxWorld,
1772
+ int xOffset,
1773
+ int yOffset)
1774
+ {
1775
+ if (!pixels_ || !circles || count <= 0 || r <= 0) return;
1776
+ const std::uint8_t (*spans)[2] = CanvasMath::instance().circleRadiusSpans(r);
1777
+ const int diameter = r * 2 + 1;
1778
+ const int w = width_;
1779
+ const int h = height_;
1780
+ const int minCenterY = yBandMinWorld - r;
1781
+ const int maxCenterY = yBandMaxWorld + r;
1782
+ const CircleEntry *begin = std::lower_bound(circles, circles + count, minCenterY,
1783
+ [](const CircleEntry &entry, int y) {
1784
+ return static_cast<int>(entry.y) < y;
1785
+ });
1786
+ const CircleEntry *end = std::upper_bound(begin, circles + count, maxCenterY,
1787
+ [](int y, const CircleEntry &entry) {
1788
+ return y < static_cast<int>(entry.y);
1789
+ });
1790
+ for (const CircleEntry *it = begin; it != end; ++it) {
1791
+ const CircleEntry &entry = *it;
1792
+ const int worldCy = static_cast<int>(entry.y);
1793
+ const int cx = static_cast<int>(entry.x) - xOffset;
1794
+ const int cy = worldCy - yOffset;
1795
+ const pixel::native_t color = entry.color;
1796
+ const int xOriginCanvas = cx - r;
1797
+ const int yOriginCanvas = cy - r;
1798
+ int row0 = 0;
1799
+ int row1 = diameter - 1;
1800
+ if (yOriginCanvas + row0 < 0) row0 = -yOriginCanvas;
1801
+ if (yOriginCanvas + row1 >= h) row1 = h - 1 - yOriginCanvas;
1802
+ if (row0 > row1) continue;
1803
+ if (spans) {
1804
+ for (int row = row0; row <= row1; row++) {
1805
+ const int py = yOriginCanvas + row;
1806
+ int x0 = xOriginCanvas + spans[row][0];
1807
+ int x1 = xOriginCanvas + spans[row][1];
1808
+ if (x0 < 0) x0 = 0;
1809
+ if (x1 >= w) x1 = w - 1;
1810
+ if (x0 > x1) continue;
1811
+ fillSpanColor(py, x0, x1 - x0 + 1, color);
1812
+ }
1813
+ } else {
1814
+ const int rr = r * r;
1815
+ for (int row = row0; row <= row1; row++) {
1816
+ const int dy = row - r;
1817
+ const int dx = CanvasMath::integerSqrt(rr - dy * dy);
1818
+ const int py = yOriginCanvas + row;
1819
+ int x0 = cx - dx;
1820
+ int x1 = cx + dx;
1821
+ if (x0 < 0) x0 = 0;
1822
+ if (x1 >= w) x1 = w - 1;
1823
+ if (x0 > x1) continue;
1824
+ fillSpanColor(py, x0, x1 - x0 + 1, color);
1825
+ }
1826
+ }
1827
+ }
1828
+ }
1829
+
1830
+ void Canvas::strokeCircle(int cx, int cy, int r, pixel::native_t color)
1831
+ {
1832
+ if (!pixels_ || r <= 0) return;
1833
+ int x = r, y = 0, d = 1 - r;
1834
+ while (x >= y) {
1835
+ writePixel(cx + x, cy + y, color);
1836
+ writePixel(cx - x, cy + y, color);
1837
+ writePixel(cx + x, cy - y, color);
1838
+ writePixel(cx - x, cy - y, color);
1839
+ writePixel(cx + y, cy + x, color);
1840
+ writePixel(cx - y, cy + x, color);
1841
+ writePixel(cx + y, cy - x, color);
1842
+ writePixel(cx - y, cy - x, color);
1843
+ y++;
1844
+ if (d <= 0) d += 2 * y + 1;
1845
+ else { x--; d += 2 * (y - x) + 1; }
1846
+ }
1847
+ markDirtyClipped(cx - r, cy - r, cx + r, cy + r);
1848
+ }
1849
+
1850
+ void Canvas::drawLine(int x0, int y0, int x1, int y1, pixel::native_t color)
1851
+ {
1852
+ if (!pixels_) return;
1853
+ int dx = abs(x1 - x0);
1854
+ int dy = -abs(y1 - y0);
1855
+ int sx = x0 < x1 ? 1 : -1;
1856
+ int sy = y0 < y1 ? 1 : -1;
1857
+ int err = dx + dy;
1858
+ int mx0 = x0 < x1 ? x0 : x1, my0 = y0 < y1 ? y0 : y1;
1859
+ int mx1 = x0 > x1 ? x0 : x1, my1 = y0 > y1 ? y0 : y1;
1860
+ markDirtyClipped(mx0, my0, mx1, my1);
1861
+ while (1) {
1862
+ writePixel(x0, y0, color);
1863
+ if (x0 == x1 && y0 == y1) break;
1864
+ int e2 = 2 * err;
1865
+ if (e2 >= dy) { err += dy; x0 += sx; }
1866
+ if (e2 <= dx) { err += dx; y0 += sy; }
1867
+ }
1868
+ }
1869
+
1870
+ void Canvas::drawArc(int cx, int cy, int r, int start_deg, int end_deg, pixel::native_t color)
1871
+ {
1872
+ if (!pixels_ || r <= 0) return;
1873
+ start_deg = ((start_deg % 360) + 360) % 360;
1874
+ end_deg = ((end_deg % 360) + 360) % 360;
1875
+ markDirtyClipped(cx - r, cy - r, cx + r, cy + r);
1876
+ int x = r, y = 0, d = 1 - r;
1877
+ while (x >= y) {
1878
+ int points[8][2] = {
1879
+ {cx+x, cy-y}, {cx+y, cy-x}, {cx-y, cy-x}, {cx-x, cy-y},
1880
+ {cx-x, cy+y}, {cx-y, cy+x}, {cx+y, cy+x}, {cx+x, cy+y},
1881
+ };
1882
+ for (int i = 0; i < 8; i++) {
1883
+ int px = points[i][0], py = points[i][1];
1884
+ if (px < 0 || px >= width_ || py < 0 || py >= height_) continue;
1885
+ float a = atan2f(-(float)(py - cy), (float)(px - cx));
1886
+ a = a * (180.0f / 3.14159265f);
1887
+ if (a < 0) a += 360.0f;
1888
+ int deg = (int)(a + 0.5f);
1889
+ if (deg >= 360) deg -= 360;
1890
+ int in_range = (start_deg <= end_deg) ? (deg >= start_deg && deg <= end_deg) : (deg >= start_deg || deg <= end_deg);
1891
+ if (in_range) writePixel(px, py, color);
1892
+ }
1893
+ y++;
1894
+ if (d <= 0) d += 2 * y + 1;
1895
+ else { x--; d += 2 * (y - x) + 1; }
1896
+ }
1897
+ }
1898
+
1899
+ void Canvas::fillTriangle(int x0, int y0, int x1, int y1, int x2, int y2, pixel::native_t color)
1900
+ {
1901
+ if (!pixels_) return;
1902
+ if (y0 > y1) { std::swap(x0, x1); std::swap(y0, y1); }
1903
+ if (y0 > y2) { std::swap(x0, x2); std::swap(y0, y2); }
1904
+ if (y1 > y2) { std::swap(x1, x2); std::swap(y1, y2); }
1905
+ int total_h = y2 - y0;
1906
+ if (total_h == 0) {
1907
+ int mn = x0 < x1 ? (x0 < x2 ? x0 : x2) : (x1 < x2 ? x1 : x2);
1908
+ int mx = x0 > x1 ? (x0 > x2 ? x0 : x2) : (x1 > x2 ? x1 : x2);
1909
+ fillRect(mn, y0, mx - mn + 1, 1, color);
1910
+ return;
1911
+ }
1912
+ int min_x = x0 < x1 ? (x0 < x2 ? x0 : x2) : (x1 < x2 ? x1 : x2);
1913
+ int max_x = x0 > x1 ? (x0 > x2 ? x0 : x2) : (x1 > x2 ? x1 : x2);
1914
+ const ClipRect *clip = &clipStack_[clipDepth_];
1915
+ int draw_y0 = y0;
1916
+ int draw_y1 = y2;
1917
+ if (draw_y0 < clip->y0) draw_y0 = clip->y0;
1918
+ if (draw_y1 > clip->y1) draw_y1 = clip->y1;
1919
+ if (draw_y0 < 0) draw_y0 = 0;
1920
+ if (draw_y1 >= height_) draw_y1 = height_ - 1;
1921
+ if (draw_y0 > draw_y1) return;
1922
+ if (globalAlpha_ != 255 && globalAlpha_ != 0) markDirtyClipped(min_x, y0, max_x, y2);
1923
+ for (int y = draw_y0; y <= draw_y1; y++) {
1924
+ int second = (y >= y1);
1925
+ int seg_h = second ? (y2 - y1) : (y1 - y0);
1926
+ if (seg_h == 0) seg_h = 1;
1927
+ float al = (float)(y - y0) / total_h;
1928
+ float beta = second ? (float)(y - y1) / seg_h : (float)(y - y0) / seg_h;
1929
+ int ax = x0 + (int)((x2 - x0) * al);
1930
+ int bx = second ? x1 + (int)((x2 - x1) * beta) : x0 + (int)((x1 - x0) * beta);
1931
+ if (ax > bx) { int t = ax; ax = bx; bx = t; }
1932
+ if (ax < clip->x0) ax = clip->x0;
1933
+ if (bx > clip->x1) bx = clip->x1;
1934
+ if (ax < 0) ax = 0;
1935
+ if (bx >= width_) bx = width_ - 1;
1936
+ if (ax > bx) continue;
1937
+ const pixel::native_t c = color;
1938
+ #if GEA_EMBEDDED_DISPLAY_ROTATE_LANDSCAPE
1939
+ if (landscapeRot_) {
1940
+ if (globalAlpha_ == 255) {
1941
+ for (int px = ax; px <= bx; px++) rotSet(px, y, c);
1942
+ markDirty(ax, y, bx, y);
1943
+ } else if (globalAlpha_ != 0) {
1944
+ const int a = globalAlpha_;
1945
+ for (int px = ax; px <= bx; px++) rotBlend(px, y, c, a);
1946
+ }
1947
+ continue;
1948
+ }
1949
+ #endif
1950
+ #if GEA_PIXEL_STORAGE_PACKED
1951
+ std::uint8_t *dnib = packedRow(rowToPhysical(y));
1952
+ if (globalAlpha_ == 255) {
1953
+ const int count = bx - ax + 1;
1954
+ int runStart = -1;
1955
+ for (int i = 0; i < count; i++) {
1956
+ if (pixel::packed::get(dnib, ax + i) == c) {
1957
+ if (runStart >= 0) { markDirty(ax + runStart, y, ax + i - 1, y); runStart = -1; }
1958
+ continue;
1959
+ }
1960
+ if (runStart < 0) runStart = i;
1961
+ pixel::packed::set(dnib, ax + i, c);
1962
+ }
1963
+ if (runStart >= 0) markDirty(ax + runStart, y, bx, y);
1964
+ } else if (globalAlpha_ != 0) {
1965
+ const int a = globalAlpha_;
1966
+ for (int px = ax; px <= bx; px++) pixel::packed::blendPixel(dnib, px, c, a);
1967
+ }
1968
+ #else
1969
+ pixel::native_t *dst = &pixels_[rowToPhysical(y) * stride_ + ax];
1970
+ if (globalAlpha_ == 255) {
1971
+ const int count = bx - ax + 1;
1972
+ int runStart = -1;
1973
+ for (int i = 0; i < count; i++) {
1974
+ if (dst[i] == c) {
1975
+ if (runStart >= 0) {
1976
+ markDirty(ax + runStart, y, ax + i - 1, y);
1977
+ runStart = -1;
1978
+ }
1979
+ continue;
1980
+ }
1981
+ if (runStart < 0) runStart = i;
1982
+ dst[i] = c;
1983
+ }
1984
+ if (runStart >= 0) markDirty(ax + runStart, y, bx, y);
1985
+ } else if (globalAlpha_ != 0) {
1986
+ const int a = globalAlpha_;
1987
+ for (int px = ax; px <= bx; px++, dst++) *dst = pixel::blendNative(c, *dst, a);
1988
+ }
1989
+ #endif
1990
+ }
1991
+ }
1992
+
1993
+ // Present-replay variant: each flush chunk starts from scratch, so fillTriangle's
1994
+ // persistent-surface bookkeeping (per-pixel dst-compare + run-based markDirty)
1995
+ // is pure overhead there — flat span fills, one bbox markDirty.
1996
+ // Edges step incrementally in 48.16 fixed point: one divide per edge instead of
1997
+ // two float divides per scanline. The present replay rasterizes thousands of
1998
+ // triangle rows per frame and those divides dominated the raster time. 64-bit
1999
+ // accumulators keep arbitrary int coordinates overflow-safe.
2000
+ void Canvas::fillTriangleOpaque(int x0, int y0, int x1, int y1, int x2, int y2, pixel::native_t color)
2001
+ {
2002
+ if (!pixels_) return;
2003
+ if (y0 > y1) { std::swap(x0, x1); std::swap(y0, y1); }
2004
+ if (y0 > y2) { std::swap(x0, x2); std::swap(y0, y2); }
2005
+ if (y1 > y2) { std::swap(x1, x2); std::swap(y1, y2); }
2006
+ const int total_h = y2 - y0;
2007
+ if (total_h == 0) {
2008
+ int mn = x0 < x1 ? (x0 < x2 ? x0 : x2) : (x1 < x2 ? x1 : x2);
2009
+ int mx = x0 > x1 ? (x0 > x2 ? x0 : x2) : (x1 > x2 ? x1 : x2);
2010
+ fillRectOpaque(mn, y0, mx - mn + 1, 1, color);
2011
+ return;
2012
+ }
2013
+ const ClipRect *clip = &clipStack_[clipDepth_];
2014
+ int draw_y0 = y0;
2015
+ int draw_y1 = y2;
2016
+ if (draw_y0 < clip->y0) draw_y0 = clip->y0;
2017
+ if (draw_y1 > clip->y1) draw_y1 = clip->y1;
2018
+ if (draw_y0 < 0) draw_y0 = 0;
2019
+ if (draw_y1 >= height_) draw_y1 = height_ - 1;
2020
+ if (draw_y0 > draw_y1) return;
2021
+ int clip_x0 = clip->x0 < 0 ? 0 : clip->x0;
2022
+ int clip_x1 = clip->x1 >= width_ ? width_ - 1 : clip->x1;
2023
+ if (clip_x0 > clip_x1) return;
2024
+
2025
+ // Long edge y0→y2 spans both segments with one continuous accumulator, so
2026
+ // the two mesh triangles sharing it rasterize identical columns (no cracks).
2027
+ const std::int64_t stepA = ((static_cast<std::int64_t>(x2) - x0) << 16) / total_h;
2028
+ std::int64_t accA = (static_cast<std::int64_t>(x0) << 16) + stepA * (draw_y0 - y0);
2029
+
2030
+ int dirty_x0 = width_;
2031
+ int dirty_x1 = -1;
2032
+ auto rasterRows = [&](int yStart, int yEnd, std::int64_t accB, std::int64_t stepB) {
2033
+ for (int y = yStart; y <= yEnd; y++) {
2034
+ int ax = static_cast<int>(accA >> 16);
2035
+ int bx = static_cast<int>(accB >> 16);
2036
+ accA += stepA;
2037
+ accB += stepB;
2038
+ if (ax > bx) { const int t = ax; ax = bx; bx = t; }
2039
+ if (ax < clip_x0) ax = clip_x0;
2040
+ if (bx > clip_x1) bx = clip_x1;
2041
+ if (ax > bx) continue;
2042
+ fillSpanColor(rowToPhysical(y), ax, bx - ax + 1, color);
2043
+ if (ax < dirty_x0) dirty_x0 = ax;
2044
+ if (bx > dirty_x1) dirty_x1 = bx;
2045
+ }
2046
+ };
2047
+
2048
+ if (draw_y0 < y1) {
2049
+ // Upper segment rows [y0, y1): draw_y0 < y1 with draw_y0 >= y0 implies y1 > y0.
2050
+ const int yEnd = draw_y1 < y1 - 1 ? draw_y1 : y1 - 1;
2051
+ const std::int64_t stepB = ((static_cast<std::int64_t>(x1) - x0) << 16) / (y1 - y0);
2052
+ const std::int64_t accB = (static_cast<std::int64_t>(x0) << 16) + stepB * (draw_y0 - y0);
2053
+ rasterRows(draw_y0, yEnd, accB, stepB);
2054
+ }
2055
+ if (draw_y1 >= y1) {
2056
+ // Lower segment rows [y1, y2]; accA is already positioned at yStart.
2057
+ const int yStart = draw_y0 > y1 ? draw_y0 : y1;
2058
+ const int segh = y2 - y1;
2059
+ const std::int64_t stepB = segh > 0 ? ((static_cast<std::int64_t>(x2) - x1) << 16) / segh : 0;
2060
+ const std::int64_t accB = (static_cast<std::int64_t>(x1) << 16) + stepB * (yStart - y1);
2061
+ rasterRows(yStart, draw_y1, accB, stepB);
2062
+ }
2063
+ if (dirty_x1 >= dirty_x0) markDirty(dirty_x0, draw_y0, dirty_x1, draw_y1);
2064
+ }
2065
+
2066
+ void Canvas::fillTrianglesOpaqueOccluded(const TriangleEntry *tris, int count, int ox, int oy)
2067
+ {
2068
+ if (!pixels_ || count <= 0) return;
2069
+ const int rows = height_;
2070
+ // Fall back to painter's back-to-front when the chunk exceeds the coverage
2071
+ // scratch (only gea3d's small half-res chunks take the occluded path).
2072
+ if (rows <= 0 || rows > kOcclMaxRows || width_ > kOcclWords * 32) {
2073
+ for (int i = 0; i < count; i++) {
2074
+ const TriangleEntry &t = tris[i];
2075
+ fillTriangleOpaque(t.x0 - ox, t.y0 - oy, t.x1 - ox, t.y1 - oy,
2076
+ t.x2 - ox, t.y2 - oy, t.color);
2077
+ }
2078
+ return;
2079
+ }
2080
+ const int bank = occlCoreBank();
2081
+ std::uint32_t (*cov)[kOcclWords] = s_occlBits[bank];
2082
+ std::memset(cov, 0, sizeof(std::uint32_t) * static_cast<std::size_t>(rows) * kOcclWords);
2083
+
2084
+ const ClipRect *clip = &clipStack_[clipDepth_];
2085
+ const int clip_x0 = clip->x0 < 0 ? 0 : clip->x0;
2086
+ const int clip_x1 = clip->x1 >= width_ ? width_ - 1 : clip->x1;
2087
+ if (clip_x0 > clip_x1) return;
2088
+ const int clip_y0 = clip->y0 < 0 ? 0 : clip->y0;
2089
+ const int clip_y1 = clip->y1 >= rows ? rows - 1 : clip->y1;
2090
+
2091
+ int dirty_x0 = width_, dirty_x1 = -1, dirty_y0 = rows, dirty_y1 = -1;
2092
+
2093
+ // Fill only the uncovered pixels of chunk-local span [ax,bx] on row yl, then
2094
+ // mark [ax,bx] covered. Word-scan the row bitmask: each contiguous 0-bit run
2095
+ // becomes one fillSpanColor; occluded pixels cost only the bit test.
2096
+ auto fillCovered = [&](int yl, int ax, int bx, pixel::native_t color) {
2097
+ std::uint32_t *bits = cov[yl];
2098
+ const int phys = rowToPhysical(yl);
2099
+ int x = ax;
2100
+ while (x <= bx) {
2101
+ const int wi = x >> 5;
2102
+ const int wordLast = ((wi + 1) << 5) - 1; // last x index in this word
2103
+ const int hi = wordLast < bx ? wordLast : bx;
2104
+ const int nbits = hi - x + 1;
2105
+ const std::uint32_t rangeMask =
2106
+ (nbits >= 32) ? 0xFFFFFFFFu : (((1u << nbits) - 1u) << (x & 31));
2107
+ const std::uint32_t word = bits[wi];
2108
+ if ((word & rangeMask) == 0) {
2109
+ fillSpanColor(phys, x, nbits, color); // whole word-chunk uncovered
2110
+ } else if ((~word & rangeMask) != 0) {
2111
+ // mixed: fill the uncovered bit-runs within [x, hi]
2112
+ int xx = x;
2113
+ while (xx <= hi) {
2114
+ while (xx <= hi && (word & (1u << (xx & 31)))) xx++;
2115
+ if (xx > hi) break;
2116
+ const int rs = xx;
2117
+ while (xx <= hi && !(word & (1u << (xx & 31)))) xx++;
2118
+ fillSpanColor(phys, rs, xx - rs, color);
2119
+ }
2120
+ } // else: fully covered — nothing to fill
2121
+ bits[wi] = word | rangeMask;
2122
+ x = hi + 1;
2123
+ }
2124
+ if (ax < dirty_x0) dirty_x0 = ax;
2125
+ if (bx > dirty_x1) dirty_x1 = bx;
2126
+ if (yl < dirty_y0) dirty_y0 = yl;
2127
+ if (yl > dirty_y1) dirty_y1 = yl;
2128
+ };
2129
+
2130
+ // Nearest-first: the batch is farthest-first (painter's), so walk it in reverse.
2131
+ for (int ti = count - 1; ti >= 0; ti--) {
2132
+ int x0 = tris[ti].x0 - ox, y0 = tris[ti].y0 - oy;
2133
+ int x1 = tris[ti].x1 - ox, y1 = tris[ti].y1 - oy;
2134
+ int x2 = tris[ti].x2 - ox, y2 = tris[ti].y2 - oy;
2135
+ const pixel::native_t color = tris[ti].color;
2136
+ if (y0 > y1) { std::swap(x0, x1); std::swap(y0, y1); }
2137
+ if (y0 > y2) { std::swap(x0, x2); std::swap(y0, y2); }
2138
+ if (y1 > y2) { std::swap(x1, x2); std::swap(y1, y2); }
2139
+ int dy0 = y0 < clip_y0 ? clip_y0 : y0;
2140
+ int dy1 = y2 > clip_y1 ? clip_y1 : y2;
2141
+ if (dy0 > dy1) continue;
2142
+ const int total_h = y2 - y0;
2143
+ if (total_h == 0) {
2144
+ int mn = x0 < x1 ? (x0 < x2 ? x0 : x2) : (x1 < x2 ? x1 : x2);
2145
+ int mx = x0 > x1 ? (x0 > x2 ? x0 : x2) : (x1 > x2 ? x1 : x2);
2146
+ if (mn < clip_x0) mn = clip_x0;
2147
+ if (mx > clip_x1) mx = clip_x1;
2148
+ if (mn <= mx) fillCovered(y0, mn, mx, color);
2149
+ continue;
2150
+ }
2151
+ const std::int64_t stepA = ((static_cast<std::int64_t>(x2) - x0) << 16) / total_h;
2152
+ std::int64_t accA = (static_cast<std::int64_t>(x0) << 16) + stepA * (dy0 - y0);
2153
+ auto walk = [&](int yStart, int yEnd, std::int64_t accB, std::int64_t stepB) {
2154
+ for (int y = yStart; y <= yEnd; y++) {
2155
+ int ax = static_cast<int>(accA >> 16);
2156
+ int bx = static_cast<int>(accB >> 16);
2157
+ accA += stepA;
2158
+ accB += stepB;
2159
+ if (ax > bx) { const int t = ax; ax = bx; bx = t; }
2160
+ if (ax < clip_x0) ax = clip_x0;
2161
+ if (bx > clip_x1) bx = clip_x1;
2162
+ if (ax > bx) continue;
2163
+ fillCovered(y, ax, bx, color);
2164
+ }
2165
+ };
2166
+ if (dy0 < y1) {
2167
+ const int yEnd = dy1 < y1 - 1 ? dy1 : y1 - 1;
2168
+ const std::int64_t stepB = ((static_cast<std::int64_t>(x1) - x0) << 16) / (y1 - y0);
2169
+ const std::int64_t accB = (static_cast<std::int64_t>(x0) << 16) + stepB * (dy0 - y0);
2170
+ walk(dy0, yEnd, accB, stepB);
2171
+ }
2172
+ if (dy1 >= y1) {
2173
+ const int yStart = dy0 > y1 ? dy0 : y1;
2174
+ const int segh = y2 - y1;
2175
+ const std::int64_t stepB = segh > 0 ? ((static_cast<std::int64_t>(x2) - x1) << 16) / segh : 0;
2176
+ const std::int64_t accB = (static_cast<std::int64_t>(x1) << 16) + stepB * (yStart - y1);
2177
+ walk(yStart, dy1, accB, stepB);
2178
+ }
2179
+ }
2180
+ if (dirty_x1 >= dirty_x0 && dirty_y1 >= dirty_y0) markDirty(dirty_x0, dirty_y0, dirty_x1, dirty_y1);
2181
+ }
2182
+
2183
+ void Canvas::drawText(const char *text, int x, int y, pixel::native_t color, float scale)
2184
+ {
2185
+ if (!pixels_ || !text) return;
2186
+ if (scale < 0.1f) scale = 1.0f;
2187
+ int glyph_w = (int)(kBitmapFontWidth * scale + 0.5f);
2188
+ int glyph_h = (int)(kBitmapFontHeight * scale + 0.5f);
2189
+ if (glyph_w < 1) glyph_w = 1;
2190
+ if (glyph_h < 1) glyph_h = 1;
2191
+
2192
+ const ClipRect *clip = &clipStack_[clipDepth_];
2193
+ int pen_x = x;
2194
+ // One cell per CODEPOINT. Walking bytes drew a 3-byte UTF-8 sequence as three
2195
+ // cells, each byte an out-of-range codepoint the font substitutes with '?' --
2196
+ // so a lone em dash painted "???". Every measurement path already charges one
2197
+ // cell per codepoint (`measureBitmap` wraps through `nextWrappedLine`), so the
2198
+ // byte loop also disagreed with the layout that placed the text.
2199
+ for (const char *p = text; *p;) {
2200
+ const int cp = nextUtf8Codepoint(p);
2201
+ if (cp == '\n') { pen_x = x; y += glyph_h; continue; }
2202
+ if (pen_x > clip->x1 || y > clip->y1 ||
2203
+ pen_x + glyph_w - 1 < clip->x0 || y + glyph_h - 1 < clip->y0) {
2204
+ pen_x += glyph_w;
2205
+ continue;
2206
+ }
2207
+ const std::uint8_t *glyph = FontRegistry::bitmap8x16().glyphRows(cp);
2208
+
2209
+ int dy_start = 0, dy_end = glyph_h - 1;
2210
+ int dx_start = 0, dx_end = glyph_w - 1;
2211
+ if (y + dy_start < clip->y0) dy_start = clip->y0 - y;
2212
+ if (y + dy_end > clip->y1) dy_end = clip->y1 - y;
2213
+ if (pen_x + dx_start < clip->x0) dx_start = clip->x0 - pen_x;
2214
+ if (pen_x + dx_end > clip->x1) dx_end = clip->x1 - pen_x;
2215
+ if (y + dy_start < 0) dy_start = -y;
2216
+ if (pen_x + dx_start < 0) dx_start = -pen_x;
2217
+ if (y + dy_end >= height_) dy_end = height_ - 1 - y;
2218
+ if (pen_x + dx_end >= width_) dx_end = width_ - 1 - pen_x;
2219
+
2220
+ if (globalAlpha_ == 255) {
2221
+ for (int srow = 0; srow < kBitmapFontHeight; srow++) {
2222
+ std::uint8_t bits = glyph[srow];
2223
+ if (!bits) continue;
2224
+ int by0 = srow * glyph_h / kBitmapFontHeight;
2225
+ int by1 = (srow + 1) * glyph_h / kBitmapFontHeight - 1;
2226
+ if (by0 > dy_end || by1 < dy_start) continue;
2227
+ if (by0 < dy_start) by0 = dy_start;
2228
+ if (by1 > dy_end) by1 = dy_end;
2229
+ for (int scol = 0; scol < kBitmapFontWidth; scol++) {
2230
+ if (!(bits & (0x80 >> scol))) continue;
2231
+ int bx0 = scol * glyph_w / kBitmapFontWidth;
2232
+ int bx1 = (scol + 1) * glyph_w / kBitmapFontWidth - 1;
2233
+ if (bx0 > dx_end || bx1 < dx_start) continue;
2234
+ if (bx0 < dx_start) bx0 = dx_start;
2235
+ if (bx1 > dx_end) bx1 = dx_end;
2236
+ int span = bx1 - bx0 + 1;
2237
+ for (int by = by0; by <= by1; by++) {
2238
+ fillSpanColor(rowToPhysical(y + by), pen_x + bx0, span, color);
2239
+ }
2240
+ }
2241
+ }
2242
+ } else if (globalAlpha_ != 0) {
2243
+ for (int srow = 0; srow < kBitmapFontHeight; srow++) {
2244
+ std::uint8_t bits = glyph[srow];
2245
+ if (!bits) continue;
2246
+ int by0 = srow * glyph_h / kBitmapFontHeight;
2247
+ int by1 = (srow + 1) * glyph_h / kBitmapFontHeight - 1;
2248
+ if (by0 > dy_end || by1 < dy_start) continue;
2249
+ if (by0 < dy_start) by0 = dy_start;
2250
+ if (by1 > dy_end) by1 = dy_end;
2251
+ for (int scol = 0; scol < kBitmapFontWidth; scol++) {
2252
+ if (!(bits & (0x80 >> scol))) continue;
2253
+ int bx0 = scol * glyph_w / kBitmapFontWidth;
2254
+ int bx1 = (scol + 1) * glyph_w / kBitmapFontWidth - 1;
2255
+ if (bx0 > dx_end || bx1 < dx_start) continue;
2256
+ if (bx0 < dx_start) bx0 = dx_start;
2257
+ if (bx1 > dx_end) bx1 = dx_end;
2258
+ for (int by = by0; by <= by1; by++) {
2259
+ fillSpanGlobalAlpha(rowToPhysical(y + by), pen_x + bx0, bx1 - bx0 + 1, color);
2260
+ }
2261
+ }
2262
+ }
2263
+ }
2264
+ markDirty(pen_x + dx_start, y + dy_start,
2265
+ pen_x + dx_end, y + dy_end);
2266
+ pen_x += glyph_w;
2267
+ }
2268
+ }
2269
+
2270
+ #ifdef GEA_EMBEDDED_HAS_GENERATED_FONTS
2271
+ /* ---- Rasterized font rendering ---- */
2272
+
2273
+ void Canvas::drawTextFont(const char *text, int x, int y, pixel::native_t color, int font_id)
2274
+ {
2275
+ drawRasterizedText(text, x, y, color, FontRegistry::rasterized(font_id));
2276
+ }
2277
+
2278
+ void Canvas::drawTextFontFamily(const char *text, int x, int y, pixel::native_t color, int family_id, int size_px)
2279
+ {
2280
+ drawRasterizedText(text, x, y, color, FontRegistry::rasterizedFamily(family_id, size_px));
2281
+ }
2282
+
2283
+ // Sum the glyph advances for a string in a family/size, so callers can centre
2284
+ // or right-align text. The canvas API has no measureText, which forced callers
2285
+ // to hand-tune a width factor per string -- workable for one fixed readout,
2286
+ // wrong for anything variable ("VLC" vs "Pocket Casts").
2287
+ void Canvas::drawTextFontFamilyRotated90(const char *text, int lx, int ly, pixel::native_t color, int family_id, int size_px)
2288
+ {
2289
+ if (!pixels_ || !text) return;
2290
+ #if GEA_EMBEDDED_DISPLAY_ROTATE_LANDSCAPE
2291
+ // This primitive already rotates landscape-authored text onto a PORTRAIT panel
2292
+ // buffer, so it is meaningless (and out-of-bounds) against a landscape-native
2293
+ // rotated binding. It is only used by the P4 DSI targets, never a rotated one.
2294
+ if (landscapeRot_) return;
2295
+ #endif
2296
+ RasterizedFont font = FontRegistry::rasterizedFamily(family_id, size_px);
2297
+ if (!font.valid()) return;
2298
+
2299
+ int pen_x = lx;
2300
+ int pen_y = ly;
2301
+ for (const char *p = text; *p;) {
2302
+ const int cp = nextUtf8Codepoint(p);
2303
+ if (cp == '\n') { pen_x = lx; pen_y += font.lineHeight(); continue; }
2304
+ Glyph glyph{};
2305
+ if (!font.glyph(cp, &glyph)) { pen_x += font.sizePx() / 2; continue; }
2306
+ const int gx = pen_x + glyph.bearingX;
2307
+ const int gy = pen_y + font.ascender() - glyph.bearingY;
2308
+ const pixel::native_t c = color;
2309
+ for (int row = 0; row < glyph.height; row++) {
2310
+ const int l_y = gy + row;
2311
+ // landscape x advances along glyph columns; transform per pixel.
2312
+ for (int col = 0; col < glyph.width; col++) {
2313
+ const int l_x = gx + col;
2314
+ const int panel_x = l_y;
2315
+ const int panel_y = height_ - 1 - l_x;
2316
+ if (panel_x < 0 || panel_x >= width_ || panel_y < 0 || panel_y >= height_) continue;
2317
+ int alpha = font.coverage(glyph, row, col);
2318
+ if (alpha == 0) continue;
2319
+ std::uint8_t a = (globalAlpha_ == 255) ? alpha : (alpha * globalAlpha_) / 255;
2320
+ if (a == 0) continue;
2321
+ #if GEA_PIXEL_STORAGE_PACKED
2322
+ pixel::packed::blendPixel(packedRow(rowToPhysical(panel_y)), panel_x, c, a);
2323
+ #else
2324
+ pixel::native_t *pixel = &pixels_[rowToPhysical(panel_y) * stride_ + panel_x];
2325
+ *pixel = (a == 255) ? c : pixel::blendNative(c, *pixel, a);
2326
+ #endif
2327
+ }
2328
+ }
2329
+ pen_x += glyph.advance;
2330
+ }
2331
+ }
2332
+
2333
+ void Canvas::drawTextFontFamilyOnBackground(const char *text, int x, int y, pixel::native_t color,
2334
+ int family_id, int size_px, pixel::native_t background)
2335
+ {
2336
+ if (!pixels_ || !text) return;
2337
+ if (globalAlpha_ != 255) {
2338
+ drawTextFontFamily(text, x, y, color, family_id, size_px);
2339
+ return;
2340
+ }
2341
+
2342
+ RasterizedFont font = FontRegistry::rasterizedFamily(family_id, size_px);
2343
+ if (!font.valid()) return;
2344
+
2345
+ const ClipRect *clip = &clipStack_[clipDepth_];
2346
+ const int clipX0 = std::max(0, clip->x0);
2347
+ const int clipY0 = std::max(0, clip->y0);
2348
+ const int clipX1 = std::min(width_ - 1, clip->x1);
2349
+ const int clipY1 = std::min(height_ - 1, clip->y1);
2350
+ if (clipX0 > clipX1 || clipY0 > clipY1) return;
2351
+
2352
+ int penX = x;
2353
+ int penY = y;
2354
+
2355
+ for (const char *p = text; *p;) {
2356
+ const int cp = nextUtf8Codepoint(p);
2357
+ if (cp == '\n') {
2358
+ penX = x;
2359
+ penY += font.lineHeight();
2360
+ continue;
2361
+ }
2362
+
2363
+ SolidGlyphCacheEntry *entry = solidGlyphCacheEntry(font, color, background, cp);
2364
+ if (!entry) {
2365
+ penX += font.sizePx() / 2;
2366
+ continue;
2367
+ }
2368
+
2369
+ const Glyph &glyph = entry->glyph;
2370
+ const int gx = penX + glyph.bearingX;
2371
+ const int gy = penY + font.ascender() - glyph.bearingY;
2372
+ if (gx > clipX1 || gy > clipY1 ||
2373
+ gx + glyph.width - 1 < clipX0 || gy + glyph.height - 1 < clipY0) {
2374
+ penX += glyph.advance;
2375
+ continue;
2376
+ }
2377
+
2378
+ int dirtyX0 = width_;
2379
+ int dirtyY0 = height_;
2380
+ int dirtyX1 = -1;
2381
+ int dirtyY1 = -1;
2382
+
2383
+ for (const SolidGlyphRow &span : entry->rows) {
2384
+ const int py = gy + span.row;
2385
+ if (py < clipY0 || py > clipY1) continue;
2386
+
2387
+ const int sx0 = gx + span.start;
2388
+ const int sx1 = sx0 + span.width - 1;
2389
+ if (sx0 > clipX1 || sx1 < clipX0) continue;
2390
+
2391
+ const int copyX0 = std::max(sx0, clipX0);
2392
+ const int copyX1 = std::min(sx1, clipX1);
2393
+ const int copyCount = copyX1 - copyX0 + 1;
2394
+ const int srcOffset = span.offset + (copyX0 - sx0);
2395
+ const pixel::native_t *src = &entry->pixels[static_cast<std::size_t>(srcOffset)];
2396
+ // Glyph cache is native pixels — a straight native row copy unless the
2397
+ // framebuffer is bound through the landscape transform.
2398
+ #if GEA_EMBEDDED_DISPLAY_ROTATE_LANDSCAPE
2399
+ if (landscapeRot_) {
2400
+ for (int i = 0; i < copyCount; ++i) rotSet(copyX0 + i, py, src[i]);
2401
+ } else {
2402
+ #endif
2403
+ #if GEA_PIXEL_STORAGE_PACKED
2404
+ pixel::packed::writeUnpacked(packedRow(rowToPhysical(py)), copyX0, src, copyCount);
2405
+ #else
2406
+ std::memcpy(&pixels_[rowToPhysical(py) * stride_ + copyX0], src,
2407
+ static_cast<std::size_t>(copyCount) * sizeof(pixel::native_t));
2408
+ #endif
2409
+ #if GEA_EMBEDDED_DISPLAY_ROTATE_LANDSCAPE
2410
+ }
2411
+ #endif
2412
+
2413
+ if (copyX0 < dirtyX0) dirtyX0 = copyX0;
2414
+ if (copyX1 > dirtyX1) dirtyX1 = copyX1;
2415
+ if (py < dirtyY0) dirtyY0 = py;
2416
+ if (py > dirtyY1) dirtyY1 = py;
2417
+ }
2418
+
2419
+ if (dirtyX0 <= dirtyX1 && dirtyY0 <= dirtyY1) markDirty(dirtyX0, dirtyY0, dirtyX1, dirtyY1);
2420
+ penX += glyph.advance;
2421
+ }
2422
+ }
2423
+
2424
+ // DIAG (compile-gated, off by default; define GEA_EMBEDDED_TEXT_SPRITE_DIAG=1):
2425
+ // per-path counters + us split for the text sprite cache, printed once per ~300
2426
+ // calls. Answers, on device, whether the cache engages for the bouncing-balls FPS
2427
+ // badge and how blit time compares to raster.
2428
+ #if GEA_EMBEDDED_TEXT_SPRITE_DIAG
2429
+ #ifdef ESP_PLATFORM
2430
+ static inline std::int64_t tsDiagNowUs() { return esp_timer_get_time(); }
2431
+ static inline std::uint32_t tsDiagCyc() { return esp_cpu_get_cycle_count(); }
2432
+ #else
2433
+ static inline std::int64_t tsDiagNowUs()
2434
+ {
2435
+ return std::chrono::duration_cast<std::chrono::microseconds>(
2436
+ std::chrono::steady_clock::now().time_since_epoch()).count();
2437
+ }
2438
+ static inline std::uint32_t tsDiagCyc() { return 0; }
2439
+ #endif
2440
+ namespace {
2441
+ struct TsDiag {
2442
+ int calls = 0, gateOff = 0, small = 0, tooLong = 0, blit = 0, built = 0, seen = 0, raster = 0, hot = 0;
2443
+ long long blitUs = 0, rasterUs = 0;
2444
+ // Last-blit sprite state: is the RLE fast path live, and how big is the sprite?
2445
+ int rleValid = -1, w = 0, h = 0, runs = 0;
2446
+ // Inside-blit phase accounting (cycle counter; cheap enough per run/row).
2447
+ long long rows = 0, rowsClip = 0, runsWalked = 0, fillPx = 0, blendPx = 0;
2448
+ long long walkCyc = 0, fillCyc = 0, blendCyc = 0;
2449
+ };
2450
+ TsDiag gTsDiag;
2451
+ }
2452
+ #endif
2453
+
2454
+ #if GEA_PIXEL_STORAGE_PACKED_BITS == 4
2455
+ namespace {
2456
+
2457
+ // Direct-mapped pre-packed glyph cache (see gTextStampEnabled above). Each entry
2458
+ // holds the glyph pre-blended over the declared backdrop, packed 2 px/byte, in
2459
+ // both x-parities so a stamp at any x is straight byte copies.
2460
+ constexpr int kGlyphStampSlots = 256;
2461
+
2462
+ struct PackedGlyphStamp {
2463
+ const RasterizedFontData *fontData = nullptr;
2464
+ int sizePx = 0;
2465
+ int codepoint = 0;
2466
+ std::uint8_t fg = 0xFF; // native 0..15 level; 0xFF = empty slot
2467
+ std::uint8_t backdrop = 0xFF;
2468
+ std::int16_t w = 0, h = 0;
2469
+ std::uint8_t *rows[2] = {nullptr, nullptr}; // [parity of gx]
2470
+ std::int16_t rowBytes[2] = {0, 0};
2471
+ std::size_t cap[2] = {0, 0};
2472
+ };
2473
+
2474
+ PackedGlyphStamp gGlyphStamps[kGlyphStampSlots];
2475
+
2476
+ inline int glyphStampSlot(const RasterizedFontData *fd, int sizePx, int cp)
2477
+ {
2478
+ std::uint32_t h = static_cast<std::uint32_t>(reinterpret_cast<std::uintptr_t>(fd));
2479
+ h = h * 31u + static_cast<std::uint32_t>(sizePx);
2480
+ h = h * 31u + static_cast<std::uint32_t>(cp);
2481
+ h ^= h >> 13;
2482
+ return static_cast<int>(h % kGlyphStampSlots);
2483
+ }
2484
+
2485
+ void glyphStampCacheReset()
2486
+ {
2487
+ for (auto &e : gGlyphStamps) e.fg = 0xFF; // buffers stay for reuse
2488
+ }
2489
+
2490
+ bool buildPackedGlyphStamp(PackedGlyphStamp &e, const gea::framework::graphics::RasterizedFont &font,
2491
+ const gea::framework::graphics::Glyph &glyph, int cp,
2492
+ std::uint8_t fg, std::uint8_t backdrop)
2493
+ {
2494
+ const int w = glyph.width, h = glyph.height;
2495
+ if (w <= 0 || h <= 0 || w > 512 || h > 512) return false;
2496
+ for (int parity = 0; parity < 2; parity++) {
2497
+ const int rb = (w + parity + 1) >> 1;
2498
+ const std::size_t need = static_cast<std::size_t>(rb) * h;
2499
+ if (e.cap[parity] < need) {
2500
+ std::uint8_t *grown = static_cast<std::uint8_t *>(std::realloc(e.rows[parity], need));
2501
+ if (!grown) return false;
2502
+ e.rows[parity] = grown;
2503
+ e.cap[parity] = need;
2504
+ }
2505
+ e.rowBytes[parity] = static_cast<std::int16_t>(rb);
2506
+ for (int row = 0; row < h; row++) {
2507
+ std::uint8_t *out = e.rows[parity] + static_cast<std::size_t>(row) * rb;
2508
+ if (parity) out[0] = 0;
2509
+ for (int col = 0; col < w; col++) {
2510
+ const std::uint8_t cov = font.coverage(glyph, row, col);
2511
+ const std::uint8_t v = cov == 0 ? backdrop
2512
+ : cov >= 248 ? fg
2513
+ : gea::framework::graphics::pixel::gray4Blend(fg, backdrop, cov);
2514
+ const int px = col + parity;
2515
+ std::uint8_t &byte = out[px >> 1];
2516
+ if (px & 1)
2517
+ byte = static_cast<std::uint8_t>((byte & 0xF0) | (v & 0x0F));
2518
+ else
2519
+ byte = static_cast<std::uint8_t>(v << 4);
2520
+ }
2521
+ }
2522
+ }
2523
+ e.fontData = font.data();
2524
+ e.sizePx = font.sizePx();
2525
+ e.codepoint = cp;
2526
+ e.fg = fg;
2527
+ e.backdrop = backdrop;
2528
+ e.w = static_cast<std::int16_t>(w);
2529
+ e.h = static_cast<std::int16_t>(h);
2530
+ return true;
2531
+ }
2532
+
2533
+ // Stamp one packed row at pixel gx: interior bytes are straight copies; only a
2534
+ // byte shared with a pixel OUTSIDE the glyph box (odd leading / even trailing
2535
+ // edge) merges with the destination.
2536
+ inline void stampPackedGlyphRow(std::uint8_t *dstRow, int gx, const std::uint8_t *src, int w)
2537
+ {
2538
+ const int parity = gx & 1;
2539
+ std::uint8_t *dst = dstRow + (gx >> 1);
2540
+ const int rb = (w + parity + 1) >> 1;
2541
+ int lead = 0;
2542
+ int trail = rb;
2543
+ const bool trailPartial = ((gx + w) & 1) != 0;
2544
+ if (parity) {
2545
+ dst[0] = static_cast<std::uint8_t>((dst[0] & 0xF0) | (src[0] & 0x0F));
2546
+ lead = 1;
2547
+ }
2548
+ if (trailPartial) trail = rb - 1;
2549
+ if (trail > lead) std::memcpy(dst + lead, src + lead, static_cast<std::size_t>(trail - lead));
2550
+ if (trailPartial && trail >= lead)
2551
+ dst[rb - 1] = static_cast<std::uint8_t>((dst[rb - 1] & 0x0F) | (src[rb - 1] & 0xF0));
2552
+ }
2553
+
2554
+ } // namespace
2555
+ #endif // GEA_PIXEL_STORAGE_PACKED_BITS == 4
2556
+
2557
+ void Canvas::drawRasterizedText(const char *text, int x, int y, pixel::native_t color, const RasterizedFont &font)
2558
+ {
2559
+ if (!pixels_ || !text || !font.valid()) return;
2560
+ const ClipRect *clip = &clipStack_[clipDepth_];
2561
+
2562
+ #if GEA_EMBEDDED_TEXT_SPRITE_DIAG
2563
+ gTsDiag.calls++;
2564
+ if (!gTextRasterCacheEnabled) gTsDiag.gateOff++;
2565
+ else if (font.sizePx() < kTextSpriteMinSizePx) gTsDiag.small++;
2566
+ if ((gTsDiag.calls % 300) == 0)
2567
+ std::printf("TSDIAG calls=%d gateOff=%d small=%d tooLong=%d blit=%d hot=%d built=%d seen=%d raster=%d blitUs=%lld rasterUs=%lld sz=%d len=%d rle=%d w=%d h=%d runs=%d rows=%lld rowsClip=%lld runsW=%lld fillPx=%lld blendPx=%lld walkUs=%lld fillUs=%lld blendUs=%lld\n",
2568
+ gTsDiag.calls, gTsDiag.gateOff, gTsDiag.small, gTsDiag.tooLong, gTsDiag.blit, gTsDiag.hot,
2569
+ gTsDiag.built, gTsDiag.seen, gTsDiag.raster, gTsDiag.blitUs, gTsDiag.rasterUs,
2570
+ font.sizePx(), (int)std::strlen(text), gTsDiag.rleValid, gTsDiag.w, gTsDiag.h, gTsDiag.runs,
2571
+ gTsDiag.rows, gTsDiag.rowsClip, gTsDiag.runsWalked, gTsDiag.fillPx, gTsDiag.blendPx,
2572
+ gTsDiag.walkCyc / 240, gTsDiag.fillCyc / 240, gTsDiag.blendCyc / 240);
2573
+ #endif
2574
+
2575
+ #if GEA_EMBEDDED_TEXT_SPRITE_CACHE
2576
+ // Large static text: blit a cached coverage sprite instead of re-rasterizing
2577
+ // the glyphs from the flash atlas every frame. See the cache comment above.
2578
+ // Opt-in per app via Display.setTextRasterCache(true).
2579
+ if (gTextRasterCacheEnabled && font.sizePx() >= kTextSpriteMinSizePx) {
2580
+ const std::size_t len = std::strlen(text);
2581
+ #if GEA_EMBEDDED_TEXT_SPRITE_DIAG
2582
+ if (len == 0 || len > static_cast<std::size_t>(kTextSpriteMaxLen)) gTsDiag.tooLong++;
2583
+ #endif
2584
+ if (len > 0 && len <= static_cast<std::size_t>(kTextSpriteMaxLen)) {
2585
+ TextSprite &slot = gTextSprites[hashTextContent(text) % kTextSpriteSlots];
2586
+ const bool idMatch = slot.fontData == font.data() &&
2587
+ slot.sizePx == font.sizePx() &&
2588
+ std::strcmp(slot.text, text) == 0;
2589
+ if (idMatch && slot.state == TextSprite::Cached) {
2590
+ #if GEA_EMBEDDED_TEXT_SPRITE_DIAG
2591
+ gTsDiag.blit++;
2592
+ gTsDiag.rleValid = slot.rleValid ? 1 : 0;
2593
+ gTsDiag.w = slot.w;
2594
+ gTsDiag.h = slot.h;
2595
+ gTsDiag.runs = (slot.rleValid && slot.rleRowStart) ? (int)slot.rleRowStart[slot.h] : 0;
2596
+ const std::int64_t __t0 = tsDiagNowUs();
2597
+ #endif
2598
+ const std::int16_t *bRowX0 = slot.rowX0;
2599
+ const std::int16_t *bRowX1 = slot.rowX1;
2600
+ const std::uint8_t *bVal = slot.rleValid ? slot.rleVal : nullptr;
2601
+ const std::uint16_t *bLen = slot.rleValid ? slot.rleLen : nullptr;
2602
+ const std::int32_t *bStart = slot.rleValid ? slot.rleRowStart : nullptr;
2603
+ #if GEA_EMBEDDED_TEXT_SPRITE_HOT_STAGE_BYTES > 0
2604
+ if (slot.rleValid) {
2605
+ if (gHotTextSprite.owner != &slot) adoptHotTextSprite(slot);
2606
+ if (gHotTextSprite.owner == &slot) {
2607
+ bRowX0 = gHotTextSprite.rowX0;
2608
+ bRowX1 = gHotTextSprite.rowX1;
2609
+ bVal = gHotTextSprite.rleVal;
2610
+ bLen = gHotTextSprite.rleLen;
2611
+ bStart = gHotTextSprite.rleRowStart;
2612
+ #if GEA_EMBEDDED_TEXT_SPRITE_DIAG
2613
+ gTsDiag.hot++;
2614
+ #endif
2615
+ }
2616
+ }
2617
+ #endif
2618
+ blitGlyphSprite(slot.cov, bRowX0, bRowX1, bVal, bLen, bStart,
2619
+ slot.minLX, slot.minLY, slot.w, slot.h, x, y, color);
2620
+ #if GEA_EMBEDDED_TEXT_SPRITE_DIAG
2621
+ gTsDiag.blitUs += tsDiagNowUs() - __t0;
2622
+ #endif
2623
+ return;
2624
+ }
2625
+ if (idMatch && slot.state == TextSprite::Seen) {
2626
+ #if GEA_EMBEDDED_TEXT_SPRITE_HOT_STAGE_BYTES > 0
2627
+ // buildTextSprite may realloc the arrays a stale staging copy points at.
2628
+ if (gHotTextSprite.owner == &slot) gHotTextSprite.owner = nullptr;
2629
+ #endif
2630
+ // Second sighting: promote to a cached sprite and blit from it.
2631
+ if (buildTextSprite(slot, text, font)) {
2632
+ #if GEA_EMBEDDED_TEXT_SPRITE_DIAG
2633
+ gTsDiag.built++;
2634
+ #endif
2635
+ slot.state = TextSprite::Cached;
2636
+ blitGlyphSprite(slot.cov, slot.rowX0, slot.rowX1,
2637
+ slot.rleValid ? slot.rleVal : nullptr,
2638
+ slot.rleValid ? slot.rleLen : nullptr,
2639
+ slot.rleValid ? slot.rleRowStart : nullptr,
2640
+ slot.minLX, slot.minLY, slot.w, slot.h, x, y, color);
2641
+ return;
2642
+ }
2643
+ slot.state = TextSprite::Empty; // too large / OOM: stop trying for this text
2644
+ } else if (!idMatch) {
2645
+ // First sighting: claim the slot and render normally this time.
2646
+ slot.fontData = font.data();
2647
+ slot.sizePx = font.sizePx();
2648
+ std::strncpy(slot.text, text, kTextSpriteMaxLen);
2649
+ slot.text[kTextSpriteMaxLen] = '\0';
2650
+ slot.state = TextSprite::Seen;
2651
+ #if GEA_EMBEDDED_TEXT_SPRITE_DIAG
2652
+ gTsDiag.seen++;
2653
+ #endif
2654
+ }
2655
+ }
2656
+ }
2657
+ #endif
2658
+
2659
+ #if GEA_EMBEDDED_TEXT_SPRITE_DIAG
2660
+ gTsDiag.raster++;
2661
+ const std::int64_t __rasterT0 = tsDiagNowUs();
2662
+ struct __RasterUsScope {
2663
+ std::int64_t t0;
2664
+ ~__RasterUsScope() { gTsDiag.rasterUs += tsDiagNowUs() - t0; }
2665
+ } __rasterScope{__rasterT0};
2666
+ #endif
2667
+
2668
+ int pen_x = x;
2669
+ int pen_y = y;
2670
+
2671
+ for (const char *p = text; *p;) {
2672
+ const int cp = nextUtf8Codepoint(p);
2673
+ if (cp == '\n') { pen_x = x; pen_y += font.lineHeight(); continue; }
2674
+ Glyph glyph{};
2675
+ if (!font.glyph(cp, &glyph)) { pen_x += font.sizePx() / 2; continue; }
2676
+
2677
+ int gx = pen_x + glyph.bearingX;
2678
+ int gy = pen_y + font.ascender() - glyph.bearingY;
2679
+
2680
+ /* Skip glyph entirely if outside clip */
2681
+ if (gx > clip->x1 || gy > clip->y1 ||
2682
+ gx + glyph.width - 1 < clip->x0 || gy + glyph.height - 1 < clip->y0) {
2683
+ pen_x += glyph.advance;
2684
+ continue;
2685
+ }
2686
+
2687
+ /* Clip glyph row/col ranges */
2688
+ int row_start = 0, row_end = glyph.height - 1;
2689
+ int col_start = 0, col_end = glyph.width - 1;
2690
+ if (gy + row_start < clip->y0) row_start = clip->y0 - gy;
2691
+ if (gy + row_end > clip->y1) row_end = clip->y1 - gy;
2692
+ if (gx + col_start < clip->x0) col_start = clip->x0 - gx;
2693
+ if (gx + col_end > clip->x1) col_end = clip->x1 - gx;
2694
+ if (gy + row_start < 0) row_start = -gy;
2695
+ if (gx + col_start < 0) col_start = -gx;
2696
+ if (gy + row_end >= height_) row_end = height_ - 1 - gy;
2697
+ if (gx + col_end >= width_) col_end = width_ - 1 - gx;
2698
+
2699
+ #if GEA_PIXEL_STORAGE_PACKED_BITS == 4
2700
+ // Pre-packed stamp fast path: fully-visible glyph, full alpha, and a text
2701
+ // color distinct from the declared backdrop (equal = inverted row → true
2702
+ // blend below renders it correctly over the real background).
2703
+ if (gTextStampEnabled && globalAlpha_ == 255 &&
2704
+ #if GEA_EMBEDDED_DISPLAY_ROTATE_LANDSCAPE
2705
+ // The stamp fast path writes contiguous packed bytes per physical row,
2706
+ // which the 90° rotation breaks; fall through to the per-pixel blend.
2707
+ !landscapeRot_ &&
2708
+ #endif
2709
+ (color & 0x0F) != gTextStampBackdrop &&
2710
+ row_start == 0 && col_start == 0 &&
2711
+ row_end == glyph.height - 1 && col_end == glyph.width - 1) {
2712
+ const std::uint8_t fg4 = static_cast<std::uint8_t>(color & 0x0F);
2713
+ PackedGlyphStamp &e = gGlyphStamps[glyphStampSlot(font.data(), font.sizePx(), cp)];
2714
+ bool ready = e.fg == fg4 && e.backdrop == gTextStampBackdrop &&
2715
+ e.fontData == font.data() && e.sizePx == font.sizePx() &&
2716
+ e.codepoint == cp;
2717
+ if (!ready) {
2718
+ e.fg = 0xFF;
2719
+ ready = buildPackedGlyphStamp(e, font, glyph, cp, fg4, gTextStampBackdrop);
2720
+ }
2721
+ if (ready) {
2722
+ const int parity = gx & 1;
2723
+ const std::uint8_t *src = e.rows[parity];
2724
+ const int rb = e.rowBytes[parity];
2725
+ for (int row = 0; row < glyph.height; row++)
2726
+ stampPackedGlyphRow(packedRow(rowToPhysical(gy + row)), gx,
2727
+ src + static_cast<std::size_t>(row) * rb, glyph.width);
2728
+ markDirty(gx, gy, gx + glyph.width - 1, gy + glyph.height - 1);
2729
+ pen_x += glyph.advance;
2730
+ continue;
2731
+ }
2732
+ }
2733
+ #endif
2734
+
2735
+ const pixel::native_t c = color;
2736
+ for (int row = row_start; row <= row_end; row++) {
2737
+ int py = gy + row;
2738
+ #if GEA_EMBEDDED_DISPLAY_ROTATE_LANDSCAPE
2739
+ if (landscapeRot_) {
2740
+ for (int col = col_start; col <= col_end; col++) {
2741
+ int alpha = font.coverage(glyph, row, col);
2742
+ if (alpha == 0) continue;
2743
+ std::uint8_t a = (globalAlpha_ == 255) ? alpha : (alpha * globalAlpha_) / 255;
2744
+ if (a == 0) continue;
2745
+ rotBlend(gx + col, py, c, a);
2746
+ }
2747
+ continue;
2748
+ }
2749
+ #endif
2750
+ #if GEA_PIXEL_STORAGE_PACKED
2751
+ std::uint8_t *fbNib = packedRow(rowToPhysical(py));
2752
+ #else
2753
+ pixel::native_t *fb_row = &pixels_[rowToPhysical(py) * stride_ + gx];
2754
+ #endif
2755
+ for (int col = col_start; col <= col_end; col++) {
2756
+ int alpha = font.coverage(glyph, row, col);
2757
+ if (alpha == 0) continue;
2758
+
2759
+ std::uint8_t a = (globalAlpha_ == 255) ? alpha : (alpha * globalAlpha_) / 255;
2760
+ if (a == 0) continue;
2761
+
2762
+ #if GEA_PIXEL_STORAGE_PACKED
2763
+ pixel::packed::blendPixel(fbNib, gx + col, c, a);
2764
+ #else
2765
+ pixel::native_t *pixel = &fb_row[col];
2766
+ *pixel = (a == 255) ? c : pixel::blendNative(c, *pixel, a);
2767
+ #endif
2768
+ }
2769
+ }
2770
+ markDirty(gx + col_start, gy + row_start,
2771
+ gx + col_end, gy + row_end);
2772
+ pen_x += glyph.advance;
2773
+ }
2774
+ }
2775
+
2776
+ void Canvas::blitGlyphSprite(const std::uint8_t *cov, const std::int16_t *rowX0, const std::int16_t *rowX1,
2777
+ const std::uint8_t *rleVal, const std::uint16_t *rleLen, const std::int32_t *rleRowStart,
2778
+ int minLX, int minLY, int w, int h, int x, int y, pixel::native_t color)
2779
+ {
2780
+ if (!pixels_ || !cov || globalAlpha_ == 0) return;
2781
+ const ClipRect *clip = &clipStack_[clipDepth_];
2782
+ const std::uint8_t ga = globalAlpha_;
2783
+ const int baseX = x + minLX; // screen x of sprite column 0
2784
+ const bool useRle = rleRowStart != nullptr && rleVal != nullptr && rleLen != nullptr;
2785
+
2786
+ int dMinX = 0x7fffffff, dMinY = 0x7fffffff, dMaxX = -0x7fffffff, dMaxY = -0x7fffffff;
2787
+ for (int r = 0; r < h; r++) {
2788
+ #if GEA_EMBEDDED_TEXT_SPRITE_DIAG
2789
+ gTsDiag.rows++;
2790
+ #endif
2791
+ int cStart = rowX0[r];
2792
+ int cEnd = rowX1[r];
2793
+ if (cEnd < cStart) continue; // empty row
2794
+
2795
+ const int py = y + minLY + r;
2796
+ if (py < clip->y0 || py > clip->y1 || py < 0 || py >= height_) continue;
2797
+ #if GEA_EMBEDDED_TEXT_SPRITE_DIAG
2798
+ gTsDiag.rowsClip++;
2799
+ #endif
2800
+
2801
+ // Clip the sprite column range to the clip rect and the framebuffer width.
2802
+ if (cStart < clip->x0 - baseX) cStart = clip->x0 - baseX;
2803
+ if (cStart < -baseX) cStart = -baseX;
2804
+ if (cEnd > clip->x1 - baseX) cEnd = clip->x1 - baseX;
2805
+ if (cEnd > width_ - 1 - baseX) cEnd = width_ - 1 - baseX;
2806
+ if (cEnd < cStart) continue;
2807
+
2808
+ const int phys = rowToPhysical(py);
2809
+ #if !GEA_PIXEL_STORAGE_PACKED
2810
+ pixel::native_t *fbRow = &pixels_[phys * stride_ + baseX];
2811
+ #endif
2812
+ int touched0 = -1, touched1 = -1;
2813
+
2814
+ if (useRle) {
2815
+ // Walk this row's runs, clipped to [cStart, cEnd]. Zero-runs cost nothing;
2816
+ // solid (255) runs fast-fill; only AA-edge runs blend per pixel.
2817
+ #if GEA_EMBEDDED_TEXT_SPRITE_DIAG
2818
+ const std::uint32_t __rowC0 = tsDiagCyc();
2819
+ std::uint32_t __rowFillCyc = 0, __rowBlendCyc = 0;
2820
+ #endif
2821
+ std::int32_t k = rleRowStart[r];
2822
+ const std::int32_t kEnd = rleRowStart[r + 1];
2823
+ int runCol = 0;
2824
+ while (k < kEnd && runCol + rleLen[k] <= cStart) { runCol += rleLen[k]; k++; }
2825
+ for (; k < kEnd && runCol <= cEnd; k++) {
2826
+ #if GEA_EMBEDDED_TEXT_SPRITE_DIAG
2827
+ gTsDiag.runsWalked++;
2828
+ #endif
2829
+ const std::uint8_t v = rleVal[k];
2830
+ int segS = runCol;
2831
+ int segE = runCol + rleLen[k] - 1;
2832
+ runCol += rleLen[k];
2833
+ if (v == 0) continue;
2834
+ if (segS < cStart) segS = cStart;
2835
+ if (segE > cEnd) segE = cEnd;
2836
+ if (segS > segE) continue;
2837
+ if (ga == 255 && v == 255) {
2838
+ #if GEA_EMBEDDED_TEXT_SPRITE_DIAG
2839
+ const std::uint32_t __c0 = tsDiagCyc();
2840
+ #endif
2841
+ fillSpanColor(phys, baseX + segS, segE - segS + 1, color);
2842
+ #if GEA_EMBEDDED_TEXT_SPRITE_DIAG
2843
+ __rowFillCyc += tsDiagCyc() - __c0;
2844
+ gTsDiag.fillPx += segE - segS + 1;
2845
+ #endif
2846
+ } else {
2847
+ const std::uint8_t aa = (ga == 255) ? v : static_cast<std::uint8_t>((static_cast<int>(v) * ga) / 255);
2848
+ if (aa == 0) continue;
2849
+ #if GEA_EMBEDDED_TEXT_SPRITE_DIAG
2850
+ const std::uint32_t __c0 = tsDiagCyc();
2851
+ #endif
2852
+ for (int cc = segS; cc <= segE; cc++) {
2853
+ #if GEA_EMBEDDED_DISPLAY_ROTATE_LANDSCAPE
2854
+ if (landscapeRot_) rotBlend(baseX + cc, py, color, aa);
2855
+ else {
2856
+ #endif
2857
+ #if GEA_PIXEL_STORAGE_PACKED
2858
+ pixel::packed::blendPixel(packedRow(phys), baseX + cc, color, aa);
2859
+ #else
2860
+ pixel::native_t *p = &fbRow[cc];
2861
+ *p = (aa >= 255) ? color : pixel::blendNative(color, *p, aa);
2862
+ #endif
2863
+ #if GEA_EMBEDDED_DISPLAY_ROTATE_LANDSCAPE
2864
+ }
2865
+ #endif
2866
+ }
2867
+ #if GEA_EMBEDDED_TEXT_SPRITE_DIAG
2868
+ __rowBlendCyc += tsDiagCyc() - __c0;
2869
+ gTsDiag.blendPx += segE - segS + 1;
2870
+ #endif
2871
+ }
2872
+ if (touched0 < 0) touched0 = segS;
2873
+ touched1 = segE;
2874
+ }
2875
+ #if GEA_EMBEDDED_TEXT_SPRITE_DIAG
2876
+ gTsDiag.fillCyc += __rowFillCyc;
2877
+ gTsDiag.blendCyc += __rowBlendCyc;
2878
+ gTsDiag.walkCyc += (tsDiagCyc() - __rowC0) - __rowFillCyc - __rowBlendCyc;
2879
+ #endif
2880
+ } else {
2881
+ const std::uint8_t *covRow = cov + static_cast<std::size_t>(r) * w;
2882
+ int c = cStart;
2883
+ while (c <= cEnd) {
2884
+ const std::uint8_t a = covRow[c];
2885
+ if (a == 0) { c++; continue; }
2886
+ if (ga == 255 && a == 255) {
2887
+ const int runStart = c;
2888
+ while (c <= cEnd && covRow[c] == 255) c++;
2889
+ fillSpanColor(phys, baseX + runStart, c - runStart, color);
2890
+ if (touched0 < 0) touched0 = runStart;
2891
+ touched1 = c - 1;
2892
+ } else {
2893
+ const std::uint8_t aa = (ga == 255) ? a : static_cast<std::uint8_t>((static_cast<int>(a) * ga) / 255);
2894
+ if (aa != 0) {
2895
+ #if GEA_EMBEDDED_DISPLAY_ROTATE_LANDSCAPE
2896
+ if (landscapeRot_) rotBlend(baseX + c, py, color, aa);
2897
+ else {
2898
+ #endif
2899
+ #if GEA_PIXEL_STORAGE_PACKED
2900
+ pixel::packed::blendPixel(packedRow(phys), baseX + c, color, aa);
2901
+ #else
2902
+ pixel::native_t *p = &fbRow[c];
2903
+ *p = (aa >= 255) ? color : pixel::blendNative(color, *p, aa);
2904
+ #endif
2905
+ #if GEA_EMBEDDED_DISPLAY_ROTATE_LANDSCAPE
2906
+ }
2907
+ #endif
2908
+ if (touched0 < 0) touched0 = c;
2909
+ touched1 = c;
2910
+ }
2911
+ c++;
2912
+ }
2913
+ }
2914
+ }
2915
+
2916
+ if (touched0 >= 0) {
2917
+ const int sx0 = baseX + touched0;
2918
+ const int sx1 = baseX + touched1;
2919
+ if (sx0 < dMinX) dMinX = sx0;
2920
+ if (sx1 > dMaxX) dMaxX = sx1;
2921
+ if (py < dMinY) dMinY = py;
2922
+ if (py > dMaxY) dMaxY = py;
2923
+ }
2924
+ }
2925
+ if (dMaxX >= dMinX) markDirty(dMinX, dMinY, dMaxX, dMaxY);
2926
+ }
2927
+
2928
+ void Canvas::measureTextFont(const char *text, int max_width, int font_id, int *out_w, int *out_h)
2929
+ {
2930
+ *out_w = 0;
2931
+ *out_h = 0;
2932
+ if (!text || !text[0]) return;
2933
+
2934
+ RasterizedFont font = FontRegistry::rasterized(font_id);
2935
+ if (!font.valid()) return;
2936
+
2937
+ int line_w = 0, max_line_w = 0, lines = 1;
2938
+ if (max_width <= 0) max_width = 32767;
2939
+
2940
+ for (const char *p = text; *p;) {
2941
+ const int cp = nextUtf8Codepoint(p);
2942
+ if (cp == '\n') {
2943
+ if (line_w > max_line_w) max_line_w = line_w;
2944
+ line_w = 0;
2945
+ lines++;
2946
+ continue;
2947
+ }
2948
+ Glyph glyph{};
2949
+ int adv = font.glyph(cp, &glyph) ? glyph.advance : (font.sizePx() / 2);
2950
+ int next_w = line_w + adv;
2951
+ if (next_w > max_width && line_w > 0) {
2952
+ if (line_w > max_line_w) max_line_w = line_w;
2953
+ line_w = adv;
2954
+ lines++;
2955
+ } else {
2956
+ line_w = next_w;
2957
+ }
2958
+ }
2959
+ if (line_w > max_line_w) max_line_w = line_w;
2960
+ *out_w = max_line_w;
2961
+ *out_h = lines * font.lineHeight();
2962
+ }
2963
+ #else
2964
+ void Canvas::drawTextFont(const char *text, int x, int y, pixel::native_t color, int /*font_id*/)
2965
+ {
2966
+ drawText(text, x, y, color, 1.0f);
2967
+ }
2968
+
2969
+ void Canvas::drawTextFontFamily(const char *text, int x, int y, pixel::native_t color, int family_id, int size_px)
2970
+ {
2971
+ #if GEA_EMBEDDED_TTF_RUNTIME_FONTS
2972
+ // No baked atlas linked, but the runtime TTF rasterizer can still serve the
2973
+ // family (desktop targets feed it the bundle's font bytes). Blit its glyphs
2974
+ // directly — same loop as the rotated fallback below, minus the rotation —
2975
+ // so canvas labels render with the app's real font instead of the scaled
2976
+ // bitmap console font. Falls through to the bitmap font for families the
2977
+ // runtime rasterizer doesn't know.
2978
+ if (!pixels_ || !text) return;
2979
+ RasterizedFont font = FontRegistry::rasterizedFamily(family_id, size_px);
2980
+ if (font.valid()) {
2981
+ int pen_x = x;
2982
+ int pen_y = y;
2983
+ for (const char *p = text; *p;) {
2984
+ const int cp = nextUtf8Codepoint(p);
2985
+ if (cp == '\n') { pen_x = x; pen_y += font.lineHeight(); continue; }
2986
+ Glyph glyph{};
2987
+ if (!font.glyph(cp, &glyph)) { pen_x += font.sizePx() / 2; continue; }
2988
+ const int gx = pen_x + glyph.bearingX;
2989
+ const int gy = pen_y + font.ascender() - glyph.bearingY;
2990
+ const pixel::native_t c = color;
2991
+ for (int row = 0; row < glyph.height; row++) {
2992
+ const int py = gy + row;
2993
+ if (py < 0 || py >= height_) continue;
2994
+ for (int col = 0; col < glyph.width; col++) {
2995
+ const int px = gx + col;
2996
+ if (px < 0 || px >= width_) continue;
2997
+ int alpha = font.coverage(glyph, row, col);
2998
+ if (alpha == 0) continue;
2999
+ std::uint8_t a = (globalAlpha_ == 255) ? alpha : (alpha * globalAlpha_) / 255;
3000
+ if (a == 0) continue;
3001
+ #if GEA_EMBEDDED_DISPLAY_ROTATE_LANDSCAPE
3002
+ if (landscapeRot_) {
3003
+ rotBlend(px, py, c, a);
3004
+ continue;
3005
+ }
3006
+ #endif
3007
+ #if GEA_PIXEL_STORAGE_PACKED4
3008
+ pixel::gray4::blendPixel(gray4Row(rowToPhysical(py)), px, c, a);
3009
+ #else
3010
+ pixel::native_t *pixel = &pixels_[rowToPhysical(py) * stride_ + px];
3011
+ *pixel = (a == 255) ? c : pixel::blendNative(c, *pixel, a);
3012
+ #endif
3013
+ }
3014
+ }
3015
+ pen_x += glyph.advance;
3016
+ }
3017
+ return;
3018
+ }
3019
+ #endif
3020
+ drawText(text, x, y, color, size_px > 0 ? static_cast<float>(size_px) / 16.0f : 1.0f);
3021
+ }
3022
+
3023
+ void Canvas::drawTextFontFamilyRotated90(const char *text, int lx, int ly, pixel::native_t color, int family_id, int size_px)
3024
+ {
3025
+ if (!pixels_ || !text) return;
3026
+ #if GEA_EMBEDDED_DISPLAY_ROTATE_LANDSCAPE
3027
+ // This primitive already rotates landscape-authored text onto a PORTRAIT panel
3028
+ // buffer, so it is meaningless (and out-of-bounds) against a landscape-native
3029
+ // rotated binding. It is only used by the P4 DSI targets, never a rotated one.
3030
+ if (landscapeRot_) return;
3031
+ #endif
3032
+ RasterizedFont font = FontRegistry::rasterizedFamily(family_id, size_px);
3033
+ if (!font.valid()) return;
3034
+
3035
+ int pen_x = lx;
3036
+ int pen_y = ly;
3037
+ for (const char *p = text; *p;) {
3038
+ const int cp = nextUtf8Codepoint(p);
3039
+ if (cp == '\n') { pen_x = lx; pen_y += font.lineHeight(); continue; }
3040
+ Glyph glyph{};
3041
+ if (!font.glyph(cp, &glyph)) { pen_x += font.sizePx() / 2; continue; }
3042
+ const int gx = pen_x + glyph.bearingX;
3043
+ const int gy = pen_y + font.ascender() - glyph.bearingY;
3044
+ const pixel::native_t c = color;
3045
+ for (int row = 0; row < glyph.height; row++) {
3046
+ const int l_y = gy + row;
3047
+ // landscape x advances along glyph columns; transform per pixel.
3048
+ for (int col = 0; col < glyph.width; col++) {
3049
+ const int l_x = gx + col;
3050
+ const int panel_x = l_y;
3051
+ const int panel_y = height_ - 1 - l_x;
3052
+ if (panel_x < 0 || panel_x >= width_ || panel_y < 0 || panel_y >= height_) continue;
3053
+ int alpha = font.coverage(glyph, row, col);
3054
+ if (alpha == 0) continue;
3055
+ std::uint8_t a = (globalAlpha_ == 255) ? alpha : (alpha * globalAlpha_) / 255;
3056
+ if (a == 0) continue;
3057
+ #if GEA_PIXEL_STORAGE_PACKED
3058
+ pixel::packed::blendPixel(packedRow(rowToPhysical(panel_y)), panel_x, c, a);
3059
+ #else
3060
+ pixel::native_t *pixel = &pixels_[rowToPhysical(panel_y) * stride_ + panel_x];
3061
+ *pixel = (a == 255) ? c : pixel::blendNative(c, *pixel, a);
3062
+ #endif
3063
+ }
3064
+ }
3065
+ pen_x += glyph.advance;
3066
+ }
3067
+ }
3068
+
3069
+ void Canvas::drawTextFontFamilyOnBackground(const char *text, int x, int y, pixel::native_t color,
3070
+ int family_id, int size_px, pixel::native_t /*background*/)
3071
+ {
3072
+ drawTextFontFamily(text, x, y, color, family_id, size_px);
3073
+ }
3074
+ #endif /* GEA_EMBEDDED_HAS_GENERATED_FONTS */
3075
+
3076
+ /* ---- Text measurement ---- */
3077
+
3078
+ // Outside the baked-atlas conditional on purpose. `canvas.h` declares both of
3079
+ // these unconditionally and `CanvasRenderingContext2D::measureText` calls them
3080
+ // unconditionally, so a target with no generated font atlas -- every windowed
3081
+ // desktop build, which rasterizes the bundle's TTFs at runtime instead -- linked
3082
+ // against a declaration nothing defined and failed at `ld`. Neither body needs
3083
+ // the atlas: both ask `FontRegistry::rasterizedFamily`, which is exactly what the
3084
+ // no-atlas `drawTextFontFamily` above asks, and an invalid font answers 0 either
3085
+ // way.
3086
+ int Canvas::measureTextFontFamily(const char *text, int family_id, int size_px)
3087
+ {
3088
+ if (!text) return 0;
3089
+ RasterizedFont font = FontRegistry::rasterizedFamily(family_id, size_px);
3090
+ if (!font.valid()) return 0;
3091
+ int width = 0;
3092
+ int lineWidth = 0;
3093
+ for (const char *p = text; *p;) {
3094
+ const int cp = nextUtf8Codepoint(p);
3095
+ if (cp == '\n') {
3096
+ if (lineWidth > width) width = lineWidth;
3097
+ lineWidth = 0;
3098
+ continue;
3099
+ }
3100
+ Glyph glyph{};
3101
+ // Same fallback the draw loop uses for a missing glyph, so measure and
3102
+ // draw agree rather than drifting apart on unmapped codepoints.
3103
+ lineWidth += font.glyph(cp, &glyph) ? glyph.advance : font.sizePx() / 2;
3104
+ }
3105
+ return lineWidth > width ? lineWidth : width;
3106
+ }
3107
+
3108
+ // Vertical offset from the text's TOP-LEFT anchor to the centre of its actual
3109
+ // ink, for a family/size. fillText anchors the top of the LINE BOX, so text
3110
+ // centred by subtracting half the font size sags: the line box carries the
3111
+ // ascender and descender, which the glyphs themselves do not fill. Measuring
3112
+ // the real ink box makes `y = centreY - measureTextInkCenter(text)` exact.
3113
+ int Canvas::measureTextInkCenterFontFamily(const char *text, int family_id, int size_px)
3114
+ {
3115
+ if (!text) return 0;
3116
+ RasterizedFont font = FontRegistry::rasterizedFamily(family_id, size_px);
3117
+ if (!font.valid()) return 0;
3118
+ int top = INT32_MAX;
3119
+ int bottom = INT32_MIN;
3120
+ for (const char *p = text; *p;) {
3121
+ const int cp = nextUtf8Codepoint(p);
3122
+ if (cp == '\n') continue;
3123
+ Glyph glyph{};
3124
+ if (!font.glyph(cp, &glyph)) continue;
3125
+ if (glyph.height <= 0) continue; // spaces carry no ink
3126
+ const int gTop = font.ascender() - glyph.bearingY;
3127
+ if (gTop < top) top = gTop;
3128
+ if (gTop + glyph.height > bottom) bottom = gTop + glyph.height;
3129
+ }
3130
+ if (top > bottom) return font.ascender() / 2; // no ink (all spaces)
3131
+ return top + (bottom - top) / 2;
3132
+ }
3133
+
3134
+ void Canvas::fillQuarterCircle(int cx, int cy, int r, int quadrant, pixel::native_t color)
3135
+ {
3136
+ if (!pixels_ || r <= 0) return;
3137
+ const ClipRect *clip = &clipStack_[clipDepth_];
3138
+
3139
+ int qx0 = cx;
3140
+ int qx1 = cx;
3141
+ int qy0 = cy;
3142
+ int qy1 = cy;
3143
+ switch (quadrant) {
3144
+ case 0: qx1 = cx + r; qy0 = cy - r; break;
3145
+ case 1: qx0 = cx - r; qy0 = cy - r; break;
3146
+ case 2: qx0 = cx - r; qy1 = cy + r; break;
3147
+ case 3: qx1 = cx + r; qy1 = cy + r; break;
3148
+ default: return;
3149
+ }
3150
+ if (qx0 > clip->x1 || qx1 < clip->x0 || qy0 > clip->y1 || qy1 < clip->y0) return;
3151
+
3152
+ int visibleY0 = clip->y0;
3153
+ int visibleY1 = clip->y1;
3154
+ if (visibleY0 < 0) visibleY0 = 0;
3155
+ if (visibleY1 >= height_) visibleY1 = height_ - 1;
3156
+ if (visibleY0 > visibleY1) return;
3157
+
3158
+ int dy0 = 0;
3159
+ int dy1 = r;
3160
+ if (quadrant == 0 || quadrant == 1) {
3161
+ if (cy - dy0 > visibleY1) dy0 = cy - visibleY1;
3162
+ if (cy - dy1 < visibleY0) dy1 = cy - visibleY0;
3163
+ } else {
3164
+ if (cy + dy0 < visibleY0) dy0 = visibleY0 - cy;
3165
+ if (cy + dy1 > visibleY1) dy1 = visibleY1 - cy;
3166
+ }
3167
+ if (dy0 < 0) dy0 = 0;
3168
+ if (dy1 > r) dy1 = r;
3169
+ if (dy0 > dy1) return;
3170
+
3171
+ const int rr = r * r;
3172
+ for (int dy = dy0; dy <= dy1; dy++) {
3173
+ int dx = CanvasMath::integerSqrt(rr - dy * dy);
3174
+ int sx0, sx1, sy;
3175
+ switch (quadrant) {
3176
+ case 0: sx0 = cx; sx1 = cx + dx; sy = cy - dy; break;
3177
+ case 1: sx0 = cx - dx; sx1 = cx; sy = cy - dy; break;
3178
+ case 2: sx0 = cx - dx; sx1 = cx; sy = cy + dy; break;
3179
+ case 3: sx0 = cx; sx1 = cx + dx; sy = cy + dy; break;
3180
+ default: return;
3181
+ }
3182
+ if (sx0 < clip->x0) sx0 = clip->x0;
3183
+ if (sx1 > clip->x1) sx1 = clip->x1;
3184
+ if (sx0 < 0) sx0 = 0;
3185
+ if (sx1 >= width_) sx1 = width_ - 1;
3186
+ if (sx0 > sx1) continue;
3187
+
3188
+ fillSpanGlobalAlpha(rowToPhysical(sy), sx0, sx1 - sx0 + 1, color);
3189
+ }
3190
+ }
3191
+
3192
+ void Canvas::fillCircleBox(int x, int y, int size, pixel::native_t color)
3193
+ {
3194
+ if (!pixels_) return;
3195
+ const std::uint8_t (*spans)[2] = CanvasMath::instance().circleSpans(size);
3196
+ if (!spans) return;
3197
+ const ClipRect *clip = &clipStack_[clipDepth_];
3198
+
3199
+ if (x > clip->x1 || y > clip->y1 || x + size - 1 < clip->x0 || y + size - 1 < clip->y0) return;
3200
+
3201
+ int row0 = 0;
3202
+ int row1 = size - 1;
3203
+ if (y + row0 < clip->y0) row0 = clip->y0 - y;
3204
+ if (y + row1 > clip->y1) row1 = clip->y1 - y;
3205
+ if (y + row0 < 0) row0 = -y;
3206
+ if (y + row1 >= height_) row1 = height_ - 1 - y;
3207
+ if (row0 > row1) return;
3208
+ for (int row = row0; row <= row1; row++) {
3209
+ int sy = y + row;
3210
+
3211
+ int sx0 = x + spans[row][0];
3212
+ int sx1 = x + spans[row][1];
3213
+ if (sx0 < clip->x0) sx0 = clip->x0;
3214
+ if (sx1 > clip->x1) sx1 = clip->x1;
3215
+ if (sx0 < 0) sx0 = 0;
3216
+ if (sx1 >= width_) sx1 = width_ - 1;
3217
+ if (sx0 > sx1) continue;
3218
+
3219
+ fillSpanGlobalAlpha(rowToPhysical(sy), sx0, sx1 - sx0 + 1, color);
3220
+ }
3221
+ markDirtyClipped(x, y, x + size - 1, y + size - 1);
3222
+ }
3223
+
3224
+ void Canvas::fillRoundedRectBoxesRgb565(const std::int16_t *xs,
3225
+ const std::int16_t *ys,
3226
+ int count,
3227
+ int w,
3228
+ int h,
3229
+ int tl,
3230
+ int tr,
3231
+ int br,
3232
+ int bl,
3233
+ const pixel::native_t *colors)
3234
+ {
3235
+ if (!pixels_ || !xs || !ys || !colors || count <= 0 || w <= 0 || h <= 0) return;
3236
+
3237
+ // AA-off same-size CSS circles: draw the whole batch in one tight loop sharing
3238
+ // row spans, with ONE union markDirty. The JSX bubble-grid reaches here as
3239
+ // transformed rounded boxes; its scaled sizes are often odd and radii are rounded,
3240
+ // so the old exact even-size test missed the hot path and fell into the generic
3241
+ // four-corner rounded-rect raster.
3242
+ if (Canvas::antialiasSamples() < 2 && roundedRectIsCircleLike(w, h, tl, tr, br, bl) && h <= 256) {
3243
+ const std::uint8_t (*cachedSpans)[2] =
3244
+ (w == h) ? CanvasMath::instance().circleBoxSpans(w) : nullptr;
3245
+ std::uint16_t spanX0[256];
3246
+ std::uint16_t spanX1[256];
3247
+ if (!cachedSpans) {
3248
+ const long long ww = static_cast<long long>(w) * static_cast<long long>(w);
3249
+ const long long hh = static_cast<long long>(h) * static_cast<long long>(h);
3250
+ for (int row = 0; row < h; row++) {
3251
+ const long long dy2 = static_cast<long long>(row * 2 + 1 - h);
3252
+ long long inside = hh - dy2 * dy2;
3253
+ if (inside < 0) inside = 0;
3254
+ const int dx2 = CanvasMath::integerSqrt(static_cast<int>((ww * inside) / hh));
3255
+ int sx0 = (w - dx2) / 2;
3256
+ int sx1 = (w + dx2 - 1) / 2;
3257
+ if (sx0 < 0) sx0 = 0;
3258
+ if (sx1 >= w) sx1 = w - 1;
3259
+ spanX0[row] = static_cast<std::uint16_t>(sx0);
3260
+ spanX1[row] = static_cast<std::uint16_t>(sx1);
3261
+ }
3262
+ }
3263
+
3264
+ const ClipRect *clip = &clipStack_[clipDepth_];
3265
+ int dirtyX0 = width_;
3266
+ int dirtyY0 = height_;
3267
+ int dirtyX1 = -1;
3268
+ int dirtyY1 = -1;
3269
+ for (int i = 0; i < count; i++) {
3270
+ const int x = xs[i];
3271
+ const int y = ys[i];
3272
+ if (x > clip->x1 || y > clip->y1 || x + w - 1 < clip->x0 || y + h - 1 < clip->y0) continue;
3273
+ int boxX0 = x < clip->x0 ? clip->x0 : x;
3274
+ int boxY0 = y < clip->y0 ? clip->y0 : y;
3275
+ int boxX1 = (x + w - 1 > clip->x1) ? clip->x1 : x + w - 1;
3276
+ int boxY1 = (y + h - 1 > clip->y1) ? clip->y1 : y + h - 1;
3277
+ if (boxX0 < 0) boxX0 = 0;
3278
+ if (boxY0 < 0) boxY0 = 0;
3279
+ if (boxX1 >= width_) boxX1 = width_ - 1;
3280
+ if (boxY1 >= height_) boxY1 = height_ - 1;
3281
+ if (boxX0 > boxX1 || boxY0 > boxY1) continue;
3282
+ if (boxX0 < dirtyX0) dirtyX0 = boxX0;
3283
+ if (boxY0 < dirtyY0) dirtyY0 = boxY0;
3284
+ if (boxX1 > dirtyX1) dirtyX1 = boxX1;
3285
+ if (boxY1 > dirtyY1) dirtyY1 = boxY1;
3286
+
3287
+ int row0 = 0;
3288
+ int row1 = h - 1;
3289
+ if (y + row0 < clip->y0) row0 = clip->y0 - y;
3290
+ if (y + row1 > clip->y1) row1 = clip->y1 - y;
3291
+ if (y + row0 < 0) row0 = -y;
3292
+ if (y + row1 >= height_) row1 = height_ - 1 - y;
3293
+ const pixel::native_t color = colors[i];
3294
+ for (int row = row0; row <= row1; row++) {
3295
+ const int sy = y + row;
3296
+ int sx0 = x + static_cast<int>(cachedSpans ? cachedSpans[row][0] : spanX0[row]);
3297
+ int sx1 = x + static_cast<int>(cachedSpans ? cachedSpans[row][1] : spanX1[row]);
3298
+ if (sx0 < clip->x0) sx0 = clip->x0;
3299
+ if (sx1 > clip->x1) sx1 = clip->x1;
3300
+ if (sx0 < 0) sx0 = 0;
3301
+ if (sx1 >= width_) sx1 = width_ - 1;
3302
+ if (sx0 > sx1) continue;
3303
+ fillSpanGlobalAlpha(rowToPhysical(sy), sx0, sx1 - sx0 + 1, color);
3304
+ }
3305
+ }
3306
+ if (dirtyX0 <= dirtyX1 && dirtyY0 <= dirtyY1)
3307
+ markDirty(dirtyX0, dirtyY0, dirtyX1, dirtyY1);
3308
+ return;
3309
+ }
3310
+
3311
+ for (int i = 0; i < count; i++)
3312
+ fillRoundedRect(xs[i], ys[i], w, h, tl, tr, br, bl, colors[i]);
3313
+ }
3314
+
3315
+ void Canvas::fillRoundedRect(int x, int y, int w, int h, int tl, int tr, int br, int bl, pixel::native_t color)
3316
+ {
3317
+ if (!pixels_ || w <= 0 || h <= 0) return;
3318
+ int max_r = CanvasMath::min(w / 2, h / 2);
3319
+ if (tl > max_r) tl = max_r;
3320
+ if (tr > max_r) tr = max_r;
3321
+ if (br > max_r) br = max_r;
3322
+ if (bl > max_r) bl = max_r;
3323
+ if (tl < 0) tl = 0;
3324
+ if (tr < 0) tr = 0;
3325
+ if (br < 0) br = 0;
3326
+ if (bl < 0) bl = 0;
3327
+ if ((tl | tr | br | bl) == 0) {
3328
+ fillRect(x, y, w, h, color);
3329
+ return;
3330
+ }
3331
+ // AA-off circle fast fill: an opaque circle (square box, radius = half) with AA
3332
+ // disabled goes straight to the precomputed circleSpans lookup + tight word-fill,
3333
+ // skipping the general per-row addSpan/sqrt scanline below. This is golden's
3334
+ // 62fps circle path (its poles are marginally rounder than the integer scanline).
3335
+ if (Canvas::antialiasSamples() < 2 && w == h &&
3336
+ tl == w / 2 && tr == w / 2 && br == w / 2 && bl == w / 2 &&
3337
+ CanvasMath::instance().circleSpans(w)) {
3338
+ fillCircleBox(x, y, w, color);
3339
+ return;
3340
+ }
3341
+ int top_r = tl > tr ? tl : tr;
3342
+ int bot_r = bl > br ? bl : br;
3343
+ if (globalAlpha_ == 0) return;
3344
+
3345
+ const int aaSamples = Canvas::antialiasSamples();
3346
+ const bool useAntialias = aaSamples >= 2;
3347
+ const int aaSampleCount = useAntialias ? aaSamples * aaSamples : 1;
3348
+ const float kernelWidth = useAntialias ? roundedRectAntialiasKernelWidth(aaSamples, w, h, tl, tr, br, bl) : 1.0f;
3349
+ const int edgePad = useAntialias ? antialiasEdgePad(kernelWidth) : 0;
3350
+ const bool coverageSampleFill = useAntialias && roundedRectShouldCoverageSampleFill(w, h);
3351
+
3352
+ const ClipRect *clip = &clipStack_[clipDepth_];
3353
+ int row0 = y;
3354
+ int row1 = y + h - 1;
3355
+ if (row0 < clip->y0) row0 = clip->y0;
3356
+ if (row1 > clip->y1) row1 = clip->y1;
3357
+ if (row0 < 0) row0 = 0;
3358
+ if (row1 >= height_) row1 = height_ - 1;
3359
+ if (row0 > row1) return;
3360
+
3361
+ int dirtyX0 = width_;
3362
+ int dirtyY0 = height_;
3363
+ int dirtyX1 = -1;
3364
+ int dirtyY1 = -1;
3365
+ const int a = globalAlpha_;
3366
+
3367
+ #if GEA_EMBEDDED_DISPLAY_ROTATE_LANDSCAPE
3368
+ // Small AA rounded boxes (including the 16px JSX balls) normally sample the
3369
+ // whole shape. Traverse logical columns on a rotated canvas so those exact
3370
+ // same coverage writes are contiguous in the native framebuffer.
3371
+ if (landscapeRot_ && coverageSampleFill) {
3372
+ int col0 = x;
3373
+ int col1 = x + w - 1;
3374
+ if (col0 < clip->x0) col0 = clip->x0;
3375
+ if (col1 > clip->x1) col1 = clip->x1;
3376
+ if (col0 < 0) col0 = 0;
3377
+ if (col1 >= width_) col1 = width_ - 1;
3378
+ if (col0 > col1) return;
3379
+ for (int sx = col0; sx <= col1; ++sx) {
3380
+ #if !GEA_PIXEL_STORAGE_PACKED
3381
+ pixel::native_t *dst = &pixels_[rotPhysRow(sx) * stride_ + row0];
3382
+ #endif
3383
+ for (int sy = row0; sy <= row1; ++sy) {
3384
+ const int coverage = roundedRectCoverage(
3385
+ x, y, w, h, tl, tr, br, bl, sx, sy, aaSamples, kernelWidth);
3386
+ if (coverage <= 0) {
3387
+ #if !GEA_PIXEL_STORAGE_PACKED
3388
+ ++dst;
3389
+ #endif
3390
+ continue;
3391
+ }
3392
+ const int effectiveAlpha = coverageAlpha(a, coverage, aaSampleCount);
3393
+ if (effectiveAlpha > 0) {
3394
+ #if GEA_PIXEL_STORAGE_PACKED
3395
+ if (effectiveAlpha >= 255) rotSet(sx, sy, color);
3396
+ else rotBlend(sx, sy, color, effectiveAlpha);
3397
+ #else
3398
+ *dst = effectiveAlpha >= 255
3399
+ ? color
3400
+ : pixel::blendNative(color, *dst, effectiveAlpha);
3401
+ #endif
3402
+ }
3403
+ #if !GEA_PIXEL_STORAGE_PACKED
3404
+ ++dst;
3405
+ #endif
3406
+ }
3407
+ }
3408
+ markDirty(col0, row0, col1, row1);
3409
+ return;
3410
+ }
3411
+
3412
+ // Rotated canvas, antialiasing off: the row loop below fills each row with
3413
+ // `fillSpanColor`, and on this binding a logical row is a native COLUMN --
3414
+ // one store per native row, a PSRAM cache line each. Measured at ~1.6us per
3415
+ // pixel on a pedalboard app's 502x410 root background, which is 330ms of a
3416
+ // 451ms frame; the same area filled contiguously is single-digit ms.
3417
+ //
3418
+ // The coverage sampler above already walks columns, but it is reached only
3419
+ // for antialiased shapes of at most 4096px, so a full-screen background --
3420
+ // the one shape where this costs the most -- never sees it.
3421
+ //
3422
+ // A rounded rect is convex in every column exactly as it is in every row, so
3423
+ // the shape is walked column by column here and each column becomes one
3424
+ // contiguous native run, which is what `fillRect` already does in this
3425
+ // binding. The corner solve is the transpose of the row loop's: a column
3426
+ // inside a corner's radius is inset from the top (or the bottom) by the same
3427
+ // `integerSqrt` chord that insets the row loop's span from the side.
3428
+ //
3429
+ // Opaque only. A translucent fill has to read what it blends over, so it
3430
+ // gains nothing from a contiguous run and keeps the path it had.
3431
+ if (landscapeRot_ && !useAntialias && a >= 255) {
3432
+ int col0 = x;
3433
+ int col1 = x + w - 1;
3434
+ if (col0 < clip->x0) col0 = clip->x0;
3435
+ if (col1 > clip->x1) col1 = clip->x1;
3436
+ if (col0 < 0) col0 = 0;
3437
+ if (col1 >= width_) col1 = width_ - 1;
3438
+ if (col0 > col1) return;
3439
+ int dirtyCol0 = width_;
3440
+ int dirtyCol1 = -1;
3441
+ int dirtyRow0 = height_;
3442
+ int dirtyRow1 = -1;
3443
+ for (int sx = col0; sx <= col1; sx++) {
3444
+ int top = y;
3445
+ int bottom = y + h - 1;
3446
+ if (tl > 0 && sx < x + tl) {
3447
+ const int dx = x + tl - sx;
3448
+ const int edge = y + tl - CanvasMath::integerSqrt(tl * tl - dx * dx);
3449
+ if (edge > top) top = edge;
3450
+ }
3451
+ if (tr > 0 && sx > x + w - 1 - tr) {
3452
+ const int dx = sx - (x + w - 1 - tr);
3453
+ const int edge = y + tr - CanvasMath::integerSqrt(tr * tr - dx * dx);
3454
+ if (edge > top) top = edge;
3455
+ }
3456
+ if (bl > 0 && sx < x + bl) {
3457
+ const int dx = x + bl - sx;
3458
+ const int edge = y + h - 1 - bl + CanvasMath::integerSqrt(bl * bl - dx * dx);
3459
+ if (edge < bottom) bottom = edge;
3460
+ }
3461
+ if (br > 0 && sx > x + w - 1 - br) {
3462
+ const int dx = sx - (x + w - 1 - br);
3463
+ const int edge = y + h - 1 - br + CanvasMath::integerSqrt(br * br - dx * dx);
3464
+ if (edge < bottom) bottom = edge;
3465
+ }
3466
+ if (top < row0) top = row0;
3467
+ if (bottom > row1) bottom = row1;
3468
+ if (top > bottom) continue;
3469
+ #if GEA_PIXEL_STORAGE_PACKED
3470
+ for (int sy = top; sy <= bottom; ++sy) rotSet(sx, sy, color);
3471
+ #else
3472
+ pixel::fillNative(&pixels_[rotPhysRow(sx) * stride_ + top], bottom - top + 1, color);
3473
+ #endif
3474
+ if (sx < dirtyCol0) dirtyCol0 = sx;
3475
+ if (sx > dirtyCol1) dirtyCol1 = sx;
3476
+ if (top < dirtyRow0) dirtyRow0 = top;
3477
+ if (bottom > dirtyRow1) dirtyRow1 = bottom;
3478
+ }
3479
+ if (dirtyCol0 <= dirtyCol1 && dirtyRow0 <= dirtyRow1)
3480
+ markDirty(dirtyCol0, dirtyRow0, dirtyCol1, dirtyRow1);
3481
+ return;
3482
+ }
3483
+ #endif
3484
+
3485
+ for (int sy = row0; sy <= row1; sy++) {
3486
+ int sx0 = width_;
3487
+ int sx1 = -1;
3488
+ auto addSpan = [&](int left, int right) {
3489
+ if (left > right) return;
3490
+ if (left < clip->x0) left = clip->x0;
3491
+ if (right > clip->x1) right = clip->x1;
3492
+ if (left < 0) left = 0;
3493
+ if (right >= width_) right = width_ - 1;
3494
+ if (left > right) return;
3495
+ if (left < sx0) sx0 = left;
3496
+ if (right > sx1) sx1 = right;
3497
+ };
3498
+
3499
+ if (h - top_r - bot_r > 0 && sy >= y + top_r && sy < y + h - bot_r)
3500
+ addSpan(x, x + w - 1);
3501
+ if (top_r > 0 && sy >= y && sy < y + top_r)
3502
+ addSpan(x + tl, x + w - tr - 1);
3503
+ if (bot_r > 0 && sy >= y + h - bot_r && sy <= y + h - 1)
3504
+ addSpan(x + bl, x + w - br - 1);
3505
+ if (tl > 0 && tl < top_r && sy >= y + tl && sy < y + top_r)
3506
+ addSpan(x, x + tl - 1);
3507
+ if (tr > 0 && tr < top_r && sy >= y + tr && sy < y + top_r)
3508
+ addSpan(x + w - tr, x + w - 1);
3509
+ if (bl > 0 && bl < bot_r && sy >= y + h - bot_r && sy < y + h - bl)
3510
+ addSpan(x, x + bl - 1);
3511
+ if (br > 0 && br < bot_r && sy >= y + h - bot_r && sy < y + h - br)
3512
+ addSpan(x + w - br, x + w - 1);
3513
+
3514
+ if (tl > 0 && sy >= y && sy <= y + tl) {
3515
+ const int dy = y + tl - sy;
3516
+ const int dx = CanvasMath::integerSqrt(tl * tl - dy * dy);
3517
+ addSpan(x + tl - dx, x + tl);
3518
+ }
3519
+ if (tr > 0 && sy >= y && sy <= y + tr) {
3520
+ const int dy = y + tr - sy;
3521
+ const int dx = CanvasMath::integerSqrt(tr * tr - dy * dy);
3522
+ addSpan(x + w - 1 - tr, x + w - 1 - tr + dx);
3523
+ }
3524
+ if (bl > 0 && sy >= y + h - 1 - bl && sy <= y + h - 1) {
3525
+ const int dy = sy - (y + h - 1 - bl);
3526
+ const int dx = CanvasMath::integerSqrt(bl * bl - dy * dy);
3527
+ addSpan(x + bl - dx, x + bl);
3528
+ }
3529
+ if (br > 0 && sy >= y + h - 1 - br && sy <= y + h - 1) {
3530
+ const int dy = sy - (y + h - 1 - br);
3531
+ const int dx = CanvasMath::integerSqrt(br * br - dy * dy);
3532
+ addSpan(x + w - 1 - br, x + w - 1 - br + dx);
3533
+ }
3534
+
3535
+ int anyX0 = sx0;
3536
+ int anyX1 = sx1;
3537
+ if (useAntialias) {
3538
+ anyX0 = width_;
3539
+ anyX1 = -1;
3540
+ roundedRectAnyCoverageSpan(x, y, w, h, tl, tr, br, bl, sy, aaSamples, kernelWidth, &anyX0, &anyX1);
3541
+ if (anyX0 < clip->x0) anyX0 = clip->x0;
3542
+ if (anyX1 > clip->x1) anyX1 = clip->x1;
3543
+ if (anyX0 < x) anyX0 = x;
3544
+ if (anyX1 > x + w - 1) anyX1 = x + w - 1;
3545
+ if (anyX0 < 0) anyX0 = 0;
3546
+ if (anyX1 >= width_) anyX1 = width_ - 1;
3547
+ if (sx0 < anyX0) sx0 = anyX0;
3548
+ if (sx1 > anyX1) sx1 = anyX1;
3549
+ }
3550
+ if (anyX0 > anyX1) continue;
3551
+
3552
+ auto paintCoverageEdge = [&](int px) {
3553
+ if (px < clip->x0 || px > clip->x1 || px < 0 || px >= width_) return;
3554
+ const int coverage = useAntialias
3555
+ ? roundedRectCoverage(x, y, w, h, tl, tr, br, bl, px, sy, aaSamples, kernelWidth)
3556
+ : (roundedRectSampleContains(x,
3557
+ y,
3558
+ w,
3559
+ h,
3560
+ tl,
3561
+ tr,
3562
+ br,
3563
+ bl,
3564
+ static_cast<float>(px) + 0.5f,
3565
+ static_cast<float>(sy) + 0.5f)
3566
+ ? 1
3567
+ : 0);
3568
+ if (coverage <= 0) return;
3569
+ const int effectiveAlpha = coverageAlpha(a, coverage, aaSampleCount);
3570
+ if (effectiveAlpha <= 0) return;
3571
+ #if GEA_EMBEDDED_DISPLAY_ROTATE_LANDSCAPE
3572
+ if (landscapeRot_) rotBlend(px, sy, color, effectiveAlpha);
3573
+ else {
3574
+ #endif
3575
+ #if GEA_PIXEL_STORAGE_PACKED
3576
+ pixel::packed::blendPixel(packedRow(rowToPhysical(sy)), px, color, effectiveAlpha);
3577
+ #else
3578
+ pixel::native_t &dst = pixels_[rowToPhysical(sy) * stride_ + px];
3579
+ const pixel::native_t c = color;
3580
+ dst = (effectiveAlpha >= 255) ? c : pixel::blendNative(c, dst, effectiveAlpha);
3581
+ #endif
3582
+ #if GEA_EMBEDDED_DISPLAY_ROTATE_LANDSCAPE
3583
+ }
3584
+ #endif
3585
+ if (px < dirtyX0) dirtyX0 = px;
3586
+ if (sy < dirtyY0) dirtyY0 = sy;
3587
+ if (px > dirtyX1) dirtyX1 = px;
3588
+ if (sy > dirtyY1) dirtyY1 = sy;
3589
+ };
3590
+
3591
+ if (coverageSampleFill) {
3592
+ for (int px = anyX0; px <= anyX1; ++px) paintCoverageEdge(px);
3593
+ continue;
3594
+ } else if (useAntialias) {
3595
+ if (sx0 <= sx1) {
3596
+ const int leftEdgeEnd = std::min(anyX1, sx0 + edgePad);
3597
+ const int rightEdgeStart = std::max(anyX0, sx1 - edgePad);
3598
+ if (leftEdgeEnd >= rightEdgeStart) {
3599
+ for (int px = anyX0; px <= anyX1; ++px) paintCoverageEdge(px);
3600
+ } else {
3601
+ for (int px = anyX0; px <= leftEdgeEnd; ++px) paintCoverageEdge(px);
3602
+ for (int px = rightEdgeStart; px <= anyX1; ++px) paintCoverageEdge(px);
3603
+ }
3604
+ } else {
3605
+ for (int px = anyX0; px <= anyX1; ++px) paintCoverageEdge(px);
3606
+ }
3607
+ } else if (sx0 > sx1) {
3608
+ continue;
3609
+ }
3610
+
3611
+ // AA off: the integer span [sx0, sx1] from the integerSqrt corner solve is the
3612
+ // full opaque shape — fill it directly, with no per-pixel edge coverage
3613
+ // (roundedRectSampleContains). AA on carves the antialiased edge band (edgePad)
3614
+ // out of the solid fill and leaves those edges to the coverage passes above.
3615
+ int fillX0 = useAntialias ? sx0 + edgePad + 1 : sx0;
3616
+ int fillX1 = useAntialias ? sx1 - edgePad - 1 : sx1;
3617
+ if (fillX0 < clip->x0) fillX0 = clip->x0;
3618
+ if (fillX1 > clip->x1) fillX1 = clip->x1;
3619
+ if (fillX0 < 0) fillX0 = 0;
3620
+ if (fillX1 >= width_) fillX1 = width_ - 1;
3621
+ if (fillX0 <= fillX1) {
3622
+ if (a >= 255) {
3623
+ fillSpanColor(rowToPhysical(sy), fillX0, fillX1 - fillX0 + 1, color);
3624
+ } else {
3625
+ const pixel::native_t c = color;
3626
+ #if GEA_EMBEDDED_DISPLAY_ROTATE_LANDSCAPE
3627
+ if (landscapeRot_) {
3628
+ for (int px = fillX0; px <= fillX1; ++px) rotBlend(px, sy, c, a);
3629
+ } else {
3630
+ #endif
3631
+ #if GEA_PIXEL_STORAGE_PACKED
3632
+ std::uint8_t *dstNib = packedRow(rowToPhysical(sy));
3633
+ for (int px = fillX0; px <= fillX1; ++px) pixel::packed::blendPixel(dstNib, px, c, a);
3634
+ #else
3635
+ pixel::native_t *dst = &pixels_[rowToPhysical(sy) * stride_ + fillX0];
3636
+ for (int px = fillX0; px <= fillX1; ++px, ++dst)
3637
+ *dst = pixel::blendNative(c, *dst, a);
3638
+ #endif
3639
+ #if GEA_EMBEDDED_DISPLAY_ROTATE_LANDSCAPE
3640
+ }
3641
+ #endif
3642
+ }
3643
+ if (fillX0 < dirtyX0) dirtyX0 = fillX0;
3644
+ if (sy < dirtyY0) dirtyY0 = sy;
3645
+ if (fillX1 > dirtyX1) dirtyX1 = fillX1;
3646
+ if (sy > dirtyY1) dirtyY1 = sy;
3647
+ }
3648
+ }
3649
+ if (dirtyX0 <= dirtyX1 && dirtyY0 <= dirtyY1)
3650
+ markDirty(dirtyX0, dirtyY0, dirtyX1, dirtyY1);
3651
+ }
3652
+
3653
+ void Canvas::strokeRoundedRect(int x, int y, int w, int h, int tl, int tr, int br, int bl, int lw, pixel::native_t color)
3654
+ {
3655
+ if (!pixels_ || w <= 0 || h <= 0 || lw <= 0) return;
3656
+ const ClipRect *clip = &clipStack_[clipDepth_];
3657
+ int max_r = CanvasMath::min(w / 2, h / 2);
3658
+ if (tl > max_r) tl = max_r;
3659
+ if (tr > max_r) tr = max_r;
3660
+ if (br > max_r) br = max_r;
3661
+ if (bl > max_r) bl = max_r;
3662
+ if (tl < 0) tl = 0;
3663
+ if (tr < 0) tr = 0;
3664
+ if (br < 0) br = 0;
3665
+ if (bl < 0) bl = 0;
3666
+ if (globalAlpha_ == 0) return;
3667
+ const int aaSamples = Canvas::antialiasSamples();
3668
+ if (aaSamples >= 2) {
3669
+ const float kernelWidth = roundedRectAntialiasKernelWidth(aaSamples, w, h, tl, tr, br, bl);
3670
+ const int edgePad = antialiasEdgePad(kernelWidth);
3671
+ int row0 = y - edgePad;
3672
+ int row1 = y + h - 1 + edgePad;
3673
+ if (row0 < clip->y0) row0 = clip->y0;
3674
+ if (row1 > clip->y1) row1 = clip->y1;
3675
+ if (row0 < 0) row0 = 0;
3676
+ if (row1 >= height_) row1 = height_ - 1;
3677
+ int col0 = x - edgePad;
3678
+ int col1 = x + w - 1 + edgePad;
3679
+ if (col0 < clip->x0) col0 = clip->x0;
3680
+ if (col1 > clip->x1) col1 = clip->x1;
3681
+ if (col0 < 0) col0 = 0;
3682
+ if (col1 >= width_) col1 = width_ - 1;
3683
+ if (row0 > row1 || col0 > col1) return;
3684
+
3685
+ int dirtyX0 = width_;
3686
+ int dirtyY0 = height_;
3687
+ int dirtyX1 = -1;
3688
+ int dirtyY1 = -1;
3689
+ const int aaSampleCount = aaSamples * aaSamples;
3690
+ const int alpha = globalAlpha_;
3691
+ for (int sy = row0; sy <= row1; ++sy) {
3692
+ for (int sx = col0; sx <= col1; ++sx) {
3693
+ const int coverage = roundedRectStrokeCoverage(x, y, w, h,
3694
+ tl, tr, br, bl,
3695
+ lw,
3696
+ sx, sy,
3697
+ aaSamples,
3698
+ kernelWidth);
3699
+ const int effectiveAlpha = coverageAlpha(alpha, coverage, aaSampleCount);
3700
+ if (effectiveAlpha <= 0) continue;
3701
+ const pixel::native_t c = color;
3702
+ #if GEA_EMBEDDED_DISPLAY_ROTATE_LANDSCAPE
3703
+ if (landscapeRot_) rotBlend(sx, sy, c, effectiveAlpha);
3704
+ else {
3705
+ #endif
3706
+ #if GEA_PIXEL_STORAGE_PACKED
3707
+ pixel::packed::blendPixel(packedRow(rowToPhysical(sy)), sx, c, effectiveAlpha);
3708
+ #else
3709
+ pixel::native_t &dst = pixels_[rowToPhysical(sy) * stride_ + sx];
3710
+ dst = (effectiveAlpha >= 255) ? c : pixel::blendNative(c, dst, effectiveAlpha);
3711
+ #endif
3712
+ #if GEA_EMBEDDED_DISPLAY_ROTATE_LANDSCAPE
3713
+ }
3714
+ #endif
3715
+ if (sx < dirtyX0) dirtyX0 = sx;
3716
+ if (sy < dirtyY0) dirtyY0 = sy;
3717
+ if (sx > dirtyX1) dirtyX1 = sx;
3718
+ if (sy > dirtyY1) dirtyY1 = sy;
3719
+ }
3720
+ }
3721
+ if (dirtyX0 <= dirtyX1 && dirtyY0 <= dirtyY1)
3722
+ markDirty(dirtyX0, dirtyY0, dirtyX1, dirtyY1);
3723
+ return;
3724
+ }
3725
+ fillRect(x + tl, y, w - tl - tr, lw, color);
3726
+ fillRect(x + bl, y + h - lw, w - bl - br, lw, color);
3727
+ fillRect(x, y + tl, lw, h - tl - bl, color);
3728
+ fillRect(x + w - lw, y + tr, lw, h - tr - br, color);
3729
+ for (int q = 0; q < 4; q++) {
3730
+ int r, cx, cy;
3731
+ switch (q) {
3732
+ case 0: r = tr; cx = x + w - 1 - r; cy = y + r; break;
3733
+ case 1: r = tl; cx = x + r; cy = y + r; break;
3734
+ case 2: r = bl; cx = x + r; cy = y + h - 1 - r; break;
3735
+ case 3: r = br; cx = x + w - 1 - r; cy = y + h - 1 - r; break;
3736
+ default: continue;
3737
+ }
3738
+ if (r <= 0) continue;
3739
+ if (cx + r < clip->x0 || cx - r > clip->x1 ||
3740
+ cy + r < clip->y0 || cy - r > clip->y1)
3741
+ continue;
3742
+ int ri = r - lw;
3743
+ if (ri < 0) ri = 0;
3744
+ int dy0 = 0;
3745
+ int dy1 = r;
3746
+ if (q == 0 || q == 1) {
3747
+ if (cy - dy0 > clip->y1) dy0 = cy - clip->y1;
3748
+ if (cy - dy1 < clip->y0) dy1 = cy - clip->y0;
3749
+ } else {
3750
+ if (cy + dy0 < clip->y0) dy0 = clip->y0 - cy;
3751
+ if (cy + dy1 > clip->y1) dy1 = clip->y1 - cy;
3752
+ }
3753
+ if (dy0 < 0) dy0 = 0;
3754
+ if (dy1 > r) dy1 = r;
3755
+ if (dy0 > dy1) continue;
3756
+ for (int dy = dy0; dy <= dy1; dy++) {
3757
+ int dx_outer = CanvasMath::integerSqrt(r * r - dy * dy);
3758
+ int dx_inner = (dy <= ri) ? CanvasMath::integerSqrt(ri * ri - dy * dy) : 0;
3759
+ int sx0, sx1, sy;
3760
+ switch (q) {
3761
+ case 0: sx0 = cx + dx_inner; sx1 = cx + dx_outer; sy = cy - dy; break;
3762
+ case 1: sx0 = cx - dx_outer; sx1 = cx - dx_inner; sy = cy - dy; break;
3763
+ case 2: sx0 = cx - dx_outer; sx1 = cx - dx_inner; sy = cy + dy; break;
3764
+ case 3: sx0 = cx + dx_inner; sx1 = cx + dx_outer; sy = cy + dy; break;
3765
+ default: continue;
3766
+ }
3767
+ if (sy < clip->y0 || sy > clip->y1) continue;
3768
+ if (sx0 < clip->x0) sx0 = clip->x0;
3769
+ if (sx1 > clip->x1) sx1 = clip->x1;
3770
+ if (sx0 < 0) sx0 = 0;
3771
+ if (sx1 >= width_) sx1 = width_ - 1;
3772
+ if (sx0 > sx1 || sy < 0 || sy >= height_) continue;
3773
+
3774
+ fillSpanGlobalAlpha(rowToPhysical(sy), sx0, sx1 - sx0 + 1, color);
3775
+ }
3776
+ }
3777
+ markDirtyClipped(x, y, x + w - 1, y + h - 1);
3778
+ }
3779
+
3780
+ #if GEA_PIXEL_STORAGE_PACKED
3781
+ void Canvas::blitPacked(const std::uint8_t *src, int src_w, int src_h, int dx, int dy)
3782
+ {
3783
+ if (!pixels_ || !src || src_w <= 0 || src_h <= 0) return;
3784
+ const ClipRect *clip = &clipStack_[clipDepth_];
3785
+ const int srcRowBytes = pixel::packed::rowBytes(src_w);
3786
+ for (int r = 0; r < src_h; r++) {
3787
+ const int py = dy + r;
3788
+ if (py < clip->y0 || py > clip->y1 || py < 0 || py >= height_) continue;
3789
+ int srcX = 0;
3790
+ int dstX0 = dx;
3791
+ int dstX1 = dx + src_w - 1;
3792
+ if (dstX0 < clip->x0) { srcX += clip->x0 - dstX0; dstX0 = clip->x0; }
3793
+ if (dstX0 < 0) { srcX += -dstX0; dstX0 = 0; }
3794
+ if (dstX1 > clip->x1) dstX1 = clip->x1;
3795
+ if (dstX1 >= width_) dstX1 = width_ - 1;
3796
+ if (dstX0 > dstX1) continue;
3797
+ const int count = dstX1 - dstX0 + 1;
3798
+ #if GEA_EMBEDDED_DISPLAY_ROTATE_LANDSCAPE
3799
+ if (landscapeRot_) {
3800
+ const std::uint8_t *srcRow = src + static_cast<std::size_t>(r) * srcRowBytes;
3801
+ for (int i = 0; i < count; ++i) rotSet(dstX0 + i, py, pixel::packed::get(srcRow, srcX + i));
3802
+ } else
3803
+ #endif
3804
+ pixel::packed::copyPacked(packedRow(rowToPhysical(py)), dstX0, src + static_cast<std::size_t>(r) * srcRowBytes, srcX, count);
3805
+ }
3806
+ markDirty(dx, dy, dx + src_w - 1, dy + src_h - 1);
3807
+ }
3808
+ #endif
3809
+
3810
+ void Canvas::drawImage(
3811
+ const pixel::native_t *src, const std::uint8_t *alpha, int src_w, int src_h,
3812
+ int dx, int dy)
3813
+ {
3814
+ if (!pixels_ || !src) return;
3815
+ if (src_w <= 0 || src_h <= 0) return;
3816
+
3817
+ // Clip the source rect once instead of per-pixel.
3818
+ const ClipRect *clip = &clipStack_[clipDepth_];
3819
+ int clip_x0 = clip->x0 > 0 ? clip->x0 : 0;
3820
+ int clip_y0 = clip->y0 > 0 ? clip->y0 : 0;
3821
+ int clip_x1 = clip->x1 < width_ ? clip->x1 : width_ - 1;
3822
+ int clip_y1 = clip->y1 < height_ ? clip->y1 : height_ - 1;
3823
+
3824
+ int sx0 = 0, sy0 = 0, sx1 = src_w - 1, sy1 = src_h - 1;
3825
+ if (dx + sx0 < clip_x0) sx0 = clip_x0 - dx;
3826
+ if (dx + sx1 > clip_x1) sx1 = clip_x1 - dx;
3827
+ if (dy + sy0 < clip_y0) sy0 = clip_y0 - dy;
3828
+ if (dy + sy1 > clip_y1) sy1 = clip_y1 - dy;
3829
+ if (sx0 > sx1 || sy0 > sy1) return;
3830
+
3831
+ int row_w = sx1 - sx0 + 1;
3832
+ int dst_x = dx + sx0;
3833
+ std::uint8_t global_alpha = globalAlpha_;
3834
+ if (global_alpha == 0) return;
3835
+
3836
+ // Fast path: fully opaque drawImage (no per-pixel mask, no global alpha) -
3837
+ // becomes a row-level memcpy, dropping the per-pixel function-call and
3838
+ // clip-check overhead that dominated when many small tiles were drawn.
3839
+ if (!alpha && global_alpha == 255) {
3840
+ for (int sy = sy0; sy <= sy1; sy++) {
3841
+ const pixel::native_t *src_row = &src[sy * src_w + sx0];
3842
+ #if GEA_EMBEDDED_DISPLAY_ROTATE_LANDSCAPE
3843
+ if (landscapeRot_) { for (int i = 0; i < row_w; ++i) rotSet(dst_x + i, dy + sy, src_row[i]); }
3844
+ else {
3845
+ #endif
3846
+ #if GEA_PIXEL_STORAGE_PACKED
3847
+ pixel::packed::writeUnpacked(packedRow(rowToPhysical(dy + sy)), dst_x, src_row, row_w);
3848
+ #else
3849
+ pixel::native_t *dst_row = &pixels_[rowToPhysical(dy + sy) * stride_ + dst_x];
3850
+ std::memcpy(dst_row, src_row, static_cast<std::size_t>(row_w) * sizeof(pixel::native_t));
3851
+ #endif
3852
+ #if GEA_EMBEDDED_DISPLAY_ROTATE_LANDSCAPE
3853
+ }
3854
+ #endif
3855
+ }
3856
+ markDirty(dst_x, dy + sy0, dx + sx1, dy + sy1);
3857
+ return;
3858
+ }
3859
+
3860
+ // Global-alpha blend without per-pixel mask.
3861
+ if (!alpha) {
3862
+ for (int sy = sy0; sy <= sy1; sy++) {
3863
+ const pixel::native_t *src_row = &src[sy * src_w + sx0];
3864
+ #if GEA_EMBEDDED_DISPLAY_ROTATE_LANDSCAPE
3865
+ if (landscapeRot_) {
3866
+ for (int i = 0; i < row_w; i++) rotBlend(dst_x + i, dy + sy, src_row[i], global_alpha);
3867
+ } else {
3868
+ #endif
3869
+ #if GEA_PIXEL_STORAGE_PACKED
3870
+ std::uint8_t *dnib = packedRow(rowToPhysical(dy + sy));
3871
+ for (int i = 0; i < row_w; i++)
3872
+ pixel::packed::blendPixel(dnib, dst_x + i, src_row[i], global_alpha);
3873
+ #else
3874
+ pixel::native_t *dst_row = &pixels_[rowToPhysical(dy + sy) * stride_ + dst_x];
3875
+ for (int i = 0; i < row_w; i++)
3876
+ dst_row[i] = pixel::blendNative(src_row[i], dst_row[i], global_alpha);
3877
+ #endif
3878
+ #if GEA_EMBEDDED_DISPLAY_ROTATE_LANDSCAPE
3879
+ }
3880
+ #endif
3881
+ }
3882
+ markDirty(dst_x, dy + sy0, dx + sx1, dy + sy1);
3883
+ return;
3884
+ }
3885
+
3886
+ // Per-pixel alpha mask, optionally combined with global alpha.
3887
+ // For the common global_alpha == 255 case, walk each row as a run-length
3888
+ // pass: skip transparent runs (a == 0), memcpy opaque runs (a == 255), and
3889
+ // per-pixel blend any in-between values. With the opaque hint at decode
3890
+ // time, tiles boil down to {0, 255} alpha and this becomes "memcpy the
3891
+ // solid spans, skip the holes" - far cheaper than per-pixel branching for
3892
+ // every pixel of every row.
3893
+ for (int sy = sy0; sy <= sy1; sy++) {
3894
+ const pixel::native_t *src_row = &src[sy * src_w + sx0];
3895
+ const std::uint8_t *alpha_row = &alpha[sy * src_w + sx0];
3896
+ #if GEA_EMBEDDED_DISPLAY_ROTATE_LANDSCAPE
3897
+ if (landscapeRot_) {
3898
+ const int py = dy + sy;
3899
+ if (global_alpha == 255) {
3900
+ for (int i = 0; i < row_w; i++) {
3901
+ const std::uint8_t a = alpha_row[i];
3902
+ if (a == 0) continue;
3903
+ if (a == 255) rotSet(dst_x + i, py, src_row[i]);
3904
+ else rotBlend(dst_x + i, py, src_row[i], a);
3905
+ }
3906
+ } else {
3907
+ for (int i = 0; i < row_w; i++) {
3908
+ const std::uint8_t a = alpha_row[i];
3909
+ if (a == 0) continue;
3910
+ const int eff = (a * global_alpha) / 255;
3911
+ if (eff <= 0) continue;
3912
+ rotBlend(dst_x + i, py, src_row[i], eff);
3913
+ }
3914
+ }
3915
+ continue;
3916
+ }
3917
+ #endif
3918
+ #if GEA_PIXEL_STORAGE_PACKED
3919
+ std::uint8_t *dnib = packedRow(rowToPhysical(dy + sy));
3920
+ if (global_alpha == 255) {
3921
+ int i = 0;
3922
+ while (i < row_w) {
3923
+ while (i < row_w && alpha_row[i] == 0) i++;
3924
+ int run_start = i;
3925
+ while (i < row_w && alpha_row[i] == 255) i++;
3926
+ if (i > run_start)
3927
+ pixel::packed::writeUnpacked(dnib, dst_x + run_start, src_row + run_start, i - run_start);
3928
+ if (i < row_w && alpha_row[i] != 0 && alpha_row[i] != 255) {
3929
+ pixel::packed::blendPixel(dnib, dst_x + i, src_row[i], alpha_row[i]);
3930
+ i++;
3931
+ }
3932
+ }
3933
+ continue;
3934
+ }
3935
+ for (int i = 0; i < row_w; i++) {
3936
+ std::uint8_t a = alpha_row[i];
3937
+ if (a == 0) continue;
3938
+ int eff = (a * global_alpha) / 255;
3939
+ if (eff <= 0) continue;
3940
+ pixel::packed::blendPixel(dnib, dst_x + i, src_row[i], eff);
3941
+ }
3942
+ #else
3943
+ pixel::native_t *dst_row = &pixels_[rowToPhysical(dy + sy) * stride_ + dst_x];
3944
+
3945
+ if (global_alpha == 255) {
3946
+ int i = 0;
3947
+ while (i < row_w) {
3948
+ while (i < row_w && alpha_row[i] == 0) i++;
3949
+ int run_start = i;
3950
+ while (i < row_w && alpha_row[i] == 255) i++;
3951
+ if (i > run_start) {
3952
+ std::memcpy(dst_row + run_start, src_row + run_start, (size_t)(i - run_start) * sizeof(pixel::native_t));
3953
+ }
3954
+ if (i < row_w && alpha_row[i] != 0 && alpha_row[i] != 255) {
3955
+ dst_row[i] = pixel::blendNative(src_row[i], dst_row[i], alpha_row[i]);
3956
+ i++;
3957
+ }
3958
+ }
3959
+ continue;
3960
+ }
3961
+
3962
+ for (int i = 0; i < row_w; i++) {
3963
+ std::uint8_t a = alpha_row[i];
3964
+ if (a == 0) continue;
3965
+ int eff = (a * global_alpha) / 255;
3966
+ if (eff <= 0) continue;
3967
+ if (eff >= 255) dst_row[i] = src_row[i];
3968
+ else dst_row[i] = pixel::blendNative(src_row[i], dst_row[i], (std::uint8_t)eff);
3969
+ }
3970
+ #endif
3971
+ }
3972
+ markDirty(dst_x, dy + sy0, dx + sx1, dy + sy1);
3973
+ }
3974
+
3975
+ void Canvas::drawImage(
3976
+ const pixel::native_t *src, const std::uint8_t *alpha, int src_w, int src_h,
3977
+ int dx, int dy, int dst_w, int dst_h)
3978
+ {
3979
+ if (!pixels_ || !src) return;
3980
+ if (dst_w <= 0 || dst_h <= 0 || src_w <= 0 || src_h <= 0) return;
3981
+
3982
+ // 1:1 scale: route to the unscaled blit and its opaque row-level memcpy
3983
+ // fast path. Callers (e.g. a map at an integer zoom) often pass dst == src
3984
+ // dimensions through the scaling overload; the bilinear loop below costs
3985
+ // ~70ms for a full 720x1280 composite that memcpy covers in ~2ms.
3986
+ if (dst_w == src_w && dst_h == src_h) {
3987
+ drawImage(src, alpha, src_w, src_h, dx, dy);
3988
+ return;
3989
+ }
3990
+
3991
+ // Opaque nearest-neighbor fast path: map tiles (and other photos) load
3992
+ // opaque with no alpha buffer, and mid-gesture scaling doesn't need
3993
+ // bilinear filtering — pure int index mapping with a precomputed column
3994
+ // table is ~8x faster than the 4-sample float-bilinear loop below, which is
3995
+ // the difference between ~14fps and ~60fps while pinch-zooming a full
3996
+ // screen of tiles.
3997
+ // An alpha plane used to disqualify this fast path outright, dropping every
3998
+ // masked image onto the bilinear loop below. That is what a watchOS-style
3999
+ // icon grid is: a square sprite whose corners are transparent. Measured on
4000
+ // bubble-grid (30 icons, 410x502, esp32-s3), panning: PNG-with-alpha ran
4001
+ // 17-23fps against 59.6fps for the same icons flattened to opaque JPEG --
4002
+ // entirely this branch. Nearest sampling works exactly the same way for the
4003
+ // mask as for the colour (same index map), so the alpha case only adds a
4004
+ // per-pixel test on an already-sampled byte: skip a==0, copy a==255, blend
4005
+ // the rest. That keeps the run-length behaviour the 1:1 blit above already
4006
+ // relies on, where an anti-aliased disc is {0,255} apart from a thin edge.
4007
+ //
4008
+ // MINIFICATION ONLY. When the destination is no larger than the source, every
4009
+ // destination pixel already lands on a distinct source texel: nearest DROPS
4010
+ // texels, and the 4-tap bilinear below cannot put the dropped energy back
4011
+ // either (that needs a box/mip filter over the whole footprint), so the two
4012
+ // differ by well under a texel while bilinear costs ~8x. That decimation case
4013
+ // is what the fast path was measured on — a full screen of map tiles fitted to
4014
+ // the panel, and an icon grid whose sprites are drawn smaller than they load.
4015
+ // MAGNIFYING is the opposite: each source texel then covers more than one
4016
+ // destination pixel, so nearest replicates it into a visibly blocky run, and
4017
+ // interpolating between the neighbouring texels is the whole point of asking
4018
+ // for a bigger destination. A 2x2 image blitted at 4x4 must not come back as
4019
+ // four flat quadrants of the exact source colours. The row loop below is the
4020
+ // filtered path; its per-column source mapping is hoisted into a table there so
4021
+ // magnifying costs one bilinear blend per pixel rather than that plus an
4022
+ // integer divide per axis per pixel.
4023
+ if (globalAlpha_ == 255 && dst_w <= src_w && dst_h <= src_h) {
4024
+ const ClipRect *clip = &clipStack_[clipDepth_];
4025
+ const int clip_x0 = clip->x0 > 0 ? clip->x0 : 0;
4026
+ const int clip_y0 = clip->y0 > 0 ? clip->y0 : 0;
4027
+ const int clip_x1 = clip->x1 < width_ ? clip->x1 : width_ - 1;
4028
+ const int clip_y1 = clip->y1 < height_ ? clip->y1 : height_ - 1;
4029
+ const int x0 = dx > clip_x0 ? dx : clip_x0;
4030
+ const int y0 = dy > clip_y0 ? dy : clip_y0;
4031
+ const int x1 = dx + dst_w - 1 < clip_x1 ? dx + dst_w - 1 : clip_x1;
4032
+ const int y1 = dy + dst_h - 1 < clip_y1 ? dy + dst_h - 1 : clip_y1;
4033
+ const int count = x1 - x0 + 1;
4034
+ if (count <= 0 || y0 > y1) return;
4035
+ if (count <= 2048) {
4036
+ std::int16_t sxMap[2048];
4037
+ for (int x = x0; x <= x1; x++) {
4038
+ int sx = (((x - dx) * 2 + 1) * src_w) / (dst_w * 2);
4039
+ if (sx > src_w - 1) sx = src_w - 1;
4040
+ sxMap[x - x0] = static_cast<std::int16_t>(sx);
4041
+ }
4042
+ for (int y = y0; y <= y1; y++) {
4043
+ int sy = (((y - dy) * 2 + 1) * src_h) / (dst_h * 2);
4044
+ if (sy > src_h - 1) sy = src_h - 1;
4045
+ const pixel::native_t *src_row = &src[sy * src_w];
4046
+ const std::uint8_t *alpha_row = alpha ? &alpha[sy * src_w] : nullptr;
4047
+ #if GEA_EMBEDDED_DISPLAY_ROTATE_LANDSCAPE
4048
+ if (landscapeRot_) {
4049
+ if (!alpha_row) {
4050
+ for (int i = 0; i < count; i++) rotSet(x0 + i, y, src_row[sxMap[i]]);
4051
+ } else {
4052
+ for (int i = 0; i < count; i++) {
4053
+ const int sx = sxMap[i];
4054
+ const std::uint8_t a = alpha_row[sx];
4055
+ if (a == 0) continue;
4056
+ if (a == 255) rotSet(x0 + i, y, src_row[sx]);
4057
+ else rotBlend(x0 + i, y, src_row[sx], a);
4058
+ }
4059
+ }
4060
+ } else {
4061
+ #endif
4062
+ #if GEA_PIXEL_STORAGE_PACKED
4063
+ std::uint8_t *dnib = packedRow(rowToPhysical(y));
4064
+ if (!alpha_row) {
4065
+ for (int i = 0; i < count; i++) pixel::packed::set(dnib, x0 + i, src_row[sxMap[i]]);
4066
+ } else {
4067
+ for (int i = 0; i < count; i++) {
4068
+ const int sx = sxMap[i];
4069
+ const std::uint8_t a = alpha_row[sx];
4070
+ if (a == 0) continue;
4071
+ if (a == 255) pixel::packed::set(dnib, x0 + i, src_row[sx]);
4072
+ else pixel::packed::blendPixel(dnib, x0 + i, src_row[sx], a);
4073
+ }
4074
+ }
4075
+ #else
4076
+ pixel::native_t *dst_row = &pixels_[rowToPhysical(y) * stride_ + x0];
4077
+ if (!alpha_row) {
4078
+ for (int i = 0; i < count; i++) dst_row[i] = src_row[sxMap[i]];
4079
+ } else {
4080
+ for (int i = 0; i < count; i++) {
4081
+ const int sx = sxMap[i];
4082
+ const std::uint8_t a = alpha_row[sx];
4083
+ if (a == 0) continue;
4084
+ if (a == 255) dst_row[i] = src_row[sx];
4085
+ else dst_row[i] = pixel::blendNative(src_row[sx], dst_row[i], a);
4086
+ }
4087
+ }
4088
+ #endif
4089
+ #if GEA_EMBEDDED_DISPLAY_ROTATE_LANDSCAPE
4090
+ }
4091
+ #endif
4092
+ }
4093
+ markDirtyClipped(dx, dy, dx + dst_w - 1, dy + dst_h - 1);
4094
+ return;
4095
+ }
4096
+ }
4097
+
4098
+ auto sourceAxis = [](int dest, int srcSize, int dstSize, int *i0, int *i1, int *frac) {
4099
+ const int coord = (((dest * 2 + 1) * srcSize * 256) / (dstSize * 2)) - 128;
4100
+ if (coord <= 0 || srcSize == 1) {
4101
+ *i0 = 0;
4102
+ *i1 = 0;
4103
+ *frac = 0;
4104
+ return;
4105
+ }
4106
+ const int last = srcSize - 1;
4107
+ const int lastCoord = last * 256;
4108
+ if (coord >= lastCoord) {
4109
+ *i0 = last;
4110
+ *i1 = last;
4111
+ *frac = 0;
4112
+ return;
4113
+ }
4114
+ *i0 = coord / 256;
4115
+ *i1 = *i0 + 1;
4116
+ *frac = coord - *i0 * 256;
4117
+ };
4118
+
4119
+ const ClipRect *clip = &clipStack_[clipDepth_];
4120
+ const int clip_x0 = clip->x0 > 0 ? clip->x0 : 0;
4121
+ const int clip_y0 = clip->y0 > 0 ? clip->y0 : 0;
4122
+ const int clip_x1 = clip->x1 < width_ ? clip->x1 : width_ - 1;
4123
+ const int clip_y1 = clip->y1 < height_ ? clip->y1 : height_ - 1;
4124
+
4125
+ // The x-axis source mapping depends only on the destination COLUMN, so
4126
+ // recomputing it inside the row loop paid an integer multiply + divide per
4127
+ // destination pixel (Xtensa has no hardware divide). Precompute it once, the
4128
+ // same way the nearest path above precomputes its column table. `sourceAxis`
4129
+ // only ever reports i1 == i0 + 1 when frac > 0 (the three early returns all set
4130
+ // frac = 0), so the second index is recoverable from the fraction alone and the
4131
+ // table stays 3 bytes per column.
4132
+ constexpr int kScaledAxisTableMax = 2048;
4133
+ std::int16_t sxMap[kScaledAxisTableMax];
4134
+ std::uint8_t fxMap[kScaledAxisTableMax];
4135
+ const bool haveColumnTable = dst_w <= kScaledAxisTableMax && src_w <= 32767;
4136
+ if (haveColumnTable) {
4137
+ for (int x = 0; x < dst_w; x++) {
4138
+ int i0 = 0, i1 = 0, frac = 0;
4139
+ sourceAxis(x, src_w, dst_w, &i0, &i1, &frac);
4140
+ sxMap[x] = static_cast<std::int16_t>(i0);
4141
+ fxMap[x] = static_cast<std::uint8_t>(frac);
4142
+ }
4143
+ }
4144
+
4145
+ for (int y = 0; y < dst_h; y++) {
4146
+ int py = dy + y;
4147
+ if (py < clip_y0 || py > clip_y1) continue;
4148
+ int sy0 = 0, sy1 = 0, fy = 0;
4149
+ sourceAxis(y, src_h, dst_h, &sy0, &sy1, &fy);
4150
+ const int wy0 = 256 - fy;
4151
+ const int wy1 = fy;
4152
+ for (int x = 0; x < dst_w; x++) {
4153
+ int px = dx + x;
4154
+ if (px < clip_x0 || px > clip_x1) continue;
4155
+ int sx0 = 0, sx1 = 0, fx = 0;
4156
+ if (haveColumnTable) {
4157
+ sx0 = sxMap[x];
4158
+ fx = fxMap[x];
4159
+ sx1 = fx > 0 ? sx0 + 1 : sx0;
4160
+ } else {
4161
+ sourceAxis(x, src_w, dst_w, &sx0, &sx1, &fx);
4162
+ }
4163
+ const int wx0 = 256 - fx;
4164
+ const int wx1 = fx;
4165
+ // FLOAT accumulators (no int64 anywhere). The previous int64 version cost
4166
+ // ~160ms for a 220x220 icon on this board: Xtensa LX7 has NO hardware
4167
+ // 64-bit divide AND no hardware int64->float, so both int64 divides and
4168
+ // int64->float conversions are software routines. Here `a*weight` fits in
4169
+ // int32 (<=255*65536), so every step is int32 multiply + hardware int32->
4170
+ // float (FLOAT.S) + FPU multiply/add/divide. The result is a 0..255 channel
4171
+ // and rSum == channel*alphaSum, so float rounding stays far below 1 LSB.
4172
+ float rSum = 0.0f;
4173
+ float gSum = 0.0f;
4174
+ float bSum = 0.0f;
4175
+ float alphaSum = 0.0f;
4176
+ auto addSample = [&](int sx, int sy, int weight) {
4177
+ if (weight <= 0) return;
4178
+ const int index = sy * src_w + sx;
4179
+ const int a = alpha ? alpha[index] : 255;
4180
+ if (a <= 0) return;
4181
+ int r = 0, g = 0, b = 0, sa = 0;
4182
+ pixel::unpackNative8(src[index], &r, &g, &b, &sa);
4183
+ const float aw = static_cast<float>(a * weight); // a*weight fits int32
4184
+ rSum += static_cast<float>(r) * aw;
4185
+ gSum += static_cast<float>(g) * aw;
4186
+ bSum += static_cast<float>(b) * aw;
4187
+ alphaSum += aw;
4188
+ };
4189
+ addSample(sx0, sy0, wx0 * wy0);
4190
+ addSample(sx1, sy0, wx1 * wy0);
4191
+ addSample(sx0, sy1, wx0 * wy1);
4192
+ addSample(sx1, sy1, wx1 * wy1);
4193
+ if (alphaSum <= 0.0f) continue;
4194
+ const float invAlpha = 1.0f / alphaSum;
4195
+ const int outA = static_cast<int>(alphaSum * (1.0f / 65536.0f) + 0.5f);
4196
+ const int r = static_cast<int>(rSum * invAlpha + 0.5f);
4197
+ const int g = static_cast<int>(gSum * invAlpha + 0.5f);
4198
+ const int b = static_cast<int>(bSum * invAlpha + 0.5f);
4199
+ // Panel-endian-aware output: source samples were un-swapped by
4200
+ // unpackRgb565 above, so the averaged r,g,b are true channels. Emit in
4201
+ // framebuffer (byte-swapped) format; raw rgb565FromRgb888 made scaled
4202
+ // images / custom-font glyph atlases land un-swapped on PANEL_ENDIAN=1.
4203
+ const pixel::native_t c = pixel::packNative8(r, g, b, 255);
4204
+ if (outA >= 255) writePixel(px, py, c);
4205
+ else writePixelAlpha(px, py, c, static_cast<std::uint8_t>(outA));
4206
+ }
4207
+ }
4208
+ markDirtyClipped(dx, dy, dx + dst_w - 1, dy + dst_h - 1);
4209
+ }
4210
+
4211
+ void Canvas::drawImageRotated90CW(
4212
+ const pixel::native_t *src, const std::uint8_t *alpha, int src_w, int src_h,
4213
+ int dx, int dy, int dst_w, int dst_h)
4214
+ {
4215
+ if (!pixels_ || !src) return;
4216
+ if (dst_w <= 0 || dst_h <= 0 || src_w <= 0 || src_h <= 0) return;
4217
+
4218
+ const ClipRect *clip = &clipStack_[clipDepth_];
4219
+ const int clip_x0 = clip->x0 > 0 ? clip->x0 : 0;
4220
+ const int clip_y0 = clip->y0 > 0 ? clip->y0 : 0;
4221
+ const int clip_x1 = clip->x1 < width_ ? clip->x1 : width_ - 1;
4222
+ const int clip_y1 = clip->y1 < height_ ? clip->y1 : height_ - 1;
4223
+ const int x0 = dx > clip_x0 ? dx : clip_x0;
4224
+ const int y0 = dy > clip_y0 ? dy : clip_y0;
4225
+ const int x1 = dx + dst_w - 1 < clip_x1 ? dx + dst_w - 1 : clip_x1;
4226
+ const int y1 = dy + dst_h - 1 < clip_y1 ? dy + dst_h - 1 : clip_y1;
4227
+ if (x0 > x1 || y0 > y1) return;
4228
+
4229
+ const std::uint8_t globalAlpha = globalAlpha_;
4230
+ if (globalAlpha == 0) return;
4231
+
4232
+ for (int py = y0; py <= y1; py++) {
4233
+ const int localY = py - dy;
4234
+ int sx = (((localY * 2 + 1) * src_w) / (dst_h * 2));
4235
+ if (sx < 0) sx = 0;
4236
+ if (sx >= src_w) sx = src_w - 1;
4237
+ #if GEA_PIXEL_STORAGE_PACKED
4238
+ std::uint8_t *dnib = packedRow(rowToPhysical(py));
4239
+ #else
4240
+ pixel::native_t *dstRow = &pixels_[rowToPhysical(py) * stride_ + x0];
4241
+ #endif
4242
+ for (int px = x0; px <= x1; px++) {
4243
+ const int localX = px - dx;
4244
+ int sy = src_h - 1 - (((localX * 2 + 1) * src_h) / (dst_w * 2));
4245
+ if (sy < 0) sy = 0;
4246
+ if (sy >= src_h) sy = src_h - 1;
4247
+ const int srcIndex = sy * src_w + sx;
4248
+ const pixel::native_t source = src[srcIndex];
4249
+ int effectiveAlpha = globalAlpha;
4250
+ if (!alpha && globalAlpha == 255) effectiveAlpha = 255;
4251
+ else if (alpha) effectiveAlpha = (effectiveAlpha * alpha[srcIndex]) / 255;
4252
+ if (effectiveAlpha <= 0) continue;
4253
+ #if GEA_EMBEDDED_DISPLAY_ROTATE_LANDSCAPE
4254
+ if (landscapeRot_) rotBlend(px, py, source, effectiveAlpha);
4255
+ else
4256
+ #endif
4257
+ #if GEA_PIXEL_STORAGE_PACKED
4258
+ pixel::packed::blendPixel(dnib, px, source, effectiveAlpha);
4259
+ #else
4260
+ if (effectiveAlpha >= 255) dstRow[px - x0] = source;
4261
+ else dstRow[px - x0] = pixel::blendNative(source, dstRow[px - x0], static_cast<std::uint8_t>(effectiveAlpha));
4262
+ #endif
4263
+ }
4264
+ }
4265
+ markDirtyClipped(dx, dy, dx + dst_w - 1, dy + dst_h - 1);
4266
+ }
4267
+
4268
+ namespace {
4269
+
4270
+ int clampedCornerRadius(int radius, int w, int h)
4271
+ {
4272
+ if (radius <= 0 || w <= 0 || h <= 0) return 0;
4273
+ return std::min(radius, std::min(w, h) / 2);
4274
+ }
4275
+
4276
+ bool insideRoundedCorner(int offsetX, int offsetY, int radius)
4277
+ {
4278
+ const int dx = radius - offsetX;
4279
+ const int dy = radius - offsetY;
4280
+ return dx * dx + dy * dy <= radius * radius;
4281
+ }
4282
+
4283
+ bool insideRoundedImageRect(int x, int y, int w, int h, int tl, int tr, int br, int bl)
4284
+ {
4285
+ tl = clampedCornerRadius(tl, w, h);
4286
+ tr = clampedCornerRadius(tr, w, h);
4287
+ br = clampedCornerRadius(br, w, h);
4288
+ bl = clampedCornerRadius(bl, w, h);
4289
+ if (tl > 0 && x < tl && y < tl) return insideRoundedCorner(x, y, tl);
4290
+ if (tr > 0 && x >= w - tr && y < tr) return insideRoundedCorner(w - 1 - x, y, tr);
4291
+ if (br > 0 && x >= w - br && y >= h - br) return insideRoundedCorner(w - 1 - x, h - 1 - y, br);
4292
+ if (bl > 0 && x < bl && y >= h - bl) return insideRoundedCorner(x, h - 1 - y, bl);
4293
+ return true;
4294
+ }
4295
+
4296
+ } // namespace
4297
+
4298
+ void Canvas::drawImageRounded(
4299
+ const pixel::native_t *src, const std::uint8_t *alpha, int src_w, int src_h,
4300
+ int dx, int dy, int dst_w, int dst_h, int tl, int tr, int br, int bl)
4301
+ {
4302
+ if (!pixels_ || !src) return;
4303
+ if (dst_w <= 0 || dst_h <= 0 || src_w <= 0 || src_h <= 0) return;
4304
+ if (tl <= 0 && tr <= 0 && br <= 0 && bl <= 0) {
4305
+ drawImage(src, alpha, src_w, src_h, dx, dy, dst_w, dst_h);
4306
+ return;
4307
+ }
4308
+
4309
+ const ClipRect *clip = &clipStack_[clipDepth_];
4310
+ const int x0 = std::max(std::max(dx, 0), clip->x0);
4311
+ const int y0 = std::max(std::max(dy, 0), clip->y0);
4312
+ const int x1 = std::min(std::min(dx + dst_w - 1, width_ - 1), clip->x1);
4313
+ const int y1 = std::min(std::min(dy + dst_h - 1, height_ - 1), clip->y1);
4314
+ if (x0 > x1 || y0 > y1) return;
4315
+
4316
+ // CIRCLE fast path. A square destination of odd side 2r+1 with all four
4317
+ // radii at r is exactly the disc (lx-r)^2 + (ly-r)^2 <= r^2 -- identical to
4318
+ // what insideRoundedImageRect computes, corner by corner. A disc's row span
4319
+ // is analytic, so it can be resolved ONCE per row instead of testing every
4320
+ // pixel: the generic loop below re-clamps four corner radii and divides for
4321
+ // every pixel of the bounding box, including the ~21% that lie outside the
4322
+ // shape. Measured on bubble-grid (27 icons, esp32-s3) while dragging, which
4323
+ // re-rasterises the whole screen every frame: endBatch 85ms -> 11ms/frame,
4324
+ // 10.6fps -> 60fps.
4325
+ const int rr = clampedCornerRadius(tl, dst_w, dst_h);
4326
+ if (globalAlpha_ == 255 && tl == tr && tr == br && br == bl && dst_w == dst_h && dst_w == 2 * rr + 1 &&
4327
+ dst_w <= 1024) {
4328
+ // The chunked present replays this command once per flush chunk, so the
4329
+ // column map is rebuilt several times per icon per frame -- one integer
4330
+ // division per destination column each time (~10k divisions/frame for a
4331
+ // screen of icons). At 1:1 the map is the identity and the row copy is a
4332
+ // memcpy, so skip building it entirely.
4333
+ const bool oneToOne = (dst_w == src_w && dst_h == src_h);
4334
+ std::int16_t sxMap[1024];
4335
+ if (!oneToOne) {
4336
+ for (int i = 0; i < dst_w; i++) {
4337
+ const int sx = (i * src_w) / dst_w;
4338
+ sxMap[i] = static_cast<std::int16_t>(sx < src_w - 1 ? sx : src_w - 1);
4339
+ }
4340
+ }
4341
+ // Reuse the circle rasteriser's memoised span table -- the same
4342
+ // CanvasMath::circleRadiusSpans() fillCircleNoDirty() uses. It already
4343
+ // holds [r-dx, r+dx] per row for this radius, so the disc costs a table
4344
+ // lookup per row instead of an integer sqrt, and repeat draws of the
4345
+ // same radius (every full-size icon, every chunk that touches it) pay
4346
+ // nothing at all.
4347
+ const std::uint8_t (*spans)[2] = CanvasMath::instance().circleRadiusSpans(rr);
4348
+ for (int py = y0; py <= y1; py++) {
4349
+ const int ly = py - dy;
4350
+ int lo, hi;
4351
+ if (spans) {
4352
+ lo = spans[ly][0];
4353
+ hi = spans[ly][1];
4354
+ } else {
4355
+ const int ddy = ly - rr;
4356
+ const int span2 = rr * rr - ddy * ddy;
4357
+ if (span2 < 0) continue;
4358
+ const int hw = CanvasMath::integerSqrt(span2);
4359
+ lo = rr - hw;
4360
+ hi = rr + hw;
4361
+ }
4362
+ int xa = dx + lo;
4363
+ int xb = dx + hi;
4364
+ if (xa < x0) xa = x0;
4365
+ if (xb > x1) xb = x1;
4366
+ if (xa > xb) continue;
4367
+ // At 1:1 the source row IS the destination row. (Measured neutral --
4368
+ // the compiler already strength-reduces it -- but it states the
4369
+ // invariant rather than rediscovering it by division.)
4370
+ const int sy = oneToOne ? ly : std::min((ly * src_h) / dst_h, src_h - 1);
4371
+ const pixel::native_t *src_row = &src[sy * src_w];
4372
+ const std::uint8_t *alpha_row = alpha ? &alpha[sy * src_w] : nullptr;
4373
+ #if GEA_EMBEDDED_DISPLAY_ROTATE_LANDSCAPE
4374
+ if (landscapeRot_) {
4375
+ for (int px = xa; px <= xb; px++) {
4376
+ const int sx = sxMap[px - dx];
4377
+ if (alpha_row) {
4378
+ const std::uint8_t a = alpha_row[sx];
4379
+ if (a == 0) continue;
4380
+ if (a == 255) rotSet(px, py, src_row[sx]);
4381
+ else rotBlend(px, py, src_row[sx], a);
4382
+ } else {
4383
+ rotSet(px, py, src_row[sx]);
4384
+ }
4385
+ }
4386
+ } else {
4387
+ #endif
4388
+ #if GEA_PIXEL_STORAGE_PACKED
4389
+ std::uint8_t *dnib = packedRow(rowToPhysical(py));
4390
+ for (int px = xa; px <= xb; px++) {
4391
+ const int sx = sxMap[px - dx];
4392
+ if (alpha_row) {
4393
+ const std::uint8_t a = alpha_row[sx];
4394
+ if (a == 0) continue;
4395
+ if (a == 255) pixel::packed::set(dnib, px, src_row[sx]);
4396
+ else pixel::packed::blendPixel(dnib, px, src_row[sx], a);
4397
+ } else {
4398
+ pixel::packed::set(dnib, px, src_row[sx]);
4399
+ }
4400
+ }
4401
+ #else
4402
+ pixel::native_t *dst_row = &pixels_[rowToPhysical(py) * stride_];
4403
+ // Hoist the mask test out of the pixel loop, and take a row memcpy
4404
+ // when the blit is 1:1 and opaque -- which is every full-size icon.
4405
+ // A per-pixel gather there costs ~5ms/frame more than memcpy on a
4406
+ // full-screen repaint.
4407
+ if (!alpha_row) {
4408
+ if (oneToOne) {
4409
+ // Inline word copy rather than std::memcpy: the disc is copied
4410
+ // one ROW SPAN at a time, so a screen of icons makes ~2.2k calls
4411
+ // per frame for ~140-byte runs, where the library call's setup is
4412
+ // a real fraction of the work. Both buffers are pixel-aligned, so
4413
+ // take 2 pixels per 32-bit move when they share 4-byte alignment.
4414
+ const pixel::native_t *sp = src_row + (xa - dx);
4415
+ pixel::native_t *dp = dst_row + xa;
4416
+ int n = xb - xa + 1;
4417
+ if (((reinterpret_cast<std::uintptr_t>(sp) | reinterpret_cast<std::uintptr_t>(dp)) & 3u) == 0) {
4418
+ std::uint32_t *d32 = reinterpret_cast<std::uint32_t *>(dp);
4419
+ const std::uint32_t *s32 = reinterpret_cast<const std::uint32_t *>(sp);
4420
+ const int words = n >> 1;
4421
+ for (int i = 0; i < words; i++) d32[i] = s32[i];
4422
+ if (n & 1) dp[n - 1] = sp[n - 1];
4423
+ } else {
4424
+ for (int i = 0; i < n; i++) dp[i] = sp[i];
4425
+ }
4426
+ } else {
4427
+ for (int px = xa; px <= xb; px++) dst_row[px] = src_row[sxMap[px - dx]];
4428
+ }
4429
+ } else {
4430
+ for (int px = xa; px <= xb; px++) {
4431
+ const int sx = sxMap[px - dx];
4432
+ const std::uint8_t a = alpha_row[sx];
4433
+ if (a == 0) continue;
4434
+ if (a == 255) dst_row[px] = src_row[sx];
4435
+ else dst_row[px] = pixel::blendNative(src_row[sx], dst_row[px], a);
4436
+ }
4437
+ }
4438
+ #endif
4439
+ #if GEA_EMBEDDED_DISPLAY_ROTATE_LANDSCAPE
4440
+ }
4441
+ #endif
4442
+ }
4443
+ markDirtyClipped(dx, dy, dx + dst_w - 1, dy + dst_h - 1);
4444
+ return;
4445
+ }
4446
+
4447
+ for (int py = y0; py <= y1; py++) {
4448
+ const int localY = py - dy;
4449
+ const int sy = std::min((localY * src_h) / dst_h, src_h - 1);
4450
+ for (int px = x0; px <= x1; px++) {
4451
+ const int localX = px - dx;
4452
+ if (!insideRoundedImageRect(localX, localY, dst_w, dst_h, tl, tr, br, bl)) continue;
4453
+ const int sx = std::min((localX * src_w) / dst_w, src_w - 1);
4454
+ const int srcIndex = sy * src_w + sx;
4455
+ if (alpha)
4456
+ writePixelNativeAlpha(px, py, src[srcIndex], alpha[srcIndex]);
4457
+ else
4458
+ writePixelNative(px, py, src[srcIndex]);
4459
+ }
4460
+ }
4461
+ markDirtyClipped(dx, dy, dx + dst_w - 1, dy + dst_h - 1);
4462
+ }
4463
+
4464
+ void Canvas::drawImageTiledX(
4465
+ const pixel::native_t *src, const std::uint8_t *alpha, int src_w, int src_h,
4466
+ int dx, int dy, int width)
4467
+ {
4468
+ if (!pixels_ || !src) return;
4469
+ if (src_w <= 0 || src_h <= 0 || width <= 0) return;
4470
+
4471
+ const ClipRect *clip = &clipStack_[clipDepth_];
4472
+ const int clip_x0 = clip->x0 > 0 ? clip->x0 : 0;
4473
+ const int clip_y0 = clip->y0 > 0 ? clip->y0 : 0;
4474
+ const int clip_x1 = clip->x1 < width_ ? clip->x1 : width_ - 1;
4475
+ const int clip_y1 = clip->y1 < height_ ? clip->y1 : height_ - 1;
4476
+
4477
+ int x0 = dx;
4478
+ int x1 = dx + width - 1;
4479
+ int y0 = dy;
4480
+ int y1 = dy + src_h - 1;
4481
+ if (x0 < clip_x0) x0 = clip_x0;
4482
+ if (x1 > clip_x1) x1 = clip_x1;
4483
+ if (y0 < clip_y0) y0 = clip_y0;
4484
+ if (y1 > clip_y1) y1 = clip_y1;
4485
+ if (x0 > x1 || y0 > y1) return;
4486
+
4487
+ const std::uint8_t global_alpha = globalAlpha_;
4488
+ if (global_alpha == 0) return;
4489
+
4490
+ for (int dest_y = y0; dest_y <= y1; dest_y++) {
4491
+ const int src_y = dest_y - dy;
4492
+ int dest_x = x0;
4493
+ while (dest_x <= x1) {
4494
+ int src_x = (dest_x - dx) % src_w;
4495
+ if (src_x < 0) src_x += src_w;
4496
+ const int run_w = std::min(src_w - src_x, x1 - dest_x + 1);
4497
+ const pixel::native_t *src_row = &src[src_y * src_w + src_x];
4498
+ #if GEA_EMBEDDED_DISPLAY_ROTATE_LANDSCAPE
4499
+ if (landscapeRot_) {
4500
+ if (!alpha && global_alpha == 255) {
4501
+ for (int i = 0; i < run_w; i++) rotSet(dest_x + i, dest_y, src_row[i]);
4502
+ } else if (!alpha) {
4503
+ for (int i = 0; i < run_w; i++) rotBlend(dest_x + i, dest_y, src_row[i], global_alpha);
4504
+ } else {
4505
+ const std::uint8_t *alpha_row = &alpha[src_y * src_w + src_x];
4506
+ for (int i = 0; i < run_w; i++) {
4507
+ const std::uint8_t a = alpha_row[i];
4508
+ if (a == 0) continue;
4509
+ const int eff = (global_alpha == 255) ? a : (a * global_alpha) / 255;
4510
+ if (eff <= 0) continue;
4511
+ if (eff >= 255) rotSet(dest_x + i, dest_y, src_row[i]);
4512
+ else rotBlend(dest_x + i, dest_y, src_row[i], eff);
4513
+ }
4514
+ }
4515
+ } else {
4516
+ #endif
4517
+ #if GEA_PIXEL_STORAGE_PACKED
4518
+ std::uint8_t *dnib = packedRow(rowToPhysical(dest_y));
4519
+ if (!alpha && global_alpha == 255) {
4520
+ pixel::packed::writeUnpacked(dnib, dest_x, src_row, run_w);
4521
+ } else if (!alpha) {
4522
+ for (int i = 0; i < run_w; i++) pixel::packed::blendPixel(dnib, dest_x + i, src_row[i], global_alpha);
4523
+ } else {
4524
+ const std::uint8_t *alpha_row = &alpha[src_y * src_w + src_x];
4525
+ if (global_alpha == 255) {
4526
+ int i = 0;
4527
+ while (i < run_w) {
4528
+ while (i < run_w && alpha_row[i] == 0) i++;
4529
+ const int run_start = i;
4530
+ while (i < run_w && alpha_row[i] == 255) i++;
4531
+ if (i > run_start) pixel::packed::writeUnpacked(dnib, dest_x + run_start, src_row + run_start, i - run_start);
4532
+ if (i < run_w && alpha_row[i] != 0 && alpha_row[i] != 255) {
4533
+ pixel::packed::blendPixel(dnib, dest_x + i, src_row[i], alpha_row[i]);
4534
+ i++;
4535
+ }
4536
+ }
4537
+ } else {
4538
+ for (int i = 0; i < run_w; i++) {
4539
+ const std::uint8_t a = alpha_row[i];
4540
+ if (a == 0) continue;
4541
+ const int eff = (a * global_alpha) / 255;
4542
+ if (eff <= 0) continue;
4543
+ pixel::packed::blendPixel(dnib, dest_x + i, src_row[i], eff);
4544
+ }
4545
+ }
4546
+ }
4547
+ #else
4548
+ pixel::native_t *dst_row = &pixels_[rowToPhysical(dest_y) * stride_ + dest_x];
4549
+
4550
+ if (!alpha && global_alpha == 255) {
4551
+ std::memcpy(dst_row, src_row, static_cast<std::size_t>(run_w) * sizeof(pixel::native_t));
4552
+ } else if (!alpha) {
4553
+ for (int i = 0; i < run_w; i++) dst_row[i] = pixel::blendNative(src_row[i], dst_row[i], global_alpha);
4554
+ } else {
4555
+ const std::uint8_t *alpha_row = &alpha[src_y * src_w + src_x];
4556
+ if (global_alpha == 255) {
4557
+ int i = 0;
4558
+ while (i < run_w) {
4559
+ while (i < run_w && alpha_row[i] == 0) i++;
4560
+ const int run_start = i;
4561
+ while (i < run_w && alpha_row[i] == 255) i++;
4562
+ if (i > run_start) {
4563
+ std::memcpy(dst_row + run_start, src_row + run_start,
4564
+ static_cast<std::size_t>(i - run_start) * sizeof(pixel::native_t));
4565
+ }
4566
+ if (i < run_w && alpha_row[i] != 0 && alpha_row[i] != 255) {
4567
+ dst_row[i] = pixel::blendNative(src_row[i], dst_row[i], alpha_row[i]);
4568
+ i++;
4569
+ }
4570
+ }
4571
+ } else {
4572
+ for (int i = 0; i < run_w; i++) {
4573
+ const std::uint8_t a = alpha_row[i];
4574
+ if (a == 0) continue;
4575
+ const int eff = (a * global_alpha) / 255;
4576
+ if (eff <= 0) continue;
4577
+ if (eff >= 255) dst_row[i] = src_row[i];
4578
+ else dst_row[i] = pixel::blendNative(src_row[i], dst_row[i], static_cast<std::uint8_t>(eff));
4579
+ }
4580
+ }
4581
+ }
4582
+ #endif
4583
+ #if GEA_EMBEDDED_DISPLAY_ROTATE_LANDSCAPE
4584
+ }
4585
+ #endif
4586
+
4587
+ dest_x += run_w;
4588
+ }
4589
+ }
4590
+
4591
+ markDirty(x0, y0, x1, y1);
4592
+ }
4593
+
4594
+ } // namespace gea::framework::graphics
4595
+
4596
+ namespace gea::platform::display {
4597
+
4598
+ void Display::setAA(int samples)
4599
+ {
4600
+ gea::framework::graphics::Canvas::setAntialiasSamples(samples);
4601
+ }
4602
+
4603
+ int Display::aa()
4604
+ {
4605
+ return gea::framework::graphics::Canvas::antialiasSamples();
4606
+ }
4607
+
4608
+ } // namespace gea::platform::display