@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
@@ -0,0 +1,3138 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ #include "absolute_leaf_refresh.h"
3
+ #include "dirty_regions.h"
4
+ #include "display.h"
5
+ #include "document.h"
6
+ #include "internal.h"
7
+ #include "layout_snapshot.h"
8
+ #include "refresh_perf.h"
9
+ #include "root_scroll_refresh.h"
10
+ #include "tree_state.h"
11
+
12
+ #include <cmath>
13
+ #include <cstddef>
14
+ #include <cstdint>
15
+
16
+ #include <cstdio>
17
+ #include <cstdlib>
18
+ #include <cstring>
19
+
20
+ #ifndef GEA_EMBEDDED_FLUSH_ANCHOR_LEFT_PARTIAL_RECTS
21
+ #define GEA_EMBEDDED_FLUSH_ANCHOR_LEFT_PARTIAL_RECTS 1
22
+ #endif
23
+
24
+ // Fused replay+flush: rasterize each dirty chunk directly into the DMA buffer during
25
+ // the flush, instead of replaying into the PSRAM framebuffer and then copying. Off by
26
+ // default; opt-in per board. Only valid for simpleUnifiedReplay apps whose display list
27
+ // fully repaints each dirty region from scratch (opaque background + draws — e.g.
28
+ // bouncing-balls), because the chunk buffer is not seeded from the framebuffer.
29
+ #ifndef GEA_EMBEDDED_DISPLAY_FUSE_REPLAY_FLUSH
30
+ #define GEA_EMBEDDED_DISPLAY_FUSE_REPLAY_FLUSH 0
31
+ #endif
32
+
33
+ #ifndef GEA_EMBEDDED_DISPLAY_FUSE_INTERLEAVED_REPLAY_FLUSH
34
+ #define GEA_EMBEDDED_DISPLAY_FUSE_INTERLEAVED_REPLAY_FLUSH 0
35
+ #endif
36
+
37
+ #ifndef GEA_EMBEDDED_DISPLAY_FUSE_REPLAY_CLEAR_RGB565
38
+ #define GEA_EMBEDDED_DISPLAY_FUSE_REPLAY_CLEAR_RGB565 -1
39
+ #endif
40
+
41
+ #ifndef GEA_EMBEDDED_REPROJECT_UNIFIED_DIRTY_RECT
42
+ #define GEA_EMBEDDED_REPROJECT_UNIFIED_DIRTY_RECT 0
43
+ #endif
44
+
45
+ #ifndef GEA_EMBEDDED_BROAD_DIRTY_BBOX
46
+ #define GEA_EMBEDDED_BROAD_DIRTY_BBOX 0
47
+ #endif
48
+
49
+ #ifndef GEA_EMBEDDED_FLUSH_COALESCE_DIRTY_REGIONS
50
+ #define GEA_EMBEDDED_FLUSH_COALESCE_DIRTY_REGIONS 1
51
+ #endif
52
+
53
+ #ifndef GEA_EMBEDDED_REPLAY_COALESCE_DIRTY_REGIONS
54
+ #define GEA_EMBEDDED_REPLAY_COALESCE_DIRTY_REGIONS 0
55
+ #endif
56
+
57
+ #ifndef GEA_EMBEDDED_RETAINED_MOVE_DIRTY_GUARD_PX
58
+ #define GEA_EMBEDDED_RETAINED_MOVE_DIRTY_GUARD_PX 2
59
+ #endif
60
+
61
+ #ifndef GEA_EMBEDDED_TEXT_DIRTY_GUARD_PX
62
+ #define GEA_EMBEDDED_TEXT_DIRTY_GUARD_PX 2
63
+ #endif
64
+
65
+ // subtreeRevealsUnrecordedContent (render.cpp) is an O(nodeCount) whole-tree scan; the
66
+ // per-node keep-list guard below calls it once per content-dirty / translated node, so a
67
+ // scene with many independently-moving nodes (bouncing-balls: 64 balls translate every
68
+ // frame) pays O(N^2) reveal-checks. It exists to reveal content that was culled outside
69
+ // the record-time clip and later slid into view (sky-hop pan). Apps whose moving content
70
+ // stays within the recorded viewport can't reveal anything, so the check is pure cost.
71
+ #ifndef GEA_EMBEDDED_SUBTREE_REVEAL_CHECK
72
+ #define GEA_EMBEDDED_SUBTREE_REVEAL_CHECK 1
73
+ #endif
74
+
75
+ namespace gea::embedded::ui
76
+ {
77
+ namespace
78
+ {
79
+
80
+ #if GEA_EMBEDDED_DISPLAY_FUSE_REPLAY_FLUSH
81
+ struct FusedReplayRasterCtx
82
+ {
83
+ int screenW;
84
+ int screenH;
85
+ };
86
+
87
+ // Display::flushRectsRasterized callback. For each DMA chunk [ox,oy]..[ox+w-1,oy+h-1]
88
+ // it rebinds the draw canvas ONTO the chunk buffer — an offset base pointer with the
89
+ // chunk stride, so absolute screen (x,y) writes land at pixels[(y-oy)*w + (x-ox)] —
90
+ // then replays the dirty display-list clipped to the chunk straight into it. The
91
+ // caller (Display) DMAs the chunk and restores the canvas via rebindCanvasToFramebuffer.
92
+ void fusedReplayRaster(gea::framework::graphics::pixel::native_t *pixels, int width, int height, int ox, int oy, void *user)
93
+ {
94
+ auto *ctx = static_cast<FusedReplayRasterCtx *>(user);
95
+ auto *canvas = gea::platform::display::Display::canvas();
96
+ if (!canvas || !ctx)
97
+ return;
98
+ #if GEA_EMBEDDED_DISPLAY_FUSE_REPLAY_CLEAR_RGB565 >= 0
99
+ std::fill_n(pixels,
100
+ static_cast<std::size_t>(width) * static_cast<std::size_t>(height),
101
+ static_cast<gea::framework::graphics::pixel::native_t>(GEA_EMBEDDED_DISPLAY_FUSE_REPLAY_CLEAR_RGB565));
102
+ #endif
103
+ using PixT = gea::framework::graphics::pixel::native_t;
104
+ PixT *base = reinterpret_cast<PixT *>(pixels) -
105
+ (static_cast<std::ptrdiff_t>(oy) * width + ox);
106
+ canvas->bindPixels(base, ctx->screenW, ctx->screenH, width);
107
+ gea::platform::display::Display::resetClip();
108
+ gea::platform::display::Display::setAlpha(255);
109
+ gea::platform::display::Display::pushClip(ox, oy, width, height);
110
+ DisplayList::instance().replaySimpleClippedDirtyRegion(ox, oy, ox + width - 1, oy + height - 1, -1);
111
+ gea::platform::display::Display::popClip();
112
+ }
113
+
114
+ void fusedDirectReplayRaster(gea::framework::graphics::pixel::native_t *pixels, int width, int height, int ox, int oy, void *user)
115
+ {
116
+ auto *ctx = static_cast<FusedReplayRasterCtx *>(user);
117
+ auto *canvas = gea::platform::display::Display::canvas();
118
+ if (!canvas || !ctx)
119
+ return;
120
+ #if GEA_EMBEDDED_DISPLAY_FUSE_REPLAY_CLEAR_RGB565 >= 0
121
+ std::fill_n(pixels,
122
+ static_cast<std::size_t>(width) * static_cast<std::size_t>(height),
123
+ static_cast<gea::framework::graphics::pixel::native_t>(GEA_EMBEDDED_DISPLAY_FUSE_REPLAY_CLEAR_RGB565));
124
+ #endif
125
+ using PixT = gea::framework::graphics::pixel::native_t;
126
+ PixT *base = reinterpret_cast<PixT *>(pixels) -
127
+ (static_cast<std::ptrdiff_t>(oy) * width + ox);
128
+ canvas->bindPixels(base, ctx->screenW, ctx->screenH, width);
129
+ gea::platform::display::Display::resetClip();
130
+ gea::platform::display::Display::setAlpha(255);
131
+ gea::platform::display::Display::pushClip(ox, oy, width, height);
132
+ const DisplayReplayRegion region{ox, oy, ox + width - 1, oy + height - 1, -1};
133
+ DisplayList::instance().replayDirectDirtyRegions(&region, 1);
134
+ gea::platform::display::Display::popClip();
135
+ }
136
+ #endif
137
+
138
+ struct PreservedScrollOffset
139
+ {
140
+ int32_t x = 0;
141
+ int32_t y = 0;
142
+ };
143
+
144
+ void preserveScrollOffsets(PreservedScrollOffset *offsets, int count)
145
+ {
146
+ if (!offsets || count <= 0)
147
+ return;
148
+ auto &state = treeState();
149
+ const int n = state.nodeCount < count ? state.nodeCount : count;
150
+ for (int i = 0; i < n; ++i)
151
+ {
152
+ offsets[i].x = state.nodes[i].layout.scroll_x;
153
+ offsets[i].y = state.nodes[i].layout.scroll_y;
154
+ }
155
+ }
156
+
157
+ void restoreScrollOffsetsAfterLayout(const PreservedScrollOffset *offsets, int count)
158
+ {
159
+ if (!offsets || count <= 0)
160
+ return;
161
+ auto &state = treeState();
162
+ const int n = state.nodeCount < count ? state.nodeCount : count;
163
+ for (int i = 0; i < n; ++i)
164
+ {
165
+ Node &node = state.nodes[i];
166
+ if (node.type == NodeType::VirtualList)
167
+ {
168
+ node.layout.scroll_x = 0;
169
+ int y = offsets[i].y;
170
+ const int maxY = VirtualListRenderer::scrollMaxY(i);
171
+ if (y < 0)
172
+ y = 0;
173
+ if (y > maxY)
174
+ y = maxY;
175
+ node.layout.scroll_y = static_cast<int32_t>(y);
176
+ continue;
177
+ }
178
+ if (node.style.overflow != 2)
179
+ {
180
+ node.layout.scroll_x = 0;
181
+ node.layout.scroll_y = 0;
182
+ continue;
183
+ }
184
+ if (scrollsOverflowX(node.style))
185
+ {
186
+ int x = offsets[i].x;
187
+ const int maxX = ViewRenderer::scrollMaxX(node);
188
+ if (x < 0)
189
+ x = 0;
190
+ if (x > maxX)
191
+ x = maxX;
192
+ node.layout.scroll_x = static_cast<int32_t>(x);
193
+ }
194
+ else
195
+ {
196
+ node.layout.scroll_x = 0;
197
+ }
198
+
199
+ if (scrollsOverflowY(node.style))
200
+ {
201
+ int y = offsets[i].y;
202
+ const int maxY = ViewRenderer::scrollMaxY(node);
203
+ if (y < 0)
204
+ y = 0;
205
+ if (y > maxY)
206
+ y = maxY;
207
+ node.layout.scroll_y = static_cast<int32_t>(y);
208
+ }
209
+ else
210
+ {
211
+ node.layout.scroll_y = 0;
212
+ }
213
+ }
214
+ }
215
+
216
+ int dirtyRectArea(const DirtyRegions::Rect &r)
217
+ {
218
+ if (r.x0 > r.x1 || r.y0 > r.y1)
219
+ return 0;
220
+ return (r.x1 - r.x0 + 1) * (r.y1 - r.y0 + 1);
221
+ }
222
+
223
+ bool dirtyRectContains(const DirtyRegions::Rect &outer, const DirtyRegions::Rect &inner)
224
+ {
225
+ return outer.x0 <= inner.x0 &&
226
+ outer.y0 <= inner.y0 &&
227
+ outer.x1 >= inner.x1 &&
228
+ outer.y1 >= inner.y1;
229
+ }
230
+
231
+ bool dirtyRectCoveredByAny(const DirtyRegions::Rect *rects, int count, const DirtyRegions::Rect &inner)
232
+ {
233
+ if (!rects || count <= 0)
234
+ return false;
235
+ for (int i = 0; i < count; ++i)
236
+ {
237
+ if (dirtyRectContains(rects[i], inner))
238
+ return true;
239
+ }
240
+ return false;
241
+ }
242
+
243
+ bool styleHasRoundedRasterEdge(const ComputedStyle &style)
244
+ {
245
+ for (int i = 0; i < 4; ++i)
246
+ {
247
+ if (style.border_radius[i] > 0)
248
+ return true;
249
+ if (style.border_radius_percent[i] != kUnset && style.border_radius_percent[i] > 0)
250
+ return true;
251
+ }
252
+ return false;
253
+ }
254
+
255
+ bool dirtyRectNeedsRasterGuard(const Node &node)
256
+ {
257
+ if (hasAnyBorder(node.style))
258
+ return true;
259
+ if (rstyle(node.style).filter_blur_radius > 0 || node.render.previous_filter_blur_radius > 0)
260
+ return true;
261
+ if (node.style.mask_right_fade_width > 0)
262
+ return true;
263
+ if (rstyle(node.style).box_shadow_alpha > 0)
264
+ return true;
265
+ return node.style.has_bg && (styleHasRoundedRasterEdge(node.style) || node.style.bg_alpha < 255);
266
+ }
267
+
268
+ constexpr int kRetainedMoveDirtyGuardPx = GEA_EMBEDDED_RETAINED_MOVE_DIRTY_GUARD_PX;
269
+
270
+ DirtyRegions::Rect expandDirtyRect(DirtyRegions::Rect rect, int pad)
271
+ {
272
+ if (pad <= 0)
273
+ return rect;
274
+ rect.x0 -= pad;
275
+ rect.y0 -= pad;
276
+ rect.x1 += pad;
277
+ rect.y1 += pad;
278
+ return rect;
279
+ }
280
+
281
+ DirtyRegions::Rect dirtyRectWithRasterGuard(const Node &node, DirtyRegions::Rect rect)
282
+ {
283
+ if (!dirtyRectNeedsRasterGuard(node))
284
+ return rect;
285
+ return expandDirtyRect(rect, 1);
286
+ }
287
+
288
+ DirtyRegions::Rect dirtyRectWithRetainedMoveGuard(DirtyRegions::Rect rect)
289
+ {
290
+ // Retained absolute movement translates existing display commands and then
291
+ // streams only the collected dirty bands to the panel. Exact prev-box ∪
292
+ // cur-box math is too brittle here: a one-row miss leaves visible residue
293
+ // because no later full-frame copy cleans it up. Keep the replay/flush
294
+ // window slightly conservative for every retained move.
295
+ return expandDirtyRect(rect, kRetainedMoveDirtyGuardPx);
296
+ }
297
+
298
+ DirtyRegions::Rect uniteDirtyRects(const DirtyRegions::Rect &a, const DirtyRegions::Rect &b)
299
+ {
300
+ DirtyRegions::Rect out = a;
301
+ if (b.x0 < out.x0)
302
+ out.x0 = b.x0;
303
+ if (b.y0 < out.y0)
304
+ out.y0 = b.y0;
305
+ if (b.x1 > out.x1)
306
+ out.x1 = b.x1;
307
+ if (b.y1 > out.y1)
308
+ out.y1 = b.y1;
309
+ if (a.origin != b.origin)
310
+ out.origin = -1;
311
+ return out;
312
+ }
313
+
314
+ void coalesceHighCoverageDirtyRegions(DirtyRegions::Rect *rects, int *rect_count, int width, int height)
315
+ {
316
+ if (!rects || !rect_count || *rect_count < 2 || width <= 0 || height <= 0)
317
+ return;
318
+
319
+ DirtyRegions::Rect bounds = rects[0];
320
+ int total_area = 0;
321
+ for (int i = 0; i < *rect_count; i++)
322
+ {
323
+ total_area += dirtyRectArea(rects[i]);
324
+ bounds = uniteDirtyRects(bounds, rects[i]);
325
+ }
326
+
327
+ const int screen_area = width * height;
328
+ const bool many_rects = (*rect_count * *rect_count) >= DirtyRegions::kMaxRects;
329
+ const bool broad_paint = total_area >= screen_area - total_area;
330
+ if (!many_rects || !broad_paint)
331
+ return;
332
+
333
+ bounds.origin = -1;
334
+ rects[0] = bounds;
335
+ *rect_count = 1;
336
+ }
337
+
338
+ // Gap-merge tightness for coalesceLowCostDirtyRegions. The greedy pass merges a pair when
339
+ // the gap it adds is <= (smaller rect area >> SHIFT). SHIFT=0 = original behavior (allow a
340
+ // gap as large as the smaller rect), which chains across scattered rects into wide windows
341
+ // full of unchanged background — fine when per-window flush setup is expensive, but on a
342
+ // board whose flush pays per *pixel* (PSRAM copy) and ~0 per window, those gap pixels are
343
+ // pure waste that spike the copy and miss the TE. Raise SHIFT on such boards to keep merges
344
+ // to near-touching rects only. flush_rects stays a superset of the dirty rects either way,
345
+ // so tighter windows never leave stale pixels.
346
+ #ifndef GEA_EMBEDDED_DIRTY_COALESCE_GAP_SHIFT
347
+ #define GEA_EMBEDDED_DIRTY_COALESCE_GAP_SHIFT 0
348
+ #endif
349
+
350
+ void coalesceLowCostDirtyRegions(DirtyRegions::Rect *rects, int *rect_count)
351
+ {
352
+ if (!rects || !rect_count || *rect_count < 2)
353
+ return;
354
+
355
+ while (*rect_count > 1)
356
+ {
357
+ int bestI = -1;
358
+ int bestJ = -1;
359
+ int bestExtra = 0x7fffffff;
360
+ int bestAllowance = 0;
361
+
362
+ for (int i = 0; i < *rect_count; i++)
363
+ {
364
+ const int areaI = dirtyRectArea(rects[i]);
365
+ if (areaI <= 0)
366
+ continue;
367
+ for (int j = i + 1; j < *rect_count; j++)
368
+ {
369
+ const int areaJ = dirtyRectArea(rects[j]);
370
+ if (areaJ <= 0)
371
+ continue;
372
+ const DirtyRegions::Rect merged = uniteDirtyRects(rects[i], rects[j]);
373
+ const int extra = dirtyRectArea(merged) - areaI - areaJ;
374
+ const int allowance = (areaI < areaJ ? areaI : areaJ) >> GEA_EMBEDDED_DIRTY_COALESCE_GAP_SHIFT;
375
+ if (extra < bestExtra)
376
+ {
377
+ bestExtra = extra;
378
+ bestAllowance = allowance;
379
+ bestI = i;
380
+ bestJ = j;
381
+ }
382
+ }
383
+ }
384
+
385
+ if (bestI < 0 || bestJ < 0 || bestExtra > bestAllowance)
386
+ return;
387
+ rects[bestI] = uniteDirtyRects(rects[bestI], rects[bestJ]);
388
+ rects[bestJ] = rects[*rect_count - 1];
389
+ (*rect_count)--;
390
+ }
391
+ }
392
+
393
+ int nodeBoxWidth(const Node &node, bool usePrevious)
394
+ {
395
+ return usePrevious ? node.layout.previous_width : node.layout.width;
396
+ }
397
+
398
+ int nodeBoxHeight(const Node &node, bool usePrevious)
399
+ {
400
+ return usePrevious ? node.layout.previous_height : node.layout.height;
401
+ }
402
+
403
+ int nodeBoxRotation(const Node &node, bool usePrevious)
404
+ {
405
+ return usePrevious ? node.render.previous_transform_rotate : rstyle(node.style).transform_rotate;
406
+ }
407
+
408
+ bool hasTransformState(const Node &node)
409
+ {
410
+ const RareStyle &rs = rstyle(node.style); // one pool lookup, not 11
411
+ return rs.transform_rotate != 0 ||
412
+ node.render.previous_transform_rotate != 0 ||
413
+ rs.transform_rotate_x != 0 ||
414
+ node.render.previous_transform_rotate_x != 0 ||
415
+ rs.transform_rotate_y != 0 ||
416
+ node.render.previous_transform_rotate_y != 0 ||
417
+ rs.transform_translate_x != 0 ||
418
+ node.render.previous_transform_translate_x != 0 ||
419
+ rs.transform_translate_y != 0 ||
420
+ node.render.previous_transform_translate_y != 0 ||
421
+ rs.transform_translate_z != 0 ||
422
+ node.render.previous_transform_translate_z != 0 ||
423
+ rs.transform_translate_x_percent != 0 ||
424
+ node.render.previous_transform_translate_x_percent != 0 ||
425
+ rs.transform_translate_y_percent != 0 ||
426
+ node.render.previous_transform_translate_y_percent != 0 ||
427
+ rs.transform_scale_x != 1000 ||
428
+ node.render.previous_transform_scale_x != 1000 ||
429
+ rs.transform_scale_y != 1000 ||
430
+ node.render.previous_transform_scale_y != 1000 ||
431
+ rs.perspective > 0 ||
432
+ node.render.previous_perspective > 0;
433
+ }
434
+
435
+ bool hasThreeDimensionalTransformState(const Node &node)
436
+ {
437
+ return rstyle(node.style).transform_rotate_x != 0 ||
438
+ node.render.previous_transform_rotate_x != 0 ||
439
+ rstyle(node.style).transform_rotate_y != 0 ||
440
+ node.render.previous_transform_rotate_y != 0 ||
441
+ rstyle(node.style).transform_translate_z != 0 ||
442
+ node.render.previous_transform_translate_z != 0 ||
443
+ rstyle(node.style).perspective > 0 ||
444
+ node.render.previous_perspective > 0;
445
+ }
446
+
447
+ bool clipDirtyRect(DirtyRegions::Rect *rect, int width, int height)
448
+ {
449
+ if (!rect || rect->x0 > rect->x1 || rect->y0 > rect->y1)
450
+ return false;
451
+ if (rect->x0 < 0)
452
+ rect->x0 = 0;
453
+ if (rect->y0 < 0)
454
+ rect->y0 = 0;
455
+ if (rect->x1 >= width)
456
+ rect->x1 = width - 1;
457
+ if (rect->y1 >= height)
458
+ rect->y1 = height - 1;
459
+ return rect->x0 <= rect->x1 && rect->y0 <= rect->y1;
460
+ }
461
+
462
+ // Set for a frame whose dirty set is "broad" — many scattered movers (e.g. 64
463
+ // bouncing balls) whose union the flush will coalesce to its bounding box
464
+ // anyway (FLUSH_ADAPTIVE_COALESCE), and where the wide bbox flush is faster
465
+ // than precise windows on this QSPI board. In that case the precise
466
+ // O(n*kMaxRects) DirtyRegions::add merge (+ the later coalesce passes) is pure
467
+ // wasted CPU: it produces precise rects that are immediately discarded for the
468
+ // bbox. So accumulate ONE bbox per array (O(1) per add) instead. Single-
469
+ // threaded refresh, so a file-static flag is safe; reset after the collect.
470
+ bool g_broadDirtyBbox = false;
471
+
472
+ void addDirtyRegion(DirtyRegions::Rect *rects, int *rect_count, DirtyRegions::Rect rect, int width, int height)
473
+ {
474
+ if (!clipDirtyRect(&rect, width, height))
475
+ return;
476
+ if (g_broadDirtyBbox)
477
+ {
478
+ if (*rect_count == 0)
479
+ rects[(*rect_count)++] = rect;
480
+ else
481
+ rects[0] = uniteDirtyRects(rects[0], rect);
482
+ return;
483
+ }
484
+ DirtyRegions::add(rects, rect_count, DirtyRegions::kMaxRects, rect);
485
+ }
486
+
487
+ void appendDirtyRegion(DirtyRegions::Rect *rects, int *rect_count, DirtyRegions::Rect rect, int width, int height)
488
+ {
489
+ if (!clipDirtyRect(&rect, width, height))
490
+ return;
491
+ if (!rects || !rect_count || *rect_count >= DirtyRegions::kMaxRects)
492
+ return;
493
+ rects[(*rect_count)++] = rect;
494
+ }
495
+
496
+ bool resolveNodeCircularRadii(const Node &node, int radii[4])
497
+ {
498
+ if (!radii || node.layout.width <= 0 || node.layout.height <= 0)
499
+ return false;
500
+ const double width = static_cast<double>(node.layout.width);
501
+ const double height = static_cast<double>(node.layout.height);
502
+ double rx[4]{};
503
+ double ry[4]{};
504
+ for (int i = 0; i < 4; ++i)
505
+ {
506
+ if (node.style.border_radius_percent[i] != kUnset)
507
+ {
508
+ const double p = static_cast<double>(node.style.border_radius_percent[i]) / 1000.0;
509
+ rx[i] = std::max(0.0, width * p);
510
+ ry[i] = std::max(0.0, height * p);
511
+ }
512
+ else
513
+ {
514
+ const double r = static_cast<double>(std::max(0, static_cast<int>(node.style.border_radius[i])));
515
+ rx[i] = r;
516
+ ry[i] = r;
517
+ }
518
+ }
519
+
520
+ double scale = 1.0;
521
+ const auto constrain = [&](double limit, double sum)
522
+ {
523
+ if (limit > 0.0 && sum > limit)
524
+ scale = std::min(scale, limit / sum);
525
+ };
526
+ constrain(width, rx[0] + rx[1]);
527
+ constrain(width, rx[3] + rx[2]);
528
+ constrain(height, ry[0] + ry[3]);
529
+ constrain(height, ry[1] + ry[2]);
530
+
531
+ for (int i = 0; i < 4; ++i)
532
+ {
533
+ const double sx = rx[i] * scale;
534
+ const double sy = ry[i] * scale;
535
+ if (std::abs(sx - sy) > 1.0)
536
+ return false;
537
+ radii[i] = static_cast<int>(std::lround((sx + sy) * 0.5));
538
+ }
539
+ return true;
540
+ }
541
+
542
+ bool nodeIsCircleLikeRoundedBackground(const Node &node)
543
+ {
544
+ const int w = static_cast<int>(node.layout.width);
545
+ const int h = static_cast<int>(node.layout.height);
546
+ const int minSide = std::min(w, h);
547
+ if (minSide < 96 || std::abs(w - h) > 2)
548
+ return false;
549
+ int radii[4]{};
550
+ if (!resolveNodeCircularRadii(node, radii))
551
+ return false;
552
+ const int minRadius = std::max(1, minSide / 2 - 2);
553
+ return radii[0] >= minRadius &&
554
+ radii[1] >= minRadius &&
555
+ radii[2] >= minRadius &&
556
+ radii[3] >= minRadius;
557
+ }
558
+
559
+ int appendCircleLikeRecolorFlushRegions(DirtyRegions::Rect *rects,
560
+ int *rect_count,
561
+ const Node &node,
562
+ const DirtyRegions::Rect &recolorRect,
563
+ int width,
564
+ int height)
565
+ {
566
+ if (!nodeIsCircleLikeRoundedBackground(node))
567
+ return 0;
568
+ if (!rects || !rect_count || *rect_count >= DirtyRegions::kMaxRects)
569
+ return 0;
570
+ const int available = DirtyRegions::kMaxRects - *rect_count;
571
+ const int bandCount = std::min(DirtyRegions::kMaxRects, available);
572
+ if (bandCount < 4)
573
+ return 0;
574
+
575
+ const double cx = static_cast<double>(node.layout.x) + static_cast<double>(node.layout.width) * 0.5;
576
+ const double cy = static_cast<double>(node.layout.y) + static_cast<double>(node.layout.height) * 0.5;
577
+ const double rx = static_cast<double>(node.layout.width) * 0.5;
578
+ const double ry = static_cast<double>(node.layout.height) * 0.5;
579
+ if (rx <= 0.0 || ry <= 0.0)
580
+ return 0;
581
+
582
+ const int y0 = recolorRect.y0;
583
+ const int y1 = recolorRect.y1;
584
+ if (y0 > y1)
585
+ return 0;
586
+ const int rows = y1 - y0 + 1;
587
+ const int pad = 4;
588
+ int pixels = 0;
589
+ for (int band = 0; band < bandCount; ++band)
590
+ {
591
+ const int by0 = y0 + (rows * band) / bandCount;
592
+ const int by1 = y0 + (rows * (band + 1)) / bandCount - 1;
593
+ if (by0 > by1)
594
+ continue;
595
+ const double upper = static_cast<double>(by0) + 0.5;
596
+ const double lower = static_cast<double>(by1) + 0.5;
597
+ const double sampleY = cy < upper ? upper : (cy > lower ? lower : cy);
598
+ const double dy = (sampleY - cy) / ry;
599
+ const double dx = dy * dy >= 1.0 ? 0.0 : rx * std::sqrt(1.0 - dy * dy);
600
+ int bx0 = static_cast<int>(std::floor(cx - dx)) - pad;
601
+ int bx1 = static_cast<int>(std::ceil(cx + dx)) + pad;
602
+ if (bx0 < recolorRect.x0)
603
+ bx0 = recolorRect.x0;
604
+ if (bx1 > recolorRect.x1)
605
+ bx1 = recolorRect.x1;
606
+ DirtyRegions::Rect bandRect{bx0, by0, bx1, by1, recolorRect.origin};
607
+ const int before = *rect_count;
608
+ appendDirtyRegion(rects, rect_count, bandRect, width, height);
609
+ if (*rect_count != before)
610
+ pixels += dirtyRectArea(rects[*rect_count - 1]);
611
+ }
612
+ return pixels;
613
+ }
614
+
615
+ bool canUseStripDirtyForTransformedLeaf(const Node &node)
616
+ {
617
+ return isViewLikeNodeType(node.type) &&
618
+ node.first_child < 0 &&
619
+ node.style.display != 1 &&
620
+ node.style.has_bg &&
621
+ !hasAnyBorder(node.style) &&
622
+ hasTransformState(node);
623
+ }
624
+
625
+ bool canUseStaticBackdropStripDirtyForTransformedLeaf(const Node &node)
626
+ {
627
+ return canUseStripDirtyForTransformedLeaf(node) &&
628
+ !hasThreeDimensionalTransformState(node);
629
+ }
630
+
631
+ bool layoutSizeChangeNeedsCommandRerecord(const Node &node)
632
+ {
633
+ if (node.layout.width == node.layout.previous_width &&
634
+ node.layout.height == node.layout.previous_height)
635
+ return false;
636
+ if (node.type == NodeType::Text ||
637
+ node.type == NodeType::Image ||
638
+ node.type == NodeType::Canvas)
639
+ return true;
640
+ if (node.style.has_bg || hasAnyBorder(node.style))
641
+ return true;
642
+ if (rstyle(node.style).box_shadow_alpha > 0 || rstyle(node.style).filter_blur_radius > 0)
643
+ return true;
644
+ if (node.style.mask_right_fade_width > 0)
645
+ return true;
646
+ return false;
647
+ }
648
+
649
+ int transformedLeafDirtyShapeCount()
650
+ {
651
+ auto &state = treeState();
652
+ int count = 0;
653
+ for (int i = 0; i < state.nodeCount; i++)
654
+ {
655
+ const Node &node = state.nodes[i];
656
+ if (!node.render.dirty || !canUseStripDirtyForTransformedLeaf(node))
657
+ continue;
658
+ if (node.layout.previous_width > 0 && node.layout.previous_height > 0)
659
+ count++;
660
+ if (node.layout.width > 0 && node.layout.height > 0)
661
+ count++;
662
+ }
663
+ return count;
664
+ }
665
+
666
+ bool transformedLeafDirtyShapesAreFlat2D()
667
+ {
668
+ auto &state = treeState();
669
+ bool any = false;
670
+ for (int i = 0; i < state.nodeCount; i++)
671
+ {
672
+ const Node &node = state.nodes[i];
673
+ if (!node.render.dirty || !canUseStripDirtyForTransformedLeaf(node))
674
+ continue;
675
+ any = true;
676
+ if (hasThreeDimensionalTransformState(node))
677
+ return false;
678
+ }
679
+ return any;
680
+ }
681
+
682
+ // A node counts as dirty for the settle verdict when either its render state or
683
+ // its recorded commands changed this frame.
684
+ bool staticBackdropNodeIsDirty(int node)
685
+ {
686
+ auto &state = treeState();
687
+ if (node < 0 || node >= state.nodeCount)
688
+ return false;
689
+ return state.nodes[node].render.dirty || state.nodeCommandDirty[node];
690
+ }
691
+
692
+ // True when some PROPER ancestor of `node` is itself dirty — i.e. this node sits
693
+ // inside another dirty subtree and is therefore not a root of the change.
694
+ bool staticBackdropHasDirtyAncestor(int node)
695
+ {
696
+ auto &state = treeState();
697
+ if (node < 0 || node >= state.nodeCount)
698
+ return false;
699
+ for (int p = state.nodes[node].parent; p >= 0 && p < state.nodeCount; p = state.nodes[p].parent)
700
+ {
701
+ if (staticBackdropNodeIsDirty(p))
702
+ return true;
703
+ }
704
+ return false;
705
+ }
706
+
707
+ bool commandsAreSameOpaqueFillShape(DisplayCommand oldCommand, DisplayCommand newCommand)
708
+ {
709
+ if (oldCommand.type != newCommand.type)
710
+ return false;
711
+ if (oldCommand.bx != newCommand.bx ||
712
+ oldCommand.by != newCommand.by ||
713
+ oldCommand.bw != newCommand.bw ||
714
+ oldCommand.bh != newCommand.bh)
715
+ return false;
716
+ switch (oldCommand.type)
717
+ {
718
+ case DisplayCommandType::FillRect:
719
+ oldCommand.fill.color = newCommand.fill.color;
720
+ return std::memcmp(&oldCommand.fill, &newCommand.fill, sizeof(oldCommand.fill)) == 0;
721
+ case DisplayCommandType::FillCircle:
722
+ oldCommand.fillCircle.color = newCommand.fillCircle.color;
723
+ return std::memcmp(&oldCommand.fillCircle,
724
+ &newCommand.fillCircle,
725
+ sizeof(oldCommand.fillCircle)) == 0;
726
+ case DisplayCommandType::FillRoundedRect:
727
+ if (gea::platform::display::Display::aa() >= 2 &&
728
+ (oldCommand.fillRoundedRect.tl || oldCommand.fillRoundedRect.tr ||
729
+ oldCommand.fillRoundedRect.br || oldCommand.fillRoundedRect.bl))
730
+ return false;
731
+ oldCommand.fillRoundedRect.color = newCommand.fillRoundedRect.color;
732
+ return std::memcmp(&oldCommand.fillRoundedRect,
733
+ &newCommand.fillRoundedRect,
734
+ sizeof(oldCommand.fillRoundedRect)) == 0;
735
+ case DisplayCommandType::FillTransformedRoundedRect:
736
+ if (gea::platform::display::Display::aa() >= 2)
737
+ return false;
738
+ oldCommand.transformedRoundedRect.color = newCommand.transformedRoundedRect.color;
739
+ return std::memcmp(&oldCommand.transformedRoundedRect,
740
+ &newCommand.transformedRoundedRect,
741
+ sizeof(oldCommand.transformedRoundedRect)) == 0;
742
+ default:
743
+ return false;
744
+ }
745
+ }
746
+
747
+ // Frame-stability verdict for the static-backdrop cache.
748
+ // kDynamic — exactly one dynamic (transformed) subtree is moving: the shape the
749
+ // bake was designed for; eligible to settle/bake and to arm reproject.
750
+ // kQuiet — nothing dynamic this frame (eased animations at a keyframe pause,
751
+ // or only tolerated ticker leaves changed): the scene is MORE static
752
+ // than ever — a live cache must be KEPT, not dropped. Treating quiet
753
+ // as unstable made every fps-badge tick that landed inside the
754
+ // cube-spin's eased pauses drop the cache, and the resume re-bake +
755
+ // full-viewport sync was the ~90ms frame behind the loop-wrap fps dip.
756
+ // kFailed — a non-bakeable change happened (recolor in flight, a static node's
757
+ // content changed, two independent dynamic roots): the baked pixels
758
+ // can be stale, drop the cache.
759
+ enum class BackdropSettle
760
+ {
761
+ kFailed,
762
+ kQuiet,
763
+ kDynamic
764
+ };
765
+
766
+ BackdropSettle staticBackdropFrameSettle(bool debugPrint = false)
767
+ {
768
+ #ifndef ESP_PLATFORM
769
+ static const bool debugEnv = std::getenv("GEA_DEBUG_BACKDROP") != nullptr;
770
+ const bool debugSettle = debugPrint || debugEnv;
771
+ #else
772
+ const bool debugSettle = debugPrint;
773
+ #endif
774
+ auto &state = treeState();
775
+ // The verdict is a question about the TREE, not about array order: does ONE
776
+ // dirty subtree contain every other dirty node? This used to be answered by a
777
+ // single forward scan that anchored on the first dirty node and skipped later
778
+ // nodes that were its descendants — correct only while node indices arrived in
779
+ // PRE-order, where the first dirty node is necessarily the topmost one.
780
+ // The JSX runtime now builds children before their parent (gea::jsx::create for
781
+ // the child, then gea::jsx::child on the parent), so indices arrive in
782
+ // POST-order and the first dirty node is the DEEPEST. Anchoring on it made a
783
+ // node's own PARENT look like a second, independent dynamic root: css-3d-cube's
784
+ // spinning .cube (id 22) anchored, then its floating .cube-wrap (id 23) was
785
+ // rejected, so the live backdrop cache was dropped and re-baked EVERY frame —
786
+ // 72fps -> 25fps. Find the topmost dirty node explicitly instead, so the answer
787
+ // holds under either ordering.
788
+ int dynamicRoot = -1;
789
+ int secondRoot = -1;
790
+ for (int i = 0; i < state.nodeCount; i++)
791
+ {
792
+ const Node &node = state.nodes[i];
793
+ if (!node.render.dirty && !state.nodeCommandDirty[i])
794
+ continue;
795
+ if (node.render.bg_recolor_pending)
796
+ {
797
+ if (debugSettle)
798
+ std::printf("[settle] FAIL node=%d bg_recolor_pending\n", i);
799
+ return BackdropSettle::kFailed;
800
+ }
801
+ // Recently-changed dynamic leaves (ticking text badges) are tolerated: the
802
+ // bake excludes them and their updates flow through the normal dirty-region
803
+ // replay, so their dirtiness doesn't make the static scene unstable.
804
+ if (node.first_child < 0 && !node.render.transform_dirty &&
805
+ state.nodeBackdropCooldown[i] > 0)
806
+ continue;
807
+ // Inside another dirty subtree: carried by that subtree's root, not a root.
808
+ if (staticBackdropHasDirtyAncestor(i))
809
+ continue;
810
+ if (dynamicRoot < 0)
811
+ dynamicRoot = i;
812
+ else if (secondRoot < 0)
813
+ secondRoot = i;
814
+ }
815
+ if (secondRoot >= 0)
816
+ {
817
+ if (debugSettle)
818
+ std::printf("[settle] FAIL second dynamic root node=%d (first=%d)\n", secondRoot, dynamicRoot);
819
+ return BackdropSettle::kFailed;
820
+ }
821
+ if (dynamicRoot < 0)
822
+ {
823
+ if (debugSettle)
824
+ std::printf("[settle] QUIET no dynamic root this frame\n");
825
+ return BackdropSettle::kQuiet;
826
+ }
827
+ // The one root must be the bake's shape: a transformed subtree, not a leaf and
828
+ // not a content change on a static node.
829
+ const Node &rootNode = state.nodes[dynamicRoot];
830
+ if (!state.nodeCommandDirty[dynamicRoot] || !rootNode.render.transform_dirty ||
831
+ rootNode.first_child < 0)
832
+ {
833
+ if (debugSettle)
834
+ std::printf("[settle] FAIL node=%d cmdDirty=%d transformDirty=%d leaf=%d cooldown=%d\n",
835
+ dynamicRoot, state.nodeCommandDirty[dynamicRoot] ? 1 : 0,
836
+ rootNode.render.transform_dirty ? 1 : 0,
837
+ rootNode.first_child < 0 ? 1 : 0, state.nodeBackdropCooldown[dynamicRoot]);
838
+ return BackdropSettle::kFailed;
839
+ }
840
+ return BackdropSettle::kDynamic;
841
+ }
842
+
843
+ DirtyRegions::Rect transformedBoundsRect(const Node &node, bool usePrevious, int origin)
844
+ {
845
+ int x0, y0, x1, y1;
846
+ ViewRenderer::transformedBounds(node, usePrevious, &x0, &y0, &x1, &y1);
847
+ return DirtyRegions::Rect{x0, y0, x1, y1, origin};
848
+ }
849
+
850
+ void unionTransformedSubtreeBounds(int node, bool usePrevious, int *x0, int *y0, int *x1, int *y1, bool *any)
851
+ {
852
+ auto &state = treeState();
853
+ if (node < 0 || node >= state.nodeCount)
854
+ return;
855
+ Node &n = state.nodes[node];
856
+ if (n.style.display != 1 && n.layout.width > 0 && n.layout.height > 0)
857
+ {
858
+ int nx0, ny0, nx1, ny1;
859
+ ViewRenderer::transformedBounds(n, usePrevious, &nx0, &ny0, &nx1, &ny1);
860
+ if (!*any)
861
+ {
862
+ *x0 = nx0;
863
+ *y0 = ny0;
864
+ *x1 = nx1;
865
+ *y1 = ny1;
866
+ *any = true;
867
+ }
868
+ else
869
+ {
870
+ if (nx0 < *x0)
871
+ *x0 = nx0;
872
+ if (ny0 < *y0)
873
+ *y0 = ny0;
874
+ if (nx1 > *x1)
875
+ *x1 = nx1;
876
+ if (ny1 > *y1)
877
+ *y1 = ny1;
878
+ }
879
+ }
880
+ for (int child = n.first_child; child >= 0; child = state.nodes[child].next_sibling)
881
+ unionTransformedSubtreeBounds(child, usePrevious, x0, y0, x1, y1, any);
882
+ }
883
+
884
+ DirtyRegions::Rect transformedSubtreeBoundsRect(int node, bool usePrevious, int origin)
885
+ {
886
+ int x0 = 0, y0 = 0, x1 = -1, y1 = -1;
887
+ bool any = false;
888
+ unionTransformedSubtreeBounds(node, usePrevious, &x0, &y0, &x1, &y1, &any);
889
+ return any ? DirtyRegions::Rect{x0, y0, x1, y1, origin}
890
+ : transformedBoundsRect(treeState().nodes[node], usePrevious, origin);
891
+ }
892
+
893
+ bool dirtyRectsIntersect(const DirtyRegions::Rect &a, const DirtyRegions::Rect &b)
894
+ {
895
+ return a.x0 <= b.x1 && a.x1 >= b.x0 &&
896
+ a.y0 <= b.y1 && a.y1 >= b.y0;
897
+ }
898
+
899
+ int filterBlurRadiusForNode(const Node &node, bool usePrevious)
900
+ {
901
+ return usePrevious ? node.render.previous_filter_blur_radius : rstyle(node.style).filter_blur_radius;
902
+ }
903
+
904
+ DirtyRegions::Rect filterBlurBoundsRect(const Node &node, bool usePrevious, int origin)
905
+ {
906
+ return transformedBoundsRect(node, usePrevious, origin);
907
+ }
908
+
909
+ void expandDirtyRegionsForFilterBlur(DirtyRegions::Rect *rects,
910
+ int *rect_count,
911
+ DirtyRegions::Rect *flush_rects,
912
+ int *flush_rect_count,
913
+ bool unifiedRectPath,
914
+ int width,
915
+ int height)
916
+ {
917
+ if (!rects || !rect_count || *rect_count <= 0 || width <= 0 || height <= 0)
918
+ return;
919
+ auto &state = treeState();
920
+ const int initialRectCount = *rect_count;
921
+ for (int i = 0; i < state.nodeCount; i++)
922
+ {
923
+ const Node &node = state.nodes[i];
924
+ if (node.style.display == 1)
925
+ continue;
926
+ for (int pass = 0; pass < 2; pass++)
927
+ {
928
+ const bool usePrevious = pass == 1;
929
+ if (filterBlurRadiusForNode(node, usePrevious) <= 0)
930
+ continue;
931
+ DirtyRegions::Rect blurRect = filterBlurBoundsRect(node, usePrevious, i);
932
+ if (!clipDirtyRect(&blurRect, width, height))
933
+ continue;
934
+ bool intersects = false;
935
+ for (int r = 0; r < initialRectCount; r++)
936
+ {
937
+ if (dirtyRectsIntersect(rects[r], blurRect))
938
+ {
939
+ intersects = true;
940
+ break;
941
+ }
942
+ }
943
+ if (!intersects)
944
+ continue;
945
+ addDirtyRegion(rects, rect_count, blurRect, width, height);
946
+ if (!unifiedRectPath)
947
+ addDirtyRegion(flush_rects, flush_rect_count, blurRect, width, height);
948
+ }
949
+ }
950
+ }
951
+
952
+ void appendTransformedLeafShape(DirtyRegions::Rect *rects,
953
+ int *rect_count,
954
+ const Node &node,
955
+ bool usePrevious,
956
+ int origin,
957
+ int width,
958
+ int height,
959
+ int segmentLimit,
960
+ bool mergeSegments)
961
+ {
962
+ const int boxWidth = nodeBoxWidth(node, usePrevious);
963
+ const int boxHeight = nodeBoxHeight(node, usePrevious);
964
+ if (boxWidth <= 0 || boxHeight <= 0)
965
+ return;
966
+
967
+ const int rotate = nodeBoxRotation(node, usePrevious);
968
+ if ((rotate % 3600) == 0 || segmentLimit <= 1)
969
+ {
970
+ if (mergeSegments)
971
+ addDirtyRegion(rects, rect_count, transformedBoundsRect(node, usePrevious, origin), width, height);
972
+ else
973
+ appendDirtyRegion(rects, rect_count, transformedBoundsRect(node, usePrevious, origin), width, height);
974
+ return;
975
+ }
976
+
977
+ int longSide = boxWidth >= boxHeight ? boxWidth : boxHeight;
978
+ int shortSide = boxWidth < boxHeight ? boxWidth : boxHeight;
979
+ if (shortSide < 1)
980
+ shortSide = 1;
981
+ int segments = (longSide + shortSide - 1) / shortSide;
982
+ if (segments > segmentLimit)
983
+ segments = segmentLimit;
984
+ if (segments < 1)
985
+ segments = 1;
986
+ if (segments <= 1)
987
+ {
988
+ if (mergeSegments)
989
+ addDirtyRegion(rects, rect_count, transformedBoundsRect(node, usePrevious, origin), width, height);
990
+ else
991
+ appendDirtyRegion(rects, rect_count, transformedBoundsRect(node, usePrevious, origin), width, height);
992
+ return;
993
+ }
994
+
995
+ int16_t xs[4], ys[4];
996
+ ViewRenderer::transformedCorners(node, usePrevious, xs, ys);
997
+ struct Point
998
+ {
999
+ double x;
1000
+ double y;
1001
+ };
1002
+ Point p[4] = {
1003
+ {static_cast<double>(xs[0]), static_cast<double>(ys[0])},
1004
+ {static_cast<double>(xs[1]), static_cast<double>(ys[1])},
1005
+ {static_cast<double>(xs[2]), static_cast<double>(ys[2])},
1006
+ {static_cast<double>(xs[3]), static_cast<double>(ys[3])},
1007
+ };
1008
+
1009
+ Point start;
1010
+ Point end;
1011
+ Point offset;
1012
+ if (boxWidth >= boxHeight)
1013
+ {
1014
+ start = {(p[0].x + p[3].x) * 0.5, (p[0].y + p[3].y) * 0.5};
1015
+ end = {(p[1].x + p[2].x) * 0.5, (p[1].y + p[2].y) * 0.5};
1016
+ offset = {(p[0].x - p[3].x) * 0.5, (p[0].y - p[3].y) * 0.5};
1017
+ }
1018
+ else
1019
+ {
1020
+ start = {(p[0].x + p[1].x) * 0.5, (p[0].y + p[1].y) * 0.5};
1021
+ end = {(p[3].x + p[2].x) * 0.5, (p[3].y + p[2].y) * 0.5};
1022
+ offset = {(p[1].x - p[0].x) * 0.5, (p[1].y - p[0].y) * 0.5};
1023
+ }
1024
+
1025
+ const double dx = end.x - start.x;
1026
+ const double dy = end.y - start.y;
1027
+ for (int i = 0; i < segments; i++)
1028
+ {
1029
+ const double t0 = static_cast<double>(i) / static_cast<double>(segments);
1030
+ const double t1 = static_cast<double>(i + 1) / static_cast<double>(segments);
1031
+ Point a{start.x + dx * t0, start.y + dy * t0};
1032
+ Point b{start.x + dx * t1, start.y + dy * t1};
1033
+ Point q[4] = {
1034
+ {a.x + offset.x, a.y + offset.y},
1035
+ {b.x + offset.x, b.y + offset.y},
1036
+ {b.x - offset.x, b.y - offset.y},
1037
+ {a.x - offset.x, a.y - offset.y},
1038
+ };
1039
+
1040
+ double minX = q[0].x, maxX = q[0].x;
1041
+ double minY = q[0].y, maxY = q[0].y;
1042
+ for (int qi = 1; qi < 4; qi++)
1043
+ {
1044
+ if (q[qi].x < minX)
1045
+ minX = q[qi].x;
1046
+ if (q[qi].x > maxX)
1047
+ maxX = q[qi].x;
1048
+ if (q[qi].y < minY)
1049
+ minY = q[qi].y;
1050
+ if (q[qi].y > maxY)
1051
+ maxY = q[qi].y;
1052
+ }
1053
+
1054
+ DirtyRegions::Rect strip{
1055
+ static_cast<int>(std::floor(minX)) - 1,
1056
+ static_cast<int>(std::floor(minY)) - 1,
1057
+ static_cast<int>(std::ceil(maxX)) + 1,
1058
+ static_cast<int>(std::ceil(maxY)) + 1,
1059
+ origin};
1060
+ if (mergeSegments)
1061
+ addDirtyRegion(rects, rect_count, strip, width, height);
1062
+ else
1063
+ appendDirtyRegion(rects, rect_count, strip, width, height);
1064
+ }
1065
+ }
1066
+
1067
+ bool appendTransformedLeafDirtyRegions(DirtyRegions::Rect *rects,
1068
+ int *rect_count,
1069
+ DirtyRegions::Rect *flush_rects,
1070
+ int *flush_rect_count,
1071
+ const Node &node,
1072
+ int origin,
1073
+ int width,
1074
+ int height,
1075
+ int segmentLimit,
1076
+ bool segmentReplayRegions)
1077
+ {
1078
+ if (!canUseStripDirtyForTransformedLeaf(node))
1079
+ return false;
1080
+ if (node.layout.previous_width <= 0 && node.layout.previous_height <= 0 &&
1081
+ node.layout.width <= 0 && node.layout.height <= 0)
1082
+ return true;
1083
+
1084
+ const int previousRotate = nodeBoxRotation(node, true);
1085
+ const int currentRotate = nodeBoxRotation(node, false);
1086
+ if ((previousRotate % 3600) == 0 && (currentRotate % 3600) == 0)
1087
+ {
1088
+ bool have = false;
1089
+ DirtyRegions::Rect combined{0, 0, -1, -1, origin};
1090
+ if (node.layout.previous_width > 0 && node.layout.previous_height > 0)
1091
+ {
1092
+ combined = transformedBoundsRect(node, true, origin);
1093
+ have = true;
1094
+ }
1095
+ if (node.layout.width > 0 && node.layout.height > 0)
1096
+ {
1097
+ const DirtyRegions::Rect current = transformedBoundsRect(node, false, origin);
1098
+ combined = have ? uniteDirtyRects(combined, current) : current;
1099
+ have = true;
1100
+ }
1101
+ if (have)
1102
+ {
1103
+ appendDirtyRegion(rects, rect_count, combined, width, height);
1104
+ appendDirtyRegion(flush_rects, flush_rect_count, combined, width, height);
1105
+ }
1106
+ return true;
1107
+ }
1108
+
1109
+ appendTransformedLeafShape(rects, rect_count, node, true, origin, width, height, segmentReplayRegions ? segmentLimit : 1, !segmentReplayRegions);
1110
+ appendTransformedLeafShape(rects, rect_count, node, false, origin, width, height, segmentReplayRegions ? segmentLimit : 1, !segmentReplayRegions);
1111
+ appendTransformedLeafShape(flush_rects, flush_rect_count, node, true, origin, width, height, segmentLimit, false);
1112
+ appendTransformedLeafShape(flush_rects, flush_rect_count, node, false, origin, width, height, segmentLimit, false);
1113
+ return true;
1114
+ }
1115
+
1116
+ // ---------------------------------------------------------------------------
1117
+ // Horizontal-pan fast path.
1118
+ //
1119
+ // A side-scroller camera (sky-hop's `<div style="left: -cameraX">` inside an
1120
+ // overflow:hidden viewport) translates a wide world subtree by dx every frame.
1121
+ // The normal refresh marks the whole panned subtree's bbox dirty (~the entire
1122
+ // viewport) and re-replays every visible tile — ~73% of the screen rastered per
1123
+ // frame. This path recreates the reverted-and-never-ported `memcpy-shift
1124
+ // overflow viewport` optimization (commit 24d88b79) on the C++ runtime: shift
1125
+ // the viewport's pixels by dx in place, then repaint only:
1126
+ // - the newly-revealed edge strip,
1127
+ // - non-uniform static backdrop the shift smeared (e.g. the hill image; a
1128
+ // solid water fill is horizontally lossless under a shift, so it's skipped),
1129
+ // - independently-moving sprites (player/enemies/coins), including the ghost
1130
+ // the shift left at their previous position + dx.
1131
+ // It only engages on translate-only frames; structural/record frames fall back
1132
+ // to the normal path (which is also what brings newly-recorded tiles on-screen).
1133
+
1134
+ bool panClipToViewport(int width, int height, int *x, int *y, int *w, int *h)
1135
+ {
1136
+ if (*w <= 0 || *h <= 0 || width <= 0 || height <= 0)
1137
+ return false;
1138
+ int x0 = *x;
1139
+ int y0 = *y;
1140
+ int x1 = *x + *w - 1;
1141
+ int y1 = *y + *h - 1;
1142
+ if (x0 < 0)
1143
+ x0 = 0;
1144
+ if (y0 < 0)
1145
+ y0 = 0;
1146
+ if (x1 >= width)
1147
+ x1 = width - 1;
1148
+ if (y1 >= height)
1149
+ y1 = height - 1;
1150
+ if (x0 > x1 || y0 > y1)
1151
+ return false;
1152
+ *x = x0;
1153
+ *y = y0;
1154
+ *w = x1 - x0 + 1;
1155
+ *h = y1 - y0 + 1;
1156
+ return true;
1157
+ }
1158
+
1159
+ bool panNodeHasTransform(const Node &n)
1160
+ {
1161
+ return rstyle(n.style).transform_rotate != 0 || n.render.previous_transform_rotate != 0 ||
1162
+ rstyle(n.style).transform_rotate_x != 0 || n.render.previous_transform_rotate_x != 0 ||
1163
+ rstyle(n.style).transform_rotate_y != 0 || n.render.previous_transform_rotate_y != 0 ||
1164
+ rstyle(n.style).transform_translate_x != 0 || n.render.previous_transform_translate_x != 0 ||
1165
+ rstyle(n.style).transform_translate_y != 0 || n.render.previous_transform_translate_y != 0 ||
1166
+ rstyle(n.style).transform_translate_z != 0 || n.render.previous_transform_translate_z != 0 ||
1167
+ rstyle(n.style).transform_translate_x_percent != 0 || n.render.previous_transform_translate_x_percent != 0 ||
1168
+ rstyle(n.style).transform_translate_y_percent != 0 || n.render.previous_transform_translate_y_percent != 0 ||
1169
+ rstyle(n.style).transform_scale_x != 1000 || n.render.previous_transform_scale_x != 1000 ||
1170
+ rstyle(n.style).transform_scale_y != 1000 || n.render.previous_transform_scale_y != 1000 ||
1171
+ rstyle(n.style).perspective > 0 || n.render.previous_perspective > 0;
1172
+ }
1173
+
1174
+ bool panIsDescendantOf(int node, int ancestor)
1175
+ {
1176
+ auto &state = treeState();
1177
+ for (int p = node; p >= 0 && p < state.nodeCount; p = state.nodes[p].parent)
1178
+ {
1179
+ if (p == ancestor)
1180
+ return true;
1181
+ }
1182
+ return false;
1183
+ }
1184
+
1185
+ // True when shifting this node's painted pixels horizontally is lossless (so the
1186
+ // memcpy already placed them correctly and no repaint is needed): a plain View
1187
+ // that paints nothing or a single solid background color, with no gradient/grid,
1188
+ // border, radius, shadow, blur, mask, or partial opacity. Images/text/canvas and
1189
+ // anything non-uniform return false → they get repainted after the shift.
1190
+ bool panNodeIsHorizontallyScrollSafe(const Node &n)
1191
+ {
1192
+ if (n.type != NodeType::View)
1193
+ return false;
1194
+ if (n.style.opacity != 255)
1195
+ return false;
1196
+ if (hasAnyBorder(n.style))
1197
+ return false;
1198
+ for (int r = 0; r < 4; r++)
1199
+ {
1200
+ if (n.style.border_radius[r] != 0)
1201
+ return false;
1202
+ if (n.style.border_radius_percent[r] != kUnset && n.style.border_radius_percent[r] != 0)
1203
+ return false;
1204
+ }
1205
+ if (rstyle(n.style).filter_blur_radius > 0)
1206
+ return false;
1207
+ if (n.style.mask_right_fade_width > 0)
1208
+ return false;
1209
+ if (rstyle(n.style).box_shadow_alpha > 0 &&
1210
+ (rstyle(n.style).box_shadow_offset_x != 0 || rstyle(n.style).box_shadow_offset_y != 0 ||
1211
+ rstyle(n.style).box_shadow_blur_radius != 0 || rstyle(n.style).box_shadow_spread != 0))
1212
+ return false;
1213
+ if (n.style.has_bg)
1214
+ {
1215
+ if (n.style.bg_fill == 1)
1216
+ return false; // gradient fill (linear/radial/overlay)
1217
+ if (rstyle(n.style).bg_grid_axes != 0)
1218
+ return false; // grid overlay
1219
+ }
1220
+ return true;
1221
+ }
1222
+
1223
+ // Returns whether the region survived viewport clipping and was actually
1224
+ // replayed, so the caller can report the frame as a direct retained replay.
1225
+ bool panReplayRegion(int width, int height, int rx, int ry, int rw, int rh, int origin = -1)
1226
+ {
1227
+ if (!panClipToViewport(width, height, &rx, &ry, &rw, &rh))
1228
+ return false;
1229
+ gea::platform::display::Display::resetClip();
1230
+ gea::platform::display::Display::setAlpha(255);
1231
+ DisplayList::instance().replayDirectDirtyRegion(rx, ry, rx + rw - 1, ry + rh - 1, origin);
1232
+ refreshPerfStatsMutable().treePanRepaintArea += rw * rh;
1233
+ return true;
1234
+ }
1235
+
1236
+ bool tryHorizontalPanRefresh(int root, int width, int height, bool framebufferWasDirty,
1237
+ bool displayListWasDirty, bool displayListWasStructural,
1238
+ bool displayListFullRecord)
1239
+ {
1240
+ static int panCoverageRoot = -1;
1241
+ static int panCoverageWrapper = -1;
1242
+ static int panCoverageClipParent = -1;
1243
+ static int panCoverageWrapperX = 0;
1244
+ static int panCoveragePadding = 0;
1245
+ // Serial of the display list the padded record produced. The coverage window
1246
+ // describes THAT list; any clear() elsewhere bumps the serial and invalidates it.
1247
+ static std::uint32_t panCoverageSerial = 0;
1248
+ auto resetPanCoverage = []()
1249
+ {
1250
+ panCoverageRoot = -1;
1251
+ panCoverageWrapper = -1;
1252
+ panCoverageClipParent = -1;
1253
+ panCoverageWrapperX = 0;
1254
+ panCoveragePadding = 0;
1255
+ panCoverageSerial = 0;
1256
+ };
1257
+ if (width <= 0 || height <= 0)
1258
+ {
1259
+ resetPanCoverage();
1260
+ return false;
1261
+ }
1262
+ if (gHorizontalPanFastPathDisabled)
1263
+ {
1264
+ resetPanCoverage();
1265
+ return false;
1266
+ }
1267
+ // Need a translate-only frame: the display list must reflect the new positions
1268
+ // via in-place command translation, not a structural rebuild (which can add/
1269
+ // remove content the memcpy can't account for) or an external framebuffer dirty.
1270
+ if (framebufferWasDirty || displayListWasDirty || displayListWasStructural || displayListFullRecord)
1271
+ {
1272
+ resetPanCoverage();
1273
+ return false;
1274
+ }
1275
+ if (transformedLeafDirtyShapeCount() != 0)
1276
+ {
1277
+ resetPanCoverage();
1278
+ return false;
1279
+ }
1280
+ if (DisplayList::instance().staticBackdropActive())
1281
+ {
1282
+ resetPanCoverage();
1283
+ return false;
1284
+ }
1285
+
1286
+ auto &state = treeState();
1287
+
1288
+ // 1. Find the single pan wrapper among dirty nodes.
1289
+ int wrapper = -1;
1290
+ int panDx = 0;
1291
+ for (int i = 0; i < state.nodeCount; i++)
1292
+ {
1293
+ Node *n = &state.nodes[i];
1294
+ if (!n->render.dirty)
1295
+ continue;
1296
+ if (n->style.display == kDisplayNone)
1297
+ continue;
1298
+ if (n->first_child < 0)
1299
+ continue;
1300
+ if (n->parent < 0)
1301
+ continue;
1302
+ Node *p = &state.nodes[n->parent];
1303
+ if (p->style.overflow != 1)
1304
+ continue; // parent must clip (overflow:hidden)
1305
+ const int dx = n->layout.x - n->layout.previous_x;
1306
+ const int dy = n->layout.y - n->layout.previous_y;
1307
+ if (dx == 0 || dy != 0)
1308
+ continue;
1309
+ if (n->layout.width != n->layout.previous_width)
1310
+ continue;
1311
+ if (n->layout.height != n->layout.previous_height)
1312
+ continue;
1313
+ if (n->layout.previous_width <= 0 || n->layout.previous_height <= 0)
1314
+ continue;
1315
+ if (n->style.opacity != 255)
1316
+ continue;
1317
+ if (panNodeHasTransform(*n))
1318
+ continue;
1319
+ // The clipping parent must itself be stationary so the viewport rect is fixed.
1320
+ if (p->layout.x != p->layout.previous_x || p->layout.y != p->layout.previous_y)
1321
+ continue;
1322
+ if (p->layout.width != p->layout.previous_width || p->layout.height != p->layout.previous_height)
1323
+ continue;
1324
+ if (wrapper >= 0)
1325
+ return false; // ambiguous — more than one pan candidate
1326
+ wrapper = i;
1327
+ panDx = dx;
1328
+ }
1329
+ if (wrapper < 0)
1330
+ return false;
1331
+
1332
+ const int absDx = panDx < 0 ? -panDx : panDx;
1333
+
1334
+ // 2. The clip viewport is the wrapper's overflow:hidden parent.
1335
+ Node *W = &state.nodes[wrapper];
1336
+ Node *P = &state.nodes[W->parent];
1337
+ int vx = P->layout.x, vy = P->layout.y, vw = P->layout.width, vh = P->layout.height;
1338
+ if (!panClipToViewport(width, height, &vx, &vy, &vw, &vh))
1339
+ return false;
1340
+ if (absDx >= vw)
1341
+ return false; // teleport — a full repaint is simpler and safer
1342
+
1343
+ // 3. Decide what the memcpy can't reproduce and must be repainted explicitly:
1344
+ // every wrapper descendant that did NOT translate uniformly with the camera.
1345
+ // A descendant needs repainting when it is dirty (its appearance/size/visibility
1346
+ // changed this frame — pulsing coins, the hurt blink toggling display) OR its
1347
+ // screen delta != (dx,0) (it does not move 1:1 with the world: the camera-locked
1348
+ // player, independently-walking enemies). Uniformly-shifted descendants (the
1349
+ // static level tiles) are correctly carried by the memcpy and skipped. Hidden
1350
+ // (display:none) descendants are NOT skipped here: a camera-locked sprite that
1351
+ // just blinked off still has a stale ghost the memcpy dragged along, and its
1352
+ // repaint (which now draws no commands) is what erases it. A DIRTY node OUTSIDE
1353
+ // the wrapper (a pressed control, a HUD digit) means non-world content changed
1354
+ // under/over the shift, which a world memcpy can't honour → fall back entirely.
1355
+ constexpr int kMaxPanExtras = 48;
1356
+ int extras[kMaxPanExtras];
1357
+ int extraCount = 0;
1358
+ for (int i = 0; i < state.nodeCount; i++)
1359
+ {
1360
+ if (i == wrapper)
1361
+ continue;
1362
+ Node *n = &state.nodes[i];
1363
+ if (!panIsDescendantOf(i, wrapper))
1364
+ {
1365
+ if (n->render.dirty)
1366
+ return false; // non-world content changed — handled only by full replay
1367
+ continue; // static non-world content → step 5
1368
+ }
1369
+ const bool uniformShift = (n->layout.x - n->layout.previous_x == panDx) &&
1370
+ (n->layout.y - n->layout.previous_y == 0);
1371
+ if (!n->render.dirty && uniformShift)
1372
+ continue; // carried correctly by the memcpy
1373
+ if (extraCount >= kMaxPanExtras)
1374
+ return false;
1375
+ extras[extraCount++] = i;
1376
+ }
1377
+
1378
+ // Every reason to decline this frame has now been checked, so it is finally
1379
+ // safe to touch the retained display list. Nothing above this line may mutate
1380
+ // it: `refresh()` has already done its own display-list maintenance for this
1381
+ // frame (in-place command translation / rerecordNodeCommands) and recorded the
1382
+ // resulting per-node command bounds in state.nodeCommandDirty*, and it uses
1383
+ // those bounds to build the dirty rects it replays if this function declines.
1384
+ // Rebuilding the list and THEN declining swaps the commands out from under
1385
+ // those bounds, so the fallback replays rects that no longer describe what
1386
+ // changed and leaves dx-wide slivers of the previous frame unrepainted.
1387
+ //
1388
+ // The retained display list is clipped at record time, so commands for
1389
+ // off-viewport tiles do not exist until they scroll into view. Record a
1390
+ // padded child clip for the pan viewport, then reuse that covered command
1391
+ // window across frames until camera motion exhausts the padding.
1392
+ constexpr int kPanRecordPadding = 512;
1393
+ const bool coverageValid =
1394
+ panCoverageRoot == root &&
1395
+ panCoverageWrapper == wrapper &&
1396
+ panCoverageClipParent == W->parent &&
1397
+ panCoveragePadding == kPanRecordPadding &&
1398
+ // The coverage window describes the list this function recorded. Any clear()
1399
+ // elsewhere (refresh()'s full record, root_scroll_refresh) bumps the record
1400
+ // serial and leaves a normally-clipped list behind, so the padded-window
1401
+ // claim above would be false. Completes the identity check; it does not
1402
+ // change this app's frames, which never hit that interleaving.
1403
+ panCoverageSerial == DisplayList::instance().recordSerial() &&
1404
+ ((W->layout.x - panCoverageWrapperX) < 0
1405
+ ? -(W->layout.x - panCoverageWrapperX)
1406
+ : (W->layout.x - panCoverageWrapperX)) + absDx < kPanRecordPadding;
1407
+ if (!coverageValid)
1408
+ {
1409
+ const std::int64_t rebuildStartUs = refreshPerfNowUs();
1410
+ DisplayList::instance().clear();
1411
+ DisplayList::instance().recordNodeWithExpandedClip(
1412
+ root,
1413
+ 255,
1414
+ W->parent,
1415
+ vx - kPanRecordPadding,
1416
+ vy,
1417
+ vx + vw - 1 + kPanRecordPadding,
1418
+ vy + vh - 1);
1419
+ DisplayList::instance().weldTransformedFaces();
1420
+ state.displayListDirty = false;
1421
+ panCoverageRoot = root;
1422
+ panCoverageWrapper = wrapper;
1423
+ panCoverageClipParent = W->parent;
1424
+ panCoverageWrapperX = W->layout.x;
1425
+ panCoveragePadding = kPanRecordPadding;
1426
+ panCoverageSerial = DisplayList::instance().recordSerial();
1427
+ refreshPerfStatsMutable().treeRecordNodeUs += refreshPerfNowUs() - rebuildStartUs;
1428
+ }
1429
+
1430
+ // ---- Commit: shift the framebuffer and repaint only what the shift can't. ----
1431
+ gea::platform::display::Display::resetClip();
1432
+ gea::platform::display::Display::setAlpha(255);
1433
+ gea::platform::display::Display::scrollRect(vx, vy, vw, vh, panDx, 0);
1434
+
1435
+ // Regions this frame served by replaying the retained display list straight
1436
+ // into a scoped rect — the same replayDirectDirtyRegion the non-pan path
1437
+ // counts as a direct replay. Reported below so a pan frame is not
1438
+ // indistinguishable from a conservative full repaint in the stats.
1439
+ int directRegions = 0;
1440
+
1441
+ // 4. Newly-revealed edge strip.
1442
+ if (panDx < 0)
1443
+ directRegions += panReplayRegion(width, height, vx + vw - absDx, vy, absDx, vh, wrapper) ? 1 : 0;
1444
+ else
1445
+ directRegions += panReplayRegion(width, height, vx, vy, absDx, vh, wrapper) ? 1 : 0;
1446
+
1447
+ // 5. Non-uniform static content the shift corrupted: the hill image, but also any
1448
+ // fixed UI that overlaps the scrolled viewport (the controls, RESET button —
1449
+ // siblings drawn over the world). The memcpy moved their pixels by dx, so the
1450
+ // element's true position now shows shifted neighbours AND a ghost sits at
1451
+ // bounds+dx. Repaint the union of both so the ghost is erased and the element is
1452
+ // redrawn at its fixed position. Solid fills (the water) are horizontally
1453
+ // lossless under a shift and stay correct from the memcpy alone.
1454
+ for (int i = 0; i < state.nodeCount; i++)
1455
+ {
1456
+ Node *n = &state.nodes[i];
1457
+ if (n->style.display == kDisplayNone)
1458
+ continue;
1459
+ if (i == wrapper || panIsDescendantOf(i, wrapper))
1460
+ continue;
1461
+ if (n->render.dirty)
1462
+ continue;
1463
+ if (panNodeIsHorizontallyScrollSafe(*n))
1464
+ continue;
1465
+ const DirtyRegions::Rect b = transformedBoundsRect(*n, false, i);
1466
+ if (b.x0 > b.x1 || b.y0 > b.y1)
1467
+ continue;
1468
+ int ux0 = b.x0 < b.x0 + panDx ? b.x0 : b.x0 + panDx;
1469
+ int ux1 = b.x1 > b.x1 + panDx ? b.x1 : b.x1 + panDx;
1470
+ // Clip to the scrolled viewport — only that region was corrupted by the shift.
1471
+ if (ux0 < vx)
1472
+ ux0 = vx;
1473
+ if (ux1 > vx + vw - 1)
1474
+ ux1 = vx + vw - 1;
1475
+ int uy0 = b.y0 < vy ? vy : b.y0;
1476
+ int uy1 = b.y1 > vy + vh - 1 ? vy + vh - 1 : b.y1;
1477
+ if (ux0 > ux1 || uy0 > uy1)
1478
+ continue;
1479
+ directRegions += panReplayRegion(width, height, ux0, uy0, ux1 - ux0 + 1, uy1 - uy0 + 1, i) ? 1 : 0;
1480
+ }
1481
+
1482
+ // 6. Independently-moving sprites: redraw the union of the new bounds and the
1483
+ // ghost (previous bounds shifted by the pan) so the smeared old copy is erased.
1484
+ for (int e = 0; e < extraCount; e++)
1485
+ {
1486
+ const int id = extras[e];
1487
+ Node *n = &state.nodes[id];
1488
+ const DirtyRegions::Rect cur = transformedSubtreeBoundsRect(id, false, id);
1489
+ int x0 = cur.x0, y0 = cur.y0, x1 = cur.x1, y1 = cur.y1;
1490
+ if (n->layout.previous_width > 0 && n->layout.previous_height > 0)
1491
+ {
1492
+ const DirtyRegions::Rect prev = transformedSubtreeBoundsRect(id, true, id);
1493
+ const int gx0 = prev.x0 + panDx, gx1 = prev.x1 + panDx;
1494
+ if (gx0 < x0)
1495
+ x0 = gx0;
1496
+ if (prev.y0 < y0)
1497
+ y0 = prev.y0;
1498
+ if (gx1 > x1)
1499
+ x1 = gx1;
1500
+ if (prev.y1 > y1)
1501
+ y1 = prev.y1;
1502
+ }
1503
+ if (x0 > x1 || y0 > y1)
1504
+ continue;
1505
+ directRegions += panReplayRegion(width, height, x0, y0, x1 - x0 + 1, y1 - y0 + 1, id) ? 1 : 0;
1506
+ }
1507
+
1508
+ gea::platform::display::Display::resetClip();
1509
+ gea::platform::display::Display::setAlpha(255);
1510
+ gea::platform::display::Display::flush();
1511
+
1512
+ // Keep the static-backdrop cache reset while panning, then mirror refresh()'s tail.
1513
+ DisplayList::instance().maybeBakeStaticBackdrop(width, height, false, false);
1514
+ LayoutSnapshot::capture();
1515
+ state.canvases.forEach([](CanvasSurfaceState &surface)
1516
+ {
1517
+ if (auto *canvas = surface.canvas()) canvas->resetDirty(); });
1518
+ refreshPerfStatsMutable().treePanReplayCalls++;
1519
+ if (directRegions > 0)
1520
+ refreshPerfStatsMutable().treeDirectReplayCalls++;
1521
+ return true;
1522
+ }
1523
+
1524
+ } // namespace
1525
+
1526
+ // Render the CURRENT retained display list full-screen into `dst` (rgb565) for a
1527
+ // screenshot. The fused flush (FUSE_REPLAY_FLUSH) rasterizes into the DMA staging
1528
+ // buffer and never writes the PSRAM framebuffer, so Display::copySnapshotRgb565 returns
1529
+ // the first-ever rendered frame for a fused retained app (a frozen "frame 0"). Replaying
1530
+ // the live display list into the snapshot buffer here yields the real on-screen frame.
1531
+ // The caller must hold AppState::lock() so the frame task isn't using the shared canvas
1532
+ // or mutating the list. Returns false for non-retained (canvas/present) apps, whose
1533
+ // pixels aren't in the retained command list — the caller falls back to the present path.
1534
+ bool renderRetainedSnapshotRgb565(std::uint16_t *dst, int width, int height)
1535
+ {
1536
+ if (!dst || width <= 0 || height <= 0)
1537
+ return false;
1538
+ if (DisplayList::instance().commandCount() < 2)
1539
+ return false; // canvas/present app: nothing retained to replay
1540
+ auto *canvas = gea::platform::display::Display::canvas();
1541
+ if (!canvas)
1542
+ return false;
1543
+ using PixT = gea::framework::graphics::pixel::native_t;
1544
+ PixT *base = reinterpret_cast<PixT *>(dst);
1545
+ canvas->bindPixels(base, width, height, width);
1546
+ gea::platform::display::Display::resetClip();
1547
+ gea::platform::display::Display::setAlpha(255);
1548
+ gea::platform::display::Display::pushClip(0, 0, width, height);
1549
+ // The direct-region replay applies each node's ancestor overflow clips
1550
+ // (pushNodeReplayClips); the simple clipped walk used before SKIPS
1551
+ // PushClip/PopClip and is only valid when canReplaySimpleDirtyRegions
1552
+ // holds — which the scroll fast path's padded coverage record breaks
1553
+ // (rows recorded beyond the scroll viewport printed above it in every
1554
+ // snapshot, reading as a phantom on-screen ghost during debugging).
1555
+ {
1556
+ const DisplayReplayRegion region{0, 0, width - 1, height - 1, -1};
1557
+ DisplayList::instance().replayDirectDirtyRegions(&region, 1);
1558
+ }
1559
+ gea::platform::display::Display::popClip();
1560
+ // Restore the shared canvas onto the real framebuffer before the frame task resumes.
1561
+ gea::platform::display::Display::rebindCanvasToFramebuffer();
1562
+ const int pixels = width * height;
1563
+ for (int i = 0; i < pixels; i++)
1564
+ dst[i] = gea::framework::graphics::pixel::toRgb565(base[i]);
1565
+ return true;
1566
+ }
1567
+
1568
+ namespace
1569
+ {
1570
+ // The (root, box) the last layout in this tree was performed for.
1571
+ //
1572
+ // `computeLayout` needs it because the dirty flags alone cannot answer
1573
+ // its question -- see the comment there. Recorded rather than derived
1574
+ // from the root's own box, because a root that sizes to its content
1575
+ // never equals the box it was offered, and treating that as "not laid
1576
+ // out" would take the local-refresh fast path away from every such tree.
1577
+ //
1578
+ // -1 is not a node, so a fresh process starts out having been laid out
1579
+ // for nothing, which is the safe direction: the first call does the full
1580
+ // pass. An app switch needs no reset for the same reason from the other
1581
+ // end -- `Tree::clear` sets `nodeCount` to 0, so every call in the gap
1582
+ // before the next `mount` leaves at the root-range check above, and
1583
+ // `mount` always lays out and re-records.
1584
+ int gLayoutViewportRoot = -1;
1585
+ int gLayoutViewportWidth = -1;
1586
+ int gLayoutViewportHeight = -1;
1587
+
1588
+ void noteLaidOutViewport(int root, int width, int height)
1589
+ {
1590
+ gLayoutViewportRoot = root;
1591
+ gLayoutViewportWidth = width;
1592
+ gLayoutViewportHeight = height;
1593
+ }
1594
+ } // namespace
1595
+
1596
+ void Tree::mount(int root, int width, int height)
1597
+ {
1598
+ auto &state = treeState();
1599
+ if (root < 0 || root >= state.nodeCount)
1600
+ return;
1601
+ state.refreshSerial++;
1602
+
1603
+ state.mountedRoot = root;
1604
+ state.mountedWidth = width;
1605
+ state.mountedHeight = height;
1606
+
1607
+ // While the initial style batch is open, per-node class styles haven't been
1608
+ // applied yet, so laying out now produces UNSTYLED, content-sized boxes. That
1609
+ // garbage layout is not just unpresentable — it POISONS percent resolution:
1610
+ // `percentBasisForNode` prefers a parent's `layout.height` when it's > 0, so
1611
+ // endStyleMountBatch would resolve e.g. `max-height: 100%` against the stale
1612
+ // content height instead of the declared style chain (observed: a square board
1613
+ // clamped to its content height, collapsing flex children). Skip layout/paint
1614
+ // entirely here — the guaranteed styled re-mount after endStyleMountBatch (see
1615
+ // gea_app_entry.cpp Application::init) does the real, correct layout and present.
1616
+ if (styleMountBatchActive())
1617
+ return;
1618
+
1619
+ gea::platform::display::Display::clearNoFlush();
1620
+ gea::platform::display::Display::resetClip();
1621
+ gea::platform::display::Display::setAlpha(255);
1622
+
1623
+ LayoutEngine::instance().beginLayoutPass();
1624
+ LayoutEngine::instance().layoutNode(root, width, height);
1625
+ applyPendingScrollIntoView();
1626
+ LayoutEngine::instance().resolveAbsoluteCoords(root, 0, 0);
1627
+ noteLaidOutViewport(root, width, height);
1628
+ state.refreshSerial++;
1629
+ if (state.refreshSerial == 0)
1630
+ state.refreshSerial = 1;
1631
+ LayoutSnapshot::markChangesDirty();
1632
+
1633
+ DisplayList::instance().clear();
1634
+ DisplayList::instance().recordNode(root, 255);
1635
+ DisplayList::instance().weldTransformedFaces();
1636
+ DisplayList::instance().replay();
1637
+ state.displayListDirty = false;
1638
+ state.displayListRebuildStructural = false; // this path already repainted everything
1639
+
1640
+ // Don't present the very first mount while the initial style batch is still
1641
+ // open: per-node class styles haven't been applied yet, so this frame is
1642
+ // unstyled (block layout at the origin, no colors). endStyleMountBatch()
1643
+ // applies styles and the follow-up styled mount/refresh presents instead —
1644
+ // avoiding a flash of unstyled content (text + images, no CSS) at boot.
1645
+ if (!styleMountBatchActive())
1646
+ gea::platform::display::Display::flush();
1647
+ state.canvases.forEach([](CanvasSurfaceState &surface)
1648
+ {
1649
+ if (auto *canvas = surface.canvas()) canvas->resetDirty(); });
1650
+ LayoutSnapshot::capture();
1651
+ }
1652
+
1653
+ void Tree::computeLayout(int root, int width, int height)
1654
+ {
1655
+ auto &state = treeState();
1656
+ if (root < 0 || root >= state.nodeCount)
1657
+ return;
1658
+ // Whether the tree was last laid out for THIS viewport. Both cheap paths
1659
+ // below are keyed on the dirty flags, which answer "has the tree
1660
+ // changed" -- and that is only half of this entry point's question. A
1661
+ // caller also supplies a root and a box, and the flags say nothing about
1662
+ // whether the geometry in the tree was computed for them.
1663
+ //
1664
+ // They come apart whenever something else consumes the dirty flags
1665
+ // first, for a DIFFERENT viewport. `Document::refreshMountedIfDirty`
1666
+ // does exactly that, at the MOUNTED size, and both callers of this
1667
+ // function are native shells that run after it with a PANE root and size
1668
+ // (`macos_native_shell.mm` sets the pane node's width/height and calls
1669
+ // this; the test harness's `refresh()` then `computeLayout` is the same
1670
+ // order). Every reactive tree mutation therefore ended with the pane
1671
+ // holding the mounted viewport's geometry and this call returning
1672
+ // without touching it -- measured on gea-companion, whose detail pane
1673
+ // came back 632x261 from a `computeLayout(node, 632, 548)`, shrinking a
1674
+ // page that fits into one that does not until its rows overlapped.
1675
+ //
1676
+ // Asked as "was the last layout for this request" rather than "does the
1677
+ // root's box equal the one asked for", because those are not the same
1678
+ // question: a root that legitimately sizes to its own content never
1679
+ // equals the available box, and reading it that way takes the local
1680
+ // refresh path away from every such tree permanently (measured:
1681
+ // `run-gea-style-viewport-metrics` and
1682
+ // `run-gea-temperature-dial-local-refresh` both broke on it).
1683
+ const bool laidOutForRequest = gLayoutViewportRoot == root && gLayoutViewportWidth == width && gLayoutViewportHeight == height;
1684
+ int layout_mode = AbsoluteLeafRefresh::mode();
1685
+ if (layout_mode < 0 && laidOutForRequest)
1686
+ return;
1687
+ if (layout_mode > 0 && laidOutForRequest)
1688
+ {
1689
+ AbsoluteLeafRefresh::refreshPositions();
1690
+ }
1691
+ else
1692
+ {
1693
+ PreservedScrollOffset scrollOffsets[kMaxNodes];
1694
+ preserveScrollOffsets(scrollOffsets, kMaxNodes);
1695
+ LayoutEngine::instance().beginLayoutPass();
1696
+ LayoutEngine::instance().layoutNode(root, width, height);
1697
+ restoreScrollOffsetsAfterLayout(scrollOffsets, kMaxNodes);
1698
+ applyPendingScrollIntoView();
1699
+ LayoutEngine::instance().resolveAbsoluteCoords(root, 0, 0);
1700
+ noteLaidOutViewport(root, width, height);
1701
+ }
1702
+ state.refreshSerial++;
1703
+ if (state.refreshSerial == 0)
1704
+ state.refreshSerial = 1;
1705
+ }
1706
+
1707
+ namespace
1708
+ {
1709
+ // Scoped-relayout root for the current dirty set: the lowest ancestor
1710
+ // containing every dirty node whose own box was stable last frame — its
1711
+ // subtree can be re-laid in isolation (LayoutEngine::layoutNodeScoped)
1712
+ // instead of relayouting the whole tree. Returns -1 when no such node
1713
+ // exists below the root (full relayout).
1714
+ // A parent walk that cannot outlive the tree.
1715
+ //
1716
+ // `parent` chains are supposed to end at -1, and every walk here trusted
1717
+ // that. A tree whose parent links form a CYCLE turns each of those walks
1718
+ // into an infinite loop inside the frame -- not a crash, not a wrong
1719
+ // picture, a board that stops: the e-reader wedged for 74 seconds in
1720
+ // `Document::refreshMountedIfDirty` with the panel idle and nothing
1721
+ // queued, until the task watchdog fired. A walk bounded by the node count
1722
+ // cannot do that, and no honest chain is longer than the tree is deep, so
1723
+ // the bound costs a correct walk nothing.
1724
+ //
1725
+ // Tripping it is a DEFECT upstream -- something published a cycle -- so it
1726
+ // says so once rather than failing silently, and answers the way the
1727
+ // caller's own "no scope found" answer already means: relayout whole.
1728
+ bool walkParents(TreeState &state, int from, int &steps)
1729
+ {
1730
+ steps++;
1731
+ if (steps <= state.nodeCount + 1)
1732
+ return true;
1733
+ // Repeat rather than latch: the walk is re-entered every frame, and a
1734
+ // one-shot report is gone before a serial reader can be attached.
1735
+ static unsigned hits = 0;
1736
+ if ((hits++ & 0xffu) == 0)
1737
+ std::printf("[tree] parent chain from node=%d parent=%d exceeds nodeCount=%d -- cycle in the tree\n", from,
1738
+ from >= 0 && from < state.nodeCount ? state.nodes[from].parent : -2, state.nodeCount);
1739
+ return false;
1740
+ }
1741
+
1742
+ int scopedRelayoutRoot(TreeState &state, int root)
1743
+ {
1744
+ auto isAncestorOrSelf = [&](int node, int ancestor) {
1745
+ int steps = 0;
1746
+ for (int c = node; c >= 0 && c < state.nodeCount; c = state.nodes[c].parent) {
1747
+ if (c == ancestor)
1748
+ return true;
1749
+ if (!walkParents(state, node, steps))
1750
+ return false;
1751
+ }
1752
+ return false;
1753
+ };
1754
+ int lca = -1;
1755
+ for (int i = 0; i < state.nodeCount; i++)
1756
+ {
1757
+ // Only geometry-relevant dirt widens the relayout scope; paint-only
1758
+ // dirt (layout_dirty clear) repaints in place via the record path.
1759
+ if (!state.nodes[i].render.dirty || !state.nodes[i].render.layout_dirty)
1760
+ continue;
1761
+ if (lca < 0)
1762
+ {
1763
+ lca = i;
1764
+ continue;
1765
+ }
1766
+ int steps = 0;
1767
+ while (lca >= 0 && !isAncestorOrSelf(i, lca))
1768
+ {
1769
+ if (!walkParents(state, lca, steps))
1770
+ return -1;
1771
+ lca = state.nodes[lca].parent;
1772
+ }
1773
+ if (lca < 0)
1774
+ return -1;
1775
+ }
1776
+ if (lca < 0)
1777
+ return -1;
1778
+ // A dirty node's own box may change; the scope must be a stable strict
1779
+ // ancestor.
1780
+ return state.nodes[lca].render.dirty ? state.nodes[lca].parent : lca;
1781
+ }
1782
+
1783
+ // First ancestor-or-self of `from` (strictly below root) whose box was
1784
+ // stable last frame — a scoped-relayout candidate. Stability is only a
1785
+ // heuristic (an auto-sized box still resizes with new content):
1786
+ // layoutNodeScoped's post-layout dims check rejects those and the
1787
+ // caller retries from the candidate's parent.
1788
+ int stableScopeAt(TreeState &state, int from, int root)
1789
+ {
1790
+ int steps = 0;
1791
+ for (int scope = from; scope >= 0 && scope != root; scope = state.nodes[scope].parent)
1792
+ {
1793
+ if (!walkParents(state, from, steps))
1794
+ return -1;
1795
+ Node &a = state.nodes[scope];
1796
+ const bool dimsStable = a.layout.width == a.layout.previous_width &&
1797
+ a.layout.height == a.layout.previous_height &&
1798
+ a.layout.width > 0 && a.layout.height > 0;
1799
+ if (dimsStable && a.style.display != kDisplayNone)
1800
+ return scope;
1801
+ }
1802
+ return -1;
1803
+ }
1804
+ } // namespace
1805
+
1806
+ void Tree::refresh(int root, int width, int height)
1807
+ {
1808
+ auto &state = treeState();
1809
+ if (root < 0 || root >= state.nodeCount)
1810
+ return;
1811
+ // Bump before the scroll-only fast path returns: a scroll-only refresh still
1812
+ // moves content, so native renderers must re-sync.
1813
+ state.refreshSerial++;
1814
+ auto &perf = refreshPerfStatsMutable();
1815
+ perf.treeRefreshCalls++;
1816
+ DisplayList::instance().clearRetainedBackgroundRecolors();
1817
+
1818
+ if (state.pendingScrollIntoViewNode < 0 && RootScrollOnlyRefresh::refresh(root, width, height))
1819
+ return;
1820
+
1821
+ // This frame is NOT a pure scroll, so the software scroll register's
1822
+ // circular row rotation (engaged by Display::scrollRect during the fast
1823
+ // path above) must not survive into it: content drawn now would mix
1824
+ // rotated and unrotated rows (observed: a stale header band + the whole
1825
+ // screen duplicated ~70px lower after the weather keyboard raised, and
1826
+ // the previous screen's rows surfacing through later repaints). Reset
1827
+ // the region to identity and dirty its rows so this refresh repaints
1828
+ // them in their unrotated placement.
1829
+ #if !defined(GEA_EMBEDDED_DIRECT_CANVAS_CONTEXT) || !GEA_EMBEDDED_DIRECT_CANVAS_CONTEXT
1830
+ if (!Document::directCanvasContextUsed()) {
1831
+ if (auto *rotCanvas = gea::platform::display::Display::canvas()) {
1832
+ const int regionH = rotCanvas->scrollRegionH();
1833
+ if (regionH > 0) {
1834
+ const int regionY = rotCanvas->scrollRegionY();
1835
+ gea::platform::display::Display::resetScrollRegion();
1836
+ rotCanvas->markDirty(0, regionY, width - 1, regionY + regionH - 1);
1837
+ state.displayListDirty = true;
1838
+ }
1839
+ }
1840
+ }
1841
+ #endif
1842
+
1843
+ const std::int64_t layoutModeStartUs = refreshPerfNowUs();
1844
+ int framebufferDirtyX0 = 0;
1845
+ int framebufferDirtyY0 = 0;
1846
+ int framebufferDirtyX1 = -1;
1847
+ int framebufferDirtyY1 = -1;
1848
+ #if !defined(GEA_EMBEDDED_DIRECT_CANVAS_CONTEXT) || !GEA_EMBEDDED_DIRECT_CANVAS_CONTEXT
1849
+ auto *displayCanvas = Document::directCanvasContextUsed() ? nullptr : gea::platform::display::Display::canvas();
1850
+ const bool framebuffer_was_dirty = displayCanvas &&
1851
+ displayCanvas->dirty(&framebufferDirtyX0,
1852
+ &framebufferDirtyY0,
1853
+ &framebufferDirtyX1,
1854
+ &framebufferDirtyY1);
1855
+ #else
1856
+ const bool framebuffer_was_dirty = false;
1857
+ #endif
1858
+ int layout_mode = AbsoluteLeafRefresh::mode();
1859
+ perf.treeLayoutModeUs += refreshPerfNowUs() - layoutModeStartUs;
1860
+ if (layout_mode < 0)
1861
+ {
1862
+ if (!framebuffer_was_dirty && !state.displayListDirty && state.pendingScrollIntoViewNode < 0)
1863
+ return;
1864
+ layout_mode = state.displayListDirty ? 0 : 1;
1865
+ }
1866
+ if (state.pendingScrollIntoViewNode >= 0)
1867
+ layout_mode = 0;
1868
+
1869
+ const std::int64_t layoutStartUs = refreshPerfNowUs();
1870
+ if (layout_mode > 0)
1871
+ {
1872
+ AbsoluteLeafRefresh::refreshPositions();
1873
+ }
1874
+ else
1875
+ {
1876
+ PreservedScrollOffset scrollOffsets[kMaxNodes];
1877
+ preserveScrollOffsets(scrollOffsets, kMaxNodes);
1878
+ // Scoped relayout: when every dirty node sits under a box-stable
1879
+ // ancestor (e.g. a city-name text growing inside a fixed-size header),
1880
+ // re-lay only that subtree — the memoized available box makes the
1881
+ // scoped pass reproducible, and layoutNodeScoped falls back (returns
1882
+ // false) if the scope's own dims end up changing after all.
1883
+ bool scoped = false;
1884
+ // Paint-only frame: no node carries geometry-relevant dirt and nothing
1885
+ // structural is pending — skip the relayout entirely; the record/replay
1886
+ // flow below repaints the dirty nodes in place.
1887
+ bool anyLayoutDirty = state.displayListRebuildStructural ||
1888
+ state.pendingScrollIntoViewNode >= 0;
1889
+ if (!anyLayoutDirty)
1890
+ {
1891
+ for (int i = 0; i < state.nodeCount; i++)
1892
+ {
1893
+ if (state.nodes[i].render.dirty && state.nodes[i].render.layout_dirty)
1894
+ {
1895
+ anyLayoutDirty = true;
1896
+ break;
1897
+ }
1898
+ }
1899
+ }
1900
+ if (anyLayoutDirty)
1901
+ {
1902
+ if (state.pendingScrollIntoViewNode < 0)
1903
+ {
1904
+ int scope = scopedRelayoutRoot(state, root);
1905
+ if (scope >= 0)
1906
+ scope = stableScopeAt(state, scope, root);
1907
+ if (scope < 0)
1908
+ perf.treeScopedRejectReason = 1;
1909
+ for (int attempt = 0; scope >= 0 && attempt < 2; attempt++)
1910
+ {
1911
+ scoped = LayoutEngine::instance().layoutNodeScoped(scope, root);
1912
+ if (scoped)
1913
+ {
1914
+ perf.treeScopedLayouts++;
1915
+ break;
1916
+ }
1917
+ // Most rejects mean the scope autosized to the new content —
1918
+ // retry from the next stable ancestor up (each failed attempt's
1919
+ // partial layout is fully redone by the retry / full fallback).
1920
+ scope = stableScopeAt(state, state.nodes[scope].parent, root);
1921
+ }
1922
+ }
1923
+ if (!scoped)
1924
+ {
1925
+ LayoutEngine::instance().beginLayoutPass();
1926
+ LayoutEngine::instance().layoutNode(root, width, height);
1927
+ }
1928
+ restoreScrollOffsetsAfterLayout(scrollOffsets, kMaxNodes);
1929
+ applyPendingScrollIntoView();
1930
+ if (!scoped)
1931
+ LayoutEngine::instance().resolveAbsoluteCoords(root, 0, 0);
1932
+ noteLaidOutViewport(root, width, height);
1933
+ // Reflow ghost guard: a full relayout can MOVE nodes that carry no dirty
1934
+ // mark of their own — flex siblings shifted because a text node's box grew
1935
+ // (a city-rail chip going '--' → '20°' pushes its neighbors right). The
1936
+ // dirty pass below only visits render.dirty nodes, so an unmarked moved
1937
+ // node neither repaints its vacated box nor translates its retained
1938
+ // display commands: its old glyphs ghost at the previous position. Mark
1939
+ // every node whose box changed beyond what its ancestors' scroll deltas
1940
+ // explain (pure scroll frames stay unmarked, so scroll perf is untouched).
1941
+ for (int i = 0; i < state.nodeCount; i++)
1942
+ {
1943
+ Node &n = state.nodes[i];
1944
+ if (n.render.dirty)
1945
+ continue;
1946
+ if (n.parent < 0 && i != root)
1947
+ continue;
1948
+ if (n.style.display == kDisplayNone)
1949
+ continue;
1950
+ if (n.layout.previous_width <= 0 && n.layout.previous_height <= 0 &&
1951
+ n.layout.width <= 0 && n.layout.height <= 0)
1952
+ continue;
1953
+ if (n.layout.width == n.layout.previous_width && n.layout.height == n.layout.previous_height)
1954
+ {
1955
+ const int dx = n.layout.x - n.layout.previous_x;
1956
+ const int dy = n.layout.y - n.layout.previous_y;
1957
+ if (dx == 0 && dy == 0)
1958
+ continue;
1959
+ int scrollDx = 0;
1960
+ int scrollDy = 0;
1961
+ for (int a = n.parent; a >= 0 && a < state.nodeCount; a = state.nodes[a].parent)
1962
+ {
1963
+ scrollDx -= state.nodes[a].layout.scroll_x - state.nodes[a].layout.previous_scroll_x;
1964
+ scrollDy -= state.nodes[a].layout.scroll_y - state.nodes[a].layout.previous_scroll_y;
1965
+ }
1966
+ if (dx == scrollDx && dy == scrollDy)
1967
+ continue;
1968
+ }
1969
+ n.render.dirty = 1;
1970
+ n.render.layout_dirty = 1;
1971
+ n.render.non_scroll_dirty = 1;
1972
+ }
1973
+ } // anyLayoutDirty
1974
+ }
1975
+ // Transform geometry caches can be touched before layout settles during a
1976
+ // refresh; once absolute coords are final, invalidate that pre-layout basis.
1977
+ state.refreshSerial++;
1978
+ if (state.refreshSerial == 0)
1979
+ state.refreshSerial = 1;
1980
+ perf.treeLayoutUs += refreshPerfNowUs() - layoutStartUs;
1981
+
1982
+ const std::int64_t displayListStartUs = refreshPerfNowUs();
1983
+ const bool display_list_was_dirty = state.displayListDirty;
1984
+ // Consume the structural flag for this frame's rebuild decision. A
1985
+ // content-only rebuild (appearance change on existing nodes — partial
1986
+ // opacity, absolute-leaf resize) needs no full-viewport repaint; the
1987
+ // per-node dirty rects below cover everything that changed. Reset now; the
1988
+ // next frame's mutations re-raise it via markDisplayListDirty().
1989
+ const bool display_list_was_structural = state.displayListRebuildStructural;
1990
+ state.displayListRebuildStructural = false;
1991
+ // Record side: keep the display list and re-record ONLY dirty nodes whenever
1992
+ // there's no structural change. This is INDEPENDENT of
1993
+ // canReplayDirectDirtyRegions — that guard only restricts the incremental
1994
+ // dirty-region REPLAY (which can't reproduce a partial-opacity stack), NOT
1995
+ // whether we can avoid re-recording unchanged nodes. Decoupling the two keeps
1996
+ // partial-opacity/size animations and content-only relayouts off the full-
1997
+ // rebuild path.
1998
+ const bool keep_display_list = !state.displayListDirty;
1999
+ // Replay side additionally needs the compositing guard. When it bails (any
2000
+ // partial opacity), the list is still kept incrementally above and replayed
2001
+ // via the safe full-per-rect path below.
2002
+ int direct_replay = keep_display_list &&
2003
+ DisplayList::instance().canReplayDirectDirtyRegions(width, height);
2004
+ #if GEA_EMBEDDED_SIMPLE_REPLAY_DEBUG
2005
+ {
2006
+ // Log only the COPY frames (the ones that fell off the fused path) — those are
2007
+ // the drops. Throttled so a steady copy stream doesn't itself perturb timing.
2008
+ static int g = 0;
2009
+ if (!direct_replay && (g++ % 8) == 0)
2010
+ std::printf("[gate-COPY] dlDirty=%d structural=%d keep=%d simpleOK=%d\n",
2011
+ (int)state.displayListDirty, (int)state.displayListRebuildStructural,
2012
+ (int)keep_display_list,
2013
+ (int)DisplayList::instance().canReplaySimpleDirtyRegions(width, height));
2014
+ }
2015
+ #endif
2016
+ BackdropSettle backdropSettle = staticBackdropFrameSettle();
2017
+ #ifndef ESP_PLATFORM
2018
+ // A/B kill switch for the quiet-keeps-cache behavior (host debugging only).
2019
+ {
2020
+ static const bool legacyDrop = std::getenv("GEA_BACKDROP_LEGACY_DROP") != nullptr;
2021
+ if (legacyDrop && backdropSettle == BackdropSettle::kQuiet)
2022
+ backdropSettle = BackdropSettle::kFailed;
2023
+ }
2024
+ #endif
2025
+ // Eligible = a dynamic root is actively moving (settle/bake/reproject shape).
2026
+ const bool staticBackdropEligible =
2027
+ direct_replay != 0 && backdropSettle == BackdropSettle::kDynamic;
2028
+ // Stable = nothing happened that could stale the baked pixels. Quiet frames
2029
+ // (keyframe pauses, ticker-only frames) are stable: keep a live cache across
2030
+ // them instead of forcing the drop → re-bake → full-sync cycle on resume.
2031
+ const bool staticBackdropStable =
2032
+ direct_replay != 0 && backdropSettle != BackdropSettle::kFailed;
2033
+ #ifndef ESP_PLATFORM
2034
+ {
2035
+ static const bool debugBackdrop = std::getenv("GEA_DEBUG_BACKDROP") != nullptr;
2036
+ if (debugBackdrop)
2037
+ std::printf("[gate] dlDirty=%d keep=%d directReplay=%d settle=%s backdropActive=%d\n",
2038
+ display_list_was_dirty ? 1 : 0, keep_display_list ? 1 : 0, direct_replay,
2039
+ backdropSettle == BackdropSettle::kDynamic ? "dynamic"
2040
+ : backdropSettle == BackdropSettle::kQuiet ? "quiet"
2041
+ : "FAILED",
2042
+ DisplayList::instance().staticBackdropActive() ? 1 : 0);
2043
+ }
2044
+ #endif
2045
+ if (!staticBackdropStable && DisplayList::instance().staticBackdropActive())
2046
+ {
2047
+ // Dropping a live backdrop cache forces a re-bake + full-viewport sync later —
2048
+ // the expensive event behind animation-wrap fps dips. Log why it failed.
2049
+ std::printf("[bdrop] drop directReplay=%d — settle reasons:\n", direct_replay);
2050
+ if (direct_replay != 0)
2051
+ staticBackdropFrameSettle(/*debugPrint=*/true);
2052
+ DisplayList::instance().invalidateStaticBackdrop();
2053
+ }
2054
+ // Set when this frame took the transform-only reproject fast path — lets the
2055
+ // dirty pass reuse the reproject's (prev ∪ cur) bbox instead of re-projecting.
2056
+ bool reprojected = false;
2057
+ // Set when the display list was (re)built by a full clear()+recordNode() rather
2058
+ // than kept via in-place command translation — the horizontal-pan fast path only
2059
+ // engages on pure translate frames (see tryHorizontalPanRefresh).
2060
+ bool displayListFullRecord = false;
2061
+ if (keep_display_list)
2062
+ {
2063
+ int can_keep_display_list = 1;
2064
+ int rebuild_for_transform = 0;
2065
+ // Content-dirty nodes without render.dirty are skipped by the main loop
2066
+ // below (their commands are patched in place), but a node that was fully
2067
+ // outside the record-time clip has NO commands to patch — if it has since
2068
+ // slid into the viewport (a pulsing coin at the pan edge), the retained
2069
+ // list is incomplete and only a full record can reveal it.
2070
+ #if GEA_EMBEDDED_SUBTREE_REVEAL_CHECK
2071
+ for (int i = 0; i < state.nodeCount && can_keep_display_list; i++)
2072
+ {
2073
+ if (!state.nodeCommandDirty[i] || state.nodes[i].render.dirty)
2074
+ continue;
2075
+ if (DisplayList::instance().subtreeRevealsUnrecordedContent(i, width, height))
2076
+ can_keep_display_list = 0;
2077
+ }
2078
+ #endif
2079
+ // Set when any node's commands were re-recorded in place: a re-recorded
2080
+ // transformed face comes back with unwelded corners next to its still-welded
2081
+ // neighbors, so the weld must run again after the loop.
2082
+ bool rerecorded_any = false;
2083
+ for (int i = 0; can_keep_display_list && i < state.nodeCount; i++)
2084
+ {
2085
+ Node *n = &state.nodes[i];
2086
+ if (!n->render.dirty)
2087
+ continue;
2088
+ // Shift this node's commands still owe AFTER its ancestors translate theirs.
2089
+ // Every dirty ancestor with children translates its WHOLE subtree by its own
2090
+ // delta minus what its own ancestors already applied, so those applied deltas
2091
+ // telescope: the shift a descendant actually receives from above is exactly
2092
+ // the NEAREST such ancestor's delta — not the sum over the chain.
2093
+ //
2094
+ // Summing (what this did) is correct only while at most one ancestor is dirty.
2095
+ // The moment two nested containers move together — a camera wrapper and the
2096
+ // full-size world layers positioned at 0 inside it all report the same delta —
2097
+ // the inner ones compute applied == 0 and translate NOTHING, while every leaf
2098
+ // compensates for all of them. The leaf then cancels a shift no one applied and
2099
+ // its commands stay behind by that much, silently: the tree is right, the
2100
+ // display list is stale, and every later frame replays the world at the old
2101
+ // position until something forces a full record.
2102
+ int inherited_dx = 0;
2103
+ int inherited_dy = 0;
2104
+ for (int ancestor = n->parent; ancestor >= 0 && ancestor < state.nodeCount; ancestor = state.nodes[ancestor].parent)
2105
+ {
2106
+ Node *a = &state.nodes[ancestor];
2107
+ if (!a->render.dirty || a->first_child < 0)
2108
+ continue;
2109
+ inherited_dx = a->layout.x - a->layout.previous_x;
2110
+ inherited_dy = a->layout.y - a->layout.previous_y;
2111
+ break;
2112
+ }
2113
+ int dx = n->layout.x - n->layout.previous_x - inherited_dx;
2114
+ int dy = n->layout.y - n->layout.previous_y - inherited_dy;
2115
+ if (dx || dy)
2116
+ {
2117
+ if (n->first_child >= 0)
2118
+ DisplayList::instance().translateSubtreeCommands(i, dx, dy);
2119
+ else
2120
+ DisplayList::instance().translateNodeCommands(i, dx, dy);
2121
+ // The move may have slid content that was fully outside the
2122
+ // record-time clip (culled: no commands) into the viewport — a
2123
+ // camera/world wrapper panning the next level tile on screen, or an
2124
+ // independently-walking sprite re-entering from off-screen. The
2125
+ // retained list is then incomplete and replay would leave stale
2126
+ // background where that content entered, so force a full record.
2127
+ #if GEA_EMBEDDED_SUBTREE_REVEAL_CHECK
2128
+ if (DisplayList::instance().subtreeRevealsUnrecordedContent(i, width, height))
2129
+ {
2130
+ can_keep_display_list = 0;
2131
+ break;
2132
+ }
2133
+ #endif
2134
+ }
2135
+ if (layoutSizeChangeNeedsCommandRerecord(*n))
2136
+ state.nodeCommandDirty[i] = 1;
2137
+ if (state.nodeCommandDirty[i] && n->render.transform_dirty && n->first_child >= 0)
2138
+ {
2139
+ rebuild_for_transform = 1;
2140
+ continue;
2141
+ }
2142
+ int oldCmdX0 = 0;
2143
+ int oldCmdY0 = 0;
2144
+ int oldCmdX1 = -1;
2145
+ int oldCmdY1 = -1;
2146
+ const bool hadOldCommandBounds =
2147
+ state.nodeCommandDirty[i] &&
2148
+ DisplayList::instance().nodeCommandBounds(i, &oldCmdX0, &oldCmdY0, &oldCmdX1, &oldCmdY1);
2149
+ DisplayCommand oldSingleCommand{};
2150
+ bool hadOldSingleCommand = false;
2151
+ if (state.nodeCommandDirty[i] && DisplayList::instance().nodeCommandCount(i) == 1)
2152
+ {
2153
+ if (const DisplayCommand *oldCommand = DisplayList::instance().nodeCommandAt(i, 0))
2154
+ {
2155
+ oldSingleCommand = *oldCommand;
2156
+ hadOldSingleCommand = true;
2157
+ }
2158
+ }
2159
+ if (state.nodeCommandDirty[i] &&
2160
+ !DisplayList::instance().rerecordNodeCommands(i))
2161
+ {
2162
+ can_keep_display_list = 0;
2163
+ break;
2164
+ }
2165
+ if (state.nodeCommandDirty[i])
2166
+ rerecorded_any = true;
2167
+ if (state.nodeCommandDirty[i])
2168
+ {
2169
+ state.nodeCommandDirtyCanOverpaint[i] = 0;
2170
+ if (hadOldSingleCommand && DisplayList::instance().nodeCommandCount(i) == 1)
2171
+ {
2172
+ if (const DisplayCommand *newCommand = DisplayList::instance().nodeCommandAt(i, 0))
2173
+ state.nodeCommandDirtyCanOverpaint[i] =
2174
+ commandsAreSameOpaqueFillShape(oldSingleCommand, *newCommand) ? 1 : 0;
2175
+ }
2176
+ int newCmdX0 = 0;
2177
+ int newCmdY0 = 0;
2178
+ int newCmdX1 = -1;
2179
+ int newCmdY1 = -1;
2180
+ const bool hasNewCommandBounds =
2181
+ DisplayList::instance().nodeCommandBounds(i, &newCmdX0, &newCmdY0, &newCmdX1, &newCmdY1);
2182
+ if (hadOldCommandBounds || hasNewCommandBounds)
2183
+ {
2184
+ int bx0 = hadOldCommandBounds ? oldCmdX0 : newCmdX0;
2185
+ int by0 = hadOldCommandBounds ? oldCmdY0 : newCmdY0;
2186
+ int bx1 = hadOldCommandBounds ? oldCmdX1 : newCmdX1;
2187
+ int by1 = hadOldCommandBounds ? oldCmdY1 : newCmdY1;
2188
+ if (hasNewCommandBounds)
2189
+ {
2190
+ if (newCmdX0 < bx0)
2191
+ bx0 = newCmdX0;
2192
+ if (newCmdY0 < by0)
2193
+ by0 = newCmdY0;
2194
+ if (newCmdX1 > bx1)
2195
+ bx1 = newCmdX1;
2196
+ if (newCmdY1 > by1)
2197
+ by1 = newCmdY1;
2198
+ }
2199
+ state.nodeCommandDirtyBoundsValid[i] = 1;
2200
+ state.nodeCommandDirtyX0[i] = static_cast<int16_t>(bx0);
2201
+ state.nodeCommandDirtyY0[i] = static_cast<int16_t>(by0);
2202
+ state.nodeCommandDirtyX1[i] = static_cast<int16_t>(bx1);
2203
+ state.nodeCommandDirtyY1[i] = static_cast<int16_t>(by1);
2204
+ }
2205
+ }
2206
+ }
2207
+ if (can_keep_display_list && rerecorded_any && !rebuild_for_transform)
2208
+ {
2209
+ // Re-recorded faces carry fresh (unwelded) corners; weld them back against
2210
+ // their neighbors or the shared edges crack until the next reproject — and
2211
+ // permanently if the scene goes static.
2212
+ DisplayList::instance().weldTransformedFaces();
2213
+ }
2214
+ if (can_keep_display_list && rebuild_for_transform)
2215
+ {
2216
+ const std::int64_t recordNodeStartUs = refreshPerfNowUs();
2217
+ // Transform-only frame: if a prior full record armed it, just re-project
2218
+ // the existing commands' corners in place — skipping the full
2219
+ // clear()+recordNode() walk (the spinning cube's dominant record cost: the
2220
+ // geometry is static CSS, only the transform changes per frame). Falls back
2221
+ // to a full record on any structural/clip/command-type change.
2222
+ const bool allowSkip = direct_replay != 0 && !framebuffer_was_dirty;
2223
+ // Reproject fast path gated on the static backdrop being baked (matches spine):
2224
+ // otherwise reproject stays armed across the bake frame and re-projects the
2225
+ // stale full-scene list forever instead of re-recording lean (see backdrop notes).
2226
+ reprojected = allowSkip && DisplayList::instance().staticBackdropActive() &&
2227
+ DisplayList::instance().tryReprojectTransformed();
2228
+ if (!reprojected)
2229
+ {
2230
+ DisplayList::instance().clear();
2231
+ // This frame keeps the direct backdrop-blit replay path (unless the
2232
+ // framebuffer was externally dirtied), so let recordNode skip re-recording
2233
+ // the baked static subtrees — they're blitted, not replayed.
2234
+ DisplayList::instance().recordNode(root, 255, allowSkip);
2235
+ DisplayList::instance().weldTransformedFaces();
2236
+ DisplayList::instance().armTransformReproject(allowSkip && DisplayList::instance().staticBackdropActive());
2237
+ }
2238
+ state.displayListDirty = false;
2239
+ displayListFullRecord = !reprojected;
2240
+ perf.treeRecordNodeUs += refreshPerfNowUs() - recordNodeStartUs;
2241
+ perf.treeRecordCalls++;
2242
+ perf.treeRecordedNodes += state.nodeCount;
2243
+ perf.treeRecordedCommands += DisplayList::instance().commandCount();
2244
+ }
2245
+ else if (!can_keep_display_list)
2246
+ {
2247
+ direct_replay = 0;
2248
+ displayListFullRecord = true;
2249
+ DisplayList::instance().clear();
2250
+ DisplayList::instance().recordNode(root, 255);
2251
+ DisplayList::instance().weldTransformedFaces();
2252
+ state.displayListDirty = false;
2253
+ }
2254
+ }
2255
+ else
2256
+ {
2257
+ const std::int64_t recordNodeStartUs = refreshPerfNowUs();
2258
+ displayListFullRecord = true;
2259
+ DisplayList::instance().clear();
2260
+ DisplayList::instance().recordNode(root, 255);
2261
+ DisplayList::instance().weldTransformedFaces();
2262
+ state.displayListDirty = false;
2263
+ perf.treeRecordNodeUs += refreshPerfNowUs() - recordNodeStartUs;
2264
+ perf.treeRecordCalls++;
2265
+ perf.treeRecordedNodes += state.nodeCount;
2266
+ perf.treeRecordedCommands += DisplayList::instance().commandCount();
2267
+ }
2268
+ if (displayListFullRecord)
2269
+ perf.treeFullRecords++;
2270
+ if (reprojected)
2271
+ perf.treeReprojects++;
2272
+ perf.treeDisplayListUs += refreshPerfNowUs() - displayListStartUs;
2273
+
2274
+ // Horizontal-pan fast path: when a camera/world wrapper translated the viewport
2275
+ // this frame (and nothing structural changed), memcpy-shift the viewport instead
2276
+ // of re-replaying the whole panned scene. Handles the frame fully when it engages.
2277
+ if (tryHorizontalPanRefresh(root, width, height, framebuffer_was_dirty,
2278
+ display_list_was_dirty, display_list_was_structural,
2279
+ displayListFullRecord))
2280
+ {
2281
+ return;
2282
+ }
2283
+
2284
+ DirtyRegions::Rect rects[DirtyRegions::kMaxRects];
2285
+ DirtyRegions::Rect flush_rects[DirtyRegions::kMaxRects];
2286
+ int rect_count = 0;
2287
+ int flush_rect_count = 0;
2288
+ bool preserveFlushOnlyRecolorRegions = false;
2289
+ const std::int64_t dirtyCollectStartUs = refreshPerfNowUs();
2290
+ if (framebuffer_was_dirty)
2291
+ direct_replay = 0;
2292
+ const int transformedShapeCount = transformedLeafDirtyShapeCount();
2293
+ const bool preserveFlatTransformedReplayRects = direct_replay && transformedLeafDirtyShapesAreFlat2D();
2294
+ int transformedSegmentLimit = DirtyRegions::kMaxRects;
2295
+ if (transformedShapeCount > 0)
2296
+ {
2297
+ transformedSegmentLimit = DirtyRegions::kMaxRects / transformedShapeCount;
2298
+ if (transformedSegmentLimit < 1)
2299
+ transformedSegmentLimit = 1;
2300
+ }
2301
+ // Fast path for apps with zero rotated dirty leaves (e.g. bouncing-balls-jsx):
2302
+ // the draw-rect array and flush-rect array end up identical because the only
2303
+ // divergence point is appendTransformedLeafDirtyRegions, which is gated on
2304
+ // (direct_replay && rotated-leaf detected). Collect once, coalesce once, then
2305
+ // copy the result into flush_rects so normal JSX absolute-leaf motion keeps the
2306
+ // small dirty windows while replaying the command list only once.
2307
+ const bool unifiedRectPath = (transformedShapeCount == 0);
2308
+ // Only broad geometry animation should collapse to one bounding box. A
2309
+ // weather update can dirty many fixed text/image leaves without changing
2310
+ // their boxes; merging those paint-only leaves into one near-fullscreen rect
2311
+ // defeats retained painting.
2312
+ {
2313
+ int geometryDirtyLeafEstimate = 0;
2314
+ for (int i = 0; i < state.nodeCount; i++)
2315
+ if (state.nodes[i].render.dirty &&
2316
+ (state.nodes[i].render.layout_dirty || state.nodes[i].render.transform_dirty))
2317
+ geometryDirtyLeafEstimate++;
2318
+ g_broadDirtyBbox = GEA_EMBEDDED_BROAD_DIRTY_BBOX && unifiedRectPath &&
2319
+ geometryDirtyLeafEstimate >= DirtyRegions::kMaxRects;
2320
+ }
2321
+ for (int i = 0; i < state.nodeCount; i++)
2322
+ {
2323
+ if (!state.nodes[i].render.dirty)
2324
+ continue;
2325
+ Node *n = &state.nodes[i];
2326
+
2327
+ int dr_x0 = width, dr_y0 = height, dr_x1 = -1, dr_y1 = -1;
2328
+
2329
+ int canvas_x0 = 0, canvas_y0 = 0, canvas_x1 = -1, canvas_y1 = -1;
2330
+ const auto *canvas_surface = n->type == NodeType::Canvas ? state.canvases.find(i) : nullptr;
2331
+ const auto *canvas = canvas_surface ? canvas_surface->canvas() : nullptr;
2332
+ const bool canvas_dirty = canvas_surface &&
2333
+ canvas &&
2334
+ canvas->dirty(&canvas_x0, &canvas_y0, &canvas_x1, &canvas_y1);
2335
+
2336
+ // Glyph-incremental text dirty: setText found that only a middle run of glyphs
2337
+ // changed within an unchanged box. Flush just that run across the node's height
2338
+ // instead of the whole (possibly near-fullscreen-wide) text box — a 26vmin
2339
+ // ticker then re-copies only its changed digits, fitting a TE-locked frame.
2340
+ if (n->type == NodeType::Text && n->render.text_partial_dirty && !canvas_dirty &&
2341
+ !n->render.transform_dirty && n->layout.width > 0 && n->layout.height > 0)
2342
+ {
2343
+ // Y extent: prefer the recorded glyph command bounds (cap-height..baseline,
2344
+ // no line-height leading — ~0.7x the layout box, and a union of old+new so
2345
+ // both glyphs are covered) over the full box, so the changed-digit re-flush
2346
+ // copies only the glyph rows. Only when the node didn't move/resize
2347
+ // vertically (else the old rows at the prior position must be covered too).
2348
+ int py0 = n->layout.y;
2349
+ int py1 = static_cast<int>(n->layout.y + n->layout.height - 1);
2350
+ if (state.nodeCommandDirtyBoundsValid[i] &&
2351
+ n->layout.y == n->layout.previous_y &&
2352
+ n->layout.height == n->layout.previous_height)
2353
+ {
2354
+ py0 = state.nodeCommandDirtyY0[i];
2355
+ py1 = state.nodeCommandDirtyY1[i];
2356
+ }
2357
+ DirtyRegions::Rect partial{n->render.text_dirty_x0, py0, n->render.text_dirty_x1, py1, i};
2358
+ partial = expandDirtyRect(partial, GEA_EMBEDDED_TEXT_DIRTY_GUARD_PX);
2359
+ partial = dirtyRectWithRasterGuard(*n, partial);
2360
+ addDirtyRegion(rects, &rect_count, partial, width, height);
2361
+ if (!unifiedRectPath)
2362
+ addDirtyRegion(flush_rects, &flush_rect_count, partial, width, height);
2363
+ continue;
2364
+ }
2365
+
2366
+ if (!canvas_dirty &&
2367
+ direct_replay &&
2368
+ n->render.bg_recolor_pending &&
2369
+ n->first_child < 0 &&
2370
+ !hasAnyBorder(n->style) &&
2371
+ n->style.opacity == 255 &&
2372
+ rstyle(n->style).filter_blur_radius <= 0 &&
2373
+ rstyle(n->style).box_shadow_blur_radius <= 0 &&
2374
+ n->layout.x == n->layout.previous_x &&
2375
+ n->layout.y == n->layout.previous_y &&
2376
+ n->layout.width == n->layout.previous_width &&
2377
+ n->layout.height == n->layout.previous_height &&
2378
+ !n->render.transform_dirty)
2379
+ {
2380
+ int recolorX0 = 0;
2381
+ int recolorY0 = 0;
2382
+ int recolorX1 = -1;
2383
+ int recolorY1 = -1;
2384
+ if (DisplayList::instance().recolorRetainedSolidBackground(i,
2385
+ n->render.bg_recolor_from,
2386
+ n->render.bg_recolor_to,
2387
+ &recolorX0,
2388
+ &recolorY0,
2389
+ &recolorX1,
2390
+ &recolorY1))
2391
+ {
2392
+ const DirtyRegions::Rect recolorRect{recolorX0, recolorY0, recolorX1, recolorY1, i};
2393
+ int recolorPixels = appendCircleLikeRecolorFlushRegions(flush_rects,
2394
+ &flush_rect_count,
2395
+ *n,
2396
+ recolorRect,
2397
+ width,
2398
+ height);
2399
+ if (recolorPixels > 0)
2400
+ {
2401
+ preserveFlushOnlyRecolorRegions = true;
2402
+ }
2403
+ else
2404
+ {
2405
+ addDirtyRegion(flush_rects, &flush_rect_count, recolorRect, width, height);
2406
+ recolorPixels = dirtyRectArea(recolorRect);
2407
+ }
2408
+ // The recolor only replaced pixels that matched the OLD background colour
2409
+ // exactly. Every antialiased edge of a node drawn OVER this background is a
2410
+ // blend of the old colour with that node's colour, so it matched nothing and
2411
+ // is now stale (the dial's tick marks and labels keep a halo of the previous
2412
+ // background). Dirty those nodes: a scoped direct replay of their paint
2413
+ // bounds redraws background + foreground there exactly as a full replay
2414
+ // would, which is the only repair that also covers glyph runs (they have no
2415
+ // coverage function to re-blend against).
2416
+ {
2417
+ int repairRects[DirtyRegions::kMaxRects * 4];
2418
+ const int repairCount = DisplayList::instance().collectRecolorForegroundRepairRects(
2419
+ i, recolorX0, recolorY0, recolorX1, recolorY1, repairRects, DirtyRegions::kMaxRects);
2420
+ for (int ri = 0; ri < repairCount; ri++)
2421
+ {
2422
+ // origin -1: the region's pixels come from the background node and the
2423
+ // foreground node both, so the replay must walk the whole draw order.
2424
+ const DirtyRegions::Rect repair{
2425
+ repairRects[ri * 4 + 0], repairRects[ri * 4 + 1],
2426
+ repairRects[ri * 4 + 2], repairRects[ri * 4 + 3], -1};
2427
+ addDirtyRegion(rects, &rect_count, repair, width, height);
2428
+ if (!unifiedRectPath)
2429
+ addDirtyRegion(flush_rects, &flush_rect_count, repair, width, height);
2430
+ }
2431
+ }
2432
+ perf.treeBgRecolorCalls++;
2433
+ perf.treeBgRecolorPixels += recolorPixels;
2434
+ n->render.dirty = 0;
2435
+ n->render.layout_dirty = 0;
2436
+ n->render.non_scroll_dirty = 0;
2437
+ n->render.bg_recolor_pending = 0;
2438
+ continue;
2439
+ }
2440
+ }
2441
+ n->render.bg_recolor_pending = 0;
2442
+
2443
+ // Moved transform-free leaf fast path (the per-frame hot path for the 64
2444
+ // bouncing balls): its dirty rect is prev-box ∪ cur-box plus the retained
2445
+ // movement guard. For a transform-free node, transformedBoundsRect()
2446
+ // returns precisely the layout
2447
+ // box — so the slow path below burns the canUseCommandDirtyBounds probe plus
2448
+ // two transformedBoundsRect() calls (with their pooled transform reads + the
2449
+ // hasTransformChain walk) only to recompute that same union. Build it directly.
2450
+ // Gated on a layout change so paint-only nodes still get the tighter
2451
+ // canUseCommandDirtyBounds rect. anyTransformActive() is cached + the dirty
2452
+ // pass runs after all mid-refresh refreshSerial bumps, so no extra scan.
2453
+ if (n->type != NodeType::Canvas && !n->render.transform_dirty &&
2454
+ n->first_child < 0 &&
2455
+ n->layout.width > 0 && n->layout.height > 0 &&
2456
+ n->layout.previous_width > 0 && n->layout.previous_height > 0 &&
2457
+ (n->layout.x != n->layout.previous_x || n->layout.y != n->layout.previous_y ||
2458
+ n->layout.width != n->layout.previous_width ||
2459
+ n->layout.height != n->layout.previous_height) &&
2460
+ !ViewRenderer::anyTransformActive())
2461
+ {
2462
+ const int cx0 = n->layout.x;
2463
+ const int cy0 = n->layout.y;
2464
+ const int cx1 = cx0 + n->layout.width - 1;
2465
+ const int cy1 = cy0 + n->layout.height - 1;
2466
+ const int px0 = n->layout.previous_x;
2467
+ const int py0 = n->layout.previous_y;
2468
+ const int px1 = px0 + n->layout.previous_width - 1;
2469
+ const int py1 = py0 + n->layout.previous_height - 1;
2470
+ DirtyRegions::Rect leafRect{cx0 < px0 ? cx0 : px0,
2471
+ cy0 < py0 ? cy0 : py0,
2472
+ cx1 > px1 ? cx1 : px1,
2473
+ cy1 > py1 ? cy1 : py1,
2474
+ i};
2475
+ leafRect = dirtyRectWithRetainedMoveGuard(leafRect);
2476
+ leafRect = dirtyRectWithRasterGuard(*n, leafRect);
2477
+ addDirtyRegion(rects, &rect_count, leafRect, width, height);
2478
+ if (!unifiedRectPath)
2479
+ addDirtyRegion(flush_rects, &flush_rect_count, leafRect, width, height);
2480
+ continue;
2481
+ }
2482
+
2483
+ bool usedReprojectRect = false;
2484
+ const bool canUseCommandDirtyBounds =
2485
+ state.nodeCommandDirtyBoundsValid[i] &&
2486
+ (!n->render.transform_dirty || state.nodeCommandDirtyCanOverpaint[i]);
2487
+ if (state.nodeCommandDirtyBoundsValid[i] &&
2488
+ canUseCommandDirtyBounds &&
2489
+ !canvas_dirty &&
2490
+ n->layout.x == n->layout.previous_x &&
2491
+ n->layout.y == n->layout.previous_y &&
2492
+ n->layout.width == n->layout.previous_width &&
2493
+ n->layout.height == n->layout.previous_height)
2494
+ {
2495
+ dr_x0 = state.nodeCommandDirtyX0[i];
2496
+ dr_y0 = state.nodeCommandDirtyY0[i];
2497
+ dr_x1 = state.nodeCommandDirtyX1[i];
2498
+ dr_y1 = state.nodeCommandDirtyY1[i];
2499
+ usedReprojectRect = true;
2500
+ }
2501
+ else if (canvas_dirty)
2502
+ {
2503
+ dr_x0 = n->layout.x + canvas_x0;
2504
+ dr_y0 = n->layout.y + canvas_y0;
2505
+ dr_x1 = n->layout.x + canvas_x1;
2506
+ dr_y1 = n->layout.y + canvas_y1;
2507
+ }
2508
+ else if (reprojected && n->render.transform_dirty && n->first_child >= 0 &&
2509
+ DisplayList::instance().reprojectDirtyRect(&dr_x0, &dr_y0, &dr_x1, &dr_y1))
2510
+ {
2511
+ // The reproject already projected every corner of this transformed subtree
2512
+ // and recorded prev∪cur as its dirty rect — reuse it instead of calling
2513
+ // transformedSubtreeBoundsRect twice (the dominant dirty-collect cost, ~1680us
2514
+ // on the css-3d-cube). UNCONDITIONAL, matching spine. This was previously
2515
+ // net-negative ONLY because reprojectDirtyRect was ballooned by the static
2516
+ // perspective stage floor (a non-moving rotateX command unioned into the rect →
2517
+ // screen-wide [-263,0,673,730]); render.cpp now gates that union on real
2518
+ // movement, so the reused rect is the tight moving-cube bbox and the reuse path
2519
+ // is the cheap win (dirty ~1990us → ~150us) with replay/flush unchanged.
2520
+ usedReprojectRect = true;
2521
+ }
2522
+ else if (direct_replay &&
2523
+ (!DisplayList::instance().staticBackdropActive() ||
2524
+ canUseStaticBackdropStripDirtyForTransformedLeaf(*n)) &&
2525
+ appendTransformedLeafDirtyRegions(rects,
2526
+ &rect_count,
2527
+ flush_rects,
2528
+ &flush_rect_count,
2529
+ *n,
2530
+ i,
2531
+ width,
2532
+ height,
2533
+ transformedSegmentLimit,
2534
+ !DisplayList::instance().staticBackdropActive()))
2535
+ {
2536
+ // Keep perspective/3D static-backdrop frames on the single-bbox path: per-face
2537
+ // segmented regions can create blit-edge seams. Flat 2D rotated leaves (clock
2538
+ // hands, needles) replay one coalesced bbox into the framebuffer but flush
2539
+ // segmented dirty strips, avoiding repeated clipped replay work.
2540
+ continue;
2541
+ }
2542
+ else if (n->layout.previous_width > 0 && n->layout.previous_height > 0)
2543
+ {
2544
+ DirtyRegions::Rect previousBounds = n->render.transform_dirty && n->first_child >= 0
2545
+ ? transformedSubtreeBoundsRect(i, true, i)
2546
+ : transformedBoundsRect(*n, true, i);
2547
+ dr_x0 = previousBounds.x0;
2548
+ dr_y0 = previousBounds.y0;
2549
+ dr_x1 = previousBounds.x1;
2550
+ dr_y1 = previousBounds.y1;
2551
+ }
2552
+
2553
+ if (!usedReprojectRect && !canvas_dirty && n->layout.width > 0 && n->layout.height > 0)
2554
+ {
2555
+ DirtyRegions::Rect currentBounds = n->render.transform_dirty && n->first_child >= 0
2556
+ ? transformedSubtreeBoundsRect(i, false, i)
2557
+ : transformedBoundsRect(*n, false, i);
2558
+ int nx0 = currentBounds.x0;
2559
+ int ny0 = currentBounds.y0;
2560
+ int nx1 = currentBounds.x1;
2561
+ int ny1 = currentBounds.y1;
2562
+ if (nx0 < dr_x0)
2563
+ dr_x0 = nx0;
2564
+ if (ny0 < dr_y0)
2565
+ dr_y0 = ny0;
2566
+ if (nx1 > dr_x1)
2567
+ dr_x1 = nx1;
2568
+ if (ny1 > dr_y1)
2569
+ dr_y1 = ny1;
2570
+ }
2571
+
2572
+ if (!usedReprojectRect && !canvas_dirty && !n->render.transform_dirty &&
2573
+ n->layout.previous_width > 0 && n->layout.previous_height > 0 &&
2574
+ (n->layout.x != n->layout.previous_x || n->layout.y != n->layout.previous_y ||
2575
+ n->layout.width != n->layout.previous_width ||
2576
+ n->layout.height != n->layout.previous_height))
2577
+ {
2578
+ DirtyRegions::Rect guarded = dirtyRectWithRetainedMoveGuard(
2579
+ DirtyRegions::Rect{dr_x0, dr_y0, dr_x1, dr_y1, i});
2580
+ dr_x0 = guarded.x0;
2581
+ dr_y0 = guarded.y0;
2582
+ dr_x1 = guarded.x1;
2583
+ dr_y1 = guarded.y1;
2584
+ }
2585
+
2586
+ if (dr_x0 > dr_x1 || dr_y0 > dr_y1)
2587
+ continue;
2588
+
2589
+ // Transformed subtrees (the spinning cube) derive their dirty bbox from the
2590
+ // min/max of int16_t-rounded projected corners. The rasterized silhouette can
2591
+ // fall up to ~1px outside that bbox, so as the cube rotates its retreating edge
2592
+ // is left 1px un-repainted — a thin trailing seam against the backdrop. Pad the
2593
+ // rect a couple px so the previous frame's edge is always covered (clipped to the
2594
+ // viewport by addDirtyRegion; after the full sync this padding blits identical
2595
+ // backdrop, so it introduces no new seam).
2596
+ // Tag the rect with the originating dirty node id. The replay
2597
+ // path uses it for a static-dispatch fast path while still
2598
+ // replaying overlapping siblings, such as overlay labels, in the
2599
+ // original draw order.
2600
+ const DirtyRegions::Rect dirtyRect =
2601
+ dirtyRectWithRasterGuard(*n, DirtyRegions::Rect{dr_x0, dr_y0, dr_x1, dr_y1, i});
2602
+ addDirtyRegion(rects, &rect_count, dirtyRect, width, height);
2603
+ if (!unifiedRectPath)
2604
+ addDirtyRegion(flush_rects, &flush_rect_count, dirtyRect, width, height);
2605
+ }
2606
+ if (display_list_was_dirty && display_list_was_structural && width > 0 && height > 0)
2607
+ {
2608
+ // A STRUCTURAL command-list rebuild can change draw order, alpha scopes,
2609
+ // or which commands exist. Repaint the viewport once so the framebuffer
2610
+ // matches the rebuilt scene instead of relying on stale incremental
2611
+ // pixels. Content-only rebuilds (appearance changes on existing nodes —
2612
+ // see markDisplayListContentDirty) skip this: the per-node dirty rects
2613
+ // above already cover every pixel that changed.
2614
+ const DirtyRegions::Rect fullViewport{0, 0, width - 1, height - 1, root};
2615
+ addDirtyRegion(rects, &rect_count, fullViewport, width, height);
2616
+ if (!unifiedRectPath)
2617
+ addDirtyRegion(flush_rects, &flush_rect_count, fullViewport, width, height);
2618
+ }
2619
+ if (width > 0 && height > 0 && DisplayList::instance().consumeBackdropFullSyncRequest())
2620
+ {
2621
+ // The static-backdrop cache was just baked. Repaint the full viewport from it
2622
+ // once (blit the whole baked backdrop + replay the cube) so the framebuffer and
2623
+ // panel become exactly the baked backdrop everywhere — eliminating the seam at
2624
+ // later per-region blit boundaries.
2625
+ const DirtyRegions::Rect fullViewport{0, 0, width - 1, height - 1, root};
2626
+ addDirtyRegion(rects, &rect_count, fullViewport, width, height);
2627
+ if (!unifiedRectPath)
2628
+ addDirtyRegion(flush_rects, &flush_rect_count, fullViewport, width, height);
2629
+ }
2630
+ if (framebuffer_was_dirty)
2631
+ {
2632
+ // Some platforms can clear or dirty the retained framebuffer outside
2633
+ // node mutation tracking. Replay that canvas area so static nodes are
2634
+ // restored even when no corresponding DOM-ish node changed this frame.
2635
+ const DirtyRegions::Rect framebufferRect{
2636
+ framebufferDirtyX0,
2637
+ framebufferDirtyY0,
2638
+ framebufferDirtyX1,
2639
+ framebufferDirtyY1,
2640
+ root};
2641
+ addDirtyRegion(rects, &rect_count, framebufferRect, width, height);
2642
+ if (!unifiedRectPath)
2643
+ addDirtyRegion(flush_rects, &flush_rect_count, framebufferRect, width, height);
2644
+ }
2645
+ // filter: blur() is rebuilt by diffing the fully rendered filtered source
2646
+ // against its saved background. If a dirty rect touches a filtered node,
2647
+ // replay the full filtered source/output bounds so the cache never mixes
2648
+ // retained pixels with the current frame.
2649
+ expandDirtyRegionsForFilterBlur(rects, &rect_count, flush_rects, &flush_rect_count, unifiedRectPath, width, height);
2650
+ perf.treeDirtyCollectUs += refreshPerfNowUs() - dirtyCollectStartUs;
2651
+ // Done collecting (and the structural/framebuffer/filter adds above); clear the
2652
+ // broad-bbox flag so it can't leak into any later addDirtyRegion path.
2653
+ g_broadDirtyBbox = false;
2654
+
2655
+ const std::int64_t dirtyCoalesceStartUs = refreshPerfNowUs();
2656
+ if (!unifiedRectPath || GEA_EMBEDDED_REPLAY_COALESCE_DIRTY_REGIONS)
2657
+ coalesceLowCostDirtyRegions(rects, &rect_count);
2658
+ if (!preserveFlatTransformedReplayRects)
2659
+ coalesceHighCoverageDirtyRegions(rects, &rect_count, width, height);
2660
+ if (unifiedRectPath)
2661
+ {
2662
+ if (flush_rect_count > 0)
2663
+ {
2664
+ if (preserveFlushOnlyRecolorRegions)
2665
+ {
2666
+ for (int i = 0; i < rect_count; i++)
2667
+ {
2668
+ if (dirtyRectCoveredByAny(flush_rects, flush_rect_count, rects[i]))
2669
+ continue;
2670
+ appendDirtyRegion(flush_rects, &flush_rect_count, rects[i], width, height);
2671
+ }
2672
+ }
2673
+ else
2674
+ {
2675
+ for (int i = 0; i < rect_count; i++)
2676
+ addDirtyRegion(flush_rects, &flush_rect_count, rects[i], width, height);
2677
+ #if GEA_EMBEDDED_FLUSH_COALESCE_DIRTY_REGIONS
2678
+ coalesceLowCostDirtyRegions(flush_rects, &flush_rect_count);
2679
+ if (!preserveFlatTransformedReplayRects)
2680
+ coalesceHighCoverageDirtyRegions(flush_rects, &flush_rect_count, width, height);
2681
+ #endif
2682
+ }
2683
+ }
2684
+ else
2685
+ {
2686
+ std::memcpy(flush_rects, rects, sizeof(rects[0]) * static_cast<std::size_t>(rect_count));
2687
+ flush_rect_count = rect_count;
2688
+ #if GEA_EMBEDDED_FLUSH_COALESCE_DIRTY_REGIONS
2689
+ // Replay uses the tight per-region rects[] (HighCoverage only) for minimal
2690
+ // rasterize, but the FLUSH set must be LowCost-coalesced: the CO5300 pays a
2691
+ // large per-window setup penalty, so merging nearby windows (extra-area <=
2692
+ // smaller-rect, ~no real pixel cost) collapses ~24 scattered ball boxes into a
2693
+ // handful of wider windows — ~5ms flush vs ~20ms. At 52c15558 (58fps) LowCost
2694
+ // ran unconditionally on the shared rects/flush set; the unified path later
2695
+ // split them and dropped LowCost from the flush set, which is the regression.
2696
+ coalesceLowCostDirtyRegions(flush_rects, &flush_rect_count);
2697
+ if (!preserveFlatTransformedReplayRects)
2698
+ coalesceHighCoverageDirtyRegions(flush_rects, &flush_rect_count, width, height);
2699
+ #endif
2700
+ }
2701
+ }
2702
+ else
2703
+ {
2704
+ #if GEA_EMBEDDED_FLUSH_COALESCE_DIRTY_REGIONS
2705
+ coalesceLowCostDirtyRegions(flush_rects, &flush_rect_count);
2706
+ if (!preserveFlatTransformedReplayRects)
2707
+ coalesceHighCoverageDirtyRegions(flush_rects, &flush_rect_count, width, height);
2708
+ #endif
2709
+ }
2710
+ perf.treeDirtyCoalesceUs += refreshPerfNowUs() - dirtyCoalesceStartUs;
2711
+
2712
+ gea::platform::display::DisplayFlushRect flushRects[DirtyRegions::kMaxRects];
2713
+ int flushRectCount = 0;
2714
+ if (rect_count > 0)
2715
+ {
2716
+ perf.treeReplayRegions += rect_count;
2717
+ for (int i = 0; i < rect_count; i++)
2718
+ {
2719
+ if (rects[i].origin >= 0)
2720
+ perf.treeReplayOriginRegions++;
2721
+ if (perf.treeReplayRegionSampleCount < gea::embedded::ui::RefreshPerfStats::kMaxTreeReplayRegionSamples)
2722
+ {
2723
+ const int sample = perf.treeReplayRegionSampleCount++;
2724
+ perf.treeReplayRegionX0[sample] = static_cast<std::int16_t>(rects[i].x0);
2725
+ perf.treeReplayRegionY0[sample] = static_cast<std::int16_t>(rects[i].y0);
2726
+ perf.treeReplayRegionX1[sample] = static_cast<std::int16_t>(rects[i].x1);
2727
+ perf.treeReplayRegionY1[sample] = static_cast<std::int16_t>(rects[i].y1);
2728
+ perf.treeReplayRegionOrigin[sample] = static_cast<std::int16_t>(rects[i].origin);
2729
+ }
2730
+ }
2731
+ }
2732
+ const bool hasFlushOnlyRecolorRegions = preserveFlushOnlyRecolorRegions && flush_rect_count > 0;
2733
+ const bool simpleDirtyReplayAvailable =
2734
+ direct_replay && unifiedRectPath && DisplayList::instance().canReplaySimpleDirtyRegions(width, height);
2735
+ const bool simpleUnifiedReplay = simpleDirtyReplayAvailable && rect_count > 0 && !hasFlushOnlyRecolorRegions;
2736
+ const bool interleavedUnifiedFlush =
2737
+ direct_replay && unifiedRectPath && rect_count > 0 && !simpleDirtyReplayAvailable && !hasFlushOnlyRecolorRegions;
2738
+ #if GEA_EMBEDDED_SIMPLE_REPLAY_DEBUG
2739
+ {
2740
+ static int b = 0;
2741
+ if ((b++ % 600) == 0)
2742
+ std::printf("[branch] txShapes=%d unifiedRect=%d simpleAvail=%d simpleUnified=%d interleaved=%d recolorOnly=%d FUSE=%d\n",
2743
+ transformedShapeCount, (int)unifiedRectPath, (int)simpleDirtyReplayAvailable,
2744
+ (int)simpleUnifiedReplay, (int)interleavedUnifiedFlush, (int)hasFlushOnlyRecolorRegions,
2745
+ (int)GEA_EMBEDDED_DISPLAY_FUSE_REPLAY_FLUSH);
2746
+ }
2747
+ #endif
2748
+ if (simpleUnifiedReplay)
2749
+ {
2750
+ perf.treeDirectReplayCalls++;
2751
+ #if GEA_EMBEDDED_DISPLAY_FUSE_REPLAY_FLUSH
2752
+ // Fused: skip the separate replay-into-framebuffer pass entirely. Hand the
2753
+ // coalesced dirty windows to the flush, which chunks them and calls
2754
+ // fusedReplayRaster to replay the display-list straight into each DMA buffer.
2755
+ {
2756
+ FusedReplayRasterCtx fctx{width, height};
2757
+ gea::platform::display::DisplayFlushRect sparseRects[DirtyRegions::kMaxRects];
2758
+ int sparseCount = 0;
2759
+ for (int i = 0; i < flush_rect_count && sparseCount < DirtyRegions::kMaxRects; i++)
2760
+ {
2761
+ DirtyRegions::Rect *r = &flush_rects[i];
2762
+ if (r->x0 > r->x1 || r->y0 > r->y1)
2763
+ continue;
2764
+ sparseRects[sparseCount++] =
2765
+ gea::platform::display::DisplayFlushRect{r->x0, r->y0, r->x1, r->y1};
2766
+ }
2767
+ const std::int64_t flushStartUs = refreshPerfNowUs();
2768
+ if (sparseCount > 0)
2769
+ {
2770
+ // Deferred per-chunk drain: chunks pipeline (rasterize N+1 under DMA N via
2771
+ // the depth-2 slots). The cross-rect entry-drain now spin-waits, so this no
2772
+ // longer pays the blocking cross-core wakeup that capped it at 35fps.
2773
+ gea::platform::display::Display::flushRectsRasterized(sparseRects, sparseCount, fusedReplayRaster, &fctx, /*allowPerChunkDrain=*/false);
2774
+ gea::platform::display::Display::rebindCanvasToFramebuffer();
2775
+ }
2776
+ perf.treeFlushRectsUs += refreshPerfNowUs() - flushStartUs;
2777
+ }
2778
+ #else
2779
+ // A single wide flush of the dirty union avoids the per-window overhead and
2780
+ // the narrow-flush QSPI penalty (~4.5 vs ~45 px/us on the SH8601) that many
2781
+ // small per-rect flushes pay — but ONLY when the rects are clustered enough
2782
+ // that their bounding box is a tight cover. For scattered rects (e.g.
2783
+ // bouncing-balls spread across the panel) the union bbox approaches the full
2784
+ // surface while real coverage is a few percent, so one union flush
2785
+ // copies+TXes ~10x the pixels of sparse per-rect flushes — that flipped this
2786
+ // app from 62fps to 38fps. Gate the union flush on measured coverage, not
2787
+ // just rect count: take it only when many rects AND the union is a tight
2788
+ // cover (break-even on the SH8601 lands near union <= ~4.5x summed area;
2789
+ // 3x keeps a safe margin and still serves genuinely clustered scenes).
2790
+ long long sumArea = 0;
2791
+ int unionX0 = rects[0].x0;
2792
+ int unionY0 = rects[0].y0;
2793
+ int unionX1 = rects[0].x1;
2794
+ int unionY1 = rects[0].y1;
2795
+ for (int i = 0; i < rect_count; i++)
2796
+ {
2797
+ const DirtyRegions::Rect *r = &rects[i];
2798
+ sumArea += static_cast<long long>(r->x1 - r->x0 + 1) * static_cast<long long>(r->y1 - r->y0 + 1);
2799
+ if (r->x0 < unionX0)
2800
+ unionX0 = r->x0;
2801
+ if (r->y0 < unionY0)
2802
+ unionY0 = r->y0;
2803
+ if (r->x1 > unionX1)
2804
+ unionX1 = r->x1;
2805
+ if (r->y1 > unionY1)
2806
+ unionY1 = r->y1;
2807
+ }
2808
+ const long long unionArea =
2809
+ static_cast<long long>(unionX1 - unionX0 + 1) * static_cast<long long>(unionY1 - unionY0 + 1);
2810
+ const bool useUnionFlush =
2811
+ rect_count >= DirtyRegions::kMaxRects / 2 && unionArea <= sumArea * 3;
2812
+ // Replay every region hot, back-to-back, with NO flush interleaved — an
2813
+ // interleaved per-rect flush contends the replay working set and inflates
2814
+ // replay (11.8 vs 3.5ms). This is the 52c15558 (58fps) path.
2815
+ if (rect_count > 1)
2816
+ {
2817
+ bool usePerOriginReplay = rect_count <= 4;
2818
+ for (int i = 0; i < rect_count && usePerOriginReplay; i++)
2819
+ usePerOriginReplay = rects[i].origin >= 0;
2820
+ if (usePerOriginReplay)
2821
+ {
2822
+ for (int i = 0; i < rect_count; i++)
2823
+ {
2824
+ DirtyRegions::Rect *r = &rects[i];
2825
+ gea::platform::display::Display::resetClip();
2826
+ gea::platform::display::Display::setAlpha(255);
2827
+ gea::platform::display::Display::pushClip(r->x0, r->y0, r->x1 - r->x0 + 1, r->y1 - r->y0 + 1);
2828
+ const std::int64_t replayStartUs = refreshPerfNowUs();
2829
+ DisplayList::instance().replaySimpleClippedDirtyRegion(r->x0, r->y0, r->x1, r->y1, r->origin);
2830
+ perf.treeReplayUs += refreshPerfNowUs() - replayStartUs;
2831
+ gea::platform::display::Display::popClip();
2832
+ }
2833
+ }
2834
+ else
2835
+ {
2836
+ gea::platform::display::Display::resetClip();
2837
+ gea::platform::display::Display::setAlpha(255);
2838
+ const std::int64_t replayStartUs = refreshPerfNowUs();
2839
+ DisplayReplayRegion regions[DirtyRegions::kMaxRects];
2840
+ for (int i = 0; i < rect_count; i++)
2841
+ {
2842
+ DirtyRegions::Rect *r = &rects[i];
2843
+ regions[i] = DisplayReplayRegion{r->x0, r->y0, r->x1, r->y1, r->origin};
2844
+ }
2845
+ DisplayList::instance().replayDirectDirtyRegions(regions, rect_count);
2846
+ perf.treeReplayUs += refreshPerfNowUs() - replayStartUs;
2847
+ }
2848
+ }
2849
+ else
2850
+ {
2851
+ for (int i = 0; i < rect_count; i++)
2852
+ {
2853
+ DirtyRegions::Rect *r = &rects[i];
2854
+ gea::platform::display::Display::resetClip();
2855
+ gea::platform::display::Display::setAlpha(255);
2856
+ gea::platform::display::Display::pushClip(r->x0, r->y0, r->x1 - r->x0 + 1, r->y1 - r->y0 + 1);
2857
+ const std::int64_t replayStartUs = refreshPerfNowUs();
2858
+ DisplayList::instance().replaySimpleClippedDirtyRegion(r->x0, r->y0, r->x1, r->y1, r->origin);
2859
+ perf.treeReplayUs += refreshPerfNowUs() - replayStartUs;
2860
+ gea::platform::display::Display::popClip();
2861
+ }
2862
+ }
2863
+ const std::int64_t flushStartUs = refreshPerfNowUs();
2864
+ if (useUnionFlush)
2865
+ {
2866
+ // Clustered dirty: one wide bbox flush.
2867
+ gea::platform::display::Display::flush();
2868
+ }
2869
+ else
2870
+ {
2871
+ // Scattered dirty (bouncing-balls): flush the COALESCED flush_rects[], NOT
2872
+ // the raw replay rects[]. Replay above renders from the tight per-ball rects[]
2873
+ // (minimal rasterize), but the CO5300 pays a large per-window setup penalty
2874
+ // (~0.8ms/window), so flushing ~24 tight ball boxes serializes to ~20ms of
2875
+ // panel wait. flush_rects[] has already been merged by coalesceLowCostDirtyRegions
2876
+ // (extra-area <= smaller-rect) into a handful of wider windows covering the same
2877
+ // pixels — measured ~5ms flush vs ~20ms. This is the 52c15558 (58fps) path,
2878
+ // which flushed the coalesced flush_rects. flush_rects is a superset of rects
2879
+ // (every rect was added before coalescing), so each flushed window's framebuffer
2880
+ // content is already correct.
2881
+ gea::platform::display::DisplayFlushRect sparseRects[DirtyRegions::kMaxRects];
2882
+ int sparseCount = 0;
2883
+ for (int i = 0; i < flush_rect_count && sparseCount < DirtyRegions::kMaxRects; i++)
2884
+ {
2885
+ DirtyRegions::Rect *r = &flush_rects[i];
2886
+ if (r->x0 > r->x1 || r->y0 > r->y1)
2887
+ continue;
2888
+ sparseRects[sparseCount++] =
2889
+ gea::platform::display::DisplayFlushRect{r->x0, r->y0, r->x1, r->y1};
2890
+ }
2891
+ if (sparseCount > 0)
2892
+ gea::platform::display::Display::flushRects(sparseRects, sparseCount);
2893
+ }
2894
+ perf.treeFlushRectsUs += refreshPerfNowUs() - flushStartUs;
2895
+ #endif
2896
+ }
2897
+ else if (interleavedUnifiedFlush)
2898
+ {
2899
+ perf.treeDirectReplayCalls++;
2900
+ #if GEA_EMBEDDED_DISPLAY_FUSE_REPLAY_FLUSH && GEA_EMBEDDED_DISPLAY_FUSE_INTERLEAVED_REPLAY_FLUSH
2901
+ FusedReplayRasterCtx fctx{width, height};
2902
+ gea::platform::display::DisplayFlushRect sparseRects[DirtyRegions::kMaxRects];
2903
+ int sparseCount = 0;
2904
+ for (int i = 0; i < flush_rect_count && sparseCount < DirtyRegions::kMaxRects; i++)
2905
+ {
2906
+ DirtyRegions::Rect *r = &flush_rects[i];
2907
+ if (r->x0 > r->x1 || r->y0 > r->y1)
2908
+ continue;
2909
+ sparseRects[sparseCount++] =
2910
+ gea::platform::display::DisplayFlushRect{r->x0, r->y0, r->x1, r->y1};
2911
+ }
2912
+ const std::int64_t flushStartUs = refreshPerfNowUs();
2913
+ if (sparseCount > 0)
2914
+ {
2915
+ gea::platform::display::Display::flushRectsRasterized(sparseRects, sparseCount, fusedDirectReplayRaster, &fctx, /*allowPerChunkDrain=*/false);
2916
+ gea::platform::display::Display::rebindCanvasToFramebuffer();
2917
+ }
2918
+ perf.treeFlushRectsUs += refreshPerfNowUs() - flushStartUs;
2919
+ #else
2920
+ for (int i = 0; i < rect_count; i++)
2921
+ {
2922
+ DirtyRegions::Rect *r = &rects[i];
2923
+ gea::platform::display::Display::resetClip();
2924
+ gea::platform::display::Display::setAlpha(255);
2925
+ gea::platform::display::Display::pushClip(r->x0, r->y0, r->x1 - r->x0 + 1, r->y1 - r->y0 + 1);
2926
+ const std::int64_t replayStartUs = refreshPerfNowUs();
2927
+ const DisplayReplayRegion region{r->x0, r->y0, r->x1, r->y1, r->origin};
2928
+ DisplayList::instance().replayDirectDirtyRegions(&region, 1);
2929
+ perf.treeReplayUs += refreshPerfNowUs() - replayStartUs;
2930
+ gea::platform::display::Display::popClip();
2931
+ const std::int64_t flushStartUs = refreshPerfNowUs();
2932
+ gea::platform::display::Display::flush();
2933
+ perf.treeFlushRectsUs += refreshPerfNowUs() - flushStartUs;
2934
+ }
2935
+ #endif
2936
+ }
2937
+ else
2938
+ {
2939
+ const std::int64_t replayStartUs = refreshPerfNowUs();
2940
+ if (direct_replay && rect_count > 0)
2941
+ {
2942
+ perf.treeDirectReplayCalls++;
2943
+ gea::platform::display::Display::resetClip();
2944
+ gea::platform::display::Display::setAlpha(255);
2945
+ DisplayReplayRegion regions[DirtyRegions::kMaxRects];
2946
+ for (int i = 0; i < rect_count; i++)
2947
+ {
2948
+ DirtyRegions::Rect *r = &rects[i];
2949
+ regions[i] = DisplayReplayRegion{r->x0, r->y0, r->x1, r->y1, r->origin};
2950
+ }
2951
+ DisplayList::instance().replayDirectDirtyRegions(regions, rect_count);
2952
+ }
2953
+ else
2954
+ {
2955
+ // Conservative paint path for full display-list replay.
2956
+ for (int i = 0; i < rect_count; i++)
2957
+ {
2958
+ DirtyRegions::Rect *r = &rects[i];
2959
+ gea::platform::display::Display::resetClip();
2960
+ gea::platform::display::Display::setAlpha(255);
2961
+ gea::platform::display::Display::pushClip(r->x0, r->y0, r->x1 - r->x0 + 1, r->y1 - r->y0 + 1);
2962
+ DisplayList::instance().replay();
2963
+ gea::platform::display::Display::popClip();
2964
+ }
2965
+ }
2966
+ perf.treeReplayUs += refreshPerfNowUs() - replayStartUs;
2967
+ }
2968
+
2969
+ // Static-backdrop cache: once the static scene (bg + stage) has been stable for a
2970
+ // couple frames, bake it into the backdrop buffer so subsequent dirty-region
2971
+ // replays blit it and replay only the dynamic subtree (the cube) on top. Must run
2972
+ // HERE — before LayoutSnapshot::capture() clears render.dirty — so the bake can
2973
+ // tell the dynamic cube (still dirty) from the static scene and exclude it; the
2974
+ // bake rebinds the canvas to its own buffer and restores it before the flush
2975
+ // reads the framebuffer. A structural rebuild this frame (!stable) drops the
2976
+ // cache so it re-settles.
2977
+ #ifndef ESP_PLATFORM
2978
+ {
2979
+ static const bool debugBackdrop = std::getenv("GEA_DEBUG_BACKDROP") != nullptr;
2980
+ if (debugBackdrop)
2981
+ std::printf("[bake-gate] simpleAvail=%d unified=%d canSimple=%d structural=%d rects=%d flushRects=%d\n",
2982
+ simpleDirtyReplayAvailable ? 1 : 0, unifiedRectPath ? 1 : 0,
2983
+ DisplayList::instance().canReplaySimpleDirtyRegions(width, height) ? 1 : 0,
2984
+ display_list_was_structural ? 1 : 0, rect_count, flush_rect_count);
2985
+ }
2986
+ #endif
2987
+ DisplayList::instance().maybeBakeStaticBackdrop(
2988
+ width,
2989
+ height,
2990
+ !display_list_was_structural && staticBackdropStable,
2991
+ direct_replay != 0 && !simpleDirtyReplayAvailable && staticBackdropStable,
2992
+ staticBackdropEligible);
2993
+
2994
+ const std::int64_t flushRectsStartUs = refreshPerfNowUs();
2995
+ if (!simpleUnifiedReplay && !interleavedUnifiedFlush)
2996
+ {
2997
+ for (int i = 0; i < flush_rect_count; i++)
2998
+ {
2999
+ DirtyRegions::Rect *r = &flush_rects[i];
3000
+ if (flushRectCount < DirtyRegions::kMaxRects)
3001
+ {
3002
+ if (unifiedRectPath)
3003
+ {
3004
+ flushRects[flushRectCount++] = gea::platform::display::DisplayFlushRect{r->x0, r->y0, r->x1, r->y1};
3005
+ continue;
3006
+ }
3007
+ // A partial-width CO5300 flush window leaves a 1px stale/black column at its
3008
+ // LEFT edge on the panel (not in the framebuffer). CO5300 targets anchor the
3009
+ // window at x=0; DSI targets without that artifact can keep the actual dirty
3010
+ // x0 so narrow transformed-leaf strips stay narrow on the wire.
3011
+ #if GEA_EMBEDDED_FLUSH_ANCHOR_LEFT_PARTIAL_RECTS
3012
+ const int flushX0 = 0;
3013
+ #else
3014
+ const int flushX0 = r->x0;
3015
+ #endif
3016
+ flushRects[flushRectCount++] = gea::platform::display::DisplayFlushRect{flushX0, r->y0, r->x1, r->y1};
3017
+ }
3018
+ }
3019
+ if (flushRectCount > 0)
3020
+ gea::platform::display::Display::flushRects(flushRects, flushRectCount);
3021
+ perf.treeFlushRectsUs += refreshPerfNowUs() - flushRectsStartUs;
3022
+ }
3023
+ const std::int64_t snapshotStartUs = refreshPerfNowUs();
3024
+ LayoutSnapshot::capture();
3025
+ state.canvases.forEach([](CanvasSurfaceState &surface)
3026
+ {
3027
+ if (auto *canvas = surface.canvas()) canvas->resetDirty(); });
3028
+ #if !defined(GEA_EMBEDDED_DIRECT_CANVAS_CONTEXT) || !GEA_EMBEDDED_DIRECT_CANVAS_CONTEXT
3029
+ // displayCanvas is only declared when the direct-canvas context is off (see the
3030
+ // guard at its declaration above); with direct canvas it is always null, so the
3031
+ // resetDirty is a no-op. Guard the use to match — a global define (web build)
3032
+ // otherwise leaves this referencing an undeclared name.
3033
+ if (displayCanvas)
3034
+ displayCanvas->resetDirty();
3035
+ #endif
3036
+ perf.treeSnapshotUs += refreshPerfNowUs() - snapshotStartUs;
3037
+ }
3038
+
3039
+ void Tree::frame(int timestamp_ms)
3040
+ {
3041
+ auto &state = treeState();
3042
+ if (state.mountedRoot < 0)
3043
+ return;
3044
+ if (timestamp_ms < 0)
3045
+ timestamp_ms = 0;
3046
+ state.lastFrameMs = timestamp_ms;
3047
+
3048
+ if (state.inputTickRequired)
3049
+ tickInput(timestamp_ms);
3050
+
3051
+ // Caret blink for `<input>` focus on the pixel target. The macOS path
3052
+ // owns its own caret via NSResponder; on ESP32 InputRenderer::record
3053
+ // reads activeInputCaretVisible() each frame, and this tick is what
3054
+ // flips the bool every ~500ms.
3055
+ tickInputCaret(timestamp_ms);
3056
+
3057
+ int changed = 0;
3058
+ for (int i = 0; i < state.nodeCount; i++)
3059
+ {
3060
+ Node *n = &state.nodes[i];
3061
+ if (n->style.blink_interval_ms <= 0)
3062
+ {
3063
+ if (!n->style.blink_visible)
3064
+ {
3065
+ n->style.blink_visible = 1;
3066
+ n->render.dirty = 1;
3067
+ n->render.layout_dirty = 1;
3068
+ n->render.non_scroll_dirty = 1;
3069
+ changed = 1;
3070
+ }
3071
+ continue;
3072
+ }
3073
+
3074
+ int elapsed = timestamp_ms - n->style.blink_started_ms;
3075
+ if (elapsed < 0)
3076
+ elapsed = 0;
3077
+ int visible = ((elapsed / n->style.blink_interval_ms) % 2) == 0;
3078
+ if (n->style.blink_visible == visible)
3079
+ continue;
3080
+ n->style.blink_visible = visible;
3081
+ n->render.dirty = 1;
3082
+ n->render.layout_dirty = 1;
3083
+ n->render.non_scroll_dirty = 1;
3084
+ markDisplayListDirty();
3085
+ changed = 1;
3086
+ }
3087
+
3088
+ // Live <camera> preview: while a camera is streaming, repaint each camera
3089
+ // leaf every frame so fresh frames reach the panel — the same idea as the
3090
+ // caret/blink ticks above, but driven by the platform preview provider
3091
+ // rather than a timer.
3092
+ CameraSurfaceProvider *cameraProvider = CameraSurface::provider();
3093
+ if (cameraProvider && cameraProvider->isStreaming())
3094
+ {
3095
+ const bool nativeOverlay = cameraProvider->previewMode() == CameraPreviewMode::NativeOverlay;
3096
+ bool hasVisibleCamera = false;
3097
+ for (int i = 0; i < state.nodeCount; i++)
3098
+ {
3099
+ if (!state.nodeActive[i])
3100
+ continue;
3101
+ Node *n = &state.nodes[i];
3102
+ if (n->type != NodeType::Camera)
3103
+ continue;
3104
+ if (n->style.display == kDisplayNone)
3105
+ continue;
3106
+ hasVisibleCamera = true;
3107
+ if (nativeOverlay)
3108
+ {
3109
+ // Feed the live visual rect to the provider every frame. (record()
3110
+ // also calls positionPreviewLayer, but it only runs while the node is
3111
+ // dirty — which we deliberately avoid here — so the camera's rect
3112
+ // would otherwise never update.)
3113
+ CameraRenderer::positionNativeOverlay(*n, cameraProvider);
3114
+ continue; // camera owns its rect; presented directly below
3115
+ }
3116
+ n->render.dirty = 1;
3117
+ n->render.layout_dirty = 1;
3118
+ n->render.non_scroll_dirty = 1;
3119
+ // Content-only: the camera's blit command is unchanged frame to frame —
3120
+ // only the surface pixels it points at are refreshed — so there's no
3121
+ // draw-order change. Using the structural markDisplayListDirty() forced a
3122
+ // full-viewport rebuild + flush every frame (the whole 1280x720 panel);
3123
+ // the content variant replays and flushes just this node's rect.
3124
+ markDisplayListContentDirty();
3125
+ changed = 1;
3126
+ }
3127
+ // NativeOverlay: the platform paints the live frame straight into the
3128
+ // framebuffer at the node's rect and flushes only that region — no
3129
+ // display-list blit, no replay. Runs every frame, independent of `changed`.
3130
+ if (nativeOverlay && hasVisibleCamera)
3131
+ cameraProvider->presentNativeOverlay();
3132
+ }
3133
+
3134
+ if (changed)
3135
+ refresh(state.mountedRoot, state.mountedWidth, state.mountedHeight);
3136
+ }
3137
+
3138
+ } // namespace gea::embedded::ui