@geastack/targets 0.1.79 → 0.1.81

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.
@@ -0,0 +1,1275 @@
1
+ // Generic parallel-RGB (DPI) panel backend for the ESP32-S3 LCD peripheral.
2
+ //
3
+ // Selected by composing a board whose `chips.display` is `rgb_panel`: the panel
4
+ // has no controller IC to talk to, the S3's LCD_CAM scans a PSRAM framebuffer
5
+ // out continuously and the only board-specific facts are timings and pins,
6
+ // which board.h supplies. The backlight is either a GPIO driven by LEDC PWM or
7
+ // a line on the board's I/O expander (Waveshare's 7" routes it through a
8
+ // CH422G); a panel reset line, when the board has one, is likewise an expander
9
+ // pin. The raster/present pipeline below is shared with the Elecrow rotary's
10
+ // ST7701 target, which is where it was measured and tuned.
11
+ #include "display.h"
12
+
13
+ #include "board.h"
14
+ #include "canvas.h"
15
+ #include "display_present.h"
16
+ #if GEA_BOARD_HAS_EXPANDER
17
+ #include "chip_bindings/expanders/io_expander.h"
18
+ #endif
19
+
20
+ #ifndef GEA_EMBEDDED_DISPLAY_RGB_STRIP_RASTER
21
+ // Strip-raster fused present: compose each horizontal strip in INTERNAL SRAM
22
+ // (fast, cached, no contention with the RGB panel's continuous PSRAM scanout),
23
+ // then bulk-copy the finished strip straight to the live scanout framebuffer.
24
+ // Replaces the slow "raster 1000 scattered circles directly into the PSRAM back
25
+ // buffer (75ms under scanout contention) + memcpy back->scanout (36ms)" path for
26
+ // full-screen-redraw frames. Still composes each strip fully off-screen, so it is
27
+ // tear-equivalent to the double buffer (never exposes clear-then-draw intermediates).
28
+ #define GEA_EMBEDDED_DISPLAY_RGB_STRIP_RASTER 1
29
+ #endif
30
+
31
+ #include "driver/gpio.h"
32
+ #include "driver/ledc.h"
33
+ #include "esp_cache.h"
34
+ #include "esp_heap_caps.h"
35
+ #include "esp_lcd_panel_ops.h"
36
+ #include "esp_lcd_panel_rgb.h"
37
+ #include "esp_log.h"
38
+ #include "esp_rom_sys.h"
39
+ #include "esp_timer.h"
40
+ #include "freertos/FreeRTOS.h"
41
+ #include "freertos/task.h"
42
+ #include "soc/clk_tree_defs.h"
43
+
44
+ #include <algorithm>
45
+ #include <atomic>
46
+ #include <cstdint>
47
+ #include <cstdio>
48
+ #include <cstring>
49
+
50
+ // Second-core worker (defined later in this file). Used by the strip-raster path to
51
+ // copy a finished strip to the PSRAM scanout buffer on the other core while this
52
+ // core rasters the next strip into SRAM.
53
+ extern "C" bool gea_render_parallel_rows_submit(void (*fn)(void *, int, int), void *ctx, int y0, int y1);
54
+ extern "C" void gea_render_parallel_wait();
55
+
56
+ namespace {
57
+
58
+ constexpr const char *kTag = "rgb_panel";
59
+ constexpr int kWidth = gea::platform::display::kWidth;
60
+ constexpr int kHeight = gea::platform::display::kHeight;
61
+ constexpr std::size_t kPixelCount = static_cast<std::size_t>(kWidth) * static_cast<std::size_t>(kHeight);
62
+ constexpr std::size_t kFramebufferBytes = kPixelCount * sizeof(std::uint16_t);
63
+ // Bounce rows: the largest candidate that divides the panel height, so the
64
+ // framebuffer splits into whole bounce buffers whatever the geometry is.
65
+ constexpr int pickBounceRows(int height)
66
+ {
67
+ constexpr int candidates[] = {20, 16, 12, 10, 8, 6, 5, 4, 3, 2, 1};
68
+ for (int rows : candidates) {
69
+ if (height % rows == 0) return rows;
70
+ }
71
+ return 1;
72
+ }
73
+ constexpr int kRgbBounceRows = pickBounceRows(kHeight);
74
+ constexpr std::size_t kRgbBounceBufferPixels = static_cast<std::size_t>(kWidth) * kRgbBounceRows;
75
+ static_assert(kPixelCount % kRgbBounceBufferPixels == 0, "RGB bounce buffer must divide the framebuffer evenly");
76
+ constexpr ledc_mode_t kBacklightLedcMode = LEDC_LOW_SPEED_MODE;
77
+ constexpr ledc_channel_t kBacklightLedcChannel = LEDC_CHANNEL_0;
78
+ constexpr ledc_timer_t kBacklightLedcTimer = LEDC_TIMER_0;
79
+ constexpr ledc_timer_bit_t kBacklightLedcDutyResolution = LEDC_TIMER_10_BIT;
80
+ constexpr std::uint32_t kBacklightLedcMaxDuty = (1u << 10) - 1u;
81
+
82
+ namespace present = gea::framework::display_present;
83
+
84
+ // Internal-SRAM scratch strips that the fused present path composes into before
85
+ // copying to the PSRAM scanout buffer. Double-buffered: while core0 rasters strip
86
+ // N+1 into one half (SRAM), the worker core copies strip N from the other half to
87
+ // scanout (PSRAM) — different buffers, different buses, so they overlap with no
88
+ // contention. Two 24-row strips fit the same 46KB block one 48-row strip used.
89
+ constexpr int kStripRows = 24;
90
+ constexpr int kStripBufferRows = kStripRows * 2;
91
+ constexpr std::size_t kStripBufferPixels = static_cast<std::size_t>(kWidth) * kStripBufferRows;
92
+
93
+ gea::framework::graphics::Canvas g_canvas;
94
+ // Band canvas for the renderer's coarse 2-core replay split: bound to the SAME
95
+ // back buffer as g_canvas but with a private clip stack + dirty accumulator, so
96
+ // the worker core's band replay never races the main core on clip/dirty state.
97
+ // g_renderCoreId is the core the renderer submits from (recorded per
98
+ // gea_render_parallel_submit); Display draw calls on any OTHER core are the
99
+ // worker's band replay and route here via replayCanvas().
100
+ gea::framework::graphics::Canvas g_workerCanvas;
101
+ int g_renderCoreId = -1;
102
+
103
+ bool onWorkerCore()
104
+ {
105
+ return g_renderCoreId >= 0 && static_cast<int>(xPortGetCoreID()) != g_renderCoreId;
106
+ }
107
+
108
+ gea::framework::graphics::Canvas &replayCanvas()
109
+ {
110
+ return onWorkerCore() ? g_workerCanvas : g_canvas;
111
+ }
112
+ esp_lcd_panel_handle_t g_panel = nullptr;
113
+ std::uint16_t *g_framebuffer = nullptr;
114
+ std::uint16_t *g_drawFramebuffer = nullptr;
115
+ std::uint16_t *g_stripBuffer = nullptr;
116
+ // The strip path publishes straight to scanout and leaves g_drawFramebuffer
117
+ // untouched. If a later frame falls back to the per-command path (partial
118
+ // present with no full-screen base), re-sync the back buffer once first.
119
+ bool g_drawBufferStale = false;
120
+ bool g_initialized = false;
121
+ bool g_backlightPwmInitialized = false;
122
+ int g_brightness = 100;
123
+ int g_flushRows = kHeight;
124
+ int g_flushDepth = 1;
125
+ gea::platform::display::DisplayFlushPerfStats g_stats = {};
126
+
127
+ bool clipRect(int *x0, int *y0, int *x1, int *y1);
128
+
129
+ void cacheWritebackAll()
130
+ {
131
+ if (!g_framebuffer) return;
132
+ esp_cache_msync(g_framebuffer,
133
+ kFramebufferBytes,
134
+ ESP_CACHE_MSYNC_FLAG_DIR_C2M | ESP_CACHE_MSYNC_FLAG_UNALIGNED);
135
+ }
136
+
137
+ void cacheWritebackRect(int x0, int y0, int x1, int y1)
138
+ {
139
+ if (!g_framebuffer || !clipRect(&x0, &y0, &x1, &y1)) return;
140
+ const std::size_t begin = static_cast<std::size_t>(y0) * kWidth + static_cast<std::size_t>(x0);
141
+ const std::size_t end = static_cast<std::size_t>(y1) * kWidth + static_cast<std::size_t>(x1) + 1;
142
+ if (end <= begin || end > kPixelCount) return;
143
+ esp_cache_msync(&g_framebuffer[begin],
144
+ (end - begin) * sizeof(std::uint16_t),
145
+ ESP_CACHE_MSYNC_FLAG_DIR_C2M | ESP_CACHE_MSYNC_FLAG_UNALIGNED);
146
+ }
147
+
148
+ void addFlushStats(int64_t totalUs, int pixelCount)
149
+ {
150
+ g_stats.totalUs += totalUs;
151
+ g_stats.callCount += 1;
152
+ g_stats.pixelCount += pixelCount;
153
+ }
154
+
155
+ void addFlushStageStats(int64_t copyUs, int64_t cacheUs)
156
+ {
157
+ g_stats.copyUs += copyUs;
158
+ g_stats.completeWaitUs += cacheUs;
159
+ }
160
+
161
+ #if GEA_BOARD_HAS_EXPANDER
162
+ constexpr int kExpanderBacklightPin = gea::platform::board::expander.backlight;
163
+ constexpr int kExpanderDisplayResetPin = gea::platform::board::expander.displayReset;
164
+ #else
165
+ constexpr int kExpanderBacklightPin = -1;
166
+ constexpr int kExpanderDisplayResetPin = -1;
167
+ #endif
168
+ constexpr gpio_num_t kBacklightPin = gea::platform::board::display.backlight;
169
+
170
+ esp_err_t updateBacklightDuty()
171
+ {
172
+ if (!g_backlightPwmInitialized) return ESP_OK;
173
+ const std::uint32_t duty = (kBacklightLedcMaxDuty * static_cast<std::uint32_t>(g_brightness)) / 100u;
174
+ esp_err_t err = ledc_set_duty(kBacklightLedcMode, kBacklightLedcChannel, duty);
175
+ if (err != ESP_OK) {
176
+ ESP_LOGE(kTag, "failed to set backlight duty: %s", esp_err_to_name(err));
177
+ return err;
178
+ }
179
+ err = ledc_update_duty(kBacklightLedcMode, kBacklightLedcChannel);
180
+ if (err != ESP_OK) {
181
+ ESP_LOGE(kTag, "failed to update backlight duty: %s", esp_err_to_name(err));
182
+ return err;
183
+ }
184
+ return ESP_OK;
185
+ }
186
+
187
+ // An expander line is on/off only: any non-zero brightness lights the panel.
188
+ esp_err_t applyBacklight()
189
+ {
190
+ #if GEA_BOARD_HAS_EXPANDER
191
+ if constexpr (kExpanderBacklightPin >= 0) {
192
+ auto &expander = gea::platform::esp32::chip_bindings::expanders::ioExpander();
193
+ return expander.writePin(kExpanderBacklightPin, g_brightness > 0) ? ESP_OK : ESP_FAIL;
194
+ }
195
+ #endif
196
+ return updateBacklightDuty();
197
+ }
198
+
199
+ esp_err_t initBacklight()
200
+ {
201
+ if constexpr (kBacklightPin < 0) {
202
+ #if GEA_BOARD_HAS_EXPANDER
203
+ if constexpr (kExpanderBacklightPin >= 0) {
204
+ auto &expander = gea::platform::esp32::chip_bindings::expanders::ioExpander();
205
+ if (!expander.init()) {
206
+ ESP_LOGE(kTag, "I/O expander for the backlight did not come up");
207
+ return ESP_FAIL;
208
+ }
209
+ // Dark until the framebuffer holds a cleared frame; start() lights it.
210
+ return expander.writePin(kExpanderBacklightPin, false) ? ESP_OK : ESP_FAIL;
211
+ }
212
+ #endif
213
+ ESP_LOGW(kTag, "no backlight line declared; the panel is expected to light itself");
214
+ return ESP_OK;
215
+ } else {
216
+ ledc_timer_config_t timerConfig = {};
217
+ timerConfig.speed_mode = kBacklightLedcMode;
218
+ timerConfig.timer_num = kBacklightLedcTimer;
219
+ timerConfig.duty_resolution = kBacklightLedcDutyResolution;
220
+ timerConfig.freq_hz = 5000;
221
+ timerConfig.clk_cfg = LEDC_AUTO_CLK;
222
+ esp_err_t err = ledc_timer_config(&timerConfig);
223
+ if (err != ESP_OK) {
224
+ ESP_LOGE(kTag, "failed to configure backlight LEDC timer: %s", esp_err_to_name(err));
225
+ return err;
226
+ }
227
+
228
+ ledc_channel_config_t channelConfig = {};
229
+ channelConfig.gpio_num = kBacklightPin;
230
+ channelConfig.speed_mode = kBacklightLedcMode;
231
+ channelConfig.channel = kBacklightLedcChannel;
232
+ channelConfig.timer_sel = kBacklightLedcTimer;
233
+ channelConfig.duty = 0;
234
+ channelConfig.hpoint = 0;
235
+ err = ledc_channel_config(&channelConfig);
236
+ if (err != ESP_OK) {
237
+ ESP_LOGE(kTag, "failed to configure backlight LEDC channel: %s", esp_err_to_name(err));
238
+ return err;
239
+ }
240
+
241
+ g_backlightPwmInitialized = true;
242
+ return ESP_OK;
243
+ }
244
+ }
245
+
246
+ // A panel whose reset sits on the expander gets a pulse before the LCD
247
+ // peripheral starts scanning; one with no reset line relies on power-on.
248
+ esp_err_t resetPanel()
249
+ {
250
+ #if GEA_BOARD_HAS_EXPANDER
251
+ if constexpr (kExpanderDisplayResetPin >= 0) {
252
+ auto &expander = gea::platform::esp32::chip_bindings::expanders::ioExpander();
253
+ if (!expander.writePin(kExpanderDisplayResetPin, false)) return ESP_FAIL;
254
+ vTaskDelay(pdMS_TO_TICKS(10));
255
+ if (!expander.writePin(kExpanderDisplayResetPin, true)) return ESP_FAIL;
256
+ vTaskDelay(pdMS_TO_TICKS(120));
257
+ }
258
+ #endif
259
+ return ESP_OK;
260
+ }
261
+
262
+ esp_err_t initRgbPanel()
263
+ {
264
+ const auto &display = gea::platform::board::display;
265
+ esp_lcd_rgb_panel_config_t config = {};
266
+ config.clk_src = LCD_CLK_SRC_PLL160M;
267
+ config.timings.pclk_hz = display.pclkHz;
268
+ config.timings.h_res = kWidth;
269
+ config.timings.v_res = kHeight;
270
+ config.timings.hsync_pulse_width = display.hsyncPulseWidth;
271
+ config.timings.hsync_back_porch = display.hsyncBackPorch;
272
+ config.timings.hsync_front_porch = display.hsyncFrontPorch;
273
+ config.timings.vsync_pulse_width = display.vsyncPulseWidth;
274
+ config.timings.vsync_back_porch = display.vsyncBackPorch;
275
+ config.timings.vsync_front_porch = display.vsyncFrontPorch;
276
+ config.timings.flags.pclk_active_neg = display.pclkActiveNeg ? 1 : 0;
277
+ config.data_width = 16;
278
+ config.in_color_format = LCD_COLOR_FMT_RGB565;
279
+ config.out_color_format = LCD_COLOR_FMT_RGB565;
280
+ config.num_fbs = 1;
281
+ // Bounce buffers vs direct PSRAM scanout: with bounce, a core-0 ISR memcpys
282
+ // every scanline batch from PSRAM into internal SRAM (~27.6MB/s at 12MHz pclk)
283
+ // — a standing ~30% CPU tax on the render core. With 0 the GDMA reads the
284
+ // PSRAM framebuffer directly (no CPU in the scanout path); risk is scanout
285
+ // underrun (visible drift) when CPU PSRAM traffic starves the DMA.
286
+ #ifndef GEA_EMBEDDED_DISPLAY_RGB_BOUNCE
287
+ #define GEA_EMBEDDED_DISPLAY_RGB_BOUNCE 1
288
+ #endif
289
+ #if GEA_EMBEDDED_DISPLAY_RGB_BOUNCE
290
+ config.bounce_buffer_size_px = kRgbBounceBufferPixels;
291
+ #else
292
+ config.bounce_buffer_size_px = 0;
293
+ #endif
294
+ config.dma_burst_size = 64;
295
+ config.hsync_gpio_num = display.hsync;
296
+ config.vsync_gpio_num = display.vsync;
297
+ config.de_gpio_num = display.de;
298
+ config.pclk_gpio_num = display.pclk;
299
+ config.disp_gpio_num = display.disp;
300
+ for (int i = 0; i < 16; ++i) config.data_gpio_nums[i] = display.data[i];
301
+ config.flags.fb_in_psram = 1;
302
+
303
+ esp_err_t err = esp_lcd_new_rgb_panel(&config, &g_panel);
304
+ if (err != ESP_OK) {
305
+ ESP_LOGE(kTag, "failed to create RGB panel: %s", esp_err_to_name(err));
306
+ return err;
307
+ }
308
+ err = esp_lcd_panel_reset(g_panel);
309
+ if (err != ESP_OK) return err;
310
+ err = esp_lcd_panel_init(g_panel);
311
+ if (err != ESP_OK) return err;
312
+
313
+ void *fb = nullptr;
314
+ err = esp_lcd_rgb_panel_get_frame_buffer(g_panel, 1, &fb);
315
+ if (err != ESP_OK) {
316
+ ESP_LOGE(kTag, "failed to get RGB framebuffer: %s", esp_err_to_name(err));
317
+ return err;
318
+ }
319
+ g_framebuffer = static_cast<std::uint16_t *>(fb);
320
+ if (!g_framebuffer) return ESP_ERR_NO_MEM;
321
+
322
+ // Double buffer: the panel framebuffer (g_framebuffer) is continuously scanned out,
323
+ // so drawing directly into it exposes every intermediate step (e.g. a tick's
324
+ // background clears, THEN the tick paints — a visible flash). Render into a separate
325
+ // PSRAM back buffer instead; publishDrawRect() copies the fully-composited dirty
326
+ // region into the scanout framebuffer in one shot, so the panel only ever sees
327
+ // finished pixels. Falls back to single-buffered direct draw if PSRAM is exhausted.
328
+ g_drawFramebuffer = static_cast<std::uint16_t *>(
329
+ heap_caps_malloc(kFramebufferBytes, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
330
+ if (!g_drawFramebuffer) {
331
+ ESP_LOGW(kTag, "no PSRAM for back buffer; falling back to single-buffered draw");
332
+ g_drawFramebuffer = g_framebuffer;
333
+ }
334
+
335
+ std::memset(g_framebuffer, 0, kFramebufferBytes);
336
+ if (g_drawFramebuffer != g_framebuffer) std::memset(g_drawFramebuffer, 0, kFramebufferBytes);
337
+ cacheWritebackAll();
338
+ g_canvas.bindPixels(g_drawFramebuffer, kWidth, kHeight);
339
+ g_workerCanvas.bindPixels(g_drawFramebuffer, kWidth, kHeight);
340
+
341
+ #if GEA_EMBEDDED_DISPLAY_RGB_STRIP_RASTER
342
+ // Internal SRAM (not PSRAM): the whole point is to raster off the scanout bus.
343
+ // 16-byte aligned: rows are 960B (16-multiple), so an aligned base keeps every
344
+ // staged-replay row 16-aligned — maximal PIE-SIMD span coverage per scanline.
345
+ g_stripBuffer = static_cast<std::uint16_t *>(
346
+ heap_caps_aligned_alloc(16, kStripBufferPixels * sizeof(std::uint16_t), MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT));
347
+ ESP_LOGI(kTag, "strip-raster %s strip_buf=%p rows=%d",
348
+ g_stripBuffer ? "ON" : "OFF (no internal SRAM)", g_stripBuffer, kStripRows);
349
+ #endif
350
+ ESP_LOGI(kTag, "RGB panel ready %dx%d pclk=%d bounce_rows=%d fb=%p draw_fb=%p single_fb=%d",
351
+ kWidth,
352
+ kHeight,
353
+ display.pclkHz,
354
+ kRgbBounceRows,
355
+ g_framebuffer,
356
+ g_drawFramebuffer,
357
+ g_framebuffer == g_drawFramebuffer ? 1 : 0);
358
+ return ESP_OK;
359
+ }
360
+
361
+ void replayPresentCommand(const gea::platform::display::DisplayPresentCommand &command)
362
+ {
363
+ using Type = gea::platform::display::DisplayPresentCommandType;
364
+ switch (command.type) {
365
+ case Type::Clear:
366
+ g_canvas.clear(command.clear.color);
367
+ break;
368
+ case Type::FillRectRgb565:
369
+ g_canvas.setGlobalAlpha(command.fillRectRgb565.alpha);
370
+ g_canvas.fillRect(command.fillRectRgb565.x,
371
+ command.fillRectRgb565.y,
372
+ command.fillRectRgb565.w,
373
+ command.fillRectRgb565.h,
374
+ command.fillRectRgb565.color);
375
+ break;
376
+ case Type::StrokeRectRgb565:
377
+ g_canvas.setGlobalAlpha(command.strokeRectRgb565.alpha);
378
+ g_canvas.strokeRect(command.strokeRectRgb565.x,
379
+ command.strokeRectRgb565.y,
380
+ command.strokeRectRgb565.w,
381
+ command.strokeRectRgb565.h,
382
+ command.strokeRectRgb565.color);
383
+ break;
384
+ case Type::FillTriangleRgb565:
385
+ g_canvas.setGlobalAlpha(command.fillTriangleRgb565.alpha);
386
+ g_canvas.fillTriangle(command.fillTriangleRgb565.x0,
387
+ command.fillTriangleRgb565.y0,
388
+ command.fillTriangleRgb565.x1,
389
+ command.fillTriangleRgb565.y1,
390
+ command.fillTriangleRgb565.x2,
391
+ command.fillTriangleRgb565.y2,
392
+ command.fillTriangleRgb565.color);
393
+ break;
394
+ case Type::FillTrianglesRgb565: {
395
+ // Depth-ordered batch (farthest-first). Opaque batches take the span-occlusion
396
+ // path so each pixel is written once; translucent ones must stay painter's order.
397
+ const auto &batch = command.fillTrianglesRgb565;
398
+ if (!batch.entries) break;
399
+ g_canvas.setGlobalAlpha(batch.alpha);
400
+ if (batch.alpha == 255) {
401
+ g_canvas.fillTrianglesOpaqueOccluded(batch.entries, batch.count, 0, 0);
402
+ } else {
403
+ for (int i = 0; i < batch.count; i++) {
404
+ const auto &t = batch.entries[i];
405
+ g_canvas.fillTriangle(t.x0, t.y0, t.x1, t.y1, t.x2, t.y2, t.color);
406
+ }
407
+ }
408
+ break;
409
+ }
410
+ case Type::FillCircleRgb565:
411
+ g_canvas.setGlobalAlpha(command.fillCircleRgb565.alpha);
412
+ g_canvas.fillCircle(command.fillCircleRgb565.x,
413
+ command.fillCircleRgb565.y,
414
+ command.fillCircleRgb565.radius,
415
+ command.fillCircleRgb565.color);
416
+ break;
417
+ case Type::StrokeCircleRgb565:
418
+ g_canvas.setGlobalAlpha(command.strokeCircleRgb565.alpha);
419
+ g_canvas.strokeCircle(command.strokeCircleRgb565.x,
420
+ command.strokeCircleRgb565.y,
421
+ command.strokeCircleRgb565.radius,
422
+ command.strokeCircleRgb565.color);
423
+ break;
424
+ case Type::FillCirclesRgb565:
425
+ g_canvas.setGlobalAlpha(command.fillCirclesRgb565.alpha);
426
+ g_canvas.fillCirclesRgb565(command.fillCirclesRgb565.xs,
427
+ command.fillCirclesRgb565.ys,
428
+ command.fillCirclesRgb565.count,
429
+ command.fillCirclesRgb565.radius,
430
+ command.fillCirclesRgb565.colors);
431
+ break;
432
+ case Type::DrawImage:
433
+ g_canvas.setGlobalAlpha(command.drawImage.alpha);
434
+ g_canvas.drawImage(command.drawImage.pixels,
435
+ command.drawImage.alphaPixels,
436
+ command.drawImage.srcWidth,
437
+ command.drawImage.srcHeight,
438
+ command.drawImage.x,
439
+ command.drawImage.y);
440
+ break;
441
+ case Type::DrawImageScaled:
442
+ g_canvas.setGlobalAlpha(command.drawImageScaled.alpha);
443
+ g_canvas.drawImage(command.drawImageScaled.pixels,
444
+ command.drawImageScaled.alphaPixels,
445
+ command.drawImageScaled.srcWidth,
446
+ command.drawImageScaled.srcHeight,
447
+ command.drawImageScaled.x,
448
+ command.drawImageScaled.y,
449
+ command.drawImageScaled.w,
450
+ command.drawImageScaled.h);
451
+ break;
452
+ case Type::DrawImageRotated90CW:
453
+ g_canvas.setGlobalAlpha(command.drawImageRotated90CW.alpha);
454
+ g_canvas.drawImageRotated90CW(command.drawImageRotated90CW.pixels,
455
+ command.drawImageRotated90CW.alphaPixels,
456
+ command.drawImageRotated90CW.srcWidth,
457
+ command.drawImageRotated90CW.srcHeight,
458
+ command.drawImageRotated90CW.x,
459
+ command.drawImageRotated90CW.y,
460
+ command.drawImageRotated90CW.w,
461
+ command.drawImageRotated90CW.h);
462
+ break;
463
+ case Type::DrawImageTiledX:
464
+ g_canvas.setGlobalAlpha(command.drawImageTiledX.alpha);
465
+ g_canvas.drawImageTiledX(command.drawImageTiledX.pixels,
466
+ command.drawImageTiledX.alphaPixels,
467
+ command.drawImageTiledX.srcWidth,
468
+ command.drawImageTiledX.srcHeight,
469
+ command.drawImageTiledX.x,
470
+ command.drawImageTiledX.y,
471
+ command.drawImageTiledX.w);
472
+ break;
473
+ case Type::FillText:
474
+ g_canvas.setGlobalAlpha(command.fillText.alpha);
475
+ g_canvas.drawText(command.fillText.text,
476
+ command.fillText.x,
477
+ command.fillText.y,
478
+ command.fillText.color,
479
+ command.fillText.scale);
480
+ break;
481
+ }
482
+ }
483
+
484
+ bool clipRect(int *x0, int *y0, int *x1, int *y1)
485
+ {
486
+ if (!x0 || !y0 || !x1 || !y1) return false;
487
+ if (*x0 < 0) *x0 = 0;
488
+ if (*y0 < 0) *y0 = 0;
489
+ if (*x1 >= kWidth) *x1 = kWidth - 1;
490
+ if (*y1 >= kHeight) *y1 = kHeight - 1;
491
+ return *x0 <= *x1 && *y0 <= *y1;
492
+ }
493
+
494
+ int publishDrawRect(int x0, int y0, int x1, int y1, int *outX0 = nullptr, int *outY0 = nullptr, int *outX1 = nullptr, int *outY1 = nullptr)
495
+ {
496
+ if (!g_framebuffer || !g_drawFramebuffer || !clipRect(&x0, &y0, &x1, &y1)) return 0;
497
+ if (outX0) *outX0 = x0;
498
+ if (outY0) *outY0 = y0;
499
+ if (outX1) *outX1 = x1;
500
+ if (outY1) *outY1 = y1;
501
+ const int width = x1 - x0 + 1;
502
+ if (g_framebuffer == g_drawFramebuffer) return width * (y1 - y0 + 1);
503
+ for (int y = y0; y <= y1; ++y) {
504
+ const std::size_t offset = static_cast<std::size_t>(y) * kWidth + static_cast<std::size_t>(x0);
505
+ std::memcpy(&g_framebuffer[offset], &g_drawFramebuffer[offset], static_cast<std::size_t>(width) * sizeof(std::uint16_t));
506
+ }
507
+ return width * (y1 - y0 + 1);
508
+ }
509
+
510
+ struct RenderRowWorker {
511
+ TaskHandle_t task = nullptr;
512
+ void (*volatile fn)(void *, int, int) = nullptr;
513
+ void *volatile ctx = nullptr;
514
+ volatile int y0 = 0;
515
+ volatile int y1 = 0;
516
+ std::atomic<std::uint32_t> jobSeq{0};
517
+ std::atomic<bool> done{true};
518
+ // DIAG: cumulative on-worker band execution time (read by the wait-side print;
519
+ // only ever written between done=false and done=true, so the read is stable).
520
+ std::int64_t bandUs = 0;
521
+ bool attempted = false;
522
+ };
523
+
524
+ RenderRowWorker g_renderRowWorker;
525
+ // 12KB (was 8KB for the memcpy-only strip copies): the worker now also runs the
526
+ // renderer's full band replay (gradient projection math + rounded-rect batch +
527
+ // command handlers), which is much deeper than a strip copy.
528
+ constexpr std::uint32_t kRenderRowWorkerStackBytes = 12288;
529
+
530
+ void renderRowWorkerTask(void *)
531
+ {
532
+ // MUST start at 0 (jobSeq's initial value), NOT jobSeq.load(): submit() creates
533
+ // this task and increments jobSeq immediately after, so by the time this task
534
+ // gets its first instructions in, jobSeq is usually already 1 — loading it here
535
+ // would swallow job 1 (the caller times out and the first parallel band is
536
+ // silently dropped; for the in-place recolor that band then stays stale forever,
537
+ // since later recolors only match the CURRENT oldColor).
538
+ std::uint32_t seen = 0;
539
+ std::int64_t idleSince = esp_timer_get_time();
540
+ for (;;) {
541
+ while (g_renderRowWorker.jobSeq.load(std::memory_order_acquire) == seen) {
542
+ if (esp_timer_get_time() - idleSince > 4000) {
543
+ ulTaskNotifyTake(pdTRUE, pdMS_TO_TICKS(100));
544
+ idleSince = esp_timer_get_time();
545
+ }
546
+ }
547
+ seen = g_renderRowWorker.jobSeq.load(std::memory_order_acquire);
548
+ void (*fn)(void *, int, int) = g_renderRowWorker.fn;
549
+ const std::int64_t b0 = esp_timer_get_time();
550
+ if (fn) fn(g_renderRowWorker.ctx, g_renderRowWorker.y0, g_renderRowWorker.y1);
551
+ g_renderRowWorker.bandUs += esp_timer_get_time() - b0;
552
+ g_renderRowWorker.done.store(true, std::memory_order_release);
553
+ idleSince = esp_timer_get_time();
554
+ }
555
+ }
556
+
557
+ #if GEA_EMBEDDED_DISPLAY_RGB_STRIP_RASTER
558
+ // Runs on the worker core: copy a finished SRAM strip (ctx) to PSRAM scanout rows
559
+ // [y0,y1] and write it back so the panel's scanout DMA sees it.
560
+ void copyStripToScanoutThunk(void *ctx, int y0, int y1)
561
+ {
562
+ const std::uint16_t *src = static_cast<const std::uint16_t *>(ctx);
563
+ const int rows = y1 - y0 + 1;
564
+ std::memcpy(&g_framebuffer[static_cast<std::size_t>(y0) * kWidth],
565
+ src,
566
+ static_cast<std::size_t>(rows) * kWidth * sizeof(std::uint16_t));
567
+ cacheWritebackRect(0, y0, kWidth - 1, y1);
568
+ }
569
+
570
+ // Compose the whole frame strip-by-strip in internal SRAM, copying each finished
571
+ // strip to the live scanout buffer. Used only for full-screen-redraw frames
572
+ // (frameHasOpaqueBase), so each strip is fully composited before it is published —
573
+ // tear-equivalent to the PSRAM double buffer, but the 1000-circle raster runs in
574
+ // SRAM instead of fighting the panel's continuous scanout for PSRAM bandwidth.
575
+ //
576
+ // Pipelined across cores: this core rasters strip N+1 into one SRAM half while the
577
+ // worker core copies strip N out of the other half to scanout. Raster (SRAM-only)
578
+ // and copy (PSRAM) hit different buses, so the ~6.5ms raster hides under the ~20ms
579
+ // copy instead of adding to it.
580
+ bool presentStripFused(const present::Frame &frame)
581
+ {
582
+ if (!g_framebuffer || !g_stripBuffer) return false;
583
+ int stripRows = g_flushRows > 0 ? g_flushRows : kStripRows;
584
+ if (stripRows > kStripRows) stripRows = kStripRows;
585
+ const std::int64_t start = esp_timer_get_time();
586
+ bool inFlight = false;
587
+ int idx = 0;
588
+ for (int row = 0; row < kHeight; row += stripRows, ++idx) {
589
+ int rows = stripRows;
590
+ if (row + rows > kHeight) rows = kHeight - row;
591
+ std::uint16_t *buf = g_stripBuffer + static_cast<std::size_t>(idx & 1) * kStripRows * kWidth;
592
+ // Raster strip `idx` into its SRAM half — overlaps the worker copying the
593
+ // previous strip out of the OTHER half (different buffer + bus, no contention).
594
+ present::rasterFrameRowsStrided(buf, kWidth, 0, kWidth, row, rows, kHeight, frame);
595
+ // The single worker handles one copy at a time. Waiting here also guarantees
596
+ // the half we'll reuse two strips from now is free before we raster into it.
597
+ if (inFlight) { gea_render_parallel_wait(); inFlight = false; }
598
+ if (gea_render_parallel_rows_submit(copyStripToScanoutThunk, buf, row, row + rows - 1)) {
599
+ inFlight = true;
600
+ } else {
601
+ copyStripToScanoutThunk(buf, row, row + rows - 1); // no worker: inline copy
602
+ }
603
+ }
604
+ if (inFlight) gea_render_parallel_wait();
605
+ g_drawBufferStale = (g_drawFramebuffer != g_framebuffer);
606
+ addFlushStats(esp_timer_get_time() - start, kWidth * kHeight);
607
+ return true;
608
+ }
609
+ #endif
610
+
611
+ } // namespace
612
+
613
+ namespace {
614
+
615
+ // DIAG: band-replay split engagement — submit count + the main core's join-wait
616
+ // time, printed every 300 draw-band jobs (mirrors the esp32 backend's [worker]
617
+ // line). Tells "split never engages" apart from "split engages but doesn't help".
618
+ int g_drawBandJobs = 0;
619
+ std::int64_t g_drawBandWaitUs = 0;
620
+ bool g_lastSubmitWasDrawBand = false;
621
+
622
+ // Shared single-job submit behind both worker entry points: the strip-copy path
623
+ // (gea_render_parallel_rows_submit) and the renderer's coarse band replay
624
+ // (gea_render_parallel_submit). One job in flight at a time — both producers run
625
+ // on the frame task and join via gea_render_parallel_wait before resubmitting.
626
+ bool submitRenderWorkerJob(void (*fn)(void *, int, int), void *ctx, int y0, int y1)
627
+ {
628
+ if (!g_renderRowWorker.attempted) {
629
+ g_renderRowWorker.attempted = true;
630
+ const BaseType_t renderCore = xPortGetCoreID();
631
+ const BaseType_t workerCore = renderCore == 0 ? 1 : 0;
632
+ const UBaseType_t priority = uxTaskPriorityGet(nullptr);
633
+ const BaseType_t created = xTaskCreatePinnedToCore(renderRowWorkerTask,
634
+ "gea_rowwrk",
635
+ kRenderRowWorkerStackBytes,
636
+ nullptr,
637
+ priority,
638
+ &g_renderRowWorker.task,
639
+ workerCore);
640
+ if (created != pdPASS || !g_renderRowWorker.task) {
641
+ ESP_LOGW(kTag, "row worker create failed: create=%d stack=%u",
642
+ static_cast<int>(created),
643
+ static_cast<unsigned>(kRenderRowWorkerStackBytes));
644
+ } else {
645
+ std::printf("[render-worker] task=%p renderCore=%d workerCore=%d prio=%u stack=%u\n",
646
+ static_cast<void *>(g_renderRowWorker.task), static_cast<int>(renderCore),
647
+ static_cast<int>(workerCore), static_cast<unsigned>(priority),
648
+ static_cast<unsigned>(kRenderRowWorkerStackBytes));
649
+ }
650
+ }
651
+ if (!g_renderRowWorker.task) return false;
652
+ g_renderRowWorker.fn = fn;
653
+ g_renderRowWorker.ctx = ctx;
654
+ g_renderRowWorker.y0 = y0;
655
+ g_renderRowWorker.y1 = y1;
656
+ g_renderRowWorker.done.store(false, std::memory_order_release);
657
+ g_renderRowWorker.jobSeq.fetch_add(1, std::memory_order_release);
658
+ xTaskNotifyGive(g_renderRowWorker.task);
659
+ return true;
660
+ }
661
+
662
+ } // namespace
663
+
664
+ extern "C" bool gea_render_parallel_rows_submit(void (*fn)(void *, int, int), void *ctx, int y0, int y1)
665
+ {
666
+ g_lastSubmitWasDrawBand = false;
667
+ return submitRenderWorkerJob(fn, ctx, y0, y1);
668
+ }
669
+
670
+ // NOTE: a 410-permille biased split (worker takes more rows; both bands finish
671
+ // together) was measured and REVERTED: with the cores fully overlapped the pair
672
+ // is bus-limited, so rebalancing rows doesn't shorten the wall — it only deepens
673
+ // the PSRAM saturation window, and the bounce-fill ISR (which keeps the panel
674
+ // synced) starts missing its deadline → dropped/restarted frames. Even split
675
+ // (the weak default 500) leaves the main core a solo tail that the ISR rides.
676
+
677
+ extern "C" bool gea_render_parallel_submit(void (*fn)(void *, int, int), void *ctx, int y0, int y1)
678
+ {
679
+ // Record the render core so Display draw calls on the OTHER core (the worker's
680
+ // band replay) route to the band canvas. Re-set each submit in case the frame
681
+ // task ever migrates cores.
682
+ g_renderCoreId = static_cast<int>(xPortGetCoreID());
683
+ const bool ok = submitRenderWorkerJob(fn, ctx, y0, y1);
684
+ g_lastSubmitWasDrawBand = ok;
685
+ return ok;
686
+ }
687
+
688
+ // After a coarse band-replay joins, fold the worker canvas's dirty bbox into the
689
+ // primary so the publish copy (which reads g_canvas.dirty()) transmits both bands.
690
+ extern "C" void gea_render_parallel_merge_dirty()
691
+ {
692
+ int x0, y0, x1, y1;
693
+ if (g_workerCanvas.dirty(&x0, &y0, &x1, &y1)) g_canvas.markDirty(x0, y0, x1, y1);
694
+ g_workerCanvas.resetDirty();
695
+ }
696
+
697
+ namespace {
698
+
699
+ // SRAM-staged dirty-region replay (gea_replay_stage_* hooks): the region replay
700
+ // rasters into a per-core half of g_stripBuffer instead of read-modify-writing the
701
+ // PSRAM back buffer under the RGB panel's continuous scanout. Measured before this:
702
+ // a HALF-band replay cost the same ~20ms as the full region — the PSRAM bus, not
703
+ // the CPU, was the limit, so the 2-core split alone bought nothing. Per-core halves:
704
+ // with the band split each core stages its own (disjoint) band rows, so the halves
705
+ // never overlap; presentStripFused also uses both halves but only on canvas-present
706
+ // frames, never concurrently with a region replay.
707
+ struct ReplayStageState {
708
+ bool active = false;
709
+ int x0 = 0, y0 = 0, x1 = -1, y1 = -1; // staged window (screen coords)
710
+ bool hadDirty = false; // canvas dirty union accumulated before the
711
+ int dx0 = 0, dy0 = 0, dx1 = -1, dy1 = -1; // rebind (bindPixels resets it)
712
+ std::uint8_t alpha = 255;
713
+ // DIAG: per-strip cost decomposition (seed copy-in / replay body / copy-back),
714
+ // printed every kStageDiagStrips strips per core.
715
+ std::int64_t beginDoneUs = 0;
716
+ std::int64_t seedUs = 0, bodyUs = 0, cbUs = 0;
717
+ int strips = 0, px = 0;
718
+ };
719
+ ReplayStageState g_replayStage[2];
720
+ constexpr int kStageDiagStrips = 600;
721
+ // DIAG: PIE SIMD blend engagement (calls + 8-px groups), printed with [stage].
722
+ volatile int g_pieCalls = 0;
723
+ volatile int g_pieCount8 = 0;
724
+
725
+ } // namespace
726
+
727
+ // Staged-replay gate. Measured on css-3d-cube: staging the replay through SRAM
728
+ // strips LOST ~6fps — the per-strip re-replay multiplies commands whose raster
729
+ // cost is NOT row-proportional (the transformed face-label text re-rasters its
730
+ // full quad in every overlapping 24-row strip; rUs text went to ~10ms/frame),
731
+ // and the per-pixel blend turned out compute-bound, not PSRAM-bound, so the
732
+ // SRAM dst saved nothing. Keep the machinery (hooks + per-core windows) gated
733
+ // off for A/B; flip to 1 to re-measure.
734
+ #ifndef GEA_EMBEDDED_DISPLAY_REPLAY_SRAM_STAGE
735
+ #define GEA_EMBEDDED_DISPLAY_REPLAY_SRAM_STAGE 0
736
+ #endif
737
+
738
+ extern "C" int gea_replay_stage_rows()
739
+ {
740
+ #if GEA_EMBEDDED_DISPLAY_REPLAY_SRAM_STAGE
741
+ return g_stripBuffer ? kStripRows : 0;
742
+ #else
743
+ return 0;
744
+ #endif
745
+ }
746
+
747
+ extern "C" bool gea_replay_stage_begin(int x0, int y0, int x1, int y1)
748
+ {
749
+ if (!g_stripBuffer || !g_drawFramebuffer) return false;
750
+ if (x0 < 0) x0 = 0;
751
+ if (y0 < 0) y0 = 0;
752
+ if (x1 >= kWidth) x1 = kWidth - 1;
753
+ if (y1 >= kHeight) y1 = kHeight - 1;
754
+ const int rows = y1 - y0 + 1;
755
+ if (x0 > x1 || rows <= 0 || rows > kStripRows) return false;
756
+ const int core = xPortGetCoreID() & 1;
757
+ ReplayStageState &st = g_replayStage[core];
758
+ if (st.active) return false; // staging never nests; fall back to direct if it ever would
759
+ std::uint16_t *strip = g_stripBuffer + static_cast<std::size_t>(core) * kStripRows * kWidth;
760
+ // Seed the window from the back buffer so alpha blends and partial paints meet
761
+ // the same dst bytes the direct path would have.
762
+ const std::int64_t s0 = esp_timer_get_time();
763
+ const int width = x1 - x0 + 1;
764
+ for (int y = y0; y <= y1; ++y) {
765
+ std::memcpy(&strip[static_cast<std::size_t>(y - y0) * kWidth + x0],
766
+ &g_drawFramebuffer[static_cast<std::size_t>(y) * kWidth + x0],
767
+ static_cast<std::size_t>(width) * sizeof(std::uint16_t));
768
+ }
769
+ st.seedUs += esp_timer_get_time() - s0;
770
+ st.px += width * rows;
771
+ auto &canvas = replayCanvas();
772
+ st.hadDirty = canvas.dirty(&st.dx0, &st.dy0, &st.dx1, &st.dy1);
773
+ st.alpha = canvas.globalAlpha();
774
+ // Window binding: claim rows [0..y1] with the pixel base rewound by y0 rows, so
775
+ // screen row y lands at strip row (y - y0) — the replay keeps drawing in screen
776
+ // coordinates. Rows above the window are unbacked memory; the guard clip below
777
+ // keeps every drawer inside the window (all drawers clamp to the clip, and the
778
+ // replay never reads outside it).
779
+ canvas.bindPixels(strip - static_cast<std::size_t>(y0) * kWidth, kWidth, y1 + 1, kWidth);
780
+ canvas.setGlobalAlpha(st.alpha);
781
+ canvas.pushClip(x0, y0, width, rows);
782
+ st.active = true;
783
+ st.x0 = x0;
784
+ st.y0 = y0;
785
+ st.x1 = x1;
786
+ st.y1 = y1;
787
+ st.beginDoneUs = esp_timer_get_time();
788
+ return true;
789
+ }
790
+
791
+ extern "C" void gea_replay_stage_end()
792
+ {
793
+ const int core = xPortGetCoreID() & 1;
794
+ ReplayStageState &st = g_replayStage[core];
795
+ if (!st.active) return;
796
+ st.active = false;
797
+ const std::int64_t e0 = esp_timer_get_time();
798
+ st.bodyUs += e0 - st.beginDoneUs;
799
+ auto &canvas = replayCanvas();
800
+ int dx0, dy0, dx1, dy1;
801
+ bool dirty = canvas.dirty(&dx0, &dy0, &dx1, &dy1);
802
+ if (dirty) {
803
+ // Copy back only the painted bbox (clamped to the window) — unpainted strip
804
+ // pixels are seed-identical, so skipping them saves PSRAM write traffic.
805
+ if (dx0 < st.x0) dx0 = st.x0;
806
+ if (dy0 < st.y0) dy0 = st.y0;
807
+ if (dx1 > st.x1) dx1 = st.x1;
808
+ if (dy1 > st.y1) dy1 = st.y1;
809
+ dirty = dx0 <= dx1 && dy0 <= dy1;
810
+ }
811
+ if (dirty) {
812
+ const std::uint16_t *strip = g_stripBuffer + static_cast<std::size_t>(core) * kStripRows * kWidth;
813
+ const int width = dx1 - dx0 + 1;
814
+ for (int y = dy0; y <= dy1; ++y) {
815
+ std::memcpy(&g_drawFramebuffer[static_cast<std::size_t>(y) * kWidth + dx0],
816
+ &strip[static_cast<std::size_t>(y - st.y0) * kWidth + dx0],
817
+ static_cast<std::size_t>(width) * sizeof(std::uint16_t));
818
+ }
819
+ }
820
+ canvas.bindPixels(g_drawFramebuffer, kWidth, kHeight);
821
+ canvas.setGlobalAlpha(st.alpha);
822
+ // bindPixels reset the dirty tracker: restore the frame's accumulated union,
823
+ // then add this strip's painted bbox so the publish copy transmits it.
824
+ if (st.hadDirty) canvas.markDirty(st.dx0, st.dy0, st.dx1, st.dy1);
825
+ if (dirty) canvas.markDirty(dx0, dy0, dx1, dy1);
826
+ st.cbUs += esp_timer_get_time() - e0;
827
+ if (++st.strips >= kStageDiagStrips) {
828
+ std::printf("[stage] core%d strips=%d px=%d seed=%dus body=%dus cb=%dus (avg/strip) pie=%d/%dpx\n",
829
+ core, st.strips, st.px / st.strips,
830
+ static_cast<int>(st.seedUs / st.strips),
831
+ static_cast<int>(st.bodyUs / st.strips),
832
+ static_cast<int>(st.cbUs / st.strips),
833
+ g_pieCalls, g_pieCount8 * 8);
834
+ g_pieCalls = 0;
835
+ g_pieCount8 = 0;
836
+ st.seedUs = st.bodyUs = st.cbUs = 0;
837
+ st.strips = 0;
838
+ st.px = 0;
839
+ }
840
+ }
841
+
842
+ namespace {
843
+
844
+ // ── PIE SIMD over-blend (gea_pie_blend hooks) ────────────────────────────────
845
+ // Same S3 vector kernel as targets/esp32/display.cpp's pieBlendSpan8, minus the
846
+ // panel<->normal byte-swap steps: this board stores native-order RGB565
847
+ // (GEA_EMBEDDED_PIXEL_PANEL_ENDIAN=0), so the framebuffer bytes already ARE the
848
+ // "normal" layout the channel masks need. Contract unchanged: dst = bg in /
849
+ // result out (storage order), fgN = normal-RGB565 fg, a5 = per-pixel 0..32;
850
+ // lerp oC = bgC + ((fgC-bgC)*a5)>>5 per channel, +16 round-to-nearest.
851
+ // cb2 rows (16B apart): [0]=1, [1]=0x1F, [2]=0x3F, [5]=2048(<<11), [6]=32(<<5),
852
+ // [7]=16(round); rows 3/4 (0xFF mask, <<8) are the swap constants — unused here
853
+ // but kept so the table layout matches the esp32 kernel's documented block.
854
+ // Held: q0=bg, q1=ones, q2=fgN, q3=a5, q6=accum. Scratch: q4, q5(const/mask), q7.
855
+ void pieBlendSpan8Native(std::uint16_t *dst, const std::uint16_t *fgN, const std::int16_t *a5, int count8,
856
+ const std::int16_t *cb2)
857
+ {
858
+ int t, ad;
859
+ asm volatile(
860
+ "ee.vld.128.ip q1, %[cb], 0\n" // q1 = ones (cb2[0])
861
+ "1:\n"
862
+ "ee.vld.128.ip q0, %[d], 0\n" // q0 = bg (native order), no increment (stored back)
863
+ "ee.vld.128.ip q2, %[f], 16\n" // q2 = fgN
864
+ "ee.vld.128.ip q3, %[a], 16\n" // q3 = a5
865
+ // B channel (bits 0-4): oB = bgB + ((fgB-bgB)*a5 + 16)>>5
866
+ "addi %[ad], %[cb], 16\n ee.vld.128.ip q5, %[ad], 0\n" // q5 = mask1F
867
+ "ee.andq q4, q0, q5\n" // bgB
868
+ "ee.andq q7, q2, q5\n" // fgB
869
+ "ee.vsubs.s16 q7, q7, q4\n" // fgB-bgB
870
+ "movi %[t], 0\n wsr.sar %[t]\n ee.vmul.s16 q7, q7, q3\n" // diff*a5 (raw)
871
+ "addi %[ad], %[cb], 112\n ee.vld.128.ip q5, %[ad], 0\n ee.vadds.s16 q7, q7, q5\n" // +16 (round)
872
+ "movi %[t], 5\n wsr.sar %[t]\n ee.vmul.s16 q7, q7, q1\n" // >>5
873
+ "ee.vadds.s16 q6, q7, q4\n" // oB (accum)
874
+ // G channel (bits 5-10): mask 0x3F, repack <<5
875
+ "addi %[ad], %[cb], 32\n ee.vld.128.ip q5, %[ad], 0\n" // q5 = mask3F
876
+ "movi %[t], 5\n wsr.sar %[t]\n ee.vmul.s16 q4, q0, q1\n ee.andq q4, q4, q5\n" // bgG
877
+ "ee.vmul.s16 q7, q2, q1\n ee.andq q7, q7, q5\n" // fgG (SAR still 5)
878
+ "ee.vsubs.s16 q7, q7, q4\n" // diff
879
+ "movi %[t], 0\n wsr.sar %[t]\n ee.vmul.s16 q7, q7, q3\n" // diff*a5 (raw)
880
+ "addi %[ad], %[cb], 112\n ee.vld.128.ip q5, %[ad], 0\n ee.vadds.s16 q7, q7, q5\n" // +16
881
+ "movi %[t], 5\n wsr.sar %[t]\n ee.vmul.s16 q7, q7, q1\n" // >>5
882
+ "ee.vadds.s16 q7, q7, q4\n" // oG
883
+ "movi %[t], 0\n wsr.sar %[t]\n addi %[ad], %[cb], 96\n ee.vld.128.ip q5, %[ad], 0\n ee.vmul.s16 q7, q7, q5\n" // oG<<5 (c32)
884
+ "ee.orq q6, q6, q7\n"
885
+ // R channel (bits 11-15): mask 0x1F, repack <<11
886
+ "addi %[ad], %[cb], 16\n ee.vld.128.ip q5, %[ad], 0\n" // q5 = mask1F
887
+ "movi %[t], 11\n wsr.sar %[t]\n ee.vmul.s16 q4, q0, q1\n ee.andq q4, q4, q5\n" // bgR
888
+ "ee.vmul.s16 q7, q2, q1\n ee.andq q7, q7, q5\n" // fgR (SAR still 11)
889
+ "ee.vsubs.s16 q7, q7, q4\n"
890
+ "movi %[t], 0\n wsr.sar %[t]\n ee.vmul.s16 q7, q7, q3\n" // diff*a5 (raw)
891
+ "addi %[ad], %[cb], 112\n ee.vld.128.ip q5, %[ad], 0\n ee.vadds.s16 q7, q7, q5\n" // +16
892
+ "movi %[t], 5\n wsr.sar %[t]\n ee.vmul.s16 q7, q7, q1\n" // >>5
893
+ "ee.vadds.s16 q7, q7, q4\n" // oR
894
+ "movi %[t], 0\n wsr.sar %[t]\n addi %[ad], %[cb], 80\n ee.vld.128.ip q5, %[ad], 0\n ee.vmul.s16 q7, q7, q5\n" // oR<<11 (c2048)
895
+ "ee.orq q6, q6, q7\n" // q6 = result (native order)
896
+ "ee.vst.128.ip q6, %[d], 16\n" // store result + advance dst by 8 px
897
+ "addi %[n], %[n], -1\n bnez %[n], 1b\n"
898
+ : [d] "+r"(dst), [f] "+r"(fgN), [a] "+r"(a5), [n] "+r"(count8), [t] "=&r"(t), [ad] "=&r"(ad)
899
+ : [cb] "r"(cb2)
900
+ : "memory");
901
+ }
902
+
903
+ } // namespace
904
+
905
+ // Like-for-like on css-3d-cube (same app build, even split, no staging): scalar
906
+ // gradient replay = 28-41ms/frame, SIMD = ~13.5ms — the kernel halves the
907
+ // dominant replay cost. (An earlier "no difference" reading compared across two
908
+ // different app revisions — the example was being reworked in a parallel session
909
+ // mid-measurement.)
910
+ extern "C" bool gea_pie_blend_available() { return true; }
911
+ extern "C" void gea_pie_blend_span8(std::uint16_t *dst, const std::uint16_t *fgN, const std::int16_t *a5, int count8)
912
+ {
913
+ // Same constant block layout as the esp32 kernel (rows 3/4 unused here).
914
+ alignas(16) static const std::int16_t cb2[8][8] = {
915
+ {1, 1, 1, 1, 1, 1, 1, 1},
916
+ {0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F},
917
+ {0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F},
918
+ {0x00FF, 0x00FF, 0x00FF, 0x00FF, 0x00FF, 0x00FF, 0x00FF, 0x00FF},
919
+ {256, 256, 256, 256, 256, 256, 256, 256},
920
+ {2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048},
921
+ {32, 32, 32, 32, 32, 32, 32, 32},
922
+ {16, 16, 16, 16, 16, 16, 16, 16},
923
+ };
924
+ // PER-CORE critical section — the PIE q-registers are not saved across FreeRTOS
925
+ // context switches, so a mid-kernel preemption (WiFi/system tasks on core 0,
926
+ // the render worker's own preemptors on core 1) corrupts the blend. Per-core
927
+ // mux so the two render cores never serialize on it (proven pattern on the
928
+ // esp32 target, where corruption stripes appeared without the guard).
929
+ static portMUX_TYPE pieMux[2] = {portMUX_INITIALIZER_UNLOCKED, portMUX_INITIALIZER_UNLOCKED};
930
+ portMUX_TYPE *mux = &pieMux[xPortGetCoreID() & 1];
931
+ g_pieCalls = g_pieCalls + 1;
932
+ g_pieCount8 = g_pieCount8 + count8;
933
+ taskENTER_CRITICAL(mux);
934
+ pieBlendSpan8Native(dst, fgN, a5, count8, &cb2[0][0]);
935
+ taskEXIT_CRITICAL(mux);
936
+ }
937
+
938
+ extern "C" int gea_current_render_core()
939
+ {
940
+ return static_cast<int>(xPortGetCoreID());
941
+ }
942
+
943
+ extern "C" void gea_render_parallel_wait()
944
+ {
945
+ if (!g_renderRowWorker.task) return;
946
+ const std::int64_t w0 = esp_timer_get_time();
947
+ const std::int64_t deadline = w0 + 100000;
948
+ while (!g_renderRowWorker.done.load(std::memory_order_acquire)) {
949
+ if (esp_timer_get_time() > deadline) {
950
+ ESP_LOGW(kTag, "row worker wait timeout");
951
+ break;
952
+ }
953
+ }
954
+ if (g_lastSubmitWasDrawBand) {
955
+ g_drawBandWaitUs += esp_timer_get_time() - w0;
956
+ if (++g_drawBandJobs >= 300) {
957
+ std::printf("[worker] draw-band jobs=300 wait=%dus band=%dus avg\n",
958
+ static_cast<int>(g_drawBandWaitUs / 300),
959
+ static_cast<int>(g_renderRowWorker.bandUs / 300));
960
+ g_drawBandWaitUs = 0;
961
+ g_drawBandJobs = 0;
962
+ g_renderRowWorker.bandUs = 0;
963
+ }
964
+ }
965
+ }
966
+
967
+ namespace gea::platform::display {
968
+
969
+ bool Display::init()
970
+ {
971
+ if (g_initialized) return true;
972
+ esp_err_t err = initBacklight();
973
+ if (err != ESP_OK) return false;
974
+ err = resetPanel();
975
+ if (err != ESP_OK) {
976
+ ESP_LOGE(kTag, "panel reset failed: %s", esp_err_to_name(err));
977
+ return false;
978
+ }
979
+ err = initRgbPanel();
980
+ if (err != ESP_OK) return false;
981
+ g_initialized = true;
982
+ return true;
983
+ }
984
+
985
+ bool Display::start()
986
+ {
987
+ if (!g_initialized && !init()) return false;
988
+ setBrightness(g_brightness);
989
+ flush();
990
+ return true;
991
+ }
992
+
993
+ // Routed per-core: the worker core's band replay (and render.cpp helpers that
994
+ // draw raw pixels through canvas()) must hit the band canvas — its own clip +
995
+ // dirty accumulator over the same framebuffer. On the main core this is g_canvas.
996
+ gea::framework::graphics::Canvas *Display::canvas() { return &replayCanvas(); }
997
+
998
+ // The render layer binds canvas() onto a scratch buffer (retained snapshots for
999
+ // screenshots/OTA, fused rasterized flushes) and calls this to point it back at
1000
+ // the draw framebuffer. bindPixels resets the dirty tracker, which is right
1001
+ // here: the union it held describes the scratch buffer, not the framebuffer.
1002
+ void Display::rebindCanvasToFramebuffer()
1003
+ {
1004
+ replayCanvas().bindPixels(g_drawFramebuffer, kWidth, kHeight);
1005
+ }
1006
+
1007
+ bool Display::copySnapshotRgb565(std::uint16_t *dst, int pixelCapacity, int *width, int *height, bool)
1008
+ {
1009
+ if (width) *width = kWidth;
1010
+ if (height) *height = kHeight;
1011
+ if (!dst || pixelCapacity < static_cast<int>(kPixelCount)) return false;
1012
+ const std::uint16_t *source = g_framebuffer ? g_framebuffer : g_drawFramebuffer;
1013
+ if (!source) return false;
1014
+ std::copy_n(source, kPixelCount, dst);
1015
+ return true;
1016
+ }
1017
+
1018
+ int Display::countNonBlackPixels(bool)
1019
+ {
1020
+ const std::uint16_t *source = g_framebuffer ? g_framebuffer : g_drawFramebuffer;
1021
+ if (!source) return 0;
1022
+ int count = 0;
1023
+ for (std::size_t i = 0; i < kPixelCount; ++i) {
1024
+ if (source[i] != 0) ++count;
1025
+ }
1026
+ return count;
1027
+ }
1028
+
1029
+ void Display::clear()
1030
+ {
1031
+ g_canvas.clear(0x0000);
1032
+ flush();
1033
+ }
1034
+
1035
+ void Display::clearNoFlush() { g_canvas.clear(0x0000); }
1036
+ void Display::print(const char *) {}
1037
+
1038
+ void Display::flush()
1039
+ {
1040
+ if (!g_framebuffer || !g_drawFramebuffer) return;
1041
+ const int64_t start = esp_timer_get_time();
1042
+ int64_t copyUs = 0;
1043
+ int64_t cacheUs = 0;
1044
+ int x0 = 0;
1045
+ int y0 = 0;
1046
+ int x1 = -1;
1047
+ int y1 = -1;
1048
+ int pixels = 0;
1049
+ if (g_canvas.dirty(&x0, &y0, &x1, &y1)) {
1050
+ const int64_t copyStart = esp_timer_get_time();
1051
+ pixels = publishDrawRect(x0, y0, x1, y1, &x0, &y0, &x1, &y1);
1052
+ copyUs += esp_timer_get_time() - copyStart;
1053
+ }
1054
+ if (pixels > 0) {
1055
+ const int64_t cacheStart = esp_timer_get_time();
1056
+ cacheWritebackRect(x0, y0, x1, y1);
1057
+ cacheUs += esp_timer_get_time() - cacheStart;
1058
+ }
1059
+ g_canvas.resetDirty();
1060
+ addFlushStats(esp_timer_get_time() - start, pixels);
1061
+ addFlushStageStats(copyUs, cacheUs);
1062
+ }
1063
+
1064
+ void Display::flushRects(const DisplayFlushRect *rects, int count, bool)
1065
+ {
1066
+ if (!g_framebuffer || !g_drawFramebuffer || !rects || count <= 0) return;
1067
+ const int64_t start = esp_timer_get_time();
1068
+ int64_t copyUs = 0;
1069
+ int64_t cacheUs = 0;
1070
+ int pixels = 0;
1071
+ for (int i = 0; i < count; ++i) {
1072
+ int x0 = 0;
1073
+ int y0 = 0;
1074
+ int x1 = -1;
1075
+ int y1 = -1;
1076
+ const int64_t copyStart = esp_timer_get_time();
1077
+ const int rectPixels = publishDrawRect(rects[i].x0, rects[i].y0, rects[i].x1, rects[i].y1, &x0, &y0, &x1, &y1);
1078
+ copyUs += esp_timer_get_time() - copyStart;
1079
+ if (rectPixels > 0) {
1080
+ pixels += rectPixels;
1081
+ const int64_t cacheStart = esp_timer_get_time();
1082
+ cacheWritebackRect(x0, y0, x1, y1);
1083
+ cacheUs += esp_timer_get_time() - cacheStart;
1084
+ }
1085
+ }
1086
+ g_canvas.resetDirty();
1087
+ addFlushStats(esp_timer_get_time() - start, pixels);
1088
+ addFlushStageStats(copyUs, cacheUs);
1089
+ }
1090
+
1091
+ bool Display::streamRect(int x, int y, int w, int h, DisplayStreamRasterFn raster, void *user)
1092
+ {
1093
+ if (!g_framebuffer || !g_drawFramebuffer || !raster || w <= 0 || h <= 0) return false;
1094
+ int x0 = x;
1095
+ int y0 = y;
1096
+ int x1 = x + w - 1;
1097
+ int y1 = y + h - 1;
1098
+ if (x0 < 0) x0 = 0;
1099
+ if (y0 < 0) y0 = 0;
1100
+ if (x1 >= kWidth) x1 = kWidth - 1;
1101
+ if (y1 >= kHeight) y1 = kHeight - 1;
1102
+ if (x0 > x1 || y0 > y1) return true;
1103
+
1104
+ const int width = x1 - x0 + 1;
1105
+ const int height = y1 - y0 + 1;
1106
+ const std::size_t bytes = static_cast<std::size_t>(width) * static_cast<std::size_t>(height) * sizeof(std::uint16_t);
1107
+ auto *scratch = static_cast<std::uint16_t *>(heap_caps_malloc(bytes, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
1108
+ if (!scratch) scratch = static_cast<std::uint16_t *>(heap_caps_malloc(bytes, MALLOC_CAP_8BIT));
1109
+ if (!scratch) return false;
1110
+
1111
+ const int64_t start = esp_timer_get_time();
1112
+ raster(scratch, width, height, x0, y0, user);
1113
+ for (int row = 0; row < height; ++row) {
1114
+ std::copy_n(&scratch[static_cast<std::size_t>(row) * width],
1115
+ width,
1116
+ &g_drawFramebuffer[static_cast<std::size_t>(y0 + row) * kWidth + x0]);
1117
+ }
1118
+ heap_caps_free(scratch);
1119
+ int publishedX0 = 0;
1120
+ int publishedY0 = 0;
1121
+ int publishedX1 = -1;
1122
+ int publishedY1 = -1;
1123
+ const int pixels = publishDrawRect(x0, y0, x1, y1, &publishedX0, &publishedY0, &publishedX1, &publishedY1);
1124
+ if (pixels > 0) cacheWritebackRect(publishedX0, publishedY0, publishedX1, publishedY1);
1125
+ g_canvas.resetDirty();
1126
+ addFlushStats(esp_timer_get_time() - start, pixels);
1127
+ return true;
1128
+ }
1129
+
1130
+ // The fused path exists so a QSPI panel can overlap rasterization with the
1131
+ // DMA that carries each chunk. An RGB panel's scanout is continuous and the
1132
+ // framebuffer is already in place, so each rect is rastered into a scratch
1133
+ // block and published like any other region -- same pixels, no chunking.
1134
+ void Display::flushRectsRasterized(const DisplayFlushRect *rects, int count, DisplayStreamRasterFn raster, void *user, bool)
1135
+ {
1136
+ if (!rects || count <= 0 || !raster) return;
1137
+ for (int i = 0; i < count; ++i) {
1138
+ streamRect(rects[i].x0, rects[i].y0, rects[i].x1 - rects[i].x0 + 1, rects[i].y1 - rects[i].y0 + 1, raster, user);
1139
+ }
1140
+ rebindCanvasToFramebuffer();
1141
+ }
1142
+
1143
+ bool Display::present(const DisplayPresentCommand *commands, int commandCount)
1144
+ {
1145
+ if (!commands || commandCount <= 0) return false;
1146
+ #if GEA_EMBEDDED_DISPLAY_RGB_STRIP_RASTER
1147
+ // Fast path: full-screen-redraw frames compose in SRAM strips and publish
1148
+ // straight to scanout. Anything without a full-screen opaque base needs the
1149
+ // persistent back buffer, so it falls through.
1150
+ if (g_stripBuffer) {
1151
+ present::Frame frame;
1152
+ if (present::extractFrame(commands, commandCount, frame) &&
1153
+ present::frameHasOpaqueBase(frame, kWidth, kHeight)) {
1154
+ return presentStripFused(frame);
1155
+ }
1156
+ }
1157
+ #endif
1158
+ // Fallback: per-command replay into the PSRAM back buffer, then publish. If
1159
+ // the last frame went through the strip path, the back buffer is stale —
1160
+ // re-seed it from the live scanout before drawing the partial update on top.
1161
+ if (g_drawBufferStale && g_drawFramebuffer != g_framebuffer) {
1162
+ std::memcpy(g_drawFramebuffer, g_framebuffer, kFramebufferBytes);
1163
+ g_drawBufferStale = false;
1164
+ }
1165
+ for (int i = 0; i < commandCount; ++i) {
1166
+ replayPresentCommand(commands[i]);
1167
+ }
1168
+ g_canvas.setGlobalAlpha(255);
1169
+ flush();
1170
+ return true;
1171
+ }
1172
+
1173
+ void Display::setFlushConfig(int chunkRows, int queueDepth)
1174
+ {
1175
+ g_flushRows = chunkRows;
1176
+ g_flushDepth = queueDepth;
1177
+ }
1178
+
1179
+ void Display::reserveInternal(std::size_t) {}
1180
+ bool Display::setHighBrightnessMode(bool) { return false; }
1181
+ bool Display::highBrightnessMode() { return false; }
1182
+ // The RGB-panel backend draws straight into the framebuffer with no separate
1183
+ // internal-RAM flush staging to reserve, so the deferred-reserve apply is a no-op
1184
+ // here (matches reserveInternal above). Required since frame_scheduler now calls it.
1185
+ void Display::applyPendingInternalReserve() {}
1186
+ int Display::flushChunkRows() { return g_flushRows; }
1187
+ int Display::flushQueueDepth() { return g_flushDepth; }
1188
+ int Display::flushBufferBytes() { return 0; }
1189
+ // All clip/alpha/draw entry points below route through replayCanvas() so the
1190
+ // 2nd-core band replay lands on the worker canvas (its own clip + dirty over
1191
+ // the same framebuffer). On the main core replayCanvas() == g_canvas, so the
1192
+ // single-core paths are unchanged.
1193
+ void Display::pushClip(int x, int y, int w, int h) { replayCanvas().pushClip(x, y, w, h); }
1194
+ void Display::popClip() { replayCanvas().popClip(); }
1195
+ void Display::resetClip() { replayCanvas().resetClip(); }
1196
+ void Display::setAlpha(std::uint8_t alpha) { replayCanvas().setGlobalAlpha(alpha); }
1197
+ std::uint8_t Display::alpha() { return replayCanvas().globalAlpha(); }
1198
+ int Display::brightness() { return g_brightness; }
1199
+
1200
+ void Display::setBrightness(int brightnessPercent)
1201
+ {
1202
+ if (brightnessPercent < 0) brightnessPercent = 0;
1203
+ if (brightnessPercent > 100) brightnessPercent = 100;
1204
+ g_brightness = brightnessPercent;
1205
+ applyBacklight();
1206
+ }
1207
+
1208
+ // Tearing sync (TE/VBlank): not implemented on this target.
1209
+ void Display::setVSync(bool) {}
1210
+ void Display::invalidate() {}
1211
+ bool Display::vsyncEnabled() { return false; }
1212
+ void Display::vsyncWaitForFrame() {}
1213
+
1214
+ void Display::clip(int *x0, int *y0, int *x1, int *y1) { replayCanvas().currentClip(x0, y0, x1, y1); }
1215
+ void Display::fillRect(int x, int y, int w, int h, std::uint16_t color) { replayCanvas().fillRect(x, y, w, h, color); }
1216
+ void Display::scrollRect(int x, int y, int w, int h, int dx, int dy) { replayCanvas().scrollRect(x, y, w, h, dx, dy); }
1217
+ void Display::resetScrollRegion() { replayCanvas().setScrollRegion(0, 0, 0); }
1218
+ void Display::strokeRect(int x, int y, int w, int h, std::uint16_t color) { replayCanvas().strokeRect(x, y, w, h, color); }
1219
+ void Display::fillCircle(int cx, int cy, int r, std::uint16_t color) { replayCanvas().fillCircle(cx, cy, r, color); }
1220
+ void Display::strokeCircle(int cx, int cy, int r, std::uint16_t color) { replayCanvas().strokeCircle(cx, cy, r, color); }
1221
+ void Display::drawLine(int x0, int y0, int x1, int y1, std::uint16_t color) { replayCanvas().drawLine(x0, y0, x1, y1, color); }
1222
+ void Display::drawArc(int cx, int cy, int r, int startDeg, int endDeg, std::uint16_t color) { replayCanvas().drawArc(cx, cy, r, startDeg, endDeg, color); }
1223
+ void Display::fillTriangle(int x0, int y0, int x1, int y1, int x2, int y2, std::uint16_t color) { replayCanvas().fillTriangle(x0, y0, x1, y1, x2, y2, color); }
1224
+ void Display::drawText(const char *text, int x, int y, std::uint16_t color, float scale) { replayCanvas().drawText(text, x, y, color, scale); }
1225
+ void Display::drawTextFont(const char *text, int x, int y, std::uint16_t color, int fontId) { replayCanvas().drawTextFont(text, x, y, color, fontId); }
1226
+ void Display::drawTextFontFamily(const char *text, int x, int y, std::uint16_t color, int familyId, int sizePx) { replayCanvas().drawTextFontFamily(text, x, y, color, familyId, sizePx); }
1227
+ void Display::setPixel(int x, int y, std::uint16_t color) { replayCanvas().fillRect(x, y, 1, 1, color); }
1228
+ void Display::fillRoundedRect(int x, int y, int w, int h, int tl, int tr, int br, int bl, std::uint16_t color) { replayCanvas().fillRoundedRect(x, y, w, h, tl, tr, br, bl, color); }
1229
+ void Display::fillRoundedRectBoxesRgb565(const std::int16_t *xs, const std::int16_t *ys, int count,
1230
+ int w, int h, int tl, int tr, int br, int bl,
1231
+ const std::uint16_t *colors)
1232
+ {
1233
+ replayCanvas().fillRoundedRectBoxesRgb565(xs, ys, count, w, h, tl, tr, br, bl, colors);
1234
+ }
1235
+ void Display::strokeRoundedRect(int x, int y, int w, int h, int tl, int tr, int br, int bl, int lineWidth, std::uint16_t color) { replayCanvas().strokeRoundedRect(x, y, w, h, tl, tr, br, bl, lineWidth, color); }
1236
+ void Display::blitImage(const gea::framework::graphics::pixel::native_t *src, const std::uint8_t *alpha, int srcWidth, int srcHeight, int dx, int dy) { replayCanvas().drawImage(src, alpha, srcWidth, srcHeight, dx, dy); }
1237
+ void Display::blitImageScaled(const gea::framework::graphics::pixel::native_t *src, const std::uint8_t *alpha, int srcWidth, int srcHeight, int dx, int dy, int dstWidth, int dstHeight) { replayCanvas().drawImage(src, alpha, srcWidth, srcHeight, dx, dy, dstWidth, dstHeight); }
1238
+ void Display::setWorldOverlay(const std::uint16_t *, int, int, int, int) {}
1239
+ void Display::setWorldScroll(int) {}
1240
+
1241
+ void Display::flushStatsRead(int64_t *totalUs, int *callCount, int *pixelCount)
1242
+ {
1243
+ if (totalUs) *totalUs = g_stats.totalUs;
1244
+ if (callCount) *callCount = g_stats.callCount;
1245
+ if (pixelCount) *pixelCount = g_stats.pixelCount;
1246
+ }
1247
+
1248
+ DisplayFlushPerfStats Display::flushPerfStatsRead() { return g_stats; }
1249
+ void Display::flushStatsReset() { g_stats = {}; }
1250
+ const char *Display::flushStageName() { return "idle"; }
1251
+ int Display::flushStageChunk() { return 0; }
1252
+ DisplayFlushStageDetail Display::flushStageDetail() { return {}; }
1253
+
1254
+ } // namespace gea::platform::display
1255
+
1256
+ // Full-screen PSRAM scratch for the static-backdrop cache. Without this hook the
1257
+ // weak default in ui/render.cpp returns nullptr and the bake SILENTLY never runs —
1258
+ // an animated-transform scene (css-3d-cube) then full-rebuilds + re-rasterizes the
1259
+ // whole static stage every frame (~17fps at 480x480) instead of reprojecting over
1260
+ // a baked backdrop. Same shape as the targets/esp32/display.cpp implementation.
1261
+ extern "C" std::uint16_t *gea_backdrop_cache(int *cap_px)
1262
+ {
1263
+ static std::uint16_t *buffer = nullptr;
1264
+ static bool attempted = false;
1265
+ constexpr int kCapPx = gea::platform::display::kWidth * gea::platform::display::kHeight;
1266
+ if (!attempted)
1267
+ {
1268
+ attempted = true;
1269
+ buffer = static_cast<std::uint16_t *>(heap_caps_malloc(
1270
+ static_cast<std::size_t>(kCapPx) * sizeof(std::uint16_t), MALLOC_CAP_SPIRAM));
1271
+ }
1272
+ if (cap_px)
1273
+ *cap_px = buffer ? kCapPx : 0;
1274
+ return buffer;
1275
+ }