@geastack/targets 0.1.77

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 (348) hide show
  1. package/LICENSE +674 -0
  2. package/README.md +83 -0
  3. package/package.json +50 -0
  4. package/targets/cmake/geatsc-generated-archive-build.mjs +614 -0
  5. package/targets/cmake/geatsc_generated_archive.cmake +116 -0
  6. package/targets/cmake/geatsc_generated_archive_build.cmake +50 -0
  7. package/targets/esp32/app_project.cmake +33 -0
  8. package/targets/esp32/apps/app_manager.cpp +188 -0
  9. package/targets/esp32/apps/app_manager.h +10 -0
  10. package/targets/esp32/chip_bindings/README.md +58 -0
  11. package/targets/esp32/chip_bindings/audio/es8311.cpp +556 -0
  12. package/targets/esp32/chip_bindings/displays/co5300.cpp +510 -0
  13. package/targets/esp32/chip_bindings/displays/co5300.h +47 -0
  14. package/targets/esp32/chip_bindings/displays/co5300_async_stream.inc +79 -0
  15. package/targets/esp32/chip_bindings/displays/qspi_panel.h +65 -0
  16. package/targets/esp32/chip_bindings/displays/sh8601.cpp +583 -0
  17. package/targets/esp32/chip_bindings/displays/sh8601.h +36 -0
  18. package/targets/esp32/chip_bindings/gps/lc76g.cpp +296 -0
  19. package/targets/esp32/chip_bindings/gps/lc76g.h +7 -0
  20. package/targets/esp32/chip_bindings/imu/bmi270.cpp +299 -0
  21. package/targets/esp32/chip_bindings/imu/bmi270_config.inl +439 -0
  22. package/targets/esp32/chip_bindings/imu/qmi8658.cpp +213 -0
  23. package/targets/esp32/chip_bindings/power/axp2101.cpp +185 -0
  24. package/targets/esp32/chip_bindings/touch/cst9217.cpp +229 -0
  25. package/targets/esp32/chip_bindings/touch/cst9217_controller.h +78 -0
  26. package/targets/esp32/chip_bindings/touch/ft3168.cpp +340 -0
  27. package/targets/esp32/chip_bindings/touch/ft3168_controller.h +103 -0
  28. package/targets/esp32/chip_bindings/touch/ft6336.cpp +310 -0
  29. package/targets/esp32/chip_bindings/touch/ft6336_controller.h +90 -0
  30. package/targets/esp32/components/gea_framework/CMakeLists.txt +62 -0
  31. package/targets/esp32/connectivity/ble_hid.cpp +2916 -0
  32. package/targets/esp32/connectivity/ble_hid.h +8 -0
  33. package/targets/esp32/connectivity/diagnostics_transport.cpp +523 -0
  34. package/targets/esp32/connectivity/diagnostics_transport_offline.cpp +108 -0
  35. package/targets/esp32/connectivity/wifi.cpp +615 -0
  36. package/targets/esp32/connectivity/wifi_debug_offline.cpp +37 -0
  37. package/targets/esp32/connectivity/wifi_task_stack.h +119 -0
  38. package/targets/esp32/display.cpp +6010 -0
  39. package/targets/esp32/display_headless.cpp +468 -0
  40. package/targets/esp32/gea/platform_random.h +11 -0
  41. package/targets/esp32/gea_framework.cmake +382 -0
  42. package/targets/esp32/gpio.cpp +229 -0
  43. package/targets/esp32/host_sources.cmake +35 -0
  44. package/targets/esp32/imu_absent.cpp +36 -0
  45. package/targets/esp32/ldfragments/gea_ui_state_external.lf +35 -0
  46. package/targets/esp32/memory_config.h +64 -0
  47. package/targets/esp32/power_absent.cpp +22 -0
  48. package/targets/esp32/sdk-patches/0001-esp_ptr_dma_capable-accept-PSRAM.patch +70 -0
  49. package/targets/esp32/sdk-patches/0002-gdma-access_ext_mem-spi_master.patch +59 -0
  50. package/targets/esp32/sdk-patches/README.md +127 -0
  51. package/targets/esp32/services/app_runner.cpp +248 -0
  52. package/targets/esp32/services/app_state.cpp +56 -0
  53. package/targets/esp32/services/audio_runtime_stub.cpp +86 -0
  54. package/targets/esp32/services/battery_service.cpp +31 -0
  55. package/targets/esp32/services/device_control.cpp +1896 -0
  56. package/targets/esp32/services/device_control.h +31 -0
  57. package/targets/esp32/services/frame_scheduler.cpp +1571 -0
  58. package/targets/esp32/services/heap.cpp +129 -0
  59. package/targets/esp32/services/memory.cpp +103 -0
  60. package/targets/esp32/services/ota.cpp +840 -0
  61. package/targets/esp32/services/ota_image.cpp +162 -0
  62. package/targets/esp32/services/ota_image.h +16 -0
  63. package/targets/esp32/services/storage_service.cpp +159 -0
  64. package/targets/esp32/touch_absent.cpp +44 -0
  65. package/targets/esp32-m5stack-m5paper/CMakeLists.txt +10 -0
  66. package/targets/esp32-m5stack-m5paper/README.md +55 -0
  67. package/targets/esp32-m5stack-m5paper/dependencies.lock +76 -0
  68. package/targets/esp32-m5stack-m5paper/main/CMakeLists.txt +46 -0
  69. package/targets/esp32-m5stack-m5paper/main/Kconfig.projbuild +10 -0
  70. package/targets/esp32-m5stack-m5paper/main/app_main.cpp +114 -0
  71. package/targets/esp32-m5stack-m5paper/main/audio_stub.cpp +27 -0
  72. package/targets/esp32-m5stack-m5paper/main/buttons.cpp +111 -0
  73. package/targets/esp32-m5stack-m5paper/main/display.cpp +1074 -0
  74. package/targets/esp32-m5stack-m5paper/main/i2c.cpp +36 -0
  75. package/targets/esp32-m5stack-m5paper/main/idf_component.yml +7 -0
  76. package/targets/esp32-m5stack-m5paper/main/imu_stub.cpp +20 -0
  77. package/targets/esp32-m5stack-m5paper/main/include/board.h +100 -0
  78. package/targets/esp32-m5stack-m5paper/main/include/buttons.h +8 -0
  79. package/targets/esp32-m5stack-m5paper/main/launcher_button.cpp +82 -0
  80. package/targets/esp32-m5stack-m5paper/main/m5paper_psram.lf +20 -0
  81. package/targets/esp32-m5stack-m5paper/main/power.cpp +73 -0
  82. package/targets/esp32-m5stack-m5paper/main/sdcard_mount.cpp +82 -0
  83. package/targets/esp32-m5stack-m5paper/main/touch.cpp +279 -0
  84. package/targets/esp32-m5stack-m5paper/partitions.csv +9 -0
  85. package/targets/esp32-m5stack-m5paper/sdkconfig.defaults +84 -0
  86. package/targets/esp32-p4-m5stack-tab5/CMakeLists.txt +10 -0
  87. package/targets/esp32-p4-m5stack-tab5/dependencies.lock +276 -0
  88. package/targets/esp32-p4-m5stack-tab5/main/CMakeLists.txt +586 -0
  89. package/targets/esp32-p4-m5stack-tab5/main/Kconfig.projbuild +12 -0
  90. package/targets/esp32-p4-m5stack-tab5/main/app_main.cpp +177 -0
  91. package/targets/esp32-p4-m5stack-tab5/main/camera.cpp +2025 -0
  92. package/targets/esp32-p4-m5stack-tab5/main/display.cpp +4033 -0
  93. package/targets/esp32-p4-m5stack-tab5/main/fatfs_ffconf.h +383 -0
  94. package/targets/esp32-p4-m5stack-tab5/main/i2c.cpp +39 -0
  95. package/targets/esp32-p4-m5stack-tab5/main/idf_component.yml +21 -0
  96. package/targets/esp32-p4-m5stack-tab5/main/include/board.h +130 -0
  97. package/targets/esp32-p4-m5stack-tab5/main/include/tab5_drivers.h +68 -0
  98. package/targets/esp32-p4-m5stack-tab5/main/include/wifi_config.h.example +5 -0
  99. package/targets/esp32-p4-m5stack-tab5/main/launcher_button.cpp +188 -0
  100. package/targets/esp32-p4-m5stack-tab5/main/power.cpp +22 -0
  101. package/targets/esp32-p4-m5stack-tab5/main/sdcard_mount.cpp +125 -0
  102. package/targets/esp32-p4-m5stack-tab5/main/tab5_audio.cpp +345 -0
  103. package/targets/esp32-p4-m5stack-tab5/main/tab5_drivers.cpp +871 -0
  104. package/targets/esp32-p4-m5stack-tab5/main/tab5_imu.cpp +246 -0
  105. package/targets/esp32-p4-m5stack-tab5/main/touch.cpp +206 -0
  106. package/targets/esp32-p4-m5stack-tab5/partitions.csv +12 -0
  107. package/targets/esp32-p4-m5stack-tab5/sdkconfig.defaults +128 -0
  108. package/targets/esp32-p4-waveshare-touch-lcd-3.5/CMakeLists.txt +19 -0
  109. package/targets/esp32-p4-waveshare-touch-lcd-3.5/component-patches/0001-esp_video-csi-raw-passthrough-p4-rev-lt-v3.patch +28 -0
  110. package/targets/esp32-p4-waveshare-touch-lcd-3.5/component-patches/README.md +45 -0
  111. package/targets/esp32-p4-waveshare-touch-lcd-3.5/component-patches/apply.sh +37 -0
  112. package/targets/esp32-p4-waveshare-touch-lcd-3.5/dependencies.lock +196 -0
  113. package/targets/esp32-p4-waveshare-touch-lcd-3.5/main/CMakeLists.txt +562 -0
  114. package/targets/esp32-p4-waveshare-touch-lcd-3.5/main/Kconfig.projbuild +12 -0
  115. package/targets/esp32-p4-waveshare-touch-lcd-3.5/main/app_main.cpp +166 -0
  116. package/targets/esp32-p4-waveshare-touch-lcd-3.5/main/camera.cpp +2105 -0
  117. package/targets/esp32-p4-waveshare-touch-lcd-3.5/main/display.cpp +1730 -0
  118. package/targets/esp32-p4-waveshare-touch-lcd-3.5/main/fatfs_ffconf.h +383 -0
  119. package/targets/esp32-p4-waveshare-touch-lcd-3.5/main/i2c.cpp +39 -0
  120. package/targets/esp32-p4-waveshare-touch-lcd-3.5/main/idf_component.yml +11 -0
  121. package/targets/esp32-p4-waveshare-touch-lcd-3.5/main/include/board.h +87 -0
  122. package/targets/esp32-p4-waveshare-touch-lcd-3.5/main/include/panel_native.h +59 -0
  123. package/targets/esp32-p4-waveshare-touch-lcd-3.5/main/include/wifi_config.h.example +5 -0
  124. package/targets/esp32-p4-waveshare-touch-lcd-3.5/main/launcher_button.cpp +191 -0
  125. package/targets/esp32-p4-waveshare-touch-lcd-3.5/main/power.cpp +15 -0
  126. package/targets/esp32-p4-waveshare-touch-lcd-3.5/main/touch.cpp +306 -0
  127. package/targets/esp32-p4-waveshare-touch-lcd-3.5/partitions.csv +13 -0
  128. package/targets/esp32-p4-waveshare-touch-lcd-3.5/patches/README.md +22 -0
  129. package/targets/esp32-p4-waveshare-touch-lcd-3.5/patches/espressif__esp_video-csi-bypass.patch +28 -0
  130. package/targets/esp32-p4-waveshare-touch-lcd-3.5/sdkconfig.defaults +109 -0
  131. package/targets/esp32-p4-waveshare-touch-lcd-3.5/tools/README-camera-capture.md +84 -0
  132. package/targets/esp32-p4-waveshare-touch-lcd-3.5/tools/capture-camera.py +369 -0
  133. package/targets/esp32-p4-waveshare-touch-lcd-7/CMakeLists.txt +10 -0
  134. package/targets/esp32-p4-waveshare-touch-lcd-7/dependencies.lock +258 -0
  135. package/targets/esp32-p4-waveshare-touch-lcd-7/main/CMakeLists.txt +577 -0
  136. package/targets/esp32-p4-waveshare-touch-lcd-7/main/Kconfig.projbuild +12 -0
  137. package/targets/esp32-p4-waveshare-touch-lcd-7/main/app_main.cpp +177 -0
  138. package/targets/esp32-p4-waveshare-touch-lcd-7/main/camera.cpp +1935 -0
  139. package/targets/esp32-p4-waveshare-touch-lcd-7/main/display.cpp +2832 -0
  140. package/targets/esp32-p4-waveshare-touch-lcd-7/main/fatfs_ffconf.h +383 -0
  141. package/targets/esp32-p4-waveshare-touch-lcd-7/main/i2c.cpp +39 -0
  142. package/targets/esp32-p4-waveshare-touch-lcd-7/main/idf_component.yml +23 -0
  143. package/targets/esp32-p4-waveshare-touch-lcd-7/main/include/board.h +68 -0
  144. package/targets/esp32-p4-waveshare-touch-lcd-7/main/include/wifi_config.h.example +5 -0
  145. package/targets/esp32-p4-waveshare-touch-lcd-7/main/launcher_button.cpp +191 -0
  146. package/targets/esp32-p4-waveshare-touch-lcd-7/main/power.cpp +15 -0
  147. package/targets/esp32-p4-waveshare-touch-lcd-7/main/sdcard_mount.cpp +125 -0
  148. package/targets/esp32-p4-waveshare-touch-lcd-7/main/touch.cpp +332 -0
  149. package/targets/esp32-p4-waveshare-touch-lcd-7/partitions.csv +12 -0
  150. package/targets/esp32-p4-waveshare-touch-lcd-7/sdkconfig.defaults +122 -0
  151. package/targets/esp32-p4-waveshare-touch-lcd-7/tools/README-camera-capture.md +84 -0
  152. package/targets/esp32-p4-waveshare-touch-lcd-7/tools/capture-camera.py +369 -0
  153. package/targets/esp32-s3-devkit-n16r8.json +31 -0
  154. package/targets/esp32-s3-elecrow-rotary-2.1/CMakeLists.txt +10 -0
  155. package/targets/esp32-s3-elecrow-rotary-2.1/dependencies.lock +40 -0
  156. package/targets/esp32-s3-elecrow-rotary-2.1/main/CMakeLists.txt +549 -0
  157. package/targets/esp32-s3-elecrow-rotary-2.1/main/Kconfig.projbuild +12 -0
  158. package/targets/esp32-s3-elecrow-rotary-2.1/main/app_main.cpp +187 -0
  159. package/targets/esp32-s3-elecrow-rotary-2.1/main/display_rgb.cpp +1338 -0
  160. package/targets/esp32-s3-elecrow-rotary-2.1/main/i2c.cpp +39 -0
  161. package/targets/esp32-s3-elecrow-rotary-2.1/main/idf_component.yml +5 -0
  162. package/targets/esp32-s3-elecrow-rotary-2.1/main/include/board.h +142 -0
  163. package/targets/esp32-s3-elecrow-rotary-2.1/main/include/pcf8574.h +16 -0
  164. package/targets/esp32-s3-elecrow-rotary-2.1/main/include/rotary_encoder.h +7 -0
  165. package/targets/esp32-s3-elecrow-rotary-2.1/main/launcher_button.cpp +191 -0
  166. package/targets/esp32-s3-elecrow-rotary-2.1/main/pcf8574.cpp +86 -0
  167. package/targets/esp32-s3-elecrow-rotary-2.1/main/platform_stubs.cpp +47 -0
  168. package/targets/esp32-s3-elecrow-rotary-2.1/main/rotary_encoder.cpp +135 -0
  169. package/targets/esp32-s3-elecrow-rotary-2.1/main/touch.cpp +250 -0
  170. package/targets/esp32-s3-elecrow-rotary-2.1/partitions.csv +8 -0
  171. package/targets/esp32-s3-elecrow-rotary-2.1/sdkconfig.defaults +116 -0
  172. package/targets/esp32-s3-epaper-1.54/CMakeLists.txt +10 -0
  173. package/targets/esp32-s3-epaper-1.54/dependencies.lock +76 -0
  174. package/targets/esp32-s3-epaper-1.54/main/CMakeLists.txt +691 -0
  175. package/targets/esp32-s3-epaper-1.54/main/Kconfig.projbuild +12 -0
  176. package/targets/esp32-s3-epaper-1.54/main/app_main.cpp +181 -0
  177. package/targets/esp32-s3-epaper-1.54/main/buttons.cpp +144 -0
  178. package/targets/esp32-s3-epaper-1.54/main/display.cpp +1281 -0
  179. package/targets/esp32-s3-epaper-1.54/main/fatfs_ffconf.h +377 -0
  180. package/targets/esp32-s3-epaper-1.54/main/i2c.cpp +39 -0
  181. package/targets/esp32-s3-epaper-1.54/main/idf_component.yml +7 -0
  182. package/targets/esp32-s3-epaper-1.54/main/imu_stub.cpp +21 -0
  183. package/targets/esp32-s3-epaper-1.54/main/include/board.h +119 -0
  184. package/targets/esp32-s3-epaper-1.54/main/include/buttons.h +9 -0
  185. package/targets/esp32-s3-epaper-1.54/main/include/wifi_config.h.example +5 -0
  186. package/targets/esp32-s3-epaper-1.54/main/launcher_button.cpp +191 -0
  187. package/targets/esp32-s3-epaper-1.54/main/power.cpp +15 -0
  188. package/targets/esp32-s3-epaper-1.54/main/sdcard_mount.cpp +89 -0
  189. package/targets/esp32-s3-epaper-1.54/main/touch.cpp +299 -0
  190. package/targets/esp32-s3-epaper-1.54/partitions.csv +8 -0
  191. package/targets/esp32-s3-epaper-1.54/sdkconfig.defaults +217 -0
  192. package/targets/esp32-s3-lilygo-t-display-s3-long/CMakeLists.txt +10 -0
  193. package/targets/esp32-s3-lilygo-t-display-s3-long/README.md +29 -0
  194. package/targets/esp32-s3-lilygo-t-display-s3-long/dependencies.lock +116 -0
  195. package/targets/esp32-s3-lilygo-t-display-s3-long/main/CMakeLists.txt +90 -0
  196. package/targets/esp32-s3-lilygo-t-display-s3-long/main/idf_component.yml +7 -0
  197. package/targets/esp32-s3-lilygo-t-display-s3-long/main/include/board.h +61 -0
  198. package/targets/esp32-s3-lilygo-t-display-s3-long/main/touch.cpp +299 -0
  199. package/targets/esp32-s3-lilygo-t-display-s3-long/partitions.csv +7 -0
  200. package/targets/esp32-s3-lilygo-t-display-s3-long/sdkconfig.defaults +50 -0
  201. package/targets/esp32-s3-lilygo-t5-epaper-4.7/CMakeLists.txt +12 -0
  202. package/targets/esp32-s3-lilygo-t5-epaper-4.7/components/epd_driver/CMakeLists.txt +17 -0
  203. package/targets/esp32-s3-lilygo-t5-epaper-4.7/components/epd_driver/ed047tc1.c +269 -0
  204. package/targets/esp32-s3-lilygo-t5-epaper-4.7/components/epd_driver/ed047tc1.h +142 -0
  205. package/targets/esp32-s3-lilygo-t5-epaper-4.7/components/epd_driver/epd_driver.c +1114 -0
  206. package/targets/esp32-s3-lilygo-t5-epaper-4.7/components/epd_driver/epd_driver.h +410 -0
  207. package/targets/esp32-s3-lilygo-t5-epaper-4.7/components/epd_driver/gea_epd.c +989 -0
  208. package/targets/esp32-s3-lilygo-t5-epaper-4.7/components/epd_driver/i2s_data_bus.c +489 -0
  209. package/targets/esp32-s3-lilygo-t5-epaper-4.7/components/epd_driver/i2s_data_bus.h +104 -0
  210. package/targets/esp32-s3-lilygo-t5-epaper-4.7/components/epd_driver/rmt_pulse.c +136 -0
  211. package/targets/esp32-s3-lilygo-t5-epaper-4.7/components/epd_driver/rmt_pulse.h +78 -0
  212. package/targets/esp32-s3-lilygo-t5-epaper-4.7/components/epd_driver/utilities.h +49 -0
  213. package/targets/esp32-s3-lilygo-t5-epaper-4.7/dependencies.lock +35 -0
  214. package/targets/esp32-s3-lilygo-t5-epaper-4.7/main/CMakeLists.txt +30 -0
  215. package/targets/esp32-s3-lilygo-t5-epaper-4.7/main/Kconfig.projbuild +10 -0
  216. package/targets/esp32-s3-lilygo-t5-epaper-4.7/main/app_main.cpp +95 -0
  217. package/targets/esp32-s3-lilygo-t5-epaper-4.7/main/audio_stub.cpp +27 -0
  218. package/targets/esp32-s3-lilygo-t5-epaper-4.7/main/buttons.cpp +40 -0
  219. package/targets/esp32-s3-lilygo-t5-epaper-4.7/main/display.cpp +627 -0
  220. package/targets/esp32-s3-lilygo-t5-epaper-4.7/main/i2c.cpp +36 -0
  221. package/targets/esp32-s3-lilygo-t5-epaper-4.7/main/idf_component.yml +4 -0
  222. package/targets/esp32-s3-lilygo-t5-epaper-4.7/main/imu_stub.cpp +20 -0
  223. package/targets/esp32-s3-lilygo-t5-epaper-4.7/main/include/board.h +85 -0
  224. package/targets/esp32-s3-lilygo-t5-epaper-4.7/main/include/buttons.h +8 -0
  225. package/targets/esp32-s3-lilygo-t5-epaper-4.7/main/launcher_button.cpp +82 -0
  226. package/targets/esp32-s3-lilygo-t5-epaper-4.7/main/power.cpp +36 -0
  227. package/targets/esp32-s3-lilygo-t5-epaper-4.7/main/sdcard_mount.cpp +90 -0
  228. package/targets/esp32-s3-lilygo-t5-epaper-4.7/main/touch.cpp +293 -0
  229. package/targets/esp32-s3-lilygo-t5-epaper-4.7/partitions.csv +9 -0
  230. package/targets/esp32-s3-lilygo-t5-epaper-4.7/sdkconfig.defaults +217 -0
  231. package/targets/esp32-s3-m5stack-papers3/CMakeLists.txt +13 -0
  232. package/targets/esp32-s3-m5stack-papers3/components/papers3_epd/CMakeLists.txt +5 -0
  233. package/targets/esp32-s3-m5stack-papers3/components/papers3_epd/include/papers3_epd.h +74 -0
  234. package/targets/esp32-s3-m5stack-papers3/components/papers3_epd/papers3_epd.c +671 -0
  235. package/targets/esp32-s3-m5stack-papers3/dependencies.lock +76 -0
  236. package/targets/esp32-s3-m5stack-papers3/main/CMakeLists.txt +64 -0
  237. package/targets/esp32-s3-m5stack-papers3/main/Kconfig.projbuild +10 -0
  238. package/targets/esp32-s3-m5stack-papers3/main/app_main.cpp +96 -0
  239. package/targets/esp32-s3-m5stack-papers3/main/audio_stub.cpp +27 -0
  240. package/targets/esp32-s3-m5stack-papers3/main/buttons.cpp +49 -0
  241. package/targets/esp32-s3-m5stack-papers3/main/display.cpp +706 -0
  242. package/targets/esp32-s3-m5stack-papers3/main/i2c.cpp +36 -0
  243. package/targets/esp32-s3-m5stack-papers3/main/idf_component.yml +14 -0
  244. package/targets/esp32-s3-m5stack-papers3/main/imu.cpp +351 -0
  245. package/targets/esp32-s3-m5stack-papers3/main/include/board.h +101 -0
  246. package/targets/esp32-s3-m5stack-papers3/main/include/buttons.h +8 -0
  247. package/targets/esp32-s3-m5stack-papers3/main/launcher_button.cpp +96 -0
  248. package/targets/esp32-s3-m5stack-papers3/main/power.cpp +102 -0
  249. package/targets/esp32-s3-m5stack-papers3/main/sdcard_mount.cpp +88 -0
  250. package/targets/esp32-s3-m5stack-papers3/main/touch.cpp +287 -0
  251. package/targets/esp32-s3-m5stack-papers3/partitions.csv +9 -0
  252. package/targets/esp32-s3-m5stack-papers3/sdkconfig.defaults +232 -0
  253. package/targets/esp32-s3-m5stack-sticks3/CMakeLists.txt +10 -0
  254. package/targets/esp32-s3-m5stack-sticks3/dependencies.lock +51 -0
  255. package/targets/esp32-s3-m5stack-sticks3/main/CMakeLists.txt +51 -0
  256. package/targets/esp32-s3-m5stack-sticks3/main/Kconfig.projbuild +12 -0
  257. package/targets/esp32-s3-m5stack-sticks3/main/app_main.cpp +130 -0
  258. package/targets/esp32-s3-m5stack-sticks3/main/buttons.cpp +101 -0
  259. package/targets/esp32-s3-m5stack-sticks3/main/display.cpp +1391 -0
  260. package/targets/esp32-s3-m5stack-sticks3/main/i2c.cpp +39 -0
  261. package/targets/esp32-s3-m5stack-sticks3/main/idf_component.yml +8 -0
  262. package/targets/esp32-s3-m5stack-sticks3/main/imu_stub.cpp +9 -0
  263. package/targets/esp32-s3-m5stack-sticks3/main/include/board.h +89 -0
  264. package/targets/esp32-s3-m5stack-sticks3/main/include/buttons.h +9 -0
  265. package/targets/esp32-s3-m5stack-sticks3/main/launcher_button.cpp +191 -0
  266. package/targets/esp32-s3-m5stack-sticks3/main/power.cpp +15 -0
  267. package/targets/esp32-s3-m5stack-sticks3/main/sdcard_mount.cpp +8 -0
  268. package/targets/esp32-s3-m5stack-sticks3/main/touch.cpp +65 -0
  269. package/targets/esp32-s3-m5stack-sticks3/partitions.csv +8 -0
  270. package/targets/esp32-s3-m5stack-sticks3/sdkconfig.defaults +130 -0
  271. package/targets/esp32-s3-touch-amoled-1.75/CMakeLists.txt +10 -0
  272. package/targets/esp32-s3-touch-amoled-1.75/dependencies.lock +130 -0
  273. package/targets/esp32-s3-touch-amoled-1.75/main/CMakeLists.txt +589 -0
  274. package/targets/esp32-s3-touch-amoled-1.75/main/Kconfig.projbuild +12 -0
  275. package/targets/esp32-s3-touch-amoled-1.75/main/app_main.cpp +153 -0
  276. package/targets/esp32-s3-touch-amoled-1.75/main/i2c.cpp +39 -0
  277. package/targets/esp32-s3-touch-amoled-1.75/main/idf_component.yml +9 -0
  278. package/targets/esp32-s3-touch-amoled-1.75/main/include/board.h +110 -0
  279. package/targets/esp32-s3-touch-amoled-1.75/main/include/wifi_config.h.example +5 -0
  280. package/targets/esp32-s3-touch-amoled-1.75/main/launcher_button.cpp +191 -0
  281. package/targets/esp32-s3-touch-amoled-1.75/main/touch.cpp +45 -0
  282. package/targets/esp32-s3-touch-amoled-1.75/partitions.csv +8 -0
  283. package/targets/esp32-s3-touch-amoled-1.75/sdkconfig.defaults +179 -0
  284. package/targets/esp32-s3-touch-amoled-1.8/CMakeLists.txt +10 -0
  285. package/targets/esp32-s3-touch-amoled-1.8/dependencies.lock +105 -0
  286. package/targets/esp32-s3-touch-amoled-1.8/main/CMakeLists.txt +768 -0
  287. package/targets/esp32-s3-touch-amoled-1.8/main/Kconfig.projbuild +12 -0
  288. package/targets/esp32-s3-touch-amoled-1.8/main/app_main.cpp +172 -0
  289. package/targets/esp32-s3-touch-amoled-1.8/main/i2c.cpp +39 -0
  290. package/targets/esp32-s3-touch-amoled-1.8/main/idf_component.yml +8 -0
  291. package/targets/esp32-s3-touch-amoled-1.8/main/include/board.h +83 -0
  292. package/targets/esp32-s3-touch-amoled-1.8/main/include/wifi_config.h.example +5 -0
  293. package/targets/esp32-s3-touch-amoled-1.8/main/launcher_button.cpp +191 -0
  294. package/targets/esp32-s3-touch-amoled-1.8/main/touch.cpp +41 -0
  295. package/targets/esp32-s3-touch-amoled-1.8/partitions.csv +8 -0
  296. package/targets/esp32-s3-touch-amoled-1.8/sdkconfig.defaults +179 -0
  297. package/targets/esp32-s3-touch-amoled-2.06/CMakeLists.txt +10 -0
  298. package/targets/esp32-s3-touch-amoled-2.06/dependencies.lock +64 -0
  299. package/targets/esp32-s3-touch-amoled-2.06/main/CMakeLists.txt +1121 -0
  300. package/targets/esp32-s3-touch-amoled-2.06/main/Kconfig.projbuild +12 -0
  301. package/targets/esp32-s3-touch-amoled-2.06/main/app_main.cpp +333 -0
  302. package/targets/esp32-s3-touch-amoled-2.06/main/i2c.cpp +39 -0
  303. package/targets/esp32-s3-touch-amoled-2.06/main/idf_component.yml +27 -0
  304. package/targets/esp32-s3-touch-amoled-2.06/main/include/board.h +114 -0
  305. package/targets/esp32-s3-touch-amoled-2.06/main/include/wifi_config.h.example +5 -0
  306. package/targets/esp32-s3-touch-amoled-2.06/main/launcher_button.cpp +199 -0
  307. package/targets/esp32-s3-touch-amoled-2.06/main/sdcard_mount.cpp +105 -0
  308. package/targets/esp32-s3-touch-amoled-2.06/main/touch.cpp +49 -0
  309. package/targets/esp32-s3-touch-amoled-2.06/partitions.csv +14 -0
  310. package/targets/esp32-s3-touch-amoled-2.06/sdkconfig.defaults +273 -0
  311. package/targets/esp32-s3-touch-amoled-2.41/CMakeLists.txt +10 -0
  312. package/targets/esp32-s3-touch-amoled-2.41/main/CMakeLists.txt +71 -0
  313. package/targets/esp32-s3-touch-amoled-2.41/main/Kconfig.projbuild +12 -0
  314. package/targets/esp32-s3-touch-amoled-2.41/main/idf_component.yml +27 -0
  315. package/targets/esp32-s3-touch-amoled-2.41/main/include/board.h +108 -0
  316. package/targets/esp32-s3-touch-amoled-2.41/main/include/wifi_config.h.example +5 -0
  317. package/targets/esp32-s3-touch-amoled-2.41/main/panel_reset.cpp +82 -0
  318. package/targets/esp32-s3-touch-amoled-2.41/main/touch.cpp +49 -0
  319. package/targets/esp32-s3-touch-amoled-2.41/partitions.csv +8 -0
  320. package/targets/esp32-s3-touch-amoled-2.41/sdkconfig.defaults +273 -0
  321. package/targets/rp2350-tufty-2350/CMakeLists.txt +348 -0
  322. package/targets/rp2350-tufty-2350/README.md +53 -0
  323. package/targets/rp2350-tufty-2350/boards/pimoroni_tufty2350.h +87 -0
  324. package/targets/rp2350-tufty-2350/main/bringup.cpp +187 -0
  325. package/targets/rp2350-tufty-2350/main/include/board.h +124 -0
  326. package/targets/rp2350-tufty-2350/main/rp2350_panel.cpp +428 -0
  327. package/targets/rp2350-tufty-2350/main/rp2350_panel.h +46 -0
  328. package/targets/rp2350-tufty-2350/main/st7789_parallel.pio +7 -0
  329. package/targets/rp2350-waveshare-touch-amoled-2.41/CMakeLists.txt +345 -0
  330. package/targets/rp2350-waveshare-touch-amoled-2.41/README.md +153 -0
  331. package/targets/rp2350-waveshare-touch-amoled-2.41/boards/waveshare_rp2350_touch_amoled_2_41.h +59 -0
  332. package/targets/rp2350-waveshare-touch-amoled-2.41/main/app.cpp +984 -0
  333. package/targets/rp2350-waveshare-touch-amoled-2.41/main/bringup.cpp +222 -0
  334. package/targets/rp2350-waveshare-touch-amoled-2.41/main/include/board.h +138 -0
  335. package/targets/rp2350-waveshare-touch-amoled-2.41/main/rp2350_gea_platform.cpp +2553 -0
  336. package/targets/rp2350-waveshare-touch-amoled-2.41/main/rp2350_gea_platform.h +18 -0
  337. package/targets/rp2350-waveshare-touch-amoled-2.41/main/rp2350_host_fetch_stub.cpp +64 -0
  338. package/targets/rp2350-waveshare-touch-amoled-2.41/main/rp2350_panel.cpp +677 -0
  339. package/targets/rp2350-waveshare-touch-amoled-2.41/main/rp2350_panel.h +48 -0
  340. package/targets/rp2350-waveshare-touch-amoled-2.41/main/vendor/waveshare_psram/rp_pico_alloc.c +354 -0
  341. package/targets/rp2350-waveshare-touch-amoled-2.41/main/vendor/waveshare_psram/rp_pico_alloc.h +56 -0
  342. package/targets/rp2350-waveshare-touch-amoled-2.41/main/vendor/waveshare_psram/tlsf/tlsf.c +1284 -0
  343. package/targets/rp2350-waveshare-touch-amoled-2.41/main/vendor/waveshare_psram/tlsf/tlsf.h +95 -0
  344. package/targets/rp2350-waveshare-touch-amoled-2.41/main/vendor/waveshare_psram/tlsf/tlsf_block_functions.h +123 -0
  345. package/targets/rp2350-waveshare-touch-amoled-2.41/main/vendor/waveshare_psram/tlsf/tlsf_common.h +127 -0
  346. package/targets/rp2350-waveshare-touch-amoled-2.41/tools/rp2350-scroll-bench.py +162 -0
  347. package/targets/rp2350-waveshare-touch-amoled-2.41/tools/rp2350-scroll-parity.py +198 -0
  348. package/targets.json +154 -0
@@ -0,0 +1,4033 @@
1
+ #include "display.h"
2
+
3
+ #include "board.h"
4
+ #include "canvas.h"
5
+ #include "display_present.h"
6
+ #include "host/display_orientation.h"
7
+ #include "pixel.h"
8
+ #include "tab5_drivers.h"
9
+
10
+ #include <algorithm>
11
+ #include <atomic>
12
+ #include <cstddef>
13
+ #include <cstdint>
14
+ #include <cstring>
15
+ #include <new>
16
+ #include <utility>
17
+
18
+ #include "driver/ledc.h"
19
+ #include "driver/ppa.h"
20
+ #include "esp_cache.h"
21
+ #include "esp_err.h"
22
+ #include "esp_heap_caps.h"
23
+ #include "esp_lcd_mipi_dsi.h"
24
+ #include "esp_lcd_panel_io.h"
25
+ #include "esp_async_memcpy.h"
26
+ #include "esp_lcd_panel_ops.h"
27
+ #include "esp_ldo_regulator.h"
28
+ #include "esp_log.h"
29
+ #include "esp_timer.h"
30
+ #include "esp_private/esp_cache_private.h"
31
+ #include "freertos/FreeRTOS.h"
32
+ #include "freertos/semphr.h"
33
+ #include "freertos/task.h"
34
+ #include "hal/cache_hal.h"
35
+ #include "hal/cache_ll.h"
36
+
37
+ namespace platform_display = gea::platform::display;
38
+ namespace orientation_detail = gea::framework::display::detail;
39
+ namespace pixel = gea::framework::graphics::pixel;
40
+ namespace present = gea::framework::display_present;
41
+
42
+ extern "C" bool gea_render_parallel_submit(void (*fn)(void *, int, int), void *ctx, int y0, int y1);
43
+ extern "C" void gea_render_parallel_wait();
44
+
45
+ namespace gea::platform::esp32_p4_m5stack_tab5::display {
46
+
47
+ namespace {
48
+
49
+ constexpr const char *kTag = "m5stack_tab5_display";
50
+ constexpr int kNativeWidth = platform_display::kNativeWidth;
51
+ constexpr int kNativeHeight = platform_display::kNativeHeight;
52
+ constexpr int kMaxLogicalWidth = kNativeHeight > kNativeWidth ? kNativeHeight : kNativeWidth;
53
+ constexpr int kMaxLogicalHeight = kNativeHeight;
54
+ constexpr int kMaxPixels = kNativeWidth * kNativeHeight;
55
+ constexpr int kFlushRowsDefault = 64;
56
+ constexpr int kDsiLaneCount = 2;
57
+ constexpr float kDsiLaneBitrateMbps = 1000.0f;
58
+ constexpr float kDpiClockMhz = 80.0f;
59
+ constexpr pixel::Format kFramebufferPixelFormat = pixel::Format::Rgb565;
60
+ constexpr pixel::Format kDsiOutputPixelFormat = pixel::Format::Rgb565;
61
+ constexpr int kPanelBitsPerPixel = pixel::bitsPerPixel(kDsiOutputPixelFormat);
62
+ // Two DPI scanout framebuffers. Native portrait UI renders into the non-scanned
63
+ // buffer, syncs touched row bands, then swaps the DPI framebuffer index; full-screen
64
+ // direct producers (camera/tile paths) use the same back-buffer flip model.
65
+ constexpr int kDpiFrameBufferCount = 3;
66
+ constexpr int kDsiPhyLdoChannel = 3;
67
+ constexpr int kDsiPhyLdoVoltageMv = 2500;
68
+ constexpr ledc_channel_t kBacklightLedcChannel = LEDC_CHANNEL_1;
69
+ constexpr ledc_timer_t kBacklightLedcTimer = LEDC_TIMER_1;
70
+ constexpr int kBacklightLedcMaxDuty = 1023;
71
+ constexpr int kMaxPresentRects = 16;
72
+ constexpr int kMaxFlushRects = 64;
73
+ constexpr int kCircleDeltaMax = 96;
74
+ constexpr int kCircleDeltaMaxShift = 16;
75
+ constexpr int kCircleSpanCacheMaxRadius = 256;
76
+ constexpr int kCpuPanelMapFlushMaxPixels = 4096;
77
+ constexpr int kOwnedFrameBufferPixels = kMaxPixels;
78
+ #ifndef GEA_EMBEDDED_RENDER_PARALLEL_MIN_ROWS
79
+ #define GEA_EMBEDDED_RENDER_PARALLEL_MIN_ROWS 96
80
+ #endif
81
+ #ifndef GEA_EMBEDDED_RENDER_PARALLEL_MIN_PIXELS
82
+ #define GEA_EMBEDDED_RENDER_PARALLEL_MIN_PIXELS 65536
83
+ #endif
84
+ constexpr int kPresentParallelMinRows = GEA_EMBEDDED_RENDER_PARALLEL_MIN_ROWS;
85
+ constexpr int kPresentParallelMinPixels = GEA_EMBEDDED_RENDER_PARALLEL_MIN_PIXELS;
86
+ constexpr std::uint32_t kAsyncPresentStackBytes = 12288;
87
+
88
+ struct PanelCoord {
89
+ int x = 0;
90
+ int y = 0;
91
+ };
92
+
93
+ struct PresentRasterBand {
94
+ std::uint16_t *base = nullptr;
95
+ int stridePixels = 0;
96
+ int regionX0 = 0;
97
+ int regionWidth = 0;
98
+ int logicalY0 = 0;
99
+ int displayHeight = 0;
100
+ int maxRows = 1;
101
+ const present::Frame *frame = nullptr;
102
+ };
103
+
104
+ void rasterPresentBandRows(PresentRasterBand &job, int row0, int row1)
105
+ {
106
+ if (!job.base || !job.frame || job.regionWidth <= 0 || job.maxRows <= 0 || row0 > row1) return;
107
+ for (int r = row0; r <= row1; r += job.maxRows) {
108
+ int rows = job.maxRows;
109
+ if (r + rows > row1 + 1) rows = row1 - r + 1;
110
+ std::uint16_t *target = job.base + static_cast<std::size_t>(r) * job.stridePixels;
111
+ present::rasterFrameRowsStrided(target,
112
+ job.stridePixels,
113
+ job.regionX0,
114
+ job.regionWidth,
115
+ job.logicalY0 + r,
116
+ rows,
117
+ job.displayHeight,
118
+ *job.frame);
119
+ }
120
+ }
121
+
122
+ void rasterPresentBandThunk(void *ctx, int y0, int y1)
123
+ {
124
+ auto *job = static_cast<PresentRasterBand *>(ctx);
125
+ if (!job) return;
126
+ rasterPresentBandRows(*job, y0, y1);
127
+ }
128
+
129
+ constexpr lcd_color_format_t lcdColorFormat(pixel::Format format)
130
+ {
131
+ switch (format) {
132
+ case pixel::Format::Rgb565:
133
+ return LCD_COLOR_FMT_RGB565;
134
+ case pixel::Format::Rgb888:
135
+ return LCD_COLOR_FMT_RGB888;
136
+ case pixel::Format::Rgba8888:
137
+ case pixel::Format::Argb8888:
138
+ break;
139
+ }
140
+ return LCD_COLOR_FMT_RGB565;
141
+ }
142
+
143
+ PanelCoord panelForSourcePixel(int sourceX, int sourceY)
144
+ {
145
+ using gea::framework::display::DisplayOrientation;
146
+ switch (orientation_detail::DisplayOrientationState::orientation()) {
147
+ case DisplayOrientation::PortraitSecondary:
148
+ return {kNativeWidth - 1 - sourceX, kNativeHeight - 1 - sourceY};
149
+ case DisplayOrientation::LandscapePrimary:
150
+ return {sourceY, kNativeHeight - 1 - sourceX};
151
+ case DisplayOrientation::LandscapeSecondary:
152
+ return {kNativeWidth - 1 - sourceY, sourceX};
153
+ case DisplayOrientation::PortraitPrimary:
154
+ default:
155
+ return {sourceX, sourceY};
156
+ }
157
+ }
158
+
159
+ present::Rect clampLogicalRect(present::Rect rect, int width, int height)
160
+ {
161
+ if (width <= 0 || height <= 0) return {};
162
+ rect = present::clampAndAlign(rect, width, height);
163
+ if (!present::valid(rect)) return {};
164
+ return rect;
165
+ }
166
+
167
+ int integerSqrt(int n)
168
+ {
169
+ if (n <= 0) return 0;
170
+ int x = n;
171
+ int y = (x + 1) / 2;
172
+ while (y < x) {
173
+ x = y;
174
+ y = (x + n / x) / 2;
175
+ }
176
+ return x;
177
+ }
178
+
179
+ present::Rect physicalBoundsForLogicalRect(const present::Rect &logical)
180
+ {
181
+ if (!present::valid(logical)) return {};
182
+ const PanelCoord corners[] = {
183
+ panelForSourcePixel(logical.x0, logical.y0),
184
+ panelForSourcePixel(logical.x1, logical.y0),
185
+ panelForSourcePixel(logical.x0, logical.y1),
186
+ panelForSourcePixel(logical.x1, logical.y1),
187
+ };
188
+ present::Rect out{corners[0].x, corners[0].y, corners[0].x, corners[0].y};
189
+ for (const PanelCoord &corner : corners) {
190
+ if (corner.x < out.x0) out.x0 = corner.x;
191
+ if (corner.y < out.y0) out.y0 = corner.y;
192
+ if (corner.x > out.x1) out.x1 = corner.x;
193
+ if (corner.y > out.y1) out.y1 = corner.y;
194
+ }
195
+ return present::clampAndAlign(out, kNativeWidth, kNativeHeight);
196
+ }
197
+
198
+ long long rectArea64(const present::Rect &rect)
199
+ {
200
+ if (!present::valid(rect)) return 0;
201
+ return static_cast<long long>(rect.x1 - rect.x0 + 1) * (rect.y1 - rect.y0 + 1);
202
+ }
203
+
204
+ } // namespace
205
+
206
+ class DisplayBackend {
207
+ public:
208
+ static DisplayBackend &instance()
209
+ {
210
+ static DisplayBackend backend;
211
+ return backend;
212
+ }
213
+
214
+ bool init()
215
+ {
216
+ if (initialized_) return true;
217
+ mutex_ = xSemaphoreCreateMutex();
218
+ if (!mutex_) {
219
+ ESP_LOGE(kTag, "failed to allocate display mutex");
220
+ return false;
221
+ }
222
+
223
+ // 128-byte aligned so the PPA can target it as an output picture (the
224
+ // camera's direct-present scales straight into this framebuffer). PPA
225
+ // output to PSRAM requires the buffer base + size aligned to the cache
226
+ // line; round the size up to match.
227
+ {
228
+ const std::size_t fbBytes =
229
+ (static_cast<std::size_t>(kOwnedFrameBufferPixels) * sizeof(std::uint16_t) + 127) & ~static_cast<std::size_t>(127);
230
+ ownedFrameBuffer_ = static_cast<std::uint16_t *>(
231
+ heap_caps_aligned_alloc(128, fbBytes, MALLOC_CAP_SPIRAM | MALLOC_CAP_DMA | MALLOC_CAP_8BIT));
232
+ if (ownedFrameBuffer_) std::memset(ownedFrameBuffer_, 0, fbBytes);
233
+ }
234
+ if (!ownedFrameBuffer_) {
235
+ ESP_LOGE(kTag, "display owned framebuffer alloc failed");
236
+ return false;
237
+ }
238
+
239
+ if (!initPanel()) {
240
+ ESP_LOGE(kTag, "panel init failed");
241
+ return false;
242
+ }
243
+ bindCanvas();
244
+ if (frameBuffer_) {
245
+ std::memset(frameBuffer_, 0, static_cast<std::size_t>(kMaxPixels) * sizeof(std::uint16_t));
246
+ }
247
+ initialized_ = true;
248
+ ESP_LOGI(kTag, "display ready native=%dx%d logical=%dx%d", kNativeWidth, kNativeHeight, logicalWidth(), logicalHeight());
249
+ return true;
250
+ }
251
+
252
+ bool start() { return init(); }
253
+
254
+ gea::framework::graphics::Canvas *canvas()
255
+ {
256
+ waitForAsyncPresent();
257
+ prepareDrawingTarget();
258
+ return &replayCanvas();
259
+ }
260
+
261
+ // Public accessor: is canvas() the panel scanout buffer (no logical->panel
262
+ // rotation)? Used by the camera direct-present to skip the rotate-flush.
263
+ bool framebufferIsPanelDirect() const { return usingPanelFrameBufferDirectly(); }
264
+ bool snapshotPrefersPresented() const { return panelDirectActive_ && panelFrameBuffers_[scannedFbIndex_] != nullptr; }
265
+
266
+ // The portrait scanout buffer the camera can PPA straight into for its preview
267
+ // rect. Valid whenever the panel framebuffer is the un-rotated portrait scanout
268
+ // (logical coords == panel coords), independent of where the UI composes — so it
269
+ // stays available even though the UI now composes off-screen into ownedFrameBuffer_.
270
+ bool panelScanoutSurface(std::uint16_t **outBuffer, int *outW, int *outH) const
271
+ {
272
+ using gea::framework::display::DisplayOrientation;
273
+ if (!panelFrameBuffer_ ||
274
+ orientation_detail::DisplayOrientationState::orientation() != DisplayOrientation::PortraitPrimary ||
275
+ logicalStride_ != kNativeWidth) {
276
+ return false;
277
+ }
278
+ if (outBuffer) *outBuffer = panelFrameBuffer_;
279
+ if (outW) *outW = kNativeWidth;
280
+ if (outH) *outH = kNativeHeight;
281
+ return true;
282
+ }
283
+
284
+ // One-pass camera→panel target (see Display::panelDirectTarget). The panel scanout
285
+ // buffer always exists, so this works in ANY orientation: the camera composes its own
286
+ // sensor rotation with the orientation's rotation steps and scales+rotates straight
287
+ // into the panel, eliminating the off-screen landscape canvas + second rotate flush.
288
+ bool panelDirectTarget(int logicalX, int logicalY, int logicalW, int logicalH,
289
+ std::uint16_t **outBuf, int *outBufW, int *outBufH,
290
+ int *outPanelX, int *outPanelY, int *outPanelW, int *outPanelH,
291
+ int *outRotSteps, int *outFlip) const
292
+ {
293
+ if (!panelFrameBuffer_) return false;
294
+ present::Rect logical{logicalX, logicalY, logicalX + logicalW - 1, logicalY + logicalH - 1};
295
+ logical = clampLogicalRect(logical, logicalWidth(), logicalHeight());
296
+ if (!present::valid(logical)) return false;
297
+ const present::Rect panel = physicalBoundsForLogicalRect(logical);
298
+ if (!present::valid(panel)) return false;
299
+ const int panelW = panel.x1 - panel.x0 + 1;
300
+ const int panelH = panel.y1 - panel.y0 + 1;
301
+ // Tear-free double-buffer path: only when the producer covers the WHOLE panel
302
+ // (e.g. a full-screen camera) and a second framebuffer exists. Then it writes the
303
+ // non-scanned (back) buffer and flips it in at vblank — nothing it overwrites is
304
+ // being scanned. A sub-rect producer (windowed) can't double-buffer without also
305
+ // carrying the surrounding UI into the back buffer, so it writes the live buffer.
306
+ const bool coversPanel = panel.x0 == 0 && panel.y0 == 0 && panelW == kNativeWidth && panelH == kNativeHeight;
307
+ const bool canFlip = coversPanel && panelFrameBuffers_[1] != nullptr;
308
+ if (outBuf) {
309
+ std::uint16_t *target = panelFrameBuffer_;
310
+ if (canFlip) {
311
+ const int writable = const_cast<DisplayBackend *>(this)->selectWritablePanelFrameBufferLocked(true);
312
+ if (writable >= 0) target = panelFrameBuffers_[writable];
313
+ }
314
+ *outBuf = target;
315
+ }
316
+ if (outFlip) *outFlip = canFlip ? 1 : 0;
317
+ if (outBufW) *outBufW = kNativeWidth;
318
+ if (outBufH) *outBufH = kNativeHeight;
319
+ if (outPanelX) *outPanelX = panel.x0;
320
+ if (outPanelY) *outPanelY = panel.y0;
321
+ if (outPanelW) *outPanelW = panelW;
322
+ if (outPanelH) *outPanelH = panelH;
323
+ if (outRotSteps) {
324
+ switch (ppaRotationForCurrentOrientation()) {
325
+ case PPA_SRM_ROTATION_ANGLE_90: *outRotSteps = 1; break;
326
+ case PPA_SRM_ROTATION_ANGLE_180: *outRotSteps = 2; break;
327
+ case PPA_SRM_ROTATION_ANGLE_270: *outRotSteps = 3; break;
328
+ default: *outRotSteps = 0; break;
329
+ }
330
+ }
331
+ return true;
332
+ }
333
+
334
+ // Flip the just-written back buffer in at the next vblank (tear-free). The producer
335
+ // PPA-wrote a writable panel framebuffer (returned by panelDirectTarget with
336
+ // outFlip=1); draw_bitmap with a pointer inside an internal fb does no copy, it cache-
337
+ // syncs the rows and swaps cur_fb_index, which the DSI DMA picks up at the frame restart.
338
+ void flipPanelToBack()
339
+ {
340
+ if (!panel_ || panelFrameBuffers_[1] == nullptr) return;
341
+ const int back = selectWritablePanelFrameBufferLocked(true);
342
+ if (back < 0) return;
343
+ if (flipPanelToBufferLocked(panelFrameBuffers_[back], true)) {
344
+ resetPanelBackBufferCoherenceLocked();
345
+ lastFlipUs_ = esp_timer_get_time();
346
+ }
347
+ }
348
+
349
+ void flipPanelToBack(std::uint16_t *buffer)
350
+ {
351
+ if (!panel_ || panelFrameBuffers_[1] == nullptr || !buffer) return;
352
+ const int index = panelFrameBufferIndex(buffer);
353
+ if (index < 0 || index == scannedFbIndex_) return;
354
+ if (flipPanelToBufferLocked(buffer, true)) {
355
+ resetPanelBackBufferCoherenceLocked();
356
+ lastFlipUs_ = esp_timer_get_time();
357
+ panelDirectActive_ = true;
358
+ previousPresentValid_ = false;
359
+ frameBufferCoherent_ = false;
360
+ }
361
+ }
362
+
363
+ gea::framework::graphics::Canvas *drawingCanvas()
364
+ {
365
+ waitForAsyncPresent();
366
+ prepareDrawingTarget();
367
+ return &replayCanvas();
368
+ }
369
+
370
+ void applyOrientation()
371
+ {
372
+ take();
373
+ bindCanvasLocked();
374
+ if (!frameBuffer_) {
375
+ give();
376
+ return;
377
+ }
378
+ resetPanelBackBufferCoherenceLocked();
379
+ std::memset(frameBuffer_, 0, static_cast<std::size_t>(kMaxPixels) * sizeof(std::uint16_t));
380
+ canvas_.markDirty(0, 0, logicalWidth() - 1, logicalHeight() - 1);
381
+ previousPresentValid_ = false;
382
+ needsFullPhysicalFlush_ = true;
383
+ frameBufferCoherent_ = true;
384
+ give();
385
+ ESP_LOGI(kTag, "orientation=%s logical=%dx%d",
386
+ orientation_detail::DisplayOrientationState::orientationString().c_str(),
387
+ logicalWidth(), logicalHeight());
388
+ }
389
+
390
+ void clear()
391
+ {
392
+ clearNoFlush();
393
+ flush();
394
+ }
395
+
396
+ void clearNoFlush()
397
+ {
398
+ if (!frameBuffer_) init();
399
+ take();
400
+ bindCanvasLocked();
401
+ resetPanelBackBufferCoherenceLocked();
402
+ std::memset(frameBuffer_, 0, static_cast<std::size_t>(kMaxPixels) * sizeof(std::uint16_t));
403
+ canvas_.markDirty(0, 0, logicalWidth() - 1, logicalHeight() - 1);
404
+ previousPresentValid_ = false;
405
+ needsFullPhysicalFlush_ = true;
406
+ frameBufferCoherent_ = true;
407
+ give();
408
+ }
409
+
410
+ // Restore the draw canvas binding to the framebuffer. The engine calls
411
+ // Display::rebindCanvasToFramebuffer() after the fused rasterized-flush path
412
+ // rebinds the canvas onto a chunk buffer; this board has no rasterized flush,
413
+ // so it is idempotent here — but the symbol must exist and rebinding is the
414
+ // correct, safe restore.
415
+ void rebindCanvasToFramebuffer()
416
+ {
417
+ take();
418
+ bindCanvasLocked();
419
+ give();
420
+ }
421
+
422
+ void flush()
423
+ {
424
+ if (!init()) return;
425
+ if (asyncPresentInFlight_.load(std::memory_order_acquire)) return;
426
+ // While the panel-direct tile path owns the screen (full-frame flips of
427
+ // the scanout back buffer), the composed logical canvas is STALE — a
428
+ // flush here would paint it over the fresh tiles, alternating
429
+ // fresh/stale frames (white flicker while panning). The transition out
430
+ // of panel-direct re-arms a full flush explicitly.
431
+ if (panelDirectActive_) return;
432
+ pathExternalFlush_++;
433
+ const bool fullPhysicalFlush = needsFullPhysicalFlush_;
434
+ if (!fullPhysicalFlush && !canvas_.dirty(nullptr, nullptr, nullptr, nullptr)) return;
435
+ const std::int64_t started = esp_timer_get_time();
436
+ present::Rect dirtyRects[kMaxFlushRects];
437
+ int dirtyCount = 0;
438
+ if (fullPhysicalFlush) {
439
+ dirtyRects[0] = {0, 0, logicalWidth() - 1, logicalHeight() - 1};
440
+ dirtyCount = 1;
441
+ ESP_LOGI(kTag, "first physical flush covers full logical frame %dx%d", logicalWidth(), logicalHeight());
442
+ } else {
443
+ gea::framework::graphics::CanvasDirtyRect canvasRects[gea::framework::graphics::Canvas::kMaxDirtyRects];
444
+ const int canvasDirtyCount = canvas_.dirtyRects(canvasRects, gea::framework::graphics::Canvas::kMaxDirtyRects);
445
+ for (int i = 0; i < canvasDirtyCount; ++i) {
446
+ appendFlushRect(dirtyRects,
447
+ &dirtyCount,
448
+ kMaxFlushRects,
449
+ {canvasRects[i].x0, canvasRects[i].y0, canvasRects[i].x1, canvasRects[i].y1});
450
+ }
451
+ }
452
+ if (!fullPhysicalFlush && dirtyCount <= 0) {
453
+ int x0 = 0;
454
+ int y0 = 0;
455
+ int x1 = -1;
456
+ int y1 = -1;
457
+ if (canvas_.dirty(&x0, &y0, &x1, &y1)) {
458
+ appendFlushRect(dirtyRects, &dirtyCount, kMaxFlushRects, {x0, y0, x1, y1});
459
+ }
460
+ }
461
+ bool ok = true;
462
+ flushStats_.callCount++;
463
+ ok = flushPreparedLogicalRects(dirtyRects, dirtyCount);
464
+ flushStats_.totalUs += esp_timer_get_time() - started;
465
+ if (ok) {
466
+ canvas_.resetDirty();
467
+ if (fullPhysicalFlush) needsFullPhysicalFlush_ = false;
468
+ }
469
+ }
470
+
471
+ void flushRects(const platform_display::DisplayFlushRect *rects, int count)
472
+ {
473
+ waitForAsyncPresent();
474
+ if (!rects || count <= 0) return;
475
+ if (!init()) return;
476
+ if (needsFullPhysicalFlush_) {
477
+ const std::int64_t started = esp_timer_get_time();
478
+ flushStats_.callCount++;
479
+ ESP_LOGI(kTag, "first physical flush covers full logical frame %dx%d", logicalWidth(), logicalHeight());
480
+ present::Rect fullRect{0, 0, logicalWidth() - 1, logicalHeight() - 1};
481
+ const bool ok = flushPreparedLogicalRects(&fullRect, 1);
482
+ flushStats_.totalUs += esp_timer_get_time() - started;
483
+ if (ok) {
484
+ canvas_.resetDirty();
485
+ needsFullPhysicalFlush_ = false;
486
+ }
487
+ return;
488
+ }
489
+ const std::int64_t started = esp_timer_get_time();
490
+ bool ok = true;
491
+ flushStats_.callCount++;
492
+ present::Rect dirtyRects[kMaxFlushRects];
493
+ int dirtyCount = 0;
494
+ for (int i = 0; i < count; ++i) {
495
+ const auto &rect = rects[i];
496
+ appendFlushRectExact(dirtyRects, &dirtyCount, kMaxFlushRects, {rect.x0, rect.y0, rect.x1, rect.y1});
497
+ }
498
+ ok = flushPreparedLogicalRects(dirtyRects, dirtyCount);
499
+ flushStats_.totalUs += esp_timer_get_time() - started;
500
+ if (ok) canvas_.resetDirty();
501
+ }
502
+
503
+ bool streamRect(int x, int y, int w, int h, platform_display::DisplayStreamRasterFn raster, void *user)
504
+ {
505
+ waitForAsyncPresent();
506
+ if (!raster || w <= 0 || h <= 0) return false;
507
+ if (!init()) return false;
508
+ prepareDrawingTarget();
509
+ const int x0 = std::max(0, x);
510
+ const int y0 = std::max(0, y);
511
+ const int x1 = std::min(logicalWidth() - 1, x + w - 1);
512
+ const int y1 = std::min(logicalHeight() - 1, y + h - 1);
513
+ if (x0 > x1 || y0 > y1) return true;
514
+
515
+ const int width = x1 - x0 + 1;
516
+ const int maxRows = std::max(1, kFlushRowsDefault);
517
+ for (int row = y0; row <= y1; row += maxRows) {
518
+ int rows = maxRows;
519
+ if (row + rows > y1 + 1) rows = y1 - row + 1;
520
+ if (x0 == 0 && width == logicalStride_) {
521
+ raster(frameBuffer_ + static_cast<std::size_t>(row) * logicalStride_, width, rows, x0, row, user);
522
+ } else {
523
+ for (int copyRow = 0; copyRow < rows; ++copyRow) {
524
+ raster(frameBuffer_ + static_cast<std::size_t>(row + copyRow) * logicalStride_ + x0,
525
+ width,
526
+ 1,
527
+ x0,
528
+ row + copyRow,
529
+ user);
530
+ }
531
+ }
532
+ }
533
+ canvas_.markDirty(x0, y0, x1, y1);
534
+ frameBufferCoherent_ = true;
535
+ flush();
536
+ return true;
537
+ }
538
+
539
+ bool presentCommands(const platform_display::DisplayPresentCommand *commands, int commandCount)
540
+ {
541
+ if (!commands || commandCount <= 0 || !init()) return false;
542
+ presentCalls_++;
543
+ present::Frame current;
544
+ if (!present::extractFrame(commands, commandCount, current)) {
545
+ pathRejected_++;
546
+ return false;
547
+ }
548
+ if (!present::frameHasOpaqueBase(current, logicalWidth(), logicalHeight())) {
549
+ pathRejected_++;
550
+ return false;
551
+ }
552
+ if (!isFastClearFillCirclesFrame(current) && !frameBufferCoherent_) {
553
+ previousPresentValid_ = false;
554
+ needsFullPhysicalFlush_ = true;
555
+ }
556
+ const bool tileShape = framePpaTileEligible(current);
557
+ if (!tileShape && (scrollOriginX_ != 0 || scrollOriginY_ != 0)) {
558
+ // A non-tile frame can't run on the wrapped surface: linearize by
559
+ // forcing a full rebuild at origin (0,0).
560
+ scrollOriginX_ = 0;
561
+ scrollOriginY_ = 0;
562
+ panelSyncedForTorus_ = false;
563
+ previousPresentValid_ = false;
564
+ needsFullPhysicalFlush_ = true;
565
+ }
566
+ // PANEL-DIRECT TILE PATH: raster the whole tile frame straight into the
567
+ // NON-SCANNED panel buffer and flip it in at vblank. The default present
568
+ // composes into ownedFrameBuffer_ then PPA-copies owned->panel — and that
569
+ // 0-degree full-screen PPA copy measures a constant ~43ms (the PPA moves
570
+ // ~86MB/s against the DSI-scanned PSRAM), capping every present at ~20fps
571
+ // no matter how little was rastered. Direct raster (~15ms with the
572
+ // memcpy/nearest blits) + draw_bitmap's internal row sync (~11ms) + a
573
+ // tear-free flip ≈ 26ms — pan, pinch, and load all land at ~38fps.
574
+ {
575
+ static bool gateLogged = false;
576
+ if (!gateLogged) {
577
+ gateLogged = true;
578
+ ESP_LOGI(kTag, "panel-direct gate: tile=%d fb1=%d orient=%d lw=%d lh=%d nw=%d nh=%d",
579
+ tileShape ? 1 : 0, panelFrameBuffers_[1] != nullptr ? 1 : 0,
580
+ static_cast<int>(orientation_detail::DisplayOrientationState::orientation()),
581
+ logicalWidth(), logicalHeight(), kNativeWidth, kNativeHeight);
582
+ }
583
+ }
584
+ if (tileShape && panelFrameBuffers_[1] != nullptr &&
585
+ orientation_detail::DisplayOrientationState::orientation() ==
586
+ gea::framework::display::DisplayOrientation::PortraitPrimary &&
587
+ logicalWidth() == kNativeWidth && logicalHeight() == kNativeHeight) {
588
+ scrollOriginX_ = 0;
589
+ scrollOriginY_ = 0;
590
+ panelSyncedForTorus_ = false;
591
+ const std::int64_t started = esp_timer_get_time();
592
+ flushStats_.callCount++;
593
+ // Scan alignment: the previous flip latches at the next frame restart.
594
+ // If it was recent, wait for one refresh boundary before writing the
595
+ // buffer it released — otherwise the base fill paints the LIVE frame
596
+ // (white flashes while panning).
597
+ const int backIndex = selectWritablePanelFrameBufferLocked(true);
598
+ if (backIndex < 0) return false;
599
+ std::uint16_t *back = panelFrameBuffers_[backIndex];
600
+ const int height = logicalHeight();
601
+ const int width = logicalWidth();
602
+ const int maxRows = std::max(1, kFlushRowsDefault);
603
+ for (int row = 0; row < height; row += maxRows) {
604
+ int rows = maxRows;
605
+ if (row + rows > height) rows = height - row;
606
+ // Occlusion: when the band is fully covered by opaque tile blits,
607
+ // skip the base fill (command 0) — at ~100MB/s PSRAM bandwidth the
608
+ // fill's 1.8MB of throwaway writes per frame cost ~12ms alone.
609
+ std::size_t firstCommand = 0;
610
+ {
611
+ // Interval-union over x of commands spanning ALL of this band.
612
+ int covered = 0;
613
+ int spans[16][2];
614
+ int spanCount = 0;
615
+ for (std::size_t i = 1; i < current.commands.size() && spanCount < 16; ++i) {
616
+ const present::Command &c = current.commands[i];
617
+ const present::Rect b = present::commandBounds(c, width, height);
618
+ if (!present::valid(b) || b.y0 > row || b.y1 < row + rows - 1) continue;
619
+ spans[spanCount][0] = std::max(0, b.x0);
620
+ spans[spanCount][1] = std::min(width - 1, b.x1);
621
+ spanCount++;
622
+ }
623
+ // Sort the few spans by start (insertion sort) and union them.
624
+ for (int a = 1; a < spanCount; ++a) {
625
+ for (int b2 = a; b2 > 0 && spans[b2][0] < spans[b2 - 1][0]; --b2) {
626
+ std::swap(spans[b2][0], spans[b2 - 1][0]);
627
+ std::swap(spans[b2][1], spans[b2 - 1][1]);
628
+ }
629
+ }
630
+ int reach = 0;
631
+ for (int a = 0; a < spanCount; ++a) {
632
+ if (spans[a][0] > reach) break;
633
+ if (spans[a][1] + 1 > reach) reach = spans[a][1] + 1;
634
+ }
635
+ covered = reach >= width ? 1 : 0;
636
+ if (covered) firstCommand = 1;
637
+ }
638
+ std::uint16_t *target = back + static_cast<std::size_t>(row) * kNativeWidth;
639
+ const std::int64_t rasterStartUs = esp_timer_get_time();
640
+ gea::framework::graphics::Canvas bandCanvas;
641
+ bandCanvas.bindPixels(target, kNativeWidth, rows, kNativeWidth);
642
+ for (std::size_t i = firstCommand; i < current.commands.size(); ++i) {
643
+ const present::Command &cmd = current.commands[i];
644
+ // Band pre-skip: without it every command rasters against every
645
+ // 64-row chunk — ~25 sidebar text commands x 20 chunks walked
646
+ // glyph loops 500x per frame (+110ms measured).
647
+ if (cmd.type != gea::platform::display::DisplayPresentCommandType::Clear) {
648
+ const present::Rect bounds = present::commandBounds(cmd, width, height);
649
+ if (!present::valid(bounds) || bounds.y1 < row || bounds.y0 > row + rows - 1) continue;
650
+ }
651
+ present::rasterCommandRows(bandCanvas, target, 0, kNativeWidth, row, rows, height, cmd);
652
+ }
653
+ flushStats_.rasterUs += esp_timer_get_time() - rasterStartUs;
654
+ }
655
+ take();
656
+ const std::int64_t flipStartUs = esp_timer_get_time();
657
+ // Drain a stale refresh grant so the post-flip wait (next frame's
658
+ // pre-raster) observes a boundary that happened AFTER this flip.
659
+ drainRefreshDoneLocked();
660
+ flipPanelToBack();
661
+ lastFlipUs_ = esp_timer_get_time();
662
+ flushStats_.copyUs += lastFlipUs_ - flipStartUs;
663
+ give();
664
+ flushStats_.totalUs += esp_timer_get_time() - started;
665
+ flushStats_.chunkCount++;
666
+ flushStats_.pixelCount += logicalWidth() * height;
667
+ static int directHits = 0;
668
+ directHits++;
669
+ pathDirect_++;
670
+ if ((directHits & 15) == 1) {
671
+ ESP_LOGI(kTag, "panel-direct tile frame #%d total=%lldus", directHits,
672
+ static_cast<long long>(esp_timer_get_time() - started));
673
+ }
674
+ // Mark the mode: the composed (owned) framebuffer is now STALE. The
675
+ // canvas flush is suppressed while active; the transition out
676
+ // re-arms a full composed repaint.
677
+ panelDirectActive_ = true;
678
+ previousPresentValid_ = false;
679
+ frameBufferCoherent_ = false;
680
+ canvas_.resetDirty();
681
+ return true;
682
+ }
683
+ // LANDSCAPE PANEL-NATIVE PRESENT: the panel is portrait-native and the
684
+ // PPA's 90-degree rotation costs ~150ms/frame (measured) — no pipelining
685
+ // can hide that. Instead, tiles are PRE-ROTATED once at decode (worker
686
+ // core), every command's geometry is transformed into panel space, and
687
+ // the frame rasters DIRECTLY into the portrait back scanout buffer like
688
+ // the portrait panel-direct path. Sidebar text draws via the rotated
689
+ // glyph blitter in a full-buffer pass.
690
+ {
691
+ using gea::framework::display::DisplayOrientation;
692
+ const DisplayOrientation orient = orientation_detail::DisplayOrientationState::orientation();
693
+ const bool landscape = orient == DisplayOrientation::LandscapePrimary;
694
+ {
695
+ static bool landGateLogged = false;
696
+ if (!landGateLogged && landscape) {
697
+ landGateLogged = true;
698
+ ESP_LOGI(kTag, "landscape gate: tile=%d fb1=%d lw=%d lh=%d nW=%d nH=%d",
699
+ tileShape ? 1 : 0, panelFrameBuffers_[1] != nullptr ? 1 : 0, logicalWidth(), logicalHeight(),
700
+ kNativeWidth, kNativeHeight);
701
+ }
702
+ }
703
+ if (tileShape && landscape && panelFrameBuffers_[1] != nullptr &&
704
+ logicalWidth() == kNativeHeight && logicalHeight() == kNativeWidth) {
705
+ scrollOriginX_ = 0;
706
+ scrollOriginY_ = 0;
707
+ panelSyncedForTorus_ = false;
708
+ const std::int64_t started = esp_timer_get_time();
709
+ flushStats_.callCount++;
710
+ // Transform geometry to panel space IN PLACE (landscape-primary:
711
+ // panel = {srcY, kNativeHeight - 1 - srcX}); FillText keeps its
712
+ // landscape anchor for the rotated text pass.
713
+ using Type = gea::platform::display::DisplayPresentCommandType;
714
+ for (present::Command &cmd : current.commands) {
715
+ if (cmd.type == Type::Clear || cmd.type == Type::FillText) continue;
716
+ const int lx = cmd.x;
717
+ const int ly = cmd.y;
718
+ const int lw2 = cmd.w;
719
+ const int lh2 = cmd.h;
720
+ cmd.x = ly;
721
+ cmd.y = kNativeHeight - lx - lw2;
722
+ cmd.w = lh2;
723
+ cmd.h = lw2;
724
+ if (cmd.type == Type::DrawImage || cmd.type == Type::DrawImageScaled) {
725
+ const int sw = cmd.srcWidth;
726
+ cmd.srcWidth = cmd.srcHeight;
727
+ cmd.srcHeight = sw;
728
+ }
729
+ }
730
+ // Scan alignment (same as the portrait path).
731
+ {
732
+ const std::int64_t alignStart = esp_timer_get_time();
733
+ waitForReleasedPanelBufferLocked();
734
+ landAlignUs_ = static_cast<int>(esp_timer_get_time() - alignStart);
735
+ }
736
+ const int backIndex = selectWritablePanelFrameBufferLocked(true);
737
+ if (backIndex < 0) return false;
738
+ std::uint16_t *back = panelFrameBuffers_[backIndex];
739
+ const int height = kNativeHeight;
740
+ const int width = kNativeWidth;
741
+ // PAN FAST PATH: when every image command moved by ONE common
742
+ // translation since the previous frame, copy the overlap from the
743
+ // front buffer (frame N-1) and raster only the exposed strips and
744
+ // the moved small rects (pins/labels). A full-screen re-raster is
745
+ // ~40ms; the copy is ~15ms for the map region.
746
+ // DISABLED pending debugging: v1 had a copy-direction defect that
747
+ // wiped tiles and pathological dirty-raster cost (212-378ms). The
748
+ // full raster below is correct at ~76ms.
749
+ constexpr bool kPanFastPathEnabled = true;
750
+ bool panMode = false;
751
+ int pdx = 0, pdy = 0;
752
+ present::Rect dirtyRects[64];
753
+ int dirtyCount = 0;
754
+ const std::int64_t panDetectStart = esp_timer_get_time();
755
+ const std::uint32_t railHash = railContentHash(current, kNativeWidth, kNativeHeight);
756
+ if (kPanFastPathEnabled && !landPrevValid_[backIndex]) {
757
+ panBailReason_ = 1;
758
+ panBailCounts_[1]++;
759
+ }
760
+ if (kPanFastPathEnabled && landPrevValid_[backIndex]) {
761
+ bool haveDelta = false;
762
+ bool consistent = true;
763
+ int imgPairs = 0;
764
+ for (const present::Command &cmd : current.commands) {
765
+ if (cmd.type != Type::DrawImage && cmd.type != Type::DrawImageScaled) continue;
766
+ for (int j = 0; j < landPrevCount_[backIndex]; ++j) {
767
+ const LandPrevCmd &prev = landPrev_[backIndex][j];
768
+ if (prev.pixels != cmd.pixels || prev.type != static_cast<std::int16_t>(cmd.type)) continue;
769
+ // Same image at a different scale (fallback ancestors swap
770
+ // span levels while tiles stream): not a translation pair —
771
+ // the dirty phase repaints it — but no reason to bail.
772
+ if (prev.w != cmd.w || prev.h != cmd.h) break;
773
+ const int dx = cmd.x - prev.x;
774
+ const int dy = cmd.y - prev.y;
775
+ if (!haveDelta) { pdx = dx; pdy = dy; haveDelta = true; }
776
+ else if (dx != pdx || dy != pdy) consistent = false;
777
+ imgPairs++;
778
+ break;
779
+ }
780
+ if (!consistent) break;
781
+ }
782
+ panMode = haveDelta && consistent && imgPairs >= 4 &&
783
+ railHash == landPrevRailHash_[backIndex] &&
784
+ pdx > -440 && pdx < 440 && pdy > -440 && pdy < 440;
785
+ if (!panMode) {
786
+ int reason = 2;
787
+ if (!haveDelta) reason = 2;
788
+ else if (!consistent) reason = 3;
789
+ else if (imgPairs < 4) reason = 4;
790
+ else reason = 5;
791
+ panBailReason_ = reason;
792
+ panBailCounts_[reason]++;
793
+ }
794
+ if (panMode) {
795
+ // Small-rect dirties: previous + current fills/text in the map
796
+ // region (pins, labels) so movers repaint and ghosts clear.
797
+ auto addDirty = [&](present::Rect r) {
798
+ // Each fresh tile is ~1.3ms of honest raster; only bail to a
799
+ // full re-raster when the dirty set rivals the whole screen.
800
+ if (dirtyCount >= 60) { panMode = false; panBailReason_ = 6; panBailCounts_[6]++; return; }
801
+ if (!present::valid(r)) return;
802
+ dirtyRects[dirtyCount++] = r;
803
+ };
804
+ for (int j = 0; j < landPrevCount_[backIndex] && panMode; ++j) {
805
+ const LandPrevCmd &prev = landPrev_[backIndex][j];
806
+ if (prev.pixels) continue;
807
+ addDirty(present::Rect{prev.x, prev.y, prev.x + prev.w - 1, prev.y + prev.h - 1});
808
+ }
809
+ for (std::size_t ci = 0; ci < current.commands.size(); ++ci) {
810
+ const present::Command &cmd = current.commands[ci];
811
+ if (!panMode) break;
812
+ if (ci == 0) continue; // base fill participates in strip rasters only
813
+ if (cmd.type == Type::Clear) continue;
814
+ if (cmd.type == Type::DrawImage || cmd.type == Type::DrawImageScaled) {
815
+ // A draw is clean only when its previous instance moved by
816
+ // exactly the pan delta at the same scale; everything else
817
+ // (fresh tile, rescaled ancestor) repaints, including the
818
+ // previous footprint so stale pixels clear.
819
+ bool clean = false;
820
+ for (int j = 0; j < landPrevCount_[backIndex]; ++j) {
821
+ const LandPrevCmd &prev = landPrev_[backIndex][j];
822
+ if (prev.pixels != cmd.pixels) continue;
823
+ if (prev.w == cmd.w && prev.h == cmd.h &&
824
+ cmd.x - prev.x == pdx && cmd.y - prev.y == pdy) {
825
+ clean = true;
826
+ } else {
827
+ addDirty(present::Rect{prev.x, prev.y, prev.x + prev.w - 1, prev.y + prev.h - 1});
828
+ }
829
+ break;
830
+ }
831
+ if (!clean) addDirty(present::commandBounds(cmd, width, height));
832
+ continue;
833
+ }
834
+ if (cmd.type == Type::FillText) {
835
+ // Rail text only; rail rows aren't copied or touched in
836
+ // pan mode, so nothing to do.
837
+ continue;
838
+ }
839
+ const present::Rect b = present::commandBounds(cmd, width, height);
840
+ // Rail-region fills (panel rows >= kRailPanelRow) stay put.
841
+ if (b.y0 >= kRailPanelRow) continue;
842
+ addDirty(b);
843
+ }
844
+ }
845
+ }
846
+ panDetectUs_ = static_cast<int>(esp_timer_get_time() - panDetectStart);
847
+ if (panMode) {
848
+ // NO COPY: the back buffer already holds this buffer's previous
849
+ // frame (N-2); the strips below cover the N-2 -> N exposure.
850
+ panKickUs_ = 0;
851
+ // Exposed strips (disjoint from the copied block) raster while
852
+ // the DMA streams; interior rects wait for completion below.
853
+ present::Rect stripRects[4];
854
+ int stripCount = 0;
855
+ if (pdy > 0) stripRects[stripCount++] = present::Rect{0, 0, width - 1, pdy - 1};
856
+ if (pdy < 0) stripRects[stripCount++] = present::Rect{0, kRailPanelRow + pdy, width - 1, kRailPanelRow - 1};
857
+ if (pdx > 0) stripRects[stripCount++] = present::Rect{0, 0, pdx - 1, kRailPanelRow - 1};
858
+ if (pdx < 0) stripRects[stripCount++] = present::Rect{width + pdx, 0, width - 1, kRailPanelRow - 1};
859
+ const std::int64_t rasterStartUs = esp_timer_get_time();
860
+ for (int sIdx = 0; sIdx < stripCount; ++sIdx) {
861
+ present::Rect rect = stripRects[sIdx];
862
+ if (rect.y0 < 0) rect.y0 = 0;
863
+ if (rect.x0 < 0) rect.x0 = 0;
864
+ if (rect.y1 >= kRailPanelRow) rect.y1 = kRailPanelRow - 1;
865
+ if (rect.x1 >= width) rect.x1 = width - 1;
866
+ if (!present::valid(rect)) continue;
867
+ const int rows = rect.y1 - rect.y0 + 1;
868
+ std::uint16_t *target = back + static_cast<std::size_t>(rect.y0) * width;
869
+ gea::framework::graphics::Canvas bandCanvas;
870
+ bandCanvas.bindPixels(target, width, rows, width);
871
+ bandCanvas.pushClip(rect.x0, 0, rect.x1 - rect.x0 + 1, rows);
872
+ for (std::size_t i = 0; i < current.commands.size(); ++i) {
873
+ const present::Command &cmd = current.commands[i];
874
+ if (cmd.type == Type::FillText) continue;
875
+ if (cmd.type != Type::Clear) {
876
+ const present::Rect bounds = present::commandBounds(cmd, width, height);
877
+ if (!present::valid(bounds) || bounds.y1 < rect.y0 || bounds.y0 > rect.y1 ||
878
+ bounds.x1 < rect.x0 || bounds.x0 > rect.x1) continue;
879
+ }
880
+ present::rasterCommandRows(bandCanvas, target, 0, width, rect.y0, rows, height, cmd);
881
+ }
882
+ bandCanvas.resetClip();
883
+ }
884
+ panStripUs_ = static_cast<int>(esp_timer_get_time() - rasterStartUs);
885
+ panWaitUs_ = 0;
886
+ const std::int64_t panInteriorStart = esp_timer_get_time();
887
+ // Interior dirty rects (pins, fresh tiles) over the copied area.
888
+ for (int d = 0; d < dirtyCount; ++d) {
889
+ present::Rect rect = dirtyRects[d];
890
+ if (rect.y0 < 0) rect.y0 = 0;
891
+ if (rect.x0 < 0) rect.x0 = 0;
892
+ if (rect.y1 >= kRailPanelRow) rect.y1 = kRailPanelRow - 1;
893
+ if (rect.x1 >= width) rect.x1 = width - 1;
894
+ if (!present::valid(rect)) continue;
895
+ const int rows = rect.y1 - rect.y0 + 1;
896
+ std::uint16_t *target = back + static_cast<std::size_t>(rect.y0) * width;
897
+ gea::framework::graphics::Canvas bandCanvas;
898
+ bandCanvas.bindPixels(target, width, rows, width);
899
+ bandCanvas.pushClip(rect.x0, 0, rect.x1 - rect.x0 + 1, rows);
900
+ for (std::size_t i = 0; i < current.commands.size(); ++i) {
901
+ const present::Command &cmd = current.commands[i];
902
+ if (cmd.type == Type::FillText) continue;
903
+ if (cmd.type != Type::Clear) {
904
+ const present::Rect bounds = present::commandBounds(cmd, width, height);
905
+ if (!present::valid(bounds) || bounds.y1 < rect.y0 || bounds.y0 > rect.y1 ||
906
+ bounds.x1 < rect.x0 || bounds.x0 > rect.x1) continue;
907
+ }
908
+ present::rasterCommandRows(bandCanvas, target, 0, width, rect.y0, rows, height, cmd);
909
+ }
910
+ bandCanvas.resetClip();
911
+ }
912
+ flushStats_.rasterUs += esp_timer_get_time() - rasterStartUs;
913
+ panInteriorUs_ = static_cast<int>(esp_timer_get_time() - panInteriorStart);
914
+ }
915
+ // Snapshot this frame's commands into THIS buffer's slot for the
916
+ // next time it becomes the back buffer (two frames from now).
917
+ landPrevCount_[backIndex] = 0;
918
+ landPrevValid_[backIndex] = false;
919
+ bool snapshotOverflow = false;
920
+ for (std::size_t ci = 0; ci < current.commands.size(); ++ci) {
921
+ const present::Command &cmd = current.commands[ci];
922
+ if (landPrevCount_[backIndex] >= kLandPrevMax) { snapshotOverflow = true; break; }
923
+ if (ci == 0) continue; // base fill: never a dirty source
924
+ if (cmd.type == Type::Clear || cmd.type == Type::FillText) continue;
925
+ const bool isImage = cmd.type == Type::DrawImage || cmd.type == Type::DrawImageScaled;
926
+ const present::Rect b = present::commandBounds(cmd, width, height);
927
+ if (!isImage && present::valid(b) && b.y0 >= kRailPanelRow) continue; // static rail fills
928
+ LandPrevCmd &slot = landPrev_[backIndex][landPrevCount_[backIndex]];
929
+ slot.pixels = isImage ? cmd.pixels : nullptr;
930
+ slot.type = static_cast<std::int16_t>(cmd.type);
931
+ slot.x = cmd.x;
932
+ slot.y = cmd.y;
933
+ slot.w = cmd.w;
934
+ slot.h = cmd.h;
935
+ landPrevCount_[backIndex]++;
936
+ }
937
+ if (!snapshotOverflow && landPrevCount_[backIndex] > 0) landPrevValid_[backIndex] = true;
938
+ landPrevRailHash_[backIndex] = railHash;
939
+ const int maxRows = std::max(1, kFlushRowsDefault);
940
+ if (!panMode)
941
+ for (int row = 0; row < height; row += maxRows) {
942
+ int rows = maxRows;
943
+ if (row + rows > height) rows = height - row;
944
+ // Occlusion: skip the base fill when opaque blits cover the band.
945
+ std::size_t firstCommand = 0;
946
+ {
947
+ int spans[16][2];
948
+ int spanCount = 0;
949
+ for (std::size_t i = 1; i < current.commands.size() && spanCount < 16; ++i) {
950
+ const present::Command &c = current.commands[i];
951
+ if (c.type == Type::FillText) continue;
952
+ const present::Rect b = present::commandBounds(c, width, height);
953
+ if (!present::valid(b) || b.y0 > row || b.y1 < row + rows - 1) continue;
954
+ spans[spanCount][0] = std::max(0, b.x0);
955
+ spans[spanCount][1] = std::min(width - 1, b.x1);
956
+ spanCount++;
957
+ }
958
+ for (int a = 1; a < spanCount; ++a) {
959
+ for (int b2 = a; b2 > 0 && spans[b2][0] < spans[b2 - 1][0]; --b2) {
960
+ std::swap(spans[b2][0], spans[b2 - 1][0]);
961
+ std::swap(spans[b2][1], spans[b2 - 1][1]);
962
+ }
963
+ }
964
+ int reach = 0;
965
+ for (int a = 0; a < spanCount; ++a) {
966
+ if (spans[a][0] > reach) break;
967
+ if (spans[a][1] + 1 > reach) reach = spans[a][1] + 1;
968
+ }
969
+ if (reach >= width) firstCommand = 1;
970
+ }
971
+ std::uint16_t *target = back + static_cast<std::size_t>(row) * kNativeWidth;
972
+ const std::int64_t rasterStartUs = esp_timer_get_time();
973
+ gea::framework::graphics::Canvas bandCanvas;
974
+ bandCanvas.bindPixels(target, kNativeWidth, rows, kNativeWidth);
975
+ for (std::size_t i = firstCommand; i < current.commands.size(); ++i) {
976
+ const present::Command &cmd = current.commands[i];
977
+ if (cmd.type == Type::FillText) continue; // rotated full-buffer pass below
978
+ if (cmd.type != Type::Clear) {
979
+ const present::Rect bounds = present::commandBounds(cmd, width, height);
980
+ if (!present::valid(bounds) || bounds.y1 < row || bounds.y0 > row + rows - 1) continue;
981
+ }
982
+ present::rasterCommandRows(bandCanvas, target, 0, kNativeWidth, row, rows, height, cmd);
983
+ }
984
+ flushStats_.rasterUs += esp_timer_get_time() - rasterStartUs;
985
+ }
986
+ landRasterUs_ = static_cast<int>(esp_timer_get_time() - started) - landAlignUs_;
987
+ landPanMode_ = panMode ? 1 : 0;
988
+ if (panMode) landPanFrames_++; else landFullFrames_++;
989
+ // Sidebar text: rotated glyph blits over the full back buffer
990
+ // (landscape anchors; the blitter does the panel transform per pixel).
991
+ if (!panMode) {
992
+ const std::int64_t textStartUs = esp_timer_get_time();
993
+ gea::framework::graphics::Canvas fullCanvas;
994
+ fullCanvas.bindPixels(back, kNativeWidth, kNativeHeight, kNativeWidth);
995
+ for (const present::Command &cmd : current.commands) {
996
+ if (cmd.type != Type::FillText || cmd.fontFamilyId < 0) continue;
997
+ fullCanvas.drawTextFontFamilyRotated90(cmd.text.c_str(), cmd.x, cmd.y, cmd.color,
998
+ cmd.fontFamilyId, cmd.fontSizePx);
999
+ }
1000
+ flushStats_.rasterUs += esp_timer_get_time() - textStartUs;
1001
+ landTextUs_ = static_cast<int>(esp_timer_get_time() - textStartUs);
1002
+ }
1003
+ take();
1004
+ const std::int64_t flipStartUs = esp_timer_get_time();
1005
+ drainRefreshDoneLocked();
1006
+ flipPanelToBack();
1007
+ lastFlipUs_ = esp_timer_get_time();
1008
+ flushStats_.copyUs += lastFlipUs_ - flipStartUs;
1009
+ landFlipUs_ = static_cast<int>(lastFlipUs_ - flipStartUs);
1010
+ give();
1011
+ landTotalUs_ = static_cast<int>(esp_timer_get_time() - started);
1012
+ flushStats_.totalUs += esp_timer_get_time() - started;
1013
+ flushStats_.chunkCount++;
1014
+ flushStats_.pixelCount += width * height;
1015
+ static int landHits = 0;
1016
+ landHits++;
1017
+ pathDirect_++;
1018
+ if ((landHits & 15) == 1) {
1019
+ ESP_LOGI(kTag, "landscape panel-native frame #%d total=%lldus", landHits,
1020
+ static_cast<long long>(esp_timer_get_time() - started));
1021
+ }
1022
+ panelDirectActive_ = true;
1023
+ previousPresentValid_ = false;
1024
+ frameBufferCoherent_ = false;
1025
+ canvas_.resetDirty();
1026
+ return true;
1027
+ }
1028
+ }
1029
+ if (panelDirectActive_) {
1030
+ // A frame that ISN'T panel-direct is taking over: the scanout holds
1031
+ // tile content the composed path knows nothing about. Force a full
1032
+ // composed repaint + flush.
1033
+ panelDirectActive_ = false;
1034
+ previousPresentValid_ = false;
1035
+ needsFullPhysicalFlush_ = true;
1036
+ resetPanelBackBufferCoherenceLocked();
1037
+ for (int i = 0; i < kDpiFrameBufferCount; ++i) landPrevValid_[i] = false;
1038
+ }
1039
+ constexpr bool kUsePanelBufferLocalCirclePrev = false;
1040
+ if (kUsePanelBufferLocalCirclePrev &&
1041
+ !asyncPresentInFlight_.load(std::memory_order_acquire) &&
1042
+ isFastClearFillCirclesFrame(current) &&
1043
+ canUseNativePanelBackBufferPath()) {
1044
+ int backIndex = -1;
1045
+ if (prepareNativePanelBackBufferForCircleFrame(&backIndex)) {
1046
+ const present::Frame *previousForBuffer =
1047
+ (backIndex >= 0 && backIndex < kDpiFrameBufferCount && panelCirclePrevValid_[backIndex] &&
1048
+ isFastClearFillCirclesFrame(panelCirclePrevFrame_[backIndex]) && !needsFullPhysicalFlush_)
1049
+ ? &panelCirclePrevFrame_[backIndex]
1050
+ : nullptr;
1051
+ const bool ok = presentClearFillCirclesFrame(current, previousForBuffer);
1052
+ if (ok) {
1053
+ if (backIndex >= 0 && backIndex < kDpiFrameBufferCount) {
1054
+ panelCirclePrevFrame_[backIndex] = std::move(current);
1055
+ panelCirclePrevValid_[backIndex] = true;
1056
+ }
1057
+ previousPresentValid_ = false;
1058
+ needsFullPhysicalFlush_ = false;
1059
+ frameBufferCoherent_ = true;
1060
+ canvas_.resetDirty();
1061
+ }
1062
+ return ok;
1063
+ }
1064
+ }
1065
+ invalidatePanelCircleFrames();
1066
+ {
1067
+ using gea::framework::display::DisplayOrientation;
1068
+ using Type = gea::platform::display::DisplayPresentCommandType;
1069
+ if (tileShape) {
1070
+ prepareDrawingTarget();
1071
+ const bool rotatedMode = !(orientation_detail::DisplayOrientationState::orientation() == DisplayOrientation::PortraitPrimary &&
1072
+ usingPanelFrameBufferDirectly());
1073
+ int shiftDx = 0;
1074
+ int shiftDy = 0;
1075
+ const int absLimitX = logicalWidth() / 2;
1076
+ const int absLimitY = logicalHeight() / 2;
1077
+ const bool panPreconditions = rotatedMode && frameBuffer_ == ownedFrameBuffer_ &&
1078
+ previousPresentValid_ && !needsFullPhysicalFlush_ && frameBufferCoherent_;
1079
+ const bool panShiftFound = panPreconditions && detectUniformShift(previousPresentFrame_, current, &shiftDx, &shiftDy);
1080
+ if (panShiftFound &&
1081
+ (shiftDx < 0 ? -shiftDx : shiftDx) < absLimitX && (shiftDy < 0 ? -shiftDy : shiftDy) < absLimitY) {
1082
+ // PAN FAST PATH: the frame is the previous one uniformly shifted.
1083
+ // Move the torus origin, raster ONLY the exposed strips and any
1084
+ // commands without a shifted twin, then rebuild the panel with
1085
+ // 1-4 big PPA rotate ops. ~30-80k rastered pixels instead of 921k.
1086
+ static int panHits = 0;
1087
+ panHits++;
1088
+ const std::int64_t rasterUs0 = flushStats_.rasterUs;
1089
+ const std::int64_t copyUs0 = flushStats_.copyUs;
1090
+ const std::int64_t txUs0 = flushStats_.txUs;
1091
+ const std::int64_t started = esp_timer_get_time();
1092
+ flushStats_.callCount++;
1093
+ scrollOriginX_ = wrapCoord(scrollOriginX_ - shiftDx, logicalWidth());
1094
+ scrollOriginY_ = wrapCoord(scrollOriginY_ - shiftDy, logicalHeight());
1095
+ present::Rect rects[kMaxPresentRects];
1096
+ int rectCount = 0;
1097
+ if (shiftDx > 0)
1098
+ present::addRect(rects, &rectCount, kMaxPresentRects, {0, 0, shiftDx - 1, logicalHeight() - 1}, logicalWidth(), logicalHeight());
1099
+ else if (shiftDx < 0)
1100
+ present::addRect(rects, &rectCount, kMaxPresentRects, {logicalWidth() + shiftDx, 0, logicalWidth() - 1, logicalHeight() - 1},
1101
+ logicalWidth(), logicalHeight());
1102
+ if (shiftDy > 0)
1103
+ present::addRect(rects, &rectCount, kMaxPresentRects, {0, 0, logicalWidth() - 1, shiftDy - 1}, logicalWidth(), logicalHeight());
1104
+ else if (shiftDy < 0)
1105
+ present::addRect(rects, &rectCount, kMaxPresentRects, {0, logicalHeight() + shiftDy, logicalWidth() - 1, logicalHeight() - 1},
1106
+ logicalWidth(), logicalHeight());
1107
+ for (std::size_t i = 1; i < current.commands.size(); ++i) {
1108
+ const present::Command &c = current.commands[i];
1109
+ bool matchedCmd = false;
1110
+ for (std::size_t j = 1; j < previousPresentFrame_.commands.size() && !matchedCmd; ++j) {
1111
+ const present::Command &p = previousPresentFrame_.commands[j];
1112
+ matchedCmd = p.type == c.type && p.pixels == c.pixels && p.srcWidth == c.srcWidth &&
1113
+ p.srcHeight == c.srcHeight &&
1114
+ (c.type != Type::DrawImageScaled || (p.w == c.w && p.h == c.h)) &&
1115
+ p.x + shiftDx == c.x && p.y + shiftDy == c.y;
1116
+ }
1117
+ if (!matchedCmd)
1118
+ present::addCommandBounds(c, rects, &rectCount, kMaxPresentRects, logicalWidth(), logicalHeight());
1119
+ }
1120
+ bool ok = true;
1121
+ for (int i = 0; i < rectCount && ok; ++i) {
1122
+ present::Rect region = clampLogicalRect(rects[i], logicalWidth(), logicalHeight());
1123
+ if (!present::valid(region)) continue;
1124
+ rasterPresentRegion(current, region);
1125
+ TorusPart parts[4];
1126
+ const int partCount = splitLogicalRectToTorus(region, parts);
1127
+ const std::int64_t syncStartUs = esp_timer_get_time();
1128
+ for (int p = 0; p < partCount && ok; ++p) ok = syncTorusPartToMemory(parts[p]);
1129
+ flushStats_.copyUs += esp_timer_get_time() - syncStartUs;
1130
+ }
1131
+ if (ok && !panelSyncedForTorus_) {
1132
+ ok = syncPanelFrameBufferRectToMemory({0, 0, kNativeWidth - 1, kNativeHeight - 1});
1133
+ panelSyncedForTorus_ = true;
1134
+ }
1135
+ if (ok) ok = flushFullPanelFromTorus();
1136
+ flushStats_.totalUs += esp_timer_get_time() - started;
1137
+ if ((panHits & 15) == 1) {
1138
+ ESP_LOGI(kTag, "torus pan #%d dx=%d dy=%d rects=%d total=%lldus raster=%lldus sync=%lldus ppa=%lldus",
1139
+ panHits, shiftDx, shiftDy, rectCount,
1140
+ static_cast<long long>(esp_timer_get_time() - started),
1141
+ static_cast<long long>(flushStats_.rasterUs - rasterUs0),
1142
+ static_cast<long long>(flushStats_.copyUs - copyUs0),
1143
+ static_cast<long long>(flushStats_.txUs - txUs0));
1144
+ }
1145
+ if (ok) {
1146
+ previousPresentFrame_ = std::move(current);
1147
+ previousPresentValid_ = true;
1148
+ frameBufferCoherent_ = true;
1149
+ canvas_.resetDirty();
1150
+ } else {
1151
+ scrollOriginX_ = 0;
1152
+ scrollOriginY_ = 0;
1153
+ panelSyncedForTorus_ = false;
1154
+ previousPresentValid_ = false;
1155
+ needsFullPhysicalFlush_ = true;
1156
+ }
1157
+ return ok;
1158
+ }
1159
+ }
1160
+ }
1161
+ if (!asyncPresentInFlight_.load(std::memory_order_acquire) &&
1162
+ isFastClearFillCirclesFrame(current)) {
1163
+ prepareDrawingTarget(false);
1164
+ const bool ok = presentClearFillCirclesFrame(current, &previousPresentFrame_);
1165
+ if (ok) {
1166
+ previousPresentFrame_ = std::move(current);
1167
+ previousPresentValid_ = true;
1168
+ needsFullPhysicalFlush_ = false;
1169
+ canvas_.resetDirty();
1170
+ }
1171
+ return ok;
1172
+ }
1173
+ const bool forceFullPanelBackRepaint = shouldForceFullPanelBackRepaint(current);
1174
+ if (forceFullPanelBackRepaint && scheduleAsyncFullPanelBackRepaint(std::move(current))) {
1175
+ return true;
1176
+ }
1177
+ if (!waitForAsyncPresent()) return false;
1178
+ present::Rect regions[kMaxPresentRects];
1179
+ int regionCount = 0;
1180
+ if (forceFullPanelBackRepaint) {
1181
+ regions[0] = {0, 0, logicalWidth() - 1, logicalHeight() - 1};
1182
+ regionCount = 1;
1183
+ } else if (previousPresentValid_) {
1184
+ regionCount = present::dirtyRects(&previousPresentFrame_,
1185
+ current,
1186
+ regions,
1187
+ kMaxPresentRects,
1188
+ logicalWidth(),
1189
+ logicalHeight());
1190
+ } else {
1191
+ regions[0] = {0, 0, logicalWidth() - 1, logicalHeight() - 1};
1192
+ regionCount = 1;
1193
+ }
1194
+ if (regionCount <= 0) {
1195
+ previousPresentFrame_ = std::move(current);
1196
+ previousPresentValid_ = true;
1197
+ return true;
1198
+ }
1199
+ prepareDrawingTarget(!regionsCoverLogicalFrame(regions, regionCount));
1200
+
1201
+ const std::int64_t started = esp_timer_get_time();
1202
+ bool ok = true;
1203
+ pathGeneral_++;
1204
+ flushStats_.callCount++;
1205
+ // MEASURED LOSS, kept dark: per-tile PPA blits cost MORE than the CPU
1206
+ // raster (flush 53-89ms -> 84-182ms on the maps tile grid) because the
1207
+ // IDF PPA driver cache-syncs the full 1.8MB output framebuffer around
1208
+ // EVERY transaction — ~30 small ops pay ~30 full-buffer msyncs. The PPA
1209
+ // only wins as one big op per region (like the rotate flush). Re-try if
1210
+ // the driver ever grows a no-sync/explicit-sync mode.
1211
+ constexpr bool kUsePpaTileBlits = false;
1212
+ const bool ppaTiles = kUsePpaTileBlits && framePpaTileEligible(current);
1213
+ present::Rect flushedRects[kMaxPresentRects];
1214
+ int flushedCount = 0;
1215
+ for (int i = 0; i < regionCount; ++i) {
1216
+ present::Rect region = clampLogicalRect(regions[i], logicalWidth(), logicalHeight());
1217
+ if (!present::valid(region)) continue;
1218
+ bool rastered = false;
1219
+ if (ppaTiles) {
1220
+ const std::int64_t ppaStartUs = esp_timer_get_time();
1221
+ rastered = ppaRasterTileRegion(current, region);
1222
+ flushStats_.rasterUs += esp_timer_get_time() - ppaStartUs;
1223
+ }
1224
+ if (!rastered) rasterPresentRegion(current, region);
1225
+ present::addRect(flushedRects, &flushedCount, kMaxPresentRects, region, logicalWidth(), logicalHeight());
1226
+ }
1227
+ ok = flushPreparedLogicalRects(flushedRects, flushedCount);
1228
+ flushStats_.totalUs += esp_timer_get_time() - started;
1229
+ if (ok) {
1230
+ previousPresentFrame_ = std::move(current);
1231
+ previousPresentValid_ = true;
1232
+ needsFullPhysicalFlush_ = false;
1233
+ frameBufferCoherent_ = true;
1234
+ canvas_.resetDirty();
1235
+ }
1236
+ return ok;
1237
+ }
1238
+
1239
+ bool shouldForceFullPanelBackRepaint(const present::Frame &current) const
1240
+ {
1241
+ if (!canUseNativePanelBackBufferPath() || scrollOriginX_ != 0 || scrollOriginY_ != 0) return false;
1242
+ if (!present::frameHasOpaqueBase(current, logicalWidth(), logicalHeight())) return false;
1243
+ if (!isFastClearFillCirclesFrame(current) || current.commands[1].circlesCount < 256) return false;
1244
+ return true;
1245
+ }
1246
+
1247
+ // A frame whose base layer is [Clear-or-full-fill, FillCircles]. Commands AFTER
1248
+ // the circle batch (FPS text, a HUD rect, ...) are overlays drawn on top — they
1249
+ // ride the incremental path via a per-frame overlay re-raster, so they no longer
1250
+ // disqualify it. Direct-canvas ctx.clear() currently emits a full-screen fill
1251
+ // rect, so accepting both base forms keeps generated apps on this path.
1252
+ bool isFastClearFillCirclesFrame(const present::Frame &frame) const
1253
+ {
1254
+ using Type = gea::platform::display::DisplayPresentCommandType;
1255
+ if (frame.commands.size() < 2) return false;
1256
+ const present::Command &base = frame.commands[0];
1257
+ const present::Command &circles = frame.commands[1];
1258
+ const bool clearBase = base.type == Type::Clear;
1259
+ const bool fillBase = base.type == Type::FillRectRgb565 &&
1260
+ base.alpha == 255 &&
1261
+ base.x <= 0 &&
1262
+ base.y <= 0 &&
1263
+ base.x + base.w >= logicalWidth() &&
1264
+ base.y + base.h >= logicalHeight();
1265
+ if ((!clearBase && !fillBase) || circles.type != Type::FillCirclesRgb565) return false;
1266
+ if (circles.alpha != 255 || circles.radius <= 0 || circles.circlesCount < 0) return false;
1267
+ return circles.hasCircleEntries();
1268
+ }
1269
+
1270
+ // The incremental circle path erases + redraws every ball (2x scattered writes
1271
+ // over the whole framebuffer — cache-thrashing) to save the cache writeback on
1272
+ // the untouched area. That trade only pays when the touched area is small; for a
1273
+ // dense/full-screen ball field the general chunked rasterizer is faster (measured
1274
+ // 21.6 vs 18.2fps for 1000 balls). So gate the incremental path on the would-be
1275
+ // dirty area, mirroring the amoled's geometric band-collapse decision.
1276
+ bool incrementalCirclePathBeneficial(const present::Frame &previous, const present::Frame &current) const
1277
+ {
1278
+ if (!isFastClearFillCirclesFrame(previous)) return false;
1279
+ if (previous.commands[0].color != current.commands[0].color) return false;
1280
+ present::Rect dirtyRects[kMaxFlushRects];
1281
+ int dirtyCount = 0;
1282
+ addCommandDirtyRectsTight(previous.commands[1], dirtyRects, &dirtyCount, kMaxFlushRects);
1283
+ addCommandDirtyRectsTight(current.commands[1], dirtyRects, &dirtyCount, kMaxFlushRects);
1284
+ for (std::size_t i = 2; i < current.commands.size(); ++i)
1285
+ addCommandDirtyRectsTight(current.commands[i], dirtyRects, &dirtyCount, kMaxFlushRects);
1286
+ for (std::size_t i = 2; i < previous.commands.size(); ++i)
1287
+ addCommandDirtyRectsTight(previous.commands[i], dirtyRects, &dirtyCount, kMaxFlushRects);
1288
+ if (dirtyCount <= 0) return true; // nothing moved — trivially cheap
1289
+ const long long dirtyArea = rectAreaSum(dirtyRects, dirtyCount);
1290
+ const long long screenArea = static_cast<long long>(logicalWidth()) * logicalHeight();
1291
+ return dirtyArea < screenArea;
1292
+ }
1293
+
1294
+ bool incrementalCirclePathBeneficial(const present::Frame &current) const
1295
+ {
1296
+ if (!previousPresentValid_ || needsFullPhysicalFlush_) return false;
1297
+ return incrementalCirclePathBeneficial(previousPresentFrame_, current);
1298
+ }
1299
+
1300
+ bool smallCircleDeltaEligible(const present::Frame &previous, const present::Frame &current) const
1301
+ {
1302
+ if (!isFastClearFillCirclesFrame(previous) || !isFastClearFillCirclesFrame(current)) return false;
1303
+ const present::Command &oldCircles = previous.commands[1];
1304
+ const present::Command &newCircles = current.commands[1];
1305
+ return oldCircles.radius == newCircles.radius &&
1306
+ oldCircles.circlesCount <= kCircleDeltaMax &&
1307
+ newCircles.circlesCount <= kCircleDeltaMax;
1308
+ }
1309
+
1310
+ bool presentClearFillCirclesFrame(const present::Frame &current, const present::Frame *previousForBuffer)
1311
+ {
1312
+ const present::Command &clear = current.commands[0];
1313
+ const present::Command &circles = current.commands[1];
1314
+ const bool previousFast =
1315
+ previousForBuffer &&
1316
+ isFastClearFillCirclesFrame(*previousForBuffer) &&
1317
+ previousForBuffer->commands[0].color == clear.color;
1318
+ const bool smallDelta = previousFast && smallCircleDeltaEligible(*previousForBuffer, current);
1319
+ const bool canIncremental =
1320
+ previousFast &&
1321
+ (smallDelta || incrementalCirclePathBeneficial(*previousForBuffer, current));
1322
+ constexpr bool kUseIncrementalCircleDirty = false;
1323
+ const bool incremental = kUseIncrementalCircleDirty && canIncremental && !needsFullPhysicalFlush_;
1324
+
1325
+ // Overlays = every command past the circle batch (e.g. the FPS text). They
1326
+ // sit on top of the balls and don't move with them, so their box — current
1327
+ // AND previous (to erase the stale overlay) — is repainted independently and
1328
+ // re-composited from scratch. Empty when the frame is pure [Clear, FillCircles].
1329
+ present::Rect overlayRects[kMaxFlushRects];
1330
+ int overlayCount = 0;
1331
+ const bool scalarCircleDelta = incremental && scalarCircleOverlayDeltaEligible(*previousForBuffer, current);
1332
+ for (std::size_t i = 2; i < current.commands.size(); ++i) {
1333
+ if (incremental) {
1334
+ if (scalarCircleDelta && isScalarCircleOverlayCommand(current.commands[i])) continue;
1335
+ } else if (isCircleOverlayCommand(current.commands[i])) {
1336
+ continue;
1337
+ }
1338
+ addCommandDirtyRectsTight(current.commands[i], overlayRects, &overlayCount, kMaxFlushRects);
1339
+ }
1340
+ if (incremental)
1341
+ for (std::size_t i = 2; i < previousForBuffer->commands.size(); ++i) {
1342
+ if (scalarCircleDelta && isScalarCircleOverlayCommand(previousForBuffer->commands[i])) continue;
1343
+ addCommandDirtyRectsTight(previousForBuffer->commands[i], overlayRects, &overlayCount, kMaxFlushRects);
1344
+ }
1345
+
1346
+ present::Rect dirtyRects[kMaxFlushRects];
1347
+ int dirtyCount = 0;
1348
+ if (!incremental) {
1349
+ dirtyRects[0] = present::fullScreen(logicalWidth(), logicalHeight());
1350
+ dirtyCount = 1;
1351
+ }
1352
+
1353
+ const std::int64_t started = esp_timer_get_time();
1354
+ flushStats_.callCount++;
1355
+ const std::int64_t rasterStartUs = esp_timer_get_time();
1356
+ if (incremental) {
1357
+ const bool deltaDrawn = drawCircleBatchDeltaRaw(previousForBuffer->commands[1],
1358
+ circles,
1359
+ clear.color,
1360
+ dirtyRects,
1361
+ &dirtyCount,
1362
+ kMaxFlushRects);
1363
+ if (!deltaDrawn) {
1364
+ addCommandDirtyRectsTight(previousForBuffer->commands[1], dirtyRects, &dirtyCount, kMaxFlushRects);
1365
+ addCommandDirtyRectsTight(circles, dirtyRects, &dirtyCount, kMaxFlushRects);
1366
+ drawCircleBatchRaw(previousForBuffer->commands[1], clear.color, true);
1367
+ drawCircleBatchRaw(circles, 0, false);
1368
+ }
1369
+ if (scalarCircleDelta)
1370
+ drawScalarCircleOverlayDelta(*previousForBuffer, current, clear.color, dirtyRects, &dirtyCount, kMaxFlushRects);
1371
+ } else {
1372
+ clearFrameBufferRows(0, logicalHeight() - 1, clear.color);
1373
+ drawCircleBatchRaw(circles, 0, false);
1374
+ drawScalarCircleOverlaysRaw(current);
1375
+ }
1376
+ // Composite overlays: re-raster their box from the full frame (clear + the
1377
+ // balls behind them + the overlay itself), so the old overlay is erased and
1378
+ // the new one lands on top of whatever balls sit behind it.
1379
+ for (int i = 0; i < overlayCount; ++i) {
1380
+ rasterPresentRegion(current, overlayRects[i]);
1381
+ if (incremental)
1382
+ addRectTight(dirtyRects, &dirtyCount, kMaxFlushRects, overlayRects[i], logicalWidth(), logicalHeight());
1383
+ }
1384
+ flushStats_.rasterUs += esp_timer_get_time() - rasterStartUs;
1385
+
1386
+ if (dirtyCount <= 0) return true;
1387
+ const bool ok = flushPreparedLogicalRects(dirtyRects, dirtyCount);
1388
+ flushStats_.totalUs += esp_timer_get_time() - started;
1389
+ if (ok) frameBufferCoherent_ = true;
1390
+ return ok;
1391
+ }
1392
+
1393
+ present::Rect circleBatchBounds(const present::Command &command) const
1394
+ {
1395
+ present::Rect bounds{};
1396
+ const auto *circles = command.circleEntries();
1397
+ if (!circles || command.circlesCount <= 0) return bounds;
1398
+ for (int i = 0; i < command.circlesCount; ++i) {
1399
+ bounds = present::unite(bounds,
1400
+ present::circleBounds(static_cast<int>(circles[i].x),
1401
+ static_cast<int>(circles[i].y),
1402
+ command.radius));
1403
+ }
1404
+ return bounds;
1405
+ }
1406
+
1407
+ void addCommandDirtyRectsTight(const present::Command &command,
1408
+ present::Rect *rects,
1409
+ int *count,
1410
+ int capacity) const
1411
+ {
1412
+ using Type = gea::platform::display::DisplayPresentCommandType;
1413
+ if (command.type == Type::FillCirclesRgb565) {
1414
+ const auto *circles = command.circleEntries();
1415
+ if (!circles || command.circlesCount <= 0) return;
1416
+ for (int i = 0; i < command.circlesCount; ++i) {
1417
+ addRectTight(rects,
1418
+ count,
1419
+ capacity,
1420
+ present::circleBounds(static_cast<int>(circles[i].x),
1421
+ static_cast<int>(circles[i].y),
1422
+ command.radius),
1423
+ logicalWidth(),
1424
+ logicalHeight());
1425
+ }
1426
+ return;
1427
+ }
1428
+ addRectTight(rects,
1429
+ count,
1430
+ capacity,
1431
+ present::commandBounds(command, logicalWidth(), logicalHeight()),
1432
+ logicalWidth(),
1433
+ logicalHeight());
1434
+ }
1435
+
1436
+ void clearFrameBufferRows(int y0, int y1, std::uint16_t color)
1437
+ {
1438
+ if (!frameBuffer_) return;
1439
+ y0 = std::max(0, y0);
1440
+ y1 = std::min(logicalHeight() - 1, y1);
1441
+ if (y0 > y1) return;
1442
+ const int width = logicalWidth();
1443
+ const int rows = y1 - y0 + 1;
1444
+ std::uint16_t *dst = frameBuffer_ + static_cast<std::size_t>(y0) * logicalStride_;
1445
+ if (logicalStride_ == width) {
1446
+ const std::size_t pixels = static_cast<std::size_t>(width) * rows;
1447
+ if (color == 0) std::memset(dst, 0, pixels * sizeof(std::uint16_t));
1448
+ else std::fill_n(dst, pixels, color);
1449
+ return;
1450
+ }
1451
+ for (int y = y0; y <= y1; ++y) {
1452
+ std::uint16_t *row = frameBuffer_ + static_cast<std::size_t>(y) * logicalStride_;
1453
+ if (color == 0) std::memset(row, 0, static_cast<std::size_t>(width) * sizeof(std::uint16_t));
1454
+ else std::fill_n(row, width, color);
1455
+ }
1456
+ }
1457
+
1458
+ int circleHalfWidth(int r, int dy)
1459
+ {
1460
+ if (r <= 0) return 0;
1461
+ const int ady = dy < 0 ? -dy : dy;
1462
+ if (ady > r) return 0;
1463
+ if (r <= kCircleSpanCacheMaxRadius) {
1464
+ if (circleSpanCacheRadius_ != r) {
1465
+ for (int y = 0; y <= r; ++y) {
1466
+ circleSpanHalfWidths_[y] = integerSqrt(r * r - y * y);
1467
+ }
1468
+ circleSpanCacheRadius_ = r;
1469
+ }
1470
+ return circleSpanHalfWidths_[ady];
1471
+ }
1472
+ return integerSqrt(r * r - dy * dy);
1473
+ }
1474
+
1475
+ void fillFrameBufferSpanRaw(int y, int x0, int x1, std::uint16_t color)
1476
+ {
1477
+ if (!frameBuffer_ || y < 0 || y >= logicalHeight()) return;
1478
+ if (x0 < 0) x0 = 0;
1479
+ if (x1 >= logicalWidth()) x1 = logicalWidth() - 1;
1480
+ if (x0 > x1) return;
1481
+ std::uint16_t *dst = frameBuffer_ + static_cast<std::size_t>(y) * logicalStride_ + x0;
1482
+ const int count = x1 - x0 + 1;
1483
+ if (color == 0) std::memset(dst, 0, static_cast<std::size_t>(count) * sizeof(std::uint16_t));
1484
+ else std::fill_n(dst, count, color);
1485
+ }
1486
+
1487
+ void fillFrameBufferColumnRaw(int x, int y0, int y1, std::uint16_t color)
1488
+ {
1489
+ if (!frameBuffer_ || x < 0 || x >= logicalWidth()) return;
1490
+ if (y0 < 0) y0 = 0;
1491
+ if (y1 >= logicalHeight()) y1 = logicalHeight() - 1;
1492
+ if (y0 > y1) return;
1493
+ std::uint16_t *dst = frameBuffer_ + static_cast<std::size_t>(y0) * logicalStride_ + x;
1494
+ const int stride = logicalStride_;
1495
+ for (int y = y0; y <= y1; ++y) {
1496
+ *dst = color;
1497
+ dst += stride;
1498
+ }
1499
+ }
1500
+
1501
+ void drawCircleRaw(int cx, int cy, int r, std::uint16_t color)
1502
+ {
1503
+ if (!frameBuffer_ || r <= 0) return;
1504
+ int dy0 = -r;
1505
+ int dy1 = r;
1506
+ if (cy + dy0 < 0) dy0 = -cy;
1507
+ if (cy + dy1 >= logicalHeight()) dy1 = logicalHeight() - 1 - cy;
1508
+ if (dy0 > dy1) return;
1509
+ for (int dy = dy0; dy <= dy1; ++dy) {
1510
+ const int halfWidth = circleHalfWidth(r, dy);
1511
+ fillFrameBufferSpanRaw(cy + dy, cx - halfWidth, cx + halfWidth, color);
1512
+ }
1513
+ }
1514
+
1515
+ void drawCircleDifferenceRaw(int cx, int cy, int r, int otherCx, int otherCy, int otherR, std::uint16_t color)
1516
+ {
1517
+ if (!frameBuffer_ || r <= 0) return;
1518
+ int y0 = cy - r;
1519
+ int y1 = cy + r;
1520
+ if (y0 < 0) y0 = 0;
1521
+ if (y1 >= logicalHeight()) y1 = logicalHeight() - 1;
1522
+ if (y0 > y1) return;
1523
+ for (int y = y0; y <= y1; ++y) {
1524
+ const int dy = y - cy;
1525
+ const int halfWidth = circleHalfWidth(r, dy);
1526
+ int x0 = cx - halfWidth;
1527
+ int x1 = cx + halfWidth;
1528
+ const int ody = y - otherCy;
1529
+ const int aody = ody < 0 ? -ody : ody;
1530
+ if (otherR <= 0 || aody > otherR) {
1531
+ fillFrameBufferSpanRaw(y, x0, x1, color);
1532
+ continue;
1533
+ }
1534
+ const int otherHalfWidth = circleHalfWidth(otherR, ody);
1535
+ const int ox0 = otherCx - otherHalfWidth;
1536
+ const int ox1 = otherCx + otherHalfWidth;
1537
+ if (x0 < ox0) fillFrameBufferSpanRaw(y, x0, std::min(x1, ox0 - 1), color);
1538
+ if (x1 > ox1) fillFrameBufferSpanRaw(y, std::max(x0, ox1 + 1), x1, color);
1539
+ }
1540
+ }
1541
+
1542
+ void drawCircleDifferenceRaw(int cx, int cy, int otherCx, int otherCy, int r, std::uint16_t color)
1543
+ {
1544
+ drawCircleDifferenceRaw(cx, cy, r, otherCx, otherCy, r, color);
1545
+ }
1546
+
1547
+ bool drawHorizontalCircleShiftDeltaRaw(int oldCx,
1548
+ int oldCy,
1549
+ int newCx,
1550
+ int newCy,
1551
+ int r,
1552
+ std::uint16_t clearColor,
1553
+ std::uint16_t newColor)
1554
+ {
1555
+ if (!frameBuffer_ || r <= 0 || oldCy != newCy) return false;
1556
+ const int dx = newCx - oldCx;
1557
+ const int adx = dx < 0 ? -dx : dx;
1558
+ if (adx <= 0 || adx > kCircleDeltaMaxShift) return false;
1559
+ if (dx > 0) {
1560
+ for (int i = 0; i < dx; ++i) {
1561
+ const int clearX = oldCx - r + i;
1562
+ const int clearHalfHeight = circleHalfWidth(r, clearX - oldCx);
1563
+ fillFrameBufferColumnRaw(clearX, oldCy - clearHalfHeight, oldCy + clearHalfHeight, clearColor);
1564
+ const int drawX = oldCx + r + 1 + i;
1565
+ const int drawHalfHeight = circleHalfWidth(r, drawX - newCx);
1566
+ fillFrameBufferColumnRaw(drawX, newCy - drawHalfHeight, newCy + drawHalfHeight, newColor);
1567
+ }
1568
+ } else {
1569
+ for (int i = 0; i < adx; ++i) {
1570
+ const int clearX = oldCx + r - i;
1571
+ const int clearHalfHeight = circleHalfWidth(r, clearX - oldCx);
1572
+ fillFrameBufferColumnRaw(clearX, oldCy - clearHalfHeight, oldCy + clearHalfHeight, clearColor);
1573
+ const int drawX = oldCx - r - 1 - i;
1574
+ const int drawHalfHeight = circleHalfWidth(r, drawX - newCx);
1575
+ fillFrameBufferColumnRaw(drawX, newCy - drawHalfHeight, newCy + drawHalfHeight, newColor);
1576
+ }
1577
+ }
1578
+ return true;
1579
+ }
1580
+
1581
+ bool appendCircleShiftDirtyRects(int oldCx,
1582
+ int oldCy,
1583
+ int newCx,
1584
+ int newCy,
1585
+ int r,
1586
+ present::Rect *rects,
1587
+ int *count,
1588
+ int capacity) const
1589
+ {
1590
+ const int dx = newCx - oldCx;
1591
+ const int dy = newCy - oldCy;
1592
+ const int adx = dx < 0 ? -dx : dx;
1593
+ const int ady = dy < 0 ? -dy : dy;
1594
+ if (dx == 0 && dy == 0) return true;
1595
+ if (dy == 0 && adx <= kCircleDeltaMaxShift) {
1596
+ if (dx > 0) {
1597
+ addRectTight(rects, count, capacity, {oldCx - r, oldCy - r, oldCx - r + dx - 1, oldCy + r}, logicalWidth(), logicalHeight());
1598
+ addRectTight(rects, count, capacity, {oldCx + r + 1, oldCy - r, oldCx + r + dx, oldCy + r}, logicalWidth(), logicalHeight());
1599
+ } else {
1600
+ addRectTight(rects, count, capacity, {oldCx + r + dx + 1, oldCy - r, oldCx + r, oldCy + r}, logicalWidth(), logicalHeight());
1601
+ addRectTight(rects, count, capacity, {oldCx + dx - r, oldCy - r, oldCx - r - 1, oldCy + r}, logicalWidth(), logicalHeight());
1602
+ }
1603
+ return true;
1604
+ }
1605
+ if (dx == 0 && ady <= kCircleDeltaMaxShift) {
1606
+ if (dy > 0) {
1607
+ addRectTight(rects, count, capacity, {oldCx - r, oldCy - r, oldCx + r, oldCy - r + dy - 1}, logicalWidth(), logicalHeight());
1608
+ addRectTight(rects, count, capacity, {oldCx - r, oldCy + r + 1, oldCx + r, oldCy + r + dy}, logicalWidth(), logicalHeight());
1609
+ } else {
1610
+ addRectTight(rects, count, capacity, {oldCx - r, oldCy + r + dy + 1, oldCx + r, oldCy + r}, logicalWidth(), logicalHeight());
1611
+ addRectTight(rects, count, capacity, {oldCx - r, oldCy + dy - r, oldCx + r, oldCy - r - 1}, logicalWidth(), logicalHeight());
1612
+ }
1613
+ return true;
1614
+ }
1615
+ return false;
1616
+ }
1617
+
1618
+ bool isScalarCircleOverlayCommand(const present::Command &command) const
1619
+ {
1620
+ using Type = gea::platform::display::DisplayPresentCommandType;
1621
+ return command.type == Type::FillCircleRgb565 && command.alpha == 255 && command.radius > 0;
1622
+ }
1623
+
1624
+ bool isCircleOverlayCommand(const present::Command &command) const
1625
+ {
1626
+ using Type = gea::platform::display::DisplayPresentCommandType;
1627
+ if (isScalarCircleOverlayCommand(command)) return true;
1628
+ return command.type == Type::FillCirclesRgb565 &&
1629
+ command.alpha == 255 &&
1630
+ command.radius > 0 &&
1631
+ command.circlesCount > 0 &&
1632
+ command.hasCircleEntries();
1633
+ }
1634
+
1635
+ int collectScalarCircleOverlayIndices(const present::Frame &frame, int *indices, int capacity) const
1636
+ {
1637
+ if (!indices || capacity <= 0) return 0;
1638
+ int count = 0;
1639
+ for (std::size_t i = 2; i < frame.commands.size(); ++i) {
1640
+ if (!isScalarCircleOverlayCommand(frame.commands[i])) continue;
1641
+ if (count >= capacity) return capacity + 1;
1642
+ indices[count++] = static_cast<int>(i);
1643
+ }
1644
+ return count;
1645
+ }
1646
+
1647
+ bool scalarCircleOverlayDeltaEligible(const present::Frame &previous, const present::Frame &current) const
1648
+ {
1649
+ int previousIndices[kCircleDeltaMax];
1650
+ int currentIndices[kCircleDeltaMax];
1651
+ const int previousCount = collectScalarCircleOverlayIndices(previous, previousIndices, kCircleDeltaMax);
1652
+ const int currentCount = collectScalarCircleOverlayIndices(current, currentIndices, kCircleDeltaMax);
1653
+ return previousCount <= kCircleDeltaMax && currentCount <= kCircleDeltaMax;
1654
+ }
1655
+
1656
+ void appendCircleDeltaDirtyRects(int oldCx,
1657
+ int oldCy,
1658
+ int oldR,
1659
+ int newCx,
1660
+ int newCy,
1661
+ int newR,
1662
+ present::Rect *rects,
1663
+ int *count,
1664
+ int capacity) const
1665
+ {
1666
+ if (oldCx == newCx && oldCy == newCy && oldR == newR) return;
1667
+ if (oldR == newR &&
1668
+ appendCircleShiftDirtyRects(oldCx, oldCy, newCx, newCy, oldR, rects, count, capacity)) {
1669
+ return;
1670
+ }
1671
+ const int dx = newCx - oldCx;
1672
+ const int dy = newCy - oldCy;
1673
+ const int dr = newR - oldR;
1674
+ const int adx = dx < 0 ? -dx : dx;
1675
+ const int ady = dy < 0 ? -dy : dy;
1676
+ const int adr = dr < 0 ? -dr : dr;
1677
+ if (adx + adr <= kCircleDeltaMaxShift && ady + adr <= kCircleDeltaMaxShift) {
1678
+ const int ux0 = std::min(oldCx - oldR, newCx - newR);
1679
+ const int uy0 = std::min(oldCy - oldR, newCy - newR);
1680
+ const int ux1 = std::max(oldCx + oldR, newCx + newR);
1681
+ const int uy1 = std::max(oldCy + oldR, newCy + newR);
1682
+ const int sideW = adx + adr;
1683
+ const int sideH = ady + adr;
1684
+ if (sideW > 0) {
1685
+ addRectTight(rects, count, capacity, {ux0, uy0, ux0 + sideW - 1, uy1}, logicalWidth(), logicalHeight());
1686
+ addRectTight(rects, count, capacity, {ux1 - sideW + 1, uy0, ux1, uy1}, logicalWidth(), logicalHeight());
1687
+ }
1688
+ if (sideH > 0) {
1689
+ addRectTight(rects, count, capacity, {ux0, uy0, ux1, uy0 + sideH - 1}, logicalWidth(), logicalHeight());
1690
+ addRectTight(rects, count, capacity, {ux0, uy1 - sideH + 1, ux1, uy1}, logicalWidth(), logicalHeight());
1691
+ }
1692
+ return;
1693
+ }
1694
+ addRectTight(rects, count, capacity, present::circleBounds(oldCx, oldCy, oldR), logicalWidth(), logicalHeight());
1695
+ addRectTight(rects, count, capacity, present::circleBounds(newCx, newCy, newR), logicalWidth(), logicalHeight());
1696
+ }
1697
+
1698
+ void drawScalarCircleOverlaysRaw(const present::Frame &current)
1699
+ {
1700
+ using Type = gea::platform::display::DisplayPresentCommandType;
1701
+ for (std::size_t i = 2; i < current.commands.size(); ++i) {
1702
+ const present::Command &command = current.commands[i];
1703
+ if (isScalarCircleOverlayCommand(command)) {
1704
+ drawCircleRaw(command.x, command.y, command.radius, command.color);
1705
+ continue;
1706
+ }
1707
+ if (command.type == Type::FillCirclesRgb565 && command.alpha == 255) {
1708
+ drawCircleBatchRaw(command, 0, false);
1709
+ }
1710
+ }
1711
+ }
1712
+
1713
+ void drawScalarCircleOverlayDelta(const present::Frame &previous,
1714
+ const present::Frame &current,
1715
+ std::uint16_t clearColor,
1716
+ present::Rect *dirtyRects,
1717
+ int *dirtyCount,
1718
+ int dirtyCapacity)
1719
+ {
1720
+ int previousIndices[kCircleDeltaMax];
1721
+ int currentIndices[kCircleDeltaMax];
1722
+ const int previousCount = collectScalarCircleOverlayIndices(previous, previousIndices, kCircleDeltaMax);
1723
+ const int currentCount = collectScalarCircleOverlayIndices(current, currentIndices, kCircleDeltaMax);
1724
+ if (previousCount > kCircleDeltaMax || currentCount > kCircleDeltaMax) return;
1725
+
1726
+ int oldToNew[kCircleDeltaMax];
1727
+ int newToOld[kCircleDeltaMax];
1728
+ std::int8_t oldMode[kCircleDeltaMax];
1729
+ for (int i = 0; i < kCircleDeltaMax; ++i) {
1730
+ oldToNew[i] = -1;
1731
+ newToOld[i] = -1;
1732
+ oldMode[i] = 0;
1733
+ }
1734
+
1735
+ for (int i = 0; i < previousCount; ++i) {
1736
+ const present::Command &oldCircle = previous.commands[previousIndices[i]];
1737
+ int best = -1;
1738
+ int bestDistance = 0x7fffffff;
1739
+ for (int j = 0; j < currentCount; ++j) {
1740
+ if (newToOld[j] >= 0) continue;
1741
+ const present::Command &newCircle = current.commands[currentIndices[j]];
1742
+ if (newCircle.color != oldCircle.color) continue;
1743
+ const int dx = newCircle.x - oldCircle.x;
1744
+ const int dy = newCircle.y - oldCircle.y;
1745
+ const int dr = newCircle.radius - oldCircle.radius;
1746
+ const int distance = (dx < 0 ? -dx : dx) + (dy < 0 ? -dy : dy) + (dr < 0 ? -dr : dr);
1747
+ if (distance < bestDistance) {
1748
+ bestDistance = distance;
1749
+ best = j;
1750
+ }
1751
+ }
1752
+ if (best >= 0) {
1753
+ oldToNew[i] = best;
1754
+ newToOld[best] = i;
1755
+ }
1756
+ }
1757
+
1758
+ for (int i = 0; i < previousCount; ++i) {
1759
+ const present::Command &oldCircle = previous.commands[previousIndices[i]];
1760
+ const int j = oldToNew[i];
1761
+ if (j < 0) {
1762
+ addRectTight(dirtyRects,
1763
+ dirtyCount,
1764
+ dirtyCapacity,
1765
+ present::circleBounds(oldCircle.x, oldCircle.y, oldCircle.radius),
1766
+ logicalWidth(),
1767
+ logicalHeight());
1768
+ drawCircleRaw(oldCircle.x, oldCircle.y, oldCircle.radius, clearColor);
1769
+ continue;
1770
+ }
1771
+ const present::Command &newCircle = current.commands[currentIndices[j]];
1772
+ if (oldCircle.x == newCircle.x && oldCircle.y == newCircle.y && oldCircle.radius == newCircle.radius) {
1773
+ oldMode[i] = 1;
1774
+ continue;
1775
+ }
1776
+ oldMode[i] = 2;
1777
+ appendCircleDeltaDirtyRects(oldCircle.x,
1778
+ oldCircle.y,
1779
+ oldCircle.radius,
1780
+ newCircle.x,
1781
+ newCircle.y,
1782
+ newCircle.radius,
1783
+ dirtyRects,
1784
+ dirtyCount,
1785
+ dirtyCapacity);
1786
+ drawCircleDifferenceRaw(oldCircle.x,
1787
+ oldCircle.y,
1788
+ oldCircle.radius,
1789
+ newCircle.x,
1790
+ newCircle.y,
1791
+ newCircle.radius,
1792
+ clearColor);
1793
+ }
1794
+
1795
+ for (int j = 0; j < currentCount; ++j) {
1796
+ const present::Command &newCircle = current.commands[currentIndices[j]];
1797
+ const int i = newToOld[j];
1798
+ if (i < 0) {
1799
+ addRectTight(dirtyRects,
1800
+ dirtyCount,
1801
+ dirtyCapacity,
1802
+ present::circleBounds(newCircle.x, newCircle.y, newCircle.radius),
1803
+ logicalWidth(),
1804
+ logicalHeight());
1805
+ drawCircleRaw(newCircle.x, newCircle.y, newCircle.radius, newCircle.color);
1806
+ continue;
1807
+ }
1808
+ if (oldMode[i] == 1) continue;
1809
+ const present::Command &oldCircle = previous.commands[previousIndices[i]];
1810
+ drawCircleDifferenceRaw(newCircle.x,
1811
+ newCircle.y,
1812
+ newCircle.radius,
1813
+ oldCircle.x,
1814
+ oldCircle.y,
1815
+ oldCircle.radius,
1816
+ newCircle.color);
1817
+ }
1818
+ }
1819
+
1820
+ bool drawCircleBatchDeltaRaw(const present::Command &previous,
1821
+ const present::Command &current,
1822
+ std::uint16_t clearColor,
1823
+ present::Rect *dirtyRects,
1824
+ int *dirtyCount,
1825
+ int dirtyCapacity)
1826
+ {
1827
+ if (!frameBuffer_ || previous.radius <= 0 || current.radius != previous.radius) return false;
1828
+ if (previous.circlesCount < 0 || current.circlesCount < 0 ||
1829
+ previous.circlesCount > kCircleDeltaMax || current.circlesCount > kCircleDeltaMax) {
1830
+ return false;
1831
+ }
1832
+ const auto *oldCircles = previous.circleEntries();
1833
+ const auto *newCircles = current.circleEntries();
1834
+ if ((previous.circlesCount > 0 && !oldCircles) || (current.circlesCount > 0 && !newCircles)) return false;
1835
+
1836
+ int oldToNew[kCircleDeltaMax];
1837
+ int newToOld[kCircleDeltaMax];
1838
+ std::int8_t oldMode[kCircleDeltaMax];
1839
+ for (int i = 0; i < kCircleDeltaMax; ++i) {
1840
+ oldToNew[i] = -1;
1841
+ newToOld[i] = -1;
1842
+ oldMode[i] = 0;
1843
+ }
1844
+
1845
+ for (int i = 0; i < previous.circlesCount; ++i) {
1846
+ const auto &oldCircle = oldCircles[i];
1847
+ int best = -1;
1848
+ int bestDistance = 0x7fffffff;
1849
+ for (int j = 0; j < current.circlesCount; ++j) {
1850
+ if (newToOld[j] >= 0) continue;
1851
+ const auto &newCircle = newCircles[j];
1852
+ if (newCircle.color != oldCircle.color) continue;
1853
+ const int dx = static_cast<int>(newCircle.x) - static_cast<int>(oldCircle.x);
1854
+ const int dy = static_cast<int>(newCircle.y) - static_cast<int>(oldCircle.y);
1855
+ const int distance = (dx < 0 ? -dx : dx) + (dy < 0 ? -dy : dy);
1856
+ if (distance < bestDistance) {
1857
+ bestDistance = distance;
1858
+ best = j;
1859
+ }
1860
+ }
1861
+ if (best >= 0) {
1862
+ oldToNew[i] = best;
1863
+ newToOld[best] = i;
1864
+ }
1865
+ }
1866
+
1867
+ const int r = current.radius;
1868
+ for (int i = 0; i < previous.circlesCount; ++i) {
1869
+ const auto &oldCircle = oldCircles[i];
1870
+ const int oldCx = static_cast<int>(oldCircle.x);
1871
+ const int oldCy = static_cast<int>(oldCircle.y);
1872
+ const int j = oldToNew[i];
1873
+ if (j < 0) {
1874
+ addRectTight(dirtyRects, dirtyCount, dirtyCapacity, present::circleBounds(oldCx, oldCy, r), logicalWidth(), logicalHeight());
1875
+ drawCircleRaw(oldCx, oldCy, r, clearColor);
1876
+ continue;
1877
+ }
1878
+ const auto &newCircle = newCircles[j];
1879
+ const int newCx = static_cast<int>(newCircle.x);
1880
+ const int newCy = static_cast<int>(newCircle.y);
1881
+ if (oldCx == newCx && oldCy == newCy) {
1882
+ oldMode[i] = 1;
1883
+ continue;
1884
+ }
1885
+ if (appendCircleShiftDirtyRects(oldCx, oldCy, newCx, newCy, r, dirtyRects, dirtyCount, dirtyCapacity)) {
1886
+ if (drawHorizontalCircleShiftDeltaRaw(oldCx,
1887
+ oldCy,
1888
+ newCx,
1889
+ newCy,
1890
+ r,
1891
+ clearColor,
1892
+ newCircle.color)) {
1893
+ oldMode[i] = 4;
1894
+ } else {
1895
+ oldMode[i] = 2;
1896
+ drawCircleDifferenceRaw(oldCx, oldCy, newCx, newCy, r, clearColor);
1897
+ }
1898
+ } else {
1899
+ oldMode[i] = 3;
1900
+ addRectTight(dirtyRects, dirtyCount, dirtyCapacity, present::circleBounds(oldCx, oldCy, r), logicalWidth(), logicalHeight());
1901
+ addRectTight(dirtyRects, dirtyCount, dirtyCapacity, present::circleBounds(newCx, newCy, r), logicalWidth(), logicalHeight());
1902
+ drawCircleRaw(oldCx, oldCy, r, clearColor);
1903
+ }
1904
+ }
1905
+
1906
+ for (int j = 0; j < current.circlesCount; ++j) {
1907
+ const auto &newCircle = newCircles[j];
1908
+ const int newCx = static_cast<int>(newCircle.x);
1909
+ const int newCy = static_cast<int>(newCircle.y);
1910
+ const int i = newToOld[j];
1911
+ if (i < 0) {
1912
+ addRectTight(dirtyRects, dirtyCount, dirtyCapacity, present::circleBounds(newCx, newCy, r), logicalWidth(), logicalHeight());
1913
+ drawCircleRaw(newCx, newCy, r, newCircle.color);
1914
+ continue;
1915
+ }
1916
+ if (oldMode[i] == 1 || oldMode[i] == 4) continue;
1917
+ const auto &oldCircle = oldCircles[i];
1918
+ if (oldMode[i] == 2)
1919
+ drawCircleDifferenceRaw(newCx, newCy, static_cast<int>(oldCircle.x), static_cast<int>(oldCircle.y), r, newCircle.color);
1920
+ else
1921
+ drawCircleRaw(newCx, newCy, r, newCircle.color);
1922
+ }
1923
+ return true;
1924
+ }
1925
+
1926
+ void drawCircleBatchRaw(const present::Command &command, std::uint16_t overrideColor, bool useOverrideColor)
1927
+ {
1928
+ if (!frameBuffer_ || command.radius <= 0 || command.circlesCount <= 0) return;
1929
+ const auto *circles = command.circleEntries();
1930
+ if (!circles) return;
1931
+ const int width = logicalWidth();
1932
+ const int height = logicalHeight();
1933
+ const int r = command.radius;
1934
+ for (int i = 0; i < command.circlesCount; ++i) {
1935
+ const int cx = static_cast<int>(circles[i].x);
1936
+ const int cy = static_cast<int>(circles[i].y);
1937
+ const std::uint16_t color = useOverrideColor ? overrideColor : circles[i].color;
1938
+ int dy0 = -r;
1939
+ int dy1 = r;
1940
+ if (cy + dy0 < 0) dy0 = -cy;
1941
+ if (cy + dy1 >= height) dy1 = height - 1 - cy;
1942
+ if (dy0 > dy1) continue;
1943
+ for (int dy = dy0; dy <= dy1; ++dy) {
1944
+ const int halfWidth = circleHalfWidth(r, dy);
1945
+ int x0 = cx - halfWidth;
1946
+ int x1 = cx + halfWidth;
1947
+ if (x0 < 0) x0 = 0;
1948
+ if (x1 >= width) x1 = width - 1;
1949
+ if (x0 > x1) continue;
1950
+ std::uint16_t *dst = frameBuffer_ + static_cast<std::size_t>(cy + dy) * logicalStride_ + x0;
1951
+ const int count = x1 - x0 + 1;
1952
+ if (color == 0) std::memset(dst, 0, static_cast<std::size_t>(count) * sizeof(std::uint16_t));
1953
+ else std::fill_n(dst, count, color);
1954
+ }
1955
+ }
1956
+ }
1957
+
1958
+ void setFlushConfig(int chunkRows, int queueDepth)
1959
+ {
1960
+ if (chunkRows > 0) flushRows_ = std::min(chunkRows, kFlushRowsDefault);
1961
+ if (queueDepth > 0) flushDepth_ = queueDepth;
1962
+ }
1963
+
1964
+ int flushChunkRows() const { return flushRows_; }
1965
+ int flushQueueDepth() const { return flushDepth_; }
1966
+ int flushBufferBytes() const { return 0; }
1967
+
1968
+ bool copySnapshotRgb565(std::uint16_t *dst, int pixelCapacity, int *width, int *height)
1969
+ {
1970
+ const int lw = logicalWidth();
1971
+ const int lh = logicalHeight();
1972
+ if (!dst || pixelCapacity < lw * lh) return false;
1973
+ if (width) *width = lw;
1974
+ if (height) *height = lh;
1975
+ // Panel-direct modes raster straight into the scanout buffers and leave
1976
+ // the composed framebuffer stale — snapshot what the GLASS shows by
1977
+ // reading the scanned panel buffer through the inverse orientation map.
1978
+ if (panelDirectActive_ && panelFrameBuffers_[scannedFbIndex_]) {
1979
+ const std::uint16_t *panel = panelFrameBuffers_[scannedFbIndex_];
1980
+ for (int ly = 0; ly < lh; ++ly) {
1981
+ std::uint16_t *out = dst + static_cast<std::size_t>(ly) * lw;
1982
+ for (int lx = 0; lx < lw; ++lx) {
1983
+ const PanelCoord pc = panelForSourcePixel(lx, ly);
1984
+ out[lx] = panel[static_cast<std::size_t>(pc.y) * kNativeWidth + pc.x];
1985
+ }
1986
+ }
1987
+ return true;
1988
+ }
1989
+ for (int row = 0; row < lh; ++row) {
1990
+ std::memcpy(dst + static_cast<std::size_t>(row) * lw,
1991
+ frameBuffer_ + static_cast<std::size_t>(row) * logicalStride_,
1992
+ static_cast<std::size_t>(lw) * sizeof(std::uint16_t));
1993
+ }
1994
+ return true;
1995
+ }
1996
+
1997
+ int countNonBlackPixels() const
1998
+ {
1999
+ if (!frameBuffer_) return 0;
2000
+ int count = 0;
2001
+ for (int y = 0; y < logicalHeight(); ++y) {
2002
+ const std::uint16_t *row = frameBuffer_ + static_cast<std::size_t>(y) * logicalStride_;
2003
+ for (int x = 0; x < logicalWidth(); ++x) {
2004
+ if (pixel::toRgb565(row[x]) != 0) ++count;
2005
+ }
2006
+ }
2007
+ return count;
2008
+ }
2009
+
2010
+ void setBrightness(int brightness)
2011
+ {
2012
+ if (brightness < 0) brightness = 0;
2013
+ if (brightness > 100) brightness = 100;
2014
+ brightness_ = brightness;
2015
+ if (brightnessInitialized_) updateBacklightDuty();
2016
+ }
2017
+
2018
+ int brightness() const { return brightness_; }
2019
+
2020
+ platform_display::DisplayFlushPerfStats flushStats() const { return flushStats_; }
2021
+ void presentPathDebug(int *calls, int *direct, int *general, int *rejected, int *tsKind, int *tsType, int *tsCount) const
2022
+ {
2023
+ *calls = presentCalls_;
2024
+ *direct = pathDirect_;
2025
+ *general = pathGeneral_;
2026
+ *rejected = pathRejected_;
2027
+ *tsKind = gTileShapeFailKind;
2028
+ *tsType = gTileShapeFailType;
2029
+ *tsCount = gTileShapeFailCount;
2030
+ }
2031
+ void landPanDebug(int *detect, int *kick, int *strips, int *wait, int *interior) const
2032
+ {
2033
+ *detect = panBailCounts_[1] + panBailCounts_[2] * 1000 + panBailCounts_[3] * 1000000;
2034
+ *kick = panBailCounts_[4] + panBailCounts_[5] * 1000 + panBailCounts_[6] * 1000000;
2035
+ *strips = panStripUs_;
2036
+ *wait = panBailReason_;
2037
+ *interior = panInteriorUs_ & 0xffffff;
2038
+ }
2039
+ void landFrameDebug(int *total, int *align, int *raster, int *text, int *flip) const
2040
+ {
2041
+ *total = landTotalUs_;
2042
+ *align = landAlignUs_;
2043
+ *raster = landRasterUs_;
2044
+ *text = landTextUs_;
2045
+ *flip = (landFlipUs_ & 0xffff) | (landPanMode_ << 16) | ((landPanFrames_ & 0xff) << 17) | ((landFullFrames_ & 0x7f) << 25);
2046
+ }
2047
+ void flushStatsReset() { flushStats_ = {}; }
2048
+
2049
+ const char *flushStageName() const { return "idle"; }
2050
+ int flushStageChunk() const { return 0; }
2051
+ platform_display::DisplayFlushStageDetail flushStageDetail() const { return {}; }
2052
+ std::uint16_t *backgroundCache(int *capPx) { return fullScreenScratch(backgroundCache_, backgroundCacheAttempted_, capPx, "background"); }
2053
+ std::uint16_t *backdropCache(int *capPx) { return fullScreenScratch(backdropCache_, backdropCacheAttempted_, capPx, "backdrop"); }
2054
+ void setRenderCore(int core)
2055
+ {
2056
+ renderCoreId_ = core;
2057
+ if (frameBuffer_) workerCanvas_.bindPixels(frameBuffer_, logicalWidth(), logicalHeight(), logicalStride_);
2058
+ }
2059
+
2060
+ void absorbWorkerDirty()
2061
+ {
2062
+ int x0 = 0;
2063
+ int y0 = 0;
2064
+ int x1 = -1;
2065
+ int y1 = -1;
2066
+ if (workerCanvas_.dirty(&x0, &y0, &x1, &y1)) canvas_.markDirty(x0, y0, x1, y1);
2067
+ workerCanvas_.resetDirty();
2068
+ }
2069
+
2070
+ private:
2071
+ DisplayBackend() = default;
2072
+
2073
+ int logicalWidth() const { return orientation_detail::DisplayOrientationState::width(); }
2074
+ int logicalHeight() const { return orientation_detail::DisplayOrientationState::height(); }
2075
+ bool onWorkerCore() const { return renderCoreId_ >= 0 && xPortGetCoreID() != renderCoreId_; }
2076
+ bool onAsyncPresentWorker() const { return asyncPresentTask_ && xTaskGetCurrentTaskHandle() == asyncPresentTask_; }
2077
+ gea::framework::graphics::Canvas &replayCanvas() { return onWorkerCore() ? workerCanvas_ : canvas_; }
2078
+
2079
+ static void asyncPresentTaskEntry(void *arg)
2080
+ {
2081
+ static_cast<DisplayBackend *>(arg)->asyncPresentTaskLoop();
2082
+ }
2083
+
2084
+ void asyncPresentTaskLoop()
2085
+ {
2086
+ for (;;) {
2087
+ ulTaskNotifyTake(pdTRUE, portMAX_DELAY);
2088
+ const bool ok = presentFullPanelBackRepaint(std::move(asyncPresentFrame_));
2089
+ asyncPresentOk_ = ok;
2090
+ asyncPresentInFlight_.store(false, std::memory_order_release);
2091
+ if (asyncPresentDoneSem_) xSemaphoreGive(asyncPresentDoneSem_);
2092
+ }
2093
+ }
2094
+
2095
+ bool ensureAsyncPresentTask()
2096
+ {
2097
+ if (asyncPresentTask_) return true;
2098
+ if (!asyncPresentDoneSem_) asyncPresentDoneSem_ = xSemaphoreCreateBinary();
2099
+ if (!asyncPresentDoneSem_) return false;
2100
+ const BaseType_t appCore = xPortGetCoreID();
2101
+ const BaseType_t workerCore = (appCore == 0) ? 1 : 0;
2102
+ const UBaseType_t priority = uxTaskPriorityGet(nullptr);
2103
+ const BaseType_t created = xTaskCreatePinnedToCore(asyncPresentTaskEntry,
2104
+ "gea_present",
2105
+ kAsyncPresentStackBytes,
2106
+ this,
2107
+ priority,
2108
+ &asyncPresentTask_,
2109
+ workerCore);
2110
+ if (created != pdPASS || !asyncPresentTask_) {
2111
+ ESP_LOGE(kTag, "async present task creation failed: %d", static_cast<int>(created));
2112
+ }
2113
+ return created == pdPASS && asyncPresentTask_;
2114
+ }
2115
+
2116
+ bool waitForAsyncPresent()
2117
+ {
2118
+ if (onAsyncPresentWorker()) return asyncPresentOk_;
2119
+ while (asyncPresentInFlight_.load(std::memory_order_acquire)) {
2120
+ if (asyncPresentDoneSem_)
2121
+ xSemaphoreTake(asyncPresentDoneSem_, pdMS_TO_TICKS(100));
2122
+ else
2123
+ taskYIELD();
2124
+ }
2125
+ return asyncPresentOk_;
2126
+ }
2127
+
2128
+ bool scheduleAsyncFullPanelBackRepaint(present::Frame &&current)
2129
+ {
2130
+ waitForAsyncPresent();
2131
+ if (!ensureAsyncPresentTask()) {
2132
+ return presentFullPanelBackRepaint(std::move(current));
2133
+ }
2134
+ if (asyncPresentDoneSem_) xSemaphoreTake(asyncPresentDoneSem_, 0);
2135
+ asyncPresentFrame_ = std::move(current);
2136
+ asyncPresentOk_ = true;
2137
+ asyncPresentInFlight_.store(true, std::memory_order_release);
2138
+ xTaskNotifyGive(asyncPresentTask_);
2139
+ return true;
2140
+ }
2141
+
2142
+ bool presentFullPanelBackRepaint(present::Frame &&current)
2143
+ {
2144
+ present::Rect region{0, 0, logicalWidth() - 1, logicalHeight() - 1};
2145
+ prepareDrawingTarget(false);
2146
+ const std::int64_t started = esp_timer_get_time();
2147
+ pathGeneral_++;
2148
+ flushStats_.callCount++;
2149
+ rasterPresentRegion(current, region);
2150
+ const bool ok = flushPreparedLogicalRects(&region, 1);
2151
+ flushStats_.totalUs += esp_timer_get_time() - started;
2152
+ if (ok) {
2153
+ previousPresentFrame_ = std::move(current);
2154
+ previousPresentValid_ = true;
2155
+ needsFullPhysicalFlush_ = false;
2156
+ frameBufferCoherent_ = true;
2157
+ canvas_.resetDirty();
2158
+ }
2159
+ return ok;
2160
+ }
2161
+
2162
+ std::uint16_t *fullScreenScratch(std::uint16_t *&buffer, bool &attempted, int *capPx, const char *label)
2163
+ {
2164
+ if (!attempted) {
2165
+ attempted = true;
2166
+ buffer = static_cast<std::uint16_t *>(
2167
+ heap_caps_malloc(static_cast<std::size_t>(kMaxPixels) * sizeof(std::uint16_t),
2168
+ MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
2169
+ if (buffer) {
2170
+ ESP_LOGI(kTag, "allocated %s cache %.1f KiB", label, (kMaxPixels * sizeof(std::uint16_t)) / 1024.0);
2171
+ } else {
2172
+ ESP_LOGW(kTag, "failed to allocate %s cache (%zu bytes)",
2173
+ label,
2174
+ static_cast<std::size_t>(kMaxPixels) * sizeof(std::uint16_t));
2175
+ }
2176
+ }
2177
+ if (capPx) *capPx = buffer ? kMaxPixels : 0;
2178
+ return buffer;
2179
+ }
2180
+
2181
+ void bindCanvas()
2182
+ {
2183
+ take();
2184
+ bindCanvasLocked();
2185
+ give();
2186
+ }
2187
+
2188
+ void bindCanvasLocked()
2189
+ {
2190
+ const int width = logicalWidth();
2191
+ const int height = logicalHeight();
2192
+ const int stride = width;
2193
+ std::uint16_t *targetFrameBuffer = preferredFrameBuffer();
2194
+ if (!targetFrameBuffer) return;
2195
+ if (frameBuffer_ != targetFrameBuffer) frameBuffer_ = targetFrameBuffer;
2196
+ if (canvas_.pixels() == frameBuffer_ && canvas_.width() == width && canvas_.height() == height && logicalStride_ == stride) return;
2197
+ logicalStride_ = stride;
2198
+ canvas_.bindPixels(frameBuffer_, width, height, logicalStride_);
2199
+ workerCanvas_.bindPixels(frameBuffer_, width, height, logicalStride_);
2200
+ }
2201
+
2202
+ std::uint16_t *preferredFrameBuffer()
2203
+ {
2204
+ using gea::framework::display::DisplayOrientation;
2205
+ if (orientation_detail::DisplayOrientationState::orientation() == DisplayOrientation::PortraitPrimary &&
2206
+ panelFrameBuffers_[1] != nullptr) {
2207
+ drainRefreshDoneLocked();
2208
+ const int current = panelFrameBufferIndex(frameBuffer_);
2209
+ if (current >= 0 &&
2210
+ panelFrameBuffers_[current] &&
2211
+ current != scannedFbIndex_ &&
2212
+ current != pendingReleasedFbIndex_) {
2213
+ return frameBuffer_;
2214
+ }
2215
+ const int writable = selectWritablePanelFrameBufferLocked(false);
2216
+ if (writable >= 0) return panelFrameBuffers_[writable];
2217
+ for (int i = 0; i < kDpiFrameBufferCount; ++i) {
2218
+ if (panelFrameBuffers_[i] && i != scannedFbIndex_) return panelFrameBuffers_[i];
2219
+ }
2220
+ }
2221
+ return ownedFrameBuffer_;
2222
+ }
2223
+
2224
+ void prepareDrawingTarget(bool preservePanelBackBuffer = true)
2225
+ {
2226
+ if (!frameBuffer_) init();
2227
+ take();
2228
+ bindCanvasLocked();
2229
+ if (preservePanelBackBuffer)
2230
+ preparePanelBackBufferForDrawingLocked();
2231
+ else
2232
+ discardPanelBackBufferCoherenceForFullOverwriteLocked();
2233
+ give();
2234
+ }
2235
+
2236
+ bool prepareNativePanelBackBufferForCircleFrame(int *outIndex)
2237
+ {
2238
+ if (outIndex) *outIndex = -1;
2239
+ if (!frameBuffer_) init();
2240
+ take();
2241
+ if (!canUseNativePanelBackBufferPath()) {
2242
+ give();
2243
+ return false;
2244
+ }
2245
+ const int index = selectWritablePanelFrameBufferLocked(true);
2246
+ if (index < 0 || !panelFrameBuffers_[index]) {
2247
+ give();
2248
+ return false;
2249
+ }
2250
+ frameBuffer_ = panelFrameBuffers_[index];
2251
+ logicalStride_ = kNativeWidth;
2252
+ canvas_.bindPixels(frameBuffer_, logicalWidth(), logicalHeight(), logicalStride_);
2253
+ workerCanvas_.bindPixels(frameBuffer_, logicalWidth(), logicalHeight(), logicalStride_);
2254
+ pendingPanelBackSyncCount_ = 0;
2255
+ clearPanelBufferStaleLocked(index);
2256
+ if (outIndex) *outIndex = index;
2257
+ give();
2258
+ return true;
2259
+ }
2260
+
2261
+ bool regionsCoverLogicalFrame(const present::Rect *rects, int count) const
2262
+ {
2263
+ if (!rects || count <= 0) return false;
2264
+ for (int i = 0; i < count; ++i) {
2265
+ const present::Rect rect = clampLogicalRect(rects[i], logicalWidth(), logicalHeight());
2266
+ if (present::valid(rect) &&
2267
+ rect.x0 <= 0 &&
2268
+ rect.y0 <= 0 &&
2269
+ rect.x1 >= logicalWidth() - 1 &&
2270
+ rect.y1 >= logicalHeight() - 1) {
2271
+ return true;
2272
+ }
2273
+ }
2274
+ return false;
2275
+ }
2276
+
2277
+ bool usingPanelFrameBufferDirectly() const
2278
+ {
2279
+ using gea::framework::display::DisplayOrientation;
2280
+ return frameBuffer_ && panelFrameBuffer_ && frameBuffer_ == panelFrameBuffer_ &&
2281
+ logicalStride_ == kNativeWidth &&
2282
+ orientation_detail::DisplayOrientationState::orientation() == DisplayOrientation::PortraitPrimary;
2283
+ }
2284
+
2285
+ bool usingNativePanelBackBufferForDrawingLocked() const
2286
+ {
2287
+ const int index = panelFrameBufferIndex(frameBuffer_);
2288
+ return selectedNativePanelFrameBufferLocked() &&
2289
+ index != pendingReleasedFbIndex_;
2290
+ }
2291
+
2292
+ bool selectedNativePanelFrameBufferLocked() const
2293
+ {
2294
+ const int index = panelFrameBufferIndex(frameBuffer_);
2295
+ return frameBuffer_ && canUseNativePanelBackBufferPath() &&
2296
+ logicalStride_ == kNativeWidth &&
2297
+ index >= 0 &&
2298
+ index != scannedFbIndex_;
2299
+ }
2300
+
2301
+ bool canUseNativePanelBackBufferPath() const
2302
+ {
2303
+ using gea::framework::display::DisplayOrientation;
2304
+ return panelFrameBuffers_[1] != nullptr &&
2305
+ logicalWidth() == kNativeWidth &&
2306
+ logicalHeight() == kNativeHeight &&
2307
+ orientation_detail::DisplayOrientationState::orientation() == DisplayOrientation::PortraitPrimary;
2308
+ }
2309
+
2310
+ int panelFrameBufferIndex(const std::uint16_t *buffer) const
2311
+ {
2312
+ for (int i = 0; i < kDpiFrameBufferCount; ++i) {
2313
+ if (buffer && buffer == panelFrameBuffers_[i]) return i;
2314
+ }
2315
+ return -1;
2316
+ }
2317
+
2318
+ void drainRefreshDoneLocked()
2319
+ {
2320
+ if (!refreshDoneSem_) {
2321
+ pendingReleasedFbIndex_ = -1;
2322
+ return;
2323
+ }
2324
+ while (xSemaphoreTake(refreshDoneSem_, 0) == pdTRUE) {
2325
+ pendingReleasedFbIndex_ = -1;
2326
+ }
2327
+ }
2328
+
2329
+ void waitForReleasedPanelBufferLocked()
2330
+ {
2331
+ if (pendingReleasedFbIndex_ < 0) {
2332
+ drainRefreshDoneLocked();
2333
+ return;
2334
+ }
2335
+ if (refreshDoneSem_) xSemaphoreTake(refreshDoneSem_, pdMS_TO_TICKS(40));
2336
+ pendingReleasedFbIndex_ = -1;
2337
+ }
2338
+
2339
+ int selectWritablePanelFrameBufferLocked(bool waitIfNeeded)
2340
+ {
2341
+ drainRefreshDoneLocked();
2342
+ for (int i = 0; i < kDpiFrameBufferCount; ++i) {
2343
+ if (!panelFrameBuffers_[i]) continue;
2344
+ if (i == scannedFbIndex_ || i == pendingReleasedFbIndex_) continue;
2345
+ return i;
2346
+ }
2347
+ if (waitIfNeeded) {
2348
+ waitForReleasedPanelBufferLocked();
2349
+ for (int i = 0; i < kDpiFrameBufferCount; ++i) {
2350
+ if (!panelFrameBuffers_[i]) continue;
2351
+ if (i == scannedFbIndex_ || i == pendingReleasedFbIndex_) continue;
2352
+ return i;
2353
+ }
2354
+ }
2355
+ return -1;
2356
+ }
2357
+
2358
+ bool flipPanelToBufferLocked(std::uint16_t *buffer, bool syncFullFrame)
2359
+ {
2360
+ if (!panel_ || !buffer) return false;
2361
+ const int index = panelFrameBufferIndex(buffer);
2362
+ if (index < 0) return false;
2363
+ waitForReleasedPanelBufferLocked();
2364
+ const int previousScanIndex = scannedFbIndex_;
2365
+ const int xEnd = syncFullFrame ? kNativeWidth : 1;
2366
+ const int yEnd = syncFullFrame ? kNativeHeight : 1;
2367
+ const esp_err_t err = esp_lcd_panel_draw_bitmap(panel_, 0, 0, xEnd, yEnd, buffer);
2368
+ if (err != ESP_OK) {
2369
+ ESP_LOGE(kTag, "DPI panel framebuffer swap failed: %s", esp_err_to_name(err));
2370
+ return false;
2371
+ }
2372
+ scannedFbIndex_ = index;
2373
+ panelFrameBuffer_ = panelFrameBuffers_[index];
2374
+ pendingReleasedFbIndex_ = previousScanIndex != index ? previousScanIndex : -1;
2375
+ return true;
2376
+ }
2377
+
2378
+ void resetPanelBackBufferCoherenceLocked()
2379
+ {
2380
+ pendingPanelBackSyncCount_ = 0;
2381
+ for (int i = 0; i < kDpiFrameBufferCount; ++i) {
2382
+ panelBufferStaleCount_[i] = 0;
2383
+ panelBufferStaleFull_[i] = false;
2384
+ }
2385
+ invalidatePanelCircleFrames();
2386
+ }
2387
+
2388
+ void invalidatePanelCircleFrames()
2389
+ {
2390
+ for (int i = 0; i < kDpiFrameBufferCount; ++i) panelCirclePrevValid_[i] = false;
2391
+ }
2392
+
2393
+ void clearPanelBufferStaleLocked(int index)
2394
+ {
2395
+ if (index < 0 || index >= kDpiFrameBufferCount) return;
2396
+ panelBufferStaleCount_[index] = 0;
2397
+ panelBufferStaleFull_[index] = false;
2398
+ }
2399
+
2400
+ void appendPanelBufferStaleRectLocked(int index, present::Rect rect)
2401
+ {
2402
+ if (index < 0 || index >= kDpiFrameBufferCount || !panelFrameBuffers_[index]) return;
2403
+ if (panelBufferStaleFull_[index]) return;
2404
+ rect = present::clampAndAlign(rect, kNativeWidth, kNativeHeight);
2405
+ if (!present::valid(rect)) return;
2406
+ if (rect.x0 <= 0 && rect.y0 <= 0 && rect.x1 >= kNativeWidth - 1 && rect.y1 >= kNativeHeight - 1) {
2407
+ panelBufferStaleCount_[index] = 0;
2408
+ panelBufferStaleFull_[index] = true;
2409
+ return;
2410
+ }
2411
+ addRectTight(panelBufferStaleRects_[index],
2412
+ &panelBufferStaleCount_[index],
2413
+ kMaxFlushRects,
2414
+ rect,
2415
+ kNativeWidth,
2416
+ kNativeHeight);
2417
+ }
2418
+
2419
+ void markPanelBuffersStaleAfterFlipLocked(const present::Rect *rects, int count)
2420
+ {
2421
+ clearPanelBufferStaleLocked(scannedFbIndex_);
2422
+ if (!rects || count <= 0) return;
2423
+ for (int i = 0; i < kDpiFrameBufferCount; ++i) {
2424
+ if (i == scannedFbIndex_ || !panelFrameBuffers_[i]) continue;
2425
+ for (int r = 0; r < count; ++r) appendPanelBufferStaleRectLocked(i, rects[r]);
2426
+ }
2427
+ }
2428
+
2429
+ void appendPanelBackSyncRectLocked(present::Rect rect)
2430
+ {
2431
+ rect = present::clampAndAlign(rect, kNativeWidth, kNativeHeight);
2432
+ if (!present::valid(rect)) return;
2433
+ addRectTight(pendingPanelBackSyncRects_,
2434
+ &pendingPanelBackSyncCount_,
2435
+ kMaxFlushRects,
2436
+ rect,
2437
+ kNativeWidth,
2438
+ kNativeHeight);
2439
+ }
2440
+
2441
+ void copyPanelRectPixels(std::uint16_t *dst, const std::uint16_t *src, present::Rect rect) const
2442
+ {
2443
+ if (!dst || !src) return;
2444
+ rect = present::clampAndAlign(rect, kNativeWidth, kNativeHeight);
2445
+ if (!present::valid(rect)) return;
2446
+ const std::size_t bytes = static_cast<std::size_t>(rect.x1 - rect.x0 + 1) * sizeof(std::uint16_t);
2447
+ for (int y = rect.y0; y <= rect.y1; ++y) {
2448
+ std::memcpy(dst + static_cast<std::size_t>(y) * kNativeWidth + rect.x0,
2449
+ src + static_cast<std::size_t>(y) * kNativeWidth + rect.x0,
2450
+ bytes);
2451
+ }
2452
+ }
2453
+
2454
+ void preparePanelBackBufferForDrawingLocked()
2455
+ {
2456
+ if (!selectedNativePanelFrameBufferLocked()) {
2457
+ resetPanelBackBufferCoherenceLocked();
2458
+ return;
2459
+ }
2460
+ const int selectedIndex = panelFrameBufferIndex(frameBuffer_);
2461
+ if (selectedIndex == pendingReleasedFbIndex_) waitForReleasedPanelBufferLocked();
2462
+ if (!usingNativePanelBackBufferForDrawingLocked()) {
2463
+ resetPanelBackBufferCoherenceLocked();
2464
+ return;
2465
+ }
2466
+ const bool needsFullCoherence = panelBufferStaleFull_[selectedIndex];
2467
+ const int staleCount = panelBufferStaleCount_[selectedIndex];
2468
+ if (!needsFullCoherence && staleCount <= 0) return;
2469
+
2470
+ const std::int64_t copyStartUs = esp_timer_get_time();
2471
+ if (needsFullCoherence) {
2472
+ const present::Rect full{0, 0, kNativeWidth - 1, kNativeHeight - 1};
2473
+ copyPanelRectPixels(frameBuffer_, panelFrameBuffer_, full);
2474
+ appendPanelBackSyncRectLocked(full);
2475
+ } else {
2476
+ for (int i = 0; i < staleCount; ++i) {
2477
+ const present::Rect rect = present::clampAndAlign(panelBufferStaleRects_[selectedIndex][i], kNativeWidth, kNativeHeight);
2478
+ if (!present::valid(rect)) continue;
2479
+ copyPanelRectPixels(frameBuffer_, panelFrameBuffer_, rect);
2480
+ appendPanelBackSyncRectLocked(rect);
2481
+ }
2482
+ }
2483
+ flushStats_.txUs += esp_timer_get_time() - copyStartUs;
2484
+ clearPanelBufferStaleLocked(selectedIndex);
2485
+ }
2486
+
2487
+ void discardPanelBackBufferCoherenceForFullOverwriteLocked()
2488
+ {
2489
+ if (!selectedNativePanelFrameBufferLocked()) {
2490
+ resetPanelBackBufferCoherenceLocked();
2491
+ return;
2492
+ }
2493
+ const int selectedIndex = panelFrameBufferIndex(frameBuffer_);
2494
+ if (selectedIndex == pendingReleasedFbIndex_) waitForReleasedPanelBufferLocked();
2495
+ pendingPanelBackSyncCount_ = 0;
2496
+ clearPanelBufferStaleLocked(selectedIndex);
2497
+ }
2498
+
2499
+ void markPanelBackBuffersStaleLocked(const present::Rect *rects, int count)
2500
+ {
2501
+ markPanelBuffersStaleAfterFlipLocked(rects, count);
2502
+ }
2503
+
2504
+ bool copyLogicalRectPixelsToPanelCpu(present::Rect logicalRect)
2505
+ {
2506
+ if (!frameBuffer_ || !panelFrameBuffer_) return false;
2507
+ logicalRect = clampLogicalRect(logicalRect, logicalWidth(), logicalHeight());
2508
+ if (!present::valid(logicalRect)) return true;
2509
+
2510
+ using gea::framework::display::DisplayOrientation;
2511
+ switch (orientation_detail::DisplayOrientationState::orientation()) {
2512
+ case DisplayOrientation::PortraitSecondary:
2513
+ for (int sy = logicalRect.y0; sy <= logicalRect.y1; ++sy) {
2514
+ const std::uint16_t *src = frameBuffer_ + static_cast<std::size_t>(sy) * logicalStride_ + logicalRect.x1;
2515
+ std::uint16_t *dst = panelFrameBuffer_ +
2516
+ static_cast<std::size_t>(kNativeHeight - 1 - sy) * kNativeWidth +
2517
+ (kNativeWidth - 1 - logicalRect.x1);
2518
+ for (int sx = logicalRect.x1; sx >= logicalRect.x0; --sx) {
2519
+ *dst++ = *src--;
2520
+ }
2521
+ }
2522
+ break;
2523
+ case DisplayOrientation::LandscapePrimary:
2524
+ for (int sx = logicalRect.x0; sx <= logicalRect.x1; ++sx) {
2525
+ const std::uint16_t *src = frameBuffer_ + static_cast<std::size_t>(logicalRect.y0) * logicalStride_ + sx;
2526
+ std::uint16_t *dst = panelFrameBuffer_ +
2527
+ static_cast<std::size_t>(kNativeHeight - 1 - sx) * kNativeWidth +
2528
+ logicalRect.y0;
2529
+ for (int sy = logicalRect.y0; sy <= logicalRect.y1; ++sy) {
2530
+ *dst++ = *src;
2531
+ src += logicalStride_;
2532
+ }
2533
+ }
2534
+ break;
2535
+ case DisplayOrientation::LandscapeSecondary:
2536
+ for (int sx = logicalRect.x0; sx <= logicalRect.x1; ++sx) {
2537
+ const std::uint16_t *src = frameBuffer_ + static_cast<std::size_t>(logicalRect.y1) * logicalStride_ + sx;
2538
+ std::uint16_t *dst = panelFrameBuffer_ +
2539
+ static_cast<std::size_t>(sx) * kNativeWidth +
2540
+ (kNativeWidth - 1 - logicalRect.y1);
2541
+ for (int sy = logicalRect.y1; sy >= logicalRect.y0; --sy) {
2542
+ *dst++ = *src;
2543
+ src -= logicalStride_;
2544
+ }
2545
+ }
2546
+ break;
2547
+ case DisplayOrientation::PortraitPrimary:
2548
+ default:
2549
+ for (int sy = logicalRect.y0; sy <= logicalRect.y1; ++sy) {
2550
+ const std::uint16_t *src = frameBuffer_ + static_cast<std::size_t>(sy) * logicalStride_ + logicalRect.x0;
2551
+ std::uint16_t *dst = panelFrameBuffer_ + static_cast<std::size_t>(sy) * kNativeWidth + logicalRect.x0;
2552
+ std::memcpy(dst, src, static_cast<std::size_t>(logicalRect.x1 - logicalRect.x0 + 1) * sizeof(std::uint16_t));
2553
+ }
2554
+ break;
2555
+ }
2556
+ return true;
2557
+ }
2558
+
2559
+ bool copyLogicalRectToPanelCpu(present::Rect logicalRect, present::Rect panelRect)
2560
+ {
2561
+ panelRect = present::clampAndAlign(panelRect, kNativeWidth, kNativeHeight);
2562
+ if (!present::valid(panelRect)) return true;
2563
+ const std::int64_t copyStartUs = esp_timer_get_time();
2564
+ const bool copied = copyLogicalRectPixelsToPanelCpu(logicalRect);
2565
+ flushStats_.txUs += esp_timer_get_time() - copyStartUs;
2566
+ if (!copied) return false;
2567
+
2568
+ const std::int64_t syncStartUs = esp_timer_get_time();
2569
+ const bool ok = syncPanelFrameBufferRectToMemory(panelRect);
2570
+ flushStats_.copyUs += esp_timer_get_time() - syncStartUs;
2571
+ return ok;
2572
+ }
2573
+
2574
+ bool flushPreparedLogicalRects(present::Rect *rects, int count)
2575
+ {
2576
+ if (!rects || count <= 0) return true;
2577
+ bool panelBackHandled = false;
2578
+ const bool panelBackOk = flushPanelBackBufferLogicalRects(rects, count, &panelBackHandled);
2579
+ if (!panelBackOk || panelBackHandled) return panelBackOk;
2580
+
2581
+ bool handled = false;
2582
+ const bool batchOk = flushSmallCpuMappedLogicalRects(rects, count, &handled);
2583
+ if (!batchOk || handled) return batchOk;
2584
+ bool ok = true;
2585
+ for (int i = 0; i < count; ++i) {
2586
+ if (!flushNativeLogicalRect(rects[i])) {
2587
+ ok = false;
2588
+ break;
2589
+ }
2590
+ }
2591
+ return ok;
2592
+ }
2593
+
2594
+ bool flushPanelBackBufferLogicalRects(const present::Rect *rects, int count, bool *handled)
2595
+ {
2596
+ if (handled) *handled = false;
2597
+ if (!rects || count <= 0) return true;
2598
+
2599
+ take();
2600
+ if (!usingNativePanelBackBufferForDrawingLocked() || scrollOriginX_ != 0 || scrollOriginY_ != 0) {
2601
+ give();
2602
+ return true;
2603
+ }
2604
+ if (handled) *handled = true;
2605
+ if (!panel_) {
2606
+ give();
2607
+ return false;
2608
+ }
2609
+
2610
+ present::Rect syncRects[kMaxFlushRects];
2611
+ int syncCount = 0;
2612
+ for (int i = 0; i < pendingPanelBackSyncCount_; ++i) {
2613
+ addRectTight(syncRects, &syncCount, kMaxFlushRects, pendingPanelBackSyncRects_[i], kNativeWidth, kNativeHeight);
2614
+ }
2615
+ for (int i = 0; i < count; ++i) {
2616
+ present::Rect rect = present::clampAndAlign(rects[i], kNativeWidth, kNativeHeight);
2617
+ if (!present::valid(rect)) continue;
2618
+ addRectTight(syncRects, &syncCount, kMaxFlushRects, rect, kNativeWidth, kNativeHeight);
2619
+ }
2620
+
2621
+ bool ok = true;
2622
+ if (syncCount > 0) {
2623
+ const std::int64_t syncStartUs = esp_timer_get_time();
2624
+ if (shouldSyncWholeCache(syncRects, syncCount))
2625
+ ok = syncWholeDataCacheToMemory();
2626
+ else if (shouldSyncRectsIndividually(syncRects, syncCount))
2627
+ ok = syncFrameBufferRectsToMemory(frameBuffer_, syncRects, syncCount, "DPI panel back framebuffer");
2628
+ else
2629
+ ok = syncFrameBufferRowBandsToMemory(frameBuffer_, syncRects, syncCount, "DPI panel back framebuffer");
2630
+ flushStats_.copyUs += esp_timer_get_time() - syncStartUs;
2631
+ }
2632
+ if (ok) {
2633
+ const std::int64_t flipStartUs = esp_timer_get_time();
2634
+ drainRefreshDoneLocked();
2635
+ ok = flipPanelToBufferLocked(frameBuffer_, false);
2636
+ lastFlipUs_ = esp_timer_get_time();
2637
+ flushStats_.copyUs += lastFlipUs_ - flipStartUs;
2638
+ }
2639
+ if (ok) {
2640
+ markPanelBackBuffersStaleLocked(rects, count);
2641
+ pendingPanelBackSyncCount_ = 0;
2642
+ flushStats_.chunkCount++;
2643
+ for (int i = 0; i < count; ++i) flushStats_.pixelCount += present::area(rects[i]);
2644
+ }
2645
+ give();
2646
+ return ok;
2647
+ }
2648
+
2649
+ bool flushSmallCpuMappedLogicalRects(present::Rect *rects, int count, bool *handled)
2650
+ {
2651
+ if (handled) *handled = false;
2652
+ if (!rects || count < 2) return true;
2653
+
2654
+ present::Rect logicalRects[kMaxFlushRects];
2655
+ present::Rect panelRects[kMaxFlushRects];
2656
+ int preparedCount = 0;
2657
+ for (int i = 0; i < count && preparedCount < kMaxFlushRects; ++i) {
2658
+ present::Rect logicalRect = clampLogicalRect(rects[i], logicalWidth(), logicalHeight());
2659
+ if (!present::valid(logicalRect)) continue;
2660
+ const int logicalPixels = (logicalRect.x1 - logicalRect.x0 + 1) * (logicalRect.y1 - logicalRect.y0 + 1);
2661
+ if (logicalPixels > kCpuPanelMapFlushMaxPixels) return true;
2662
+ const present::Rect panelRect = present::clampAndAlign(physicalBoundsForLogicalRect(logicalRect), kNativeWidth, kNativeHeight);
2663
+ if (!present::valid(panelRect)) continue;
2664
+ logicalRects[preparedCount] = logicalRect;
2665
+ panelRects[preparedCount] = panelRect;
2666
+ ++preparedCount;
2667
+ }
2668
+ if (preparedCount < 2) return true;
2669
+
2670
+ take();
2671
+ bindCanvasLocked();
2672
+ if (!panel_) {
2673
+ give();
2674
+ if (handled) *handled = true;
2675
+ return false;
2676
+ }
2677
+ if (frameBuffer_ != ownedFrameBuffer_ || scrollOriginX_ != 0 || scrollOriginY_ != 0) {
2678
+ give();
2679
+ return true;
2680
+ }
2681
+
2682
+ if (handled) *handled = true;
2683
+ bool ok = true;
2684
+ const std::int64_t copyStartUs = esp_timer_get_time();
2685
+ for (int i = 0; i < preparedCount; ++i) {
2686
+ if (!copyLogicalRectPixelsToPanelCpu(logicalRects[i])) {
2687
+ ok = false;
2688
+ break;
2689
+ }
2690
+ }
2691
+ flushStats_.txUs += esp_timer_get_time() - copyStartUs;
2692
+
2693
+ if (ok) {
2694
+ const std::int64_t syncStartUs = esp_timer_get_time();
2695
+ ok = syncPanelFrameBufferRowBandsToMemory(panelRects, preparedCount);
2696
+ flushStats_.copyUs += esp_timer_get_time() - syncStartUs;
2697
+ }
2698
+ if (ok) {
2699
+ for (int i = 0; i < preparedCount; ++i) {
2700
+ flushStats_.chunkCount++;
2701
+ flushStats_.pixelCount += present::area(panelRects[i]);
2702
+ }
2703
+ }
2704
+ give();
2705
+ return ok;
2706
+ }
2707
+
2708
+ void appendFlushRect(present::Rect *rects, int *count, int capacity, present::Rect rect) const
2709
+ {
2710
+ rect = clampLogicalRect(rect, logicalWidth(), logicalHeight());
2711
+ if (!present::valid(rect)) return;
2712
+ present::addRect(rects, count, capacity, rect, logicalWidth(), logicalHeight());
2713
+ }
2714
+
2715
+ void appendFlushRectExact(present::Rect *rects, int *count, int capacity, present::Rect rect) const
2716
+ {
2717
+ if (!rects || !count || capacity <= 0) return;
2718
+ rect = clampLogicalRect(rect, logicalWidth(), logicalHeight());
2719
+ if (!present::valid(rect)) return;
2720
+ if (*count < capacity) {
2721
+ rects[(*count)++] = rect;
2722
+ return;
2723
+ }
2724
+ present::addRect(rects, count, capacity, rect, logicalWidth(), logicalHeight());
2725
+ }
2726
+
2727
+ void addRectTight(present::Rect *rects, int *count, int capacity, present::Rect rect, int width, int height) const
2728
+ {
2729
+ if (!rects || !count || capacity <= 0) return;
2730
+ rect = present::clampAndAlign(rect, width, height);
2731
+ if (!present::valid(rect)) return;
2732
+ const long long newArea = rectArea64(rect);
2733
+ for (int i = 0; i < *count; ++i) {
2734
+ const present::Rect merged = present::unite(rects[i], rect);
2735
+ if (rectArea64(merged) <= rectArea64(rects[i]) + newArea) {
2736
+ rects[i] = merged;
2737
+ return;
2738
+ }
2739
+ }
2740
+ if (*count < capacity) {
2741
+ rects[(*count)++] = rect;
2742
+ return;
2743
+ }
2744
+ int best = 0;
2745
+ long long bestCost = 0x7fffffffffffffffLL;
2746
+ for (int i = 0; i < *count; ++i) {
2747
+ const present::Rect merged = present::unite(rects[i], rect);
2748
+ const long long cost = rectArea64(merged) - rectArea64(rects[i]);
2749
+ if (cost < bestCost) {
2750
+ bestCost = cost;
2751
+ best = i;
2752
+ }
2753
+ }
2754
+ rects[best] = present::unite(rects[best], rect);
2755
+ }
2756
+
2757
+ long long rectAreaSum(const present::Rect *rects, int count) const
2758
+ {
2759
+ if (!rects || count <= 0) return 0;
2760
+ long long area = 0;
2761
+ for (int i = 0; i < count; ++i) area += rectArea64(rects[i]);
2762
+ return area;
2763
+ }
2764
+
2765
+ long long rowBandAreaForRects(const present::Rect *rects, int count) const
2766
+ {
2767
+ if (!rects || count <= 0) return 0;
2768
+ present::Rect rowBands[kMaxFlushRects];
2769
+ int rowBandCount = 0;
2770
+ for (int i = 0; i < count; ++i) {
2771
+ const present::Rect rect = present::clampAndAlign(rects[i], kNativeWidth, kNativeHeight);
2772
+ if (!present::valid(rect)) continue;
2773
+ present::addRect(rowBands,
2774
+ &rowBandCount,
2775
+ kMaxFlushRects,
2776
+ {0, rect.y0, kNativeWidth - 1, rect.y1},
2777
+ kNativeWidth,
2778
+ kNativeHeight);
2779
+ }
2780
+ return rectAreaSum(rowBands, rowBandCount);
2781
+ }
2782
+
2783
+ bool syncFrameBufferRectToMemory(present::Rect logicalRect)
2784
+ {
2785
+ return syncBufferRectToMemory(frameBuffer_, logicalStride_, logicalWidth(), logicalHeight(), logicalRect, "DPI framebuffer");
2786
+ }
2787
+
2788
+ bool syncBufferRectToMemory(std::uint16_t *buffer,
2789
+ int stridePixels,
2790
+ int widthPixels,
2791
+ int heightPixels,
2792
+ present::Rect rect,
2793
+ const char *label)
2794
+ {
2795
+ if (!buffer) return false;
2796
+ rect = present::clampAndAlign(rect, widthPixels, heightPixels);
2797
+ if (!present::valid(rect)) return true;
2798
+ const int width = rect.x1 - rect.x0 + 1;
2799
+ if (width <= 0) return true;
2800
+ const std::size_t bytes = static_cast<std::size_t>(width) * sizeof(std::uint16_t);
2801
+ constexpr int kFlags = ESP_CACHE_MSYNC_FLAG_DIR_C2M |
2802
+ ESP_CACHE_MSYNC_FLAG_TYPE_DATA |
2803
+ ESP_CACHE_MSYNC_FLAG_UNALIGNED;
2804
+ for (int y = rect.y0; y <= rect.y1; ++y) {
2805
+ void *row = buffer + static_cast<std::size_t>(y) * stridePixels + rect.x0;
2806
+ const esp_err_t err = esp_cache_msync(row, bytes, kFlags);
2807
+ if (err == ESP_OK) continue;
2808
+ if (!cacheSyncWarned_) {
2809
+ cacheSyncWarned_ = true;
2810
+ ESP_LOGE(kTag, "%s cache writeback failed: %s", label, esp_err_to_name(err));
2811
+ }
2812
+ return false;
2813
+ }
2814
+ return true;
2815
+ }
2816
+
2817
+ bool syncBufferRectToMemoryFast(std::uint16_t *buffer,
2818
+ int stridePixels,
2819
+ int widthPixels,
2820
+ int heightPixels,
2821
+ present::Rect rect,
2822
+ const char *label)
2823
+ {
2824
+ if (!buffer) return false;
2825
+ rect = present::clampAndAlign(rect, widthPixels, heightPixels);
2826
+ if (!present::valid(rect)) return true;
2827
+ const int width = rect.x1 - rect.x0 + 1;
2828
+ if (width <= 0) return true;
2829
+ const std::size_t bytes = static_cast<std::size_t>(width) * sizeof(std::uint16_t);
2830
+ bool ok = true;
2831
+ esp_cache_sync_ops_enter_critical_section();
2832
+ for (int y = rect.y0; y <= rect.y1; ++y) {
2833
+ void *row = buffer + static_cast<std::size_t>(y) * stridePixels + rect.x0;
2834
+ if (cache_hal_writeback_addr(static_cast<std::uint32_t>(reinterpret_cast<std::uintptr_t>(row)),
2835
+ static_cast<std::uint32_t>(bytes))) {
2836
+ continue;
2837
+ }
2838
+ ok = false;
2839
+ break;
2840
+ }
2841
+ esp_cache_sync_ops_exit_critical_section();
2842
+ if (ok) return true;
2843
+ if (!cacheSyncWarned_) {
2844
+ cacheSyncWarned_ = true;
2845
+ ESP_LOGE(kTag, "%s fast cache writeback failed", label ? label : "framebuffer");
2846
+ }
2847
+ return false;
2848
+ }
2849
+
2850
+ bool syncPanelFrameBufferRectToMemory(present::Rect panelRect)
2851
+ {
2852
+ return syncBufferRectToMemory(panelFrameBuffer_, kNativeWidth, kNativeWidth, kNativeHeight, panelRect, "DPI panel framebuffer");
2853
+ }
2854
+
2855
+ bool syncFrameBufferRectsToMemory(std::uint16_t *buffer,
2856
+ const present::Rect *panelRects,
2857
+ int count,
2858
+ const char *label)
2859
+ {
2860
+ if (!panelRects || count <= 0) return true;
2861
+ for (int i = 0; i < count; ++i) {
2862
+ const present::Rect rect = present::clampAndAlign(panelRects[i], kNativeWidth, kNativeHeight);
2863
+ if (!present::valid(rect)) continue;
2864
+ if (!syncBufferRectToMemoryFast(buffer, kNativeWidth, kNativeWidth, kNativeHeight, rect, label)) return false;
2865
+ }
2866
+ return true;
2867
+ }
2868
+
2869
+ bool syncWholeDataCacheToMemory()
2870
+ {
2871
+ esp_cache_sync_ops_enter_critical_section();
2872
+ cache_ll_writeback_all(CACHE_LL_LEVEL_ALL, CACHE_TYPE_DATA, CACHE_LL_ID_ALL);
2873
+ esp_cache_sync_ops_exit_critical_section();
2874
+ return true;
2875
+ }
2876
+
2877
+ bool syncFrameBufferFullRowsToMemory(std::uint16_t *buffer, int y0, int y1, const char *label)
2878
+ {
2879
+ if (!buffer) return false;
2880
+ if (y0 < 0) y0 = 0;
2881
+ if (y1 >= kNativeHeight) y1 = kNativeHeight - 1;
2882
+ if (y0 > y1) return true;
2883
+ void *start = buffer + static_cast<std::size_t>(y0) * kNativeWidth;
2884
+ const std::size_t rows = static_cast<std::size_t>(y1 - y0 + 1);
2885
+ const std::size_t bytes = rows * kNativeWidth * sizeof(std::uint16_t);
2886
+ constexpr int kFlags = ESP_CACHE_MSYNC_FLAG_DIR_C2M |
2887
+ ESP_CACHE_MSYNC_FLAG_TYPE_DATA |
2888
+ ESP_CACHE_MSYNC_FLAG_UNALIGNED;
2889
+ const esp_err_t err = esp_cache_msync(start, bytes, kFlags);
2890
+ if (err == ESP_OK) return true;
2891
+ if (!cacheSyncWarned_) {
2892
+ cacheSyncWarned_ = true;
2893
+ ESP_LOGE(kTag, "%s row-band cache writeback failed: %s", label ? label : "framebuffer", esp_err_to_name(err));
2894
+ }
2895
+ return false;
2896
+ }
2897
+
2898
+ bool syncFrameBufferRowBandsToMemory(std::uint16_t *buffer, const present::Rect *panelRects, int count, const char *label)
2899
+ {
2900
+ if (!panelRects || count <= 0) return true;
2901
+ present::Rect rowBands[kMaxFlushRects];
2902
+ int rowBandCount = 0;
2903
+ for (int i = 0; i < count; ++i) {
2904
+ const present::Rect panelRect = present::clampAndAlign(panelRects[i], kNativeWidth, kNativeHeight);
2905
+ if (!present::valid(panelRect)) continue;
2906
+ present::addRect(rowBands,
2907
+ &rowBandCount,
2908
+ kMaxFlushRects,
2909
+ {0, panelRect.y0, kNativeWidth - 1, panelRect.y1},
2910
+ kNativeWidth,
2911
+ kNativeHeight);
2912
+ }
2913
+ for (int i = 0; i < rowBandCount; ++i) {
2914
+ if (!syncFrameBufferFullRowsToMemory(buffer, rowBands[i].y0, rowBands[i].y1, label)) return false;
2915
+ }
2916
+ return true;
2917
+ }
2918
+
2919
+ bool shouldSyncRectsIndividually(const present::Rect *rects, int count) const
2920
+ {
2921
+ if (!rects || count <= 1) return false;
2922
+ const long long rectArea = rectAreaSum(rects, count);
2923
+ if (rectArea <= 0) return false;
2924
+ const long long screenArea = static_cast<long long>(kNativeWidth) * kNativeHeight;
2925
+ if (rectArea >= screenArea) return false;
2926
+ const long long rowBandArea = rowBandAreaForRects(rects, count);
2927
+ return rowBandArea * 10 > rectArea * 11;
2928
+ }
2929
+
2930
+ bool shouldSyncWholeCache(const present::Rect *rects, int count) const
2931
+ {
2932
+ if (!rects || count < 8) return false;
2933
+ const long long rectArea = rectAreaSum(rects, count);
2934
+ if (rectArea <= 0) return false;
2935
+ const long long screenArea = static_cast<long long>(kNativeWidth) * kNativeHeight;
2936
+ return rectArea * 4 < screenArea;
2937
+ }
2938
+
2939
+ bool syncPanelFrameBufferFullRowsToMemory(int y0, int y1)
2940
+ {
2941
+ return syncFrameBufferFullRowsToMemory(panelFrameBuffer_, y0, y1, "DPI panel framebuffer");
2942
+ }
2943
+
2944
+ bool syncPanelFrameBufferRowBandsToMemory(const present::Rect *panelRects, int count)
2945
+ {
2946
+ return syncFrameBufferRowBandsToMemory(panelFrameBuffer_, panelRects, count, "DPI panel framebuffer");
2947
+ }
2948
+
2949
+ bool initPpaSrm()
2950
+ {
2951
+ if (ppaSrmClient_) return true;
2952
+ ppa_client_config_t config{};
2953
+ config.oper_type = PPA_OPERATION_SRM;
2954
+ config.max_pending_trans_num = 1;
2955
+ config.data_burst_length = PPA_DATA_BURST_LENGTH_128;
2956
+ const esp_err_t err = ppa_register_client(&config, &ppaSrmClient_);
2957
+ if (err != ESP_OK) {
2958
+ if (!ppaWarned_) {
2959
+ ppaWarned_ = true;
2960
+ ESP_LOGE(kTag, "PPA SRM client registration failed: %s", esp_err_to_name(err));
2961
+ }
2962
+ return false;
2963
+ }
2964
+ ESP_LOGI(kTag, "PPA SRM rotation ready");
2965
+ return true;
2966
+ }
2967
+
2968
+ ppa_srm_rotation_angle_t ppaRotationForCurrentOrientation() const
2969
+ {
2970
+ using gea::framework::display::DisplayOrientation;
2971
+ switch (orientation_detail::DisplayOrientationState::orientation()) {
2972
+ case DisplayOrientation::PortraitSecondary:
2973
+ return PPA_SRM_ROTATION_ANGLE_180;
2974
+ case DisplayOrientation::LandscapePrimary:
2975
+ return PPA_SRM_ROTATION_ANGLE_90;
2976
+ case DisplayOrientation::LandscapeSecondary:
2977
+ return PPA_SRM_ROTATION_ANGLE_270;
2978
+ case DisplayOrientation::PortraitPrimary:
2979
+ default:
2980
+ return PPA_SRM_ROTATION_ANGLE_0;
2981
+ }
2982
+ }
2983
+
2984
+ bool rotateLogicalRectToPanelWithPpa(present::Rect logicalRect, present::Rect panelRect)
2985
+ {
2986
+ if (!frameBuffer_ || !panelFrameBuffer_) return false;
2987
+ logicalRect = clampLogicalRect(logicalRect, logicalWidth(), logicalHeight());
2988
+ panelRect = present::clampAndAlign(panelRect, kNativeWidth, kNativeHeight);
2989
+ if (!present::valid(logicalRect) || !present::valid(panelRect)) return true;
2990
+ if (!initPpaSrm()) return false;
2991
+
2992
+ const int logicalRectWidth = logicalRect.x1 - logicalRect.x0 + 1;
2993
+ const int logicalRectHeight = logicalRect.y1 - logicalRect.y0 + 1;
2994
+ const std::int64_t syncStartUs = esp_timer_get_time();
2995
+ if (!syncFrameBufferRectToMemory(logicalRect) || !syncPanelFrameBufferRectToMemory(panelRect)) {
2996
+ flushStats_.copyUs += esp_timer_get_time() - syncStartUs;
2997
+ return false;
2998
+ }
2999
+ flushStats_.copyUs += esp_timer_get_time() - syncStartUs;
3000
+
3001
+ ppa_srm_oper_config_t config{};
3002
+ config.in.buffer = frameBuffer_;
3003
+ config.in.pic_w = static_cast<std::uint32_t>(logicalWidth());
3004
+ config.in.pic_h = static_cast<std::uint32_t>(logicalHeight());
3005
+ config.in.block_w = static_cast<std::uint32_t>(logicalRectWidth);
3006
+ config.in.block_h = static_cast<std::uint32_t>(logicalRectHeight);
3007
+ config.in.block_offset_x = static_cast<std::uint32_t>(logicalRect.x0);
3008
+ config.in.block_offset_y = static_cast<std::uint32_t>(logicalRect.y0);
3009
+ config.in.srm_cm = PPA_SRM_COLOR_MODE_RGB565;
3010
+ config.out.buffer = panelFrameBuffer_;
3011
+ config.out.buffer_size = static_cast<std::uint32_t>(kMaxPixels * sizeof(std::uint16_t));
3012
+ config.out.pic_w = kNativeWidth;
3013
+ config.out.pic_h = kNativeHeight;
3014
+ config.out.block_offset_x = static_cast<std::uint32_t>(panelRect.x0);
3015
+ config.out.block_offset_y = static_cast<std::uint32_t>(panelRect.y0);
3016
+ config.out.srm_cm = PPA_SRM_COLOR_MODE_RGB565;
3017
+ config.rotation_angle = ppaRotationForCurrentOrientation();
3018
+ config.scale_x = 1.0f;
3019
+ config.scale_y = 1.0f;
3020
+ config.mode = PPA_TRANS_MODE_BLOCKING;
3021
+
3022
+ const std::int64_t ppaStartUs = esp_timer_get_time();
3023
+ const esp_err_t err = ppa_do_scale_rotate_mirror(ppaSrmClient_, &config);
3024
+ flushStats_.txUs += esp_timer_get_time() - ppaStartUs;
3025
+ if (err != ESP_OK) {
3026
+ if (!ppaWarned_) {
3027
+ ppaWarned_ = true;
3028
+ ESP_LOGE(kTag, "PPA SRM present failed: %s", esp_err_to_name(err));
3029
+ }
3030
+ return false;
3031
+ }
3032
+ return true;
3033
+ }
3034
+
3035
+ bool enableDsiPhyPower()
3036
+ {
3037
+ if (dsiPhyPower_) return true;
3038
+ esp_ldo_channel_config_t ldoConfig{};
3039
+ ldoConfig.chan_id = kDsiPhyLdoChannel;
3040
+ ldoConfig.voltage_mv = kDsiPhyLdoVoltageMv;
3041
+ const esp_err_t err = esp_ldo_acquire_channel(&ldoConfig, &dsiPhyPower_);
3042
+ if (err != ESP_OK) {
3043
+ ESP_LOGE(kTag, "DSI PHY LDO enable failed: %s", esp_err_to_name(err));
3044
+ return false;
3045
+ }
3046
+ ESP_LOGI(kTag, "DSI PHY powered on LDO%d %dmV", kDsiPhyLdoChannel, kDsiPhyLdoVoltageMv);
3047
+ return true;
3048
+ }
3049
+
3050
+ bool initBacklight()
3051
+ {
3052
+ if (brightnessInitialized_) return true;
3053
+
3054
+ ledc_timer_config_t timerConfig{};
3055
+ timerConfig.speed_mode = LEDC_LOW_SPEED_MODE;
3056
+ timerConfig.duty_resolution = LEDC_TIMER_10_BIT;
3057
+ timerConfig.timer_num = kBacklightLedcTimer;
3058
+ timerConfig.freq_hz = 5000;
3059
+ timerConfig.clk_cfg = LEDC_AUTO_CLK;
3060
+ esp_err_t err = ledc_timer_config(&timerConfig);
3061
+ if (err != ESP_OK) {
3062
+ ESP_LOGE(kTag, "backlight LEDC timer init failed: %s", esp_err_to_name(err));
3063
+ return false;
3064
+ }
3065
+
3066
+ ledc_channel_config_t channelConfig{};
3067
+ channelConfig.gpio_num = gea::platform::board::display.backlight;
3068
+ channelConfig.speed_mode = LEDC_LOW_SPEED_MODE;
3069
+ channelConfig.channel = kBacklightLedcChannel;
3070
+ channelConfig.timer_sel = kBacklightLedcTimer;
3071
+ channelConfig.duty = 0;
3072
+ channelConfig.hpoint = 0;
3073
+ err = ledc_channel_config(&channelConfig);
3074
+ if (err != ESP_OK) {
3075
+ ESP_LOGE(kTag, "backlight LEDC channel init failed: %s", esp_err_to_name(err));
3076
+ return false;
3077
+ }
3078
+
3079
+ brightnessInitialized_ = true;
3080
+ updateBacklightDuty();
3081
+ return true;
3082
+ }
3083
+
3084
+ void updateBacklightDuty()
3085
+ {
3086
+ const std::uint32_t duty = static_cast<std::uint32_t>((brightness_ * kBacklightLedcMaxDuty) / 100);
3087
+ ledc_set_duty(LEDC_LOW_SPEED_MODE, kBacklightLedcChannel, duty);
3088
+ ledc_update_duty(LEDC_LOW_SPEED_MODE, kBacklightLedcChannel);
3089
+ }
3090
+
3091
+ bool initPanel()
3092
+ {
3093
+ if (panel_) return true;
3094
+
3095
+ if (!enableDsiPhyPower()) return false;
3096
+
3097
+ gea::platform::tab5::LcdPanel panelInfo;
3098
+ if (!gea::platform::tab5::initDisplayPanel(kDpiFrameBufferCount, &panelInfo)) {
3099
+ ESP_LOGE(kTag, "Tab5 LCD init failed");
3100
+ return false;
3101
+ }
3102
+ const char *controllerName = gea::platform::tab5::displayControllerName(panelInfo.controller);
3103
+
3104
+ mipiDsiBus_ = panelInfo.dsiBus;
3105
+ io_ = panelInfo.io;
3106
+ panel_ = panelInfo.panel;
3107
+ if (!panel_) {
3108
+ ESP_LOGE(kTag, "Tab5 driver did not expose an LCD panel handle");
3109
+ return false;
3110
+ }
3111
+
3112
+ if (!initBacklight()) return false;
3113
+
3114
+ void *fb0 = nullptr;
3115
+ void *fb1 = nullptr;
3116
+ void *fb2 = nullptr;
3117
+ esp_err_t err = esp_lcd_dpi_panel_get_frame_buffer(panel_, kDpiFrameBufferCount, &fb0, &fb1, &fb2);
3118
+ if (err == ESP_OK && fb0) {
3119
+ panelFrameBuffers_[0] = static_cast<std::uint16_t *>(fb0);
3120
+ panelFrameBuffers_[1] = static_cast<std::uint16_t *>(fb1); // null when num_fbs == 1
3121
+ panelFrameBuffers_[2] = static_cast<std::uint16_t *>(fb2); // null when num_fbs < 3
3122
+ scannedFbIndex_ = 0; // the driver scans fb0 first
3123
+ pendingReleasedFbIndex_ = -1;
3124
+ panelFrameBuffer_ = panelFrameBuffers_[0];
3125
+ const std::size_t panelBytes = static_cast<std::size_t>(kMaxPixels) * sizeof(std::uint16_t);
3126
+ for (int i = 0; i < kDpiFrameBufferCount; ++i) {
3127
+ if (!panelFrameBuffers_[i]) continue;
3128
+ std::memset(panelFrameBuffers_[i], 0, panelBytes);
3129
+ syncFrameBufferFullRowsToMemory(panelFrameBuffers_[i], 0, kNativeHeight - 1, "DPI panel framebuffer");
3130
+ }
3131
+ resetPanelBackBufferCoherenceLocked();
3132
+ ESP_LOGI(kTag, "using DPI panel framebuffers fb0=%p fb1=%p fb2=%p",
3133
+ panelFrameBuffers_[0],
3134
+ panelFrameBuffers_[1],
3135
+ panelFrameBuffers_[2]);
3136
+ } else {
3137
+ ESP_LOGE(kTag, "DPI panel framebuffer unavailable: %s", esp_err_to_name(err));
3138
+ return false;
3139
+ }
3140
+ // Refresh-boundary signal for scan-aligned double-buffer flips: a
3141
+ // draw_bitmap buffer swap only latches at the next frame restart, so a
3142
+ // producer must not write the just-released buffer until one refresh
3143
+ // completes (else its base fill lands on the still-scanned frame —
3144
+ // visible as white flashes while panning).
3145
+ refreshDoneSem_ = xSemaphoreCreateBinary();
3146
+ if (refreshDoneSem_) {
3147
+ esp_lcd_dpi_panel_event_callbacks_t cbs{};
3148
+ cbs.on_refresh_done = [](esp_lcd_panel_handle_t, esp_lcd_dpi_panel_event_data_t *, void *ctx) -> bool {
3149
+ BaseType_t woken = pdFALSE;
3150
+ xSemaphoreGiveFromISR(static_cast<SemaphoreHandle_t>(ctx), &woken);
3151
+ return woken == pdTRUE;
3152
+ };
3153
+ if (esp_lcd_dpi_panel_register_event_callbacks(panel_, &cbs, refreshDoneSem_) != ESP_OK) {
3154
+ ESP_LOGW(kTag, "refresh-done callback unavailable; panel-direct flips stay unaligned");
3155
+ vSemaphoreDelete(refreshDoneSem_);
3156
+ refreshDoneSem_ = nullptr;
3157
+ }
3158
+ }
3159
+ err = esp_lcd_panel_disp_on_off(panel_, true);
3160
+ if (err == ESP_ERR_NOT_SUPPORTED) {
3161
+ ESP_LOGW(kTag, "panel display-on hook unsupported by DPI panel; continuing after DSI init table");
3162
+ } else if (err != ESP_OK) {
3163
+ ESP_LOGE(kTag, "panel on failed: %s", esp_err_to_name(err));
3164
+ return false;
3165
+ }
3166
+
3167
+ // One-shot GDMA bandwidth probe: can the AXI DMA move a full frame
3168
+ // between PSRAM buffers materially faster than the PPA's measured
3169
+ // ~86MB/s or the CPU's ~120MB/s? Decides whether map pans should be a
3170
+ // DMA content-shift + strip raster. The buffers get fully overwritten
3171
+ // by the first present, so the copy is harmless.
3172
+ if (panelFrameBuffers_[1] && ownedFrameBuffer_) {
3173
+ async_memcpy_config_t mcpConfig{};
3174
+ mcpConfig.backlog = 4;
3175
+ mcpConfig.dma_burst_size = 64;
3176
+ async_memcpy_handle_t mcp = nullptr;
3177
+ if (esp_async_memcpy_install_gdma_axi(&mcpConfig, &mcp) == ESP_OK) {
3178
+ SemaphoreHandle_t done = xSemaphoreCreateBinary();
3179
+ auto benchCb = [](async_memcpy_handle_t, async_memcpy_event_t *, void *ctx) -> bool {
3180
+ BaseType_t woken = pdFALSE;
3181
+ xSemaphoreGiveFromISR(static_cast<SemaphoreHandle_t>(ctx), &woken);
3182
+ return woken == pdTRUE;
3183
+ };
3184
+ const std::size_t benchBytes = static_cast<std::size_t>(kMaxPixels) * sizeof(std::uint16_t);
3185
+ const std::int64_t benchStart = esp_timer_get_time();
3186
+ if (done &&
3187
+ esp_async_memcpy(mcp, panelFrameBuffers_[1], ownedFrameBuffer_, benchBytes, benchCb, done) == ESP_OK &&
3188
+ xSemaphoreTake(done, pdMS_TO_TICKS(500)) == pdTRUE) {
3189
+ const std::int64_t benchUs = esp_timer_get_time() - benchStart;
3190
+ ESP_LOGI(kTag, "GDMA bench: %u bytes in %lld us = %.1f MB/s", static_cast<unsigned>(benchBytes),
3191
+ static_cast<long long>(benchUs), benchUs > 0 ? benchBytes / static_cast<double>(benchUs) : 0.0);
3192
+ } else {
3193
+ ESP_LOGW(kTag, "GDMA bench failed");
3194
+ }
3195
+ if (done) vSemaphoreDelete(done);
3196
+ // Keep the channel: the landscape pan fast path uses it to
3197
+ // shift-copy the map region (~15.5ms DMA, overlapped with the
3198
+ // CPU strip raster) instead of a ~22ms CPU memcpy.
3199
+ mcp_ = mcp;
3200
+ mcpDone_ = xSemaphoreCreateBinary();
3201
+ } else {
3202
+ ESP_LOGW(kTag, "GDMA AXI async-memcpy unavailable");
3203
+ }
3204
+ }
3205
+ ESP_LOGI(kTag,
3206
+ "Tab5 %s DSI panel ready native=%dx%d logical=%dx%d fb=%s out=%s panel_bpp=%d dpi_fbs=%d",
3207
+ controllerName,
3208
+ kNativeWidth,
3209
+ kNativeHeight,
3210
+ logicalWidth(),
3211
+ logicalHeight(),
3212
+ pixel::name(kFramebufferPixelFormat),
3213
+ pixel::name(kDsiOutputPixelFormat),
3214
+ kPanelBitsPerPixel,
3215
+ kDpiFrameBufferCount);
3216
+ return true;
3217
+ }
3218
+
3219
+ bool flushNativeLogicalRect(present::Rect logicalRect)
3220
+ {
3221
+ logicalRect = clampLogicalRect(logicalRect, logicalWidth(), logicalHeight());
3222
+ if (!present::valid(logicalRect)) return true;
3223
+ const present::Rect panelRect = physicalBoundsForLogicalRect(logicalRect);
3224
+ if (!present::valid(panelRect)) return true;
3225
+ using gea::framework::display::DisplayOrientation;
3226
+ const bool directRows =
3227
+ orientation_detail::DisplayOrientationState::orientation() == DisplayOrientation::PortraitPrimary;
3228
+
3229
+ take();
3230
+ bindCanvasLocked();
3231
+ if (!panel_) {
3232
+ give();
3233
+ return false;
3234
+ }
3235
+ bool ok = true;
3236
+ const int panelWidth = panelRect.x1 - panelRect.x0 + 1;
3237
+ const int panelHeight = panelRect.y1 - panelRect.y0 + 1;
3238
+ if (directRows && usingPanelFrameBufferDirectly()) {
3239
+ const std::int64_t syncStartUs = esp_timer_get_time();
3240
+ // NOTE: this full-frame cache writeback (~40ms for 720x1280) is the dominant
3241
+ // per-frame cost. Splitting it across both cores was measured to be a net loss
3242
+ // (21.6->19.4fps, flush 40->44ms): it is PSRAM-write-bandwidth-bound, so two
3243
+ // cores just contend for the same bus while adding handshake latency. The 40ms
3244
+ // is a hard bandwidth floor for a full-screen redraw on this DSI panel.
3245
+ ok = syncFrameBufferRectToMemory(logicalRect);
3246
+ flushStats_.copyUs += esp_timer_get_time() - syncStartUs;
3247
+ flushStats_.chunkCount++;
3248
+ flushStats_.pixelCount += panelWidth * panelHeight;
3249
+ give();
3250
+ return ok;
3251
+ }
3252
+
3253
+ if (frameBuffer_ != ownedFrameBuffer_) {
3254
+ ESP_LOGE(kTag, "rotated flush requires the owned framebuffer");
3255
+ give();
3256
+ return false;
3257
+ }
3258
+ if (scrollOriginX_ != 0 || scrollOriginY_ != 0) {
3259
+ // Torus mode: the logical rect's pixels live at wrapped framebuffer
3260
+ // locations — sync + rotate each part separately.
3261
+ TorusPart parts[4];
3262
+ const int count = splitLogicalRectToTorus(logicalRect, parts);
3263
+ ok = true;
3264
+ for (int i = 0; i < count && ok; ++i) {
3265
+ const TorusPart &part = parts[i];
3266
+ const std::int64_t syncStartUs = esp_timer_get_time();
3267
+ ok = syncTorusPartToMemory(part);
3268
+ flushStats_.copyUs += esp_timer_get_time() - syncStartUs;
3269
+ if (!ok) break;
3270
+ const int w = part.torus.x1 - part.torus.x0 + 1;
3271
+ const int h = part.torus.y1 - part.torus.y0 + 1;
3272
+ const present::Rect partLogical{part.logicalX, part.logicalY, part.logicalX + w - 1, part.logicalY + h - 1};
3273
+ ok = rotateTorusPartToPanelWithPpa(part, physicalBoundsForLogicalRect(partLogical));
3274
+ }
3275
+ if (ok) {
3276
+ flushStats_.chunkCount++;
3277
+ flushStats_.pixelCount += panelWidth * panelHeight;
3278
+ }
3279
+ give();
3280
+ return ok;
3281
+ }
3282
+ const int logicalPixels = (logicalRect.x1 - logicalRect.x0 + 1) * (logicalRect.y1 - logicalRect.y0 + 1);
3283
+ if (logicalPixels <= kCpuPanelMapFlushMaxPixels) {
3284
+ ok = copyLogicalRectToPanelCpu(logicalRect, panelRect);
3285
+ } else {
3286
+ ok = rotateLogicalRectToPanelWithPpa(logicalRect, panelRect);
3287
+ }
3288
+ if (ok) {
3289
+ flushStats_.chunkCount++;
3290
+ flushStats_.pixelCount += panelWidth * panelHeight;
3291
+ }
3292
+ give();
3293
+ return ok;
3294
+ }
3295
+
3296
+ // ---- Scroll-origin (torus) panning -------------------------------------
3297
+ // A pan repaints the whole screen even though 80-90% of the pixels are the
3298
+ // SAME content at a shifted address — and a full-screen repaint is bus-
3299
+ // bound (~9MB of PSRAM traffic ≈ 60-90ms). Instead, when a frame is the
3300
+ // previous frame uniformly shifted by (dx,dy), move the framebuffer's READ
3301
+ // ORIGIN (treating it as a wrapping scroll surface) and raster only the
3302
+ // newly exposed strips. The PPA rotate pass — which runs anyway — assembles
3303
+ // the wrapped quadrants into the panel buffer. Pan frames drop from ~921k
3304
+ // rastered pixels to the strip area (~30-80k).
3305
+
3306
+ static int wrapCoord(int v, int size)
3307
+ {
3308
+ int m = v % size;
3309
+ return m < 0 ? m + size : m;
3310
+ }
3311
+
3312
+ // A logical-space rect mapped onto the torus: `torus` is where the pixels
3313
+ // live in the framebuffer; logicalX/logicalY are the content coordinates of
3314
+ // its top-left corner.
3315
+ struct TorusPart {
3316
+ present::Rect torus;
3317
+ int logicalX;
3318
+ int logicalY;
3319
+ };
3320
+
3321
+ int splitLogicalRectToTorus(const present::Rect &logical, TorusPart out[4]) const
3322
+ {
3323
+ const int w = logicalWidth();
3324
+ const int h = logicalHeight();
3325
+ const int rectW = logical.x1 - logical.x0 + 1;
3326
+ const int rectH = logical.y1 - logical.y0 + 1;
3327
+ if (rectW <= 0 || rectH <= 0) return 0;
3328
+ const int startX = wrapCoord(logical.x0 + scrollOriginX_, w);
3329
+ const int startY = wrapCoord(logical.y0 + scrollOriginY_, h);
3330
+ const int xw0 = std::min(rectW, w - startX);
3331
+ const int yh0 = std::min(rectH, h - startY);
3332
+ struct Seg {
3333
+ int torusStart;
3334
+ int logicalStart;
3335
+ int size;
3336
+ };
3337
+ const Seg xs[2] = {{startX, logical.x0, xw0}, {0, logical.x0 + xw0, rectW - xw0}};
3338
+ const Seg ys[2] = {{startY, logical.y0, yh0}, {0, logical.y0 + yh0, rectH - yh0}};
3339
+ int count = 0;
3340
+ for (const Seg &sy : ys) {
3341
+ if (sy.size <= 0) continue;
3342
+ for (const Seg &sx : xs) {
3343
+ if (sx.size <= 0) continue;
3344
+ out[count].torus = {sx.torusStart, sy.torusStart, sx.torusStart + sx.size - 1, sy.torusStart + sy.size - 1};
3345
+ out[count].logicalX = sx.logicalStart;
3346
+ out[count].logicalY = sy.logicalStart;
3347
+ count++;
3348
+ }
3349
+ }
3350
+ return count;
3351
+ }
3352
+
3353
+ // Write back one torus part's framebuffer rows to PSRAM (so the PPA's DMA
3354
+ // reads see them).
3355
+ bool syncTorusPartToMemory(const TorusPart &part)
3356
+ {
3357
+ return syncBufferRectToMemory(frameBuffer_, logicalStride_, logicalStride_, logicalHeight(), part.torus,
3358
+ "torus framebuffer part");
3359
+ }
3360
+
3361
+ // True when `current` equals `previous` with every image command shifted by
3362
+ // one uniform integer (dx,dy) (matched by pixel pointer + draw size) and an
3363
+ // identical opaque base. Unmatched commands (edge tiles entering the view)
3364
+ // are fine — the caller rasters their bounds. At least 2/3 must match so a
3365
+ // zoom (where sizes change) never false-positives.
3366
+ static bool detectUniformShift(const present::Frame &previous, const present::Frame &current, int *dx, int *dy)
3367
+ {
3368
+ using Type = gea::platform::display::DisplayPresentCommandType;
3369
+ if (previous.commands.size() < 2 || current.commands.size() < 2) return false;
3370
+ if (!present::commandsEqual(previous.commands[0], current.commands[0])) return false;
3371
+ bool have = false;
3372
+ int sx = 0;
3373
+ int sy = 0;
3374
+ int matched = 0;
3375
+ int images = 0;
3376
+ for (std::size_t i = 1; i < current.commands.size(); ++i) {
3377
+ const present::Command &c = current.commands[i];
3378
+ if (c.type != Type::DrawImage && c.type != Type::DrawImageScaled) return false;
3379
+ images++;
3380
+ for (std::size_t j = 1; j < previous.commands.size(); ++j) {
3381
+ const present::Command &p = previous.commands[j];
3382
+ if (p.type != c.type || p.pixels != c.pixels) continue;
3383
+ if (p.srcWidth != c.srcWidth || p.srcHeight != c.srcHeight) continue;
3384
+ if (c.type == Type::DrawImageScaled && (p.w != c.w || p.h != c.h)) continue;
3385
+ const int candX = c.x - p.x;
3386
+ const int candY = c.y - p.y;
3387
+ if (!have) {
3388
+ have = true;
3389
+ sx = candX;
3390
+ sy = candY;
3391
+ } else if (candX != sx || candY != sy) {
3392
+ return false;
3393
+ }
3394
+ matched++;
3395
+ break;
3396
+ }
3397
+ }
3398
+ if (!have || (sx == 0 && sy == 0)) return false;
3399
+ if (matched * 3 < images * 2) return false;
3400
+ *dx = sx;
3401
+ *dy = sy;
3402
+ return true;
3403
+ }
3404
+
3405
+ // Rotate the full torus surface into the panel buffer: one PPA op per
3406
+ // wrapped quadrant (1, 2, or 4 big ops — efficient, unlike per-tile ops).
3407
+ // Sources must already be written back (strips are synced at raster time;
3408
+ // everything else was synced when it was last rastered).
3409
+ bool flushFullPanelFromTorus()
3410
+ {
3411
+ const present::Rect full{0, 0, logicalWidth() - 1, logicalHeight() - 1};
3412
+ TorusPart parts[4];
3413
+ const int count = splitLogicalRectToTorus(full, parts);
3414
+ take();
3415
+ bindCanvasLocked();
3416
+ if (!panel_ || frameBuffer_ != ownedFrameBuffer_) {
3417
+ give();
3418
+ return false;
3419
+ }
3420
+ bool ok = true;
3421
+ for (int i = 0; i < count && ok; ++i) {
3422
+ const TorusPart &part = parts[i];
3423
+ const int w = part.torus.x1 - part.torus.x0 + 1;
3424
+ const int h = part.torus.y1 - part.torus.y0 + 1;
3425
+ const present::Rect logicalRect{part.logicalX, part.logicalY, part.logicalX + w - 1, part.logicalY + h - 1};
3426
+ const present::Rect panelRect = physicalBoundsForLogicalRect(logicalRect);
3427
+ if (!present::valid(panelRect)) continue;
3428
+ ok = rotateTorusPartToPanelWithPpa(part, panelRect);
3429
+ }
3430
+ if (ok) {
3431
+ flushStats_.chunkCount++;
3432
+ flushStats_.pixelCount += logicalWidth() * logicalHeight();
3433
+ }
3434
+ give();
3435
+ return ok;
3436
+ }
3437
+
3438
+ // Like rotateLogicalRectToPanelWithPpa, but the source block sits at the
3439
+ // part's TORUS coordinates while the panel destination comes from its
3440
+ // LOGICAL rect. No source cache sync here — the caller guarantees it.
3441
+ bool rotateTorusPartToPanelWithPpa(const TorusPart &part, present::Rect panelRect)
3442
+ {
3443
+ if (!frameBuffer_ || !panelFrameBuffer_) return false;
3444
+ panelRect = present::clampAndAlign(panelRect, kNativeWidth, kNativeHeight);
3445
+ if (!present::valid(panelRect)) return true;
3446
+ if (!initPpaSrm()) return false;
3447
+
3448
+ ppa_srm_oper_config_t config{};
3449
+ config.in.buffer = frameBuffer_;
3450
+ config.in.pic_w = static_cast<std::uint32_t>(logicalWidth());
3451
+ config.in.pic_h = static_cast<std::uint32_t>(logicalHeight());
3452
+ config.in.block_w = static_cast<std::uint32_t>(part.torus.x1 - part.torus.x0 + 1);
3453
+ config.in.block_h = static_cast<std::uint32_t>(part.torus.y1 - part.torus.y0 + 1);
3454
+ config.in.block_offset_x = static_cast<std::uint32_t>(part.torus.x0);
3455
+ config.in.block_offset_y = static_cast<std::uint32_t>(part.torus.y0);
3456
+ config.in.srm_cm = PPA_SRM_COLOR_MODE_RGB565;
3457
+ config.out.buffer = panelFrameBuffer_;
3458
+ config.out.buffer_size = static_cast<std::uint32_t>(kMaxPixels * sizeof(std::uint16_t));
3459
+ config.out.pic_w = kNativeWidth;
3460
+ config.out.pic_h = kNativeHeight;
3461
+ config.out.block_offset_x = static_cast<std::uint32_t>(panelRect.x0);
3462
+ config.out.block_offset_y = static_cast<std::uint32_t>(panelRect.y0);
3463
+ config.out.srm_cm = PPA_SRM_COLOR_MODE_RGB565;
3464
+ config.rotation_angle = ppaRotationForCurrentOrientation();
3465
+ config.scale_x = 1.0f;
3466
+ config.scale_y = 1.0f;
3467
+ config.mode = PPA_TRANS_MODE_BLOCKING;
3468
+
3469
+ const std::int64_t ppaStartUs = esp_timer_get_time();
3470
+ const esp_err_t err = ppa_do_scale_rotate_mirror(ppaSrmClient_, &config);
3471
+ flushStats_.txUs += esp_timer_get_time() - ppaStartUs;
3472
+ return err == ESP_OK;
3473
+ }
3474
+
3475
+ // True when the frame is an opaque base followed by raster-safe commands —
3476
+ // originally OPAQUE IMAGE BLITS only (the tile grid), now also opaque
3477
+ // fills and text (the in-canvas sidebar): the panel-direct path does a
3478
+ // FULL re-raster in painter's order every frame, so any command the chunk
3479
+ // rasterizer supports is z-order-safe. Images must be opaque + aligned.
3480
+ static inline int gTileShapeFailKind = 0;
3481
+ static inline int gTileShapeFailType = 0;
3482
+ static inline int gTileShapeFailCount = 0;
3483
+
3484
+ // Landscape pan fast path: previous frame's panel-space commands, used to
3485
+ // detect a pure translation and to dirty the moved small rects (pins).
3486
+ struct LandPrevCmd {
3487
+ const std::uint16_t *pixels;
3488
+ std::int16_t type;
3489
+ int x, y, w, h;
3490
+ };
3491
+ // Panel row where the (static) sidebar begins in landscape: the rail
3492
+ // occupies landscape x < 220 -> panel rows >= kNativeHeight - 220.
3493
+ static constexpr int kRailPanelRow = kNativeHeight - 220;
3494
+ static constexpr int kLandPrevMax = 192;
3495
+ // Last landscape frame's phase timings (never reset; GEADEV diagnostics).
3496
+ int landTotalUs_ = 0;
3497
+ int landAlignUs_ = 0;
3498
+ int landRasterUs_ = 0;
3499
+ int landTextUs_ = 0;
3500
+ int landFlipUs_ = 0;
3501
+ int landPanMode_ = 0;
3502
+ int landPanFrames_ = 0;
3503
+ int landFullFrames_ = 0;
3504
+ async_memcpy_handle_t mcp_ = nullptr;
3505
+ SemaphoreHandle_t mcpDone_ = nullptr;
3506
+ // Pan-path phase timings (us) for GEADEV LANDPAN.
3507
+ int panDetectUs_ = 0;
3508
+ int panKickUs_ = 0;
3509
+ int panStripUs_ = 0;
3510
+ int panWaitUs_ = 0;
3511
+ int panInteriorUs_ = 0;
3512
+ int panDmaErr_ = -1;
3513
+ // Why the last non-pan landscape frame bailed: 1=no snapshot, 2=no delta,
3514
+ // 3=inconsistent deltas, 4=too few pairs, 5=delta too large, 6=dirty overflow.
3515
+ int panBailReason_ = 0;
3516
+ int panBailCounts_[7] = {0, 0, 0, 0, 0, 0, 0};
3517
+ // One snapshot per scanout buffer: the pan path rasters against the
3518
+ // content ALREADY in the back buffer (frame N-2 for that buffer), so the
3519
+ // delta must be measured against that frame's command set.
3520
+ LandPrevCmd landPrev_[kDpiFrameBufferCount][kLandPrevMax];
3521
+ int landPrevCount_[kDpiFrameBufferCount] = {};
3522
+ bool landPrevValid_[kDpiFrameBufferCount] = {};
3523
+ // Hash of the rail-region commands (fills below kRailPanelRow + all text):
3524
+ // the pan path skips rail rows entirely, so ANY rail change must force a
3525
+ // full raster or sidebar state changes (search keyboard, zoom label)
3526
+ // never reach the glass.
3527
+ std::uint32_t landPrevRailHash_[kDpiFrameBufferCount] = {};
3528
+
3529
+ static std::uint32_t railContentHash(const present::Frame &frame, int width, int height)
3530
+ {
3531
+ using Type = gea::platform::display::DisplayPresentCommandType;
3532
+ std::uint32_t h = 2166136261u;
3533
+ auto mix = [&h](std::uint32_t v) {
3534
+ h ^= v;
3535
+ h *= 16777619u;
3536
+ };
3537
+ for (const present::Command &cmd : frame.commands) {
3538
+ if (cmd.type == Type::FillText) {
3539
+ mix(static_cast<std::uint32_t>(cmd.x * 31 + cmd.y));
3540
+ mix(cmd.color);
3541
+ for (char c : cmd.text) mix(static_cast<std::uint32_t>(c));
3542
+ continue;
3543
+ }
3544
+ if (cmd.type != Type::FillRectRgb565) continue;
3545
+ const present::Rect b = present::commandBounds(cmd, width, height);
3546
+ if (!present::valid(b) || b.y0 < height - 220) continue;
3547
+ mix(static_cast<std::uint32_t>(cmd.x * 31 + cmd.y));
3548
+ mix(static_cast<std::uint32_t>(cmd.w * 31 + cmd.h));
3549
+ mix(cmd.color);
3550
+ }
3551
+ return h;
3552
+ }
3553
+
3554
+ static bool framePpaTileEligible(const present::Frame &frame)
3555
+ {
3556
+ using Type = gea::platform::display::DisplayPresentCommandType;
3557
+ auto fail = [&](int kind, int type) {
3558
+ gTileShapeFailKind = kind;
3559
+ gTileShapeFailType = type;
3560
+ gTileShapeFailCount++;
3561
+ return false;
3562
+ };
3563
+ if (frame.commands.size() < 2) return fail(1, static_cast<int>(frame.commands.size()));
3564
+ for (std::size_t i = 1; i < frame.commands.size(); ++i) {
3565
+ const present::Command &cmd = frame.commands[i];
3566
+ if (cmd.type == Type::FillRectRgb565 || cmd.type == Type::FillText) {
3567
+ if (cmd.alpha != 255) return fail(2, static_cast<int>(cmd.type));
3568
+ continue;
3569
+ }
3570
+ if (cmd.type != Type::DrawImage && cmd.type != Type::DrawImageScaled) return fail(3, static_cast<int>(cmd.type));
3571
+ if (cmd.alphaPixels || cmd.alpha != 255 || !cmd.pixels) return fail(4, static_cast<int>(cmd.type));
3572
+ if (cmd.srcWidth <= 0 || cmd.srcHeight <= 0) return fail(5, static_cast<int>(cmd.type));
3573
+ if ((reinterpret_cast<std::uintptr_t>(cmd.pixels) & 63) != 0) return fail(6, static_cast<int>(cmd.type));
3574
+ }
3575
+ return true;
3576
+ }
3577
+
3578
+ // Raster an eligible tile frame for one region with the PPA doing the pixel
3579
+ // hauling: the CPU only fills the opaque base; every tile is a hardware DMA
3580
+ // blit (with scaling) straight into the logical framebuffer. The CPU raster
3581
+ // costs ~70-100ms for a full 720x1280 composite (PSRAM bandwidth through
3582
+ // the cache); the PPA does the same haul in ~15ms with the CPU free.
3583
+ // Returns false (caller falls back to the CPU raster) when a SCALED blit
3584
+ // only partially intersects the region — PPA block offsets can't express
3585
+ // that clip exactly — or when a PPA op is rejected.
3586
+ bool ppaRasterTileRegion(const present::Frame &frame, const present::Rect &region)
3587
+ {
3588
+ if (!frameBuffer_ || !initPpaSrm()) return false;
3589
+ using Type = gea::platform::display::DisplayPresentCommandType;
3590
+ for (std::size_t i = 1; i < frame.commands.size(); ++i) {
3591
+ const present::Command &cmd = frame.commands[i];
3592
+ if (cmd.type != Type::DrawImageScaled) continue;
3593
+ if (cmd.w == cmd.srcWidth && cmd.h == cmd.srcHeight) continue;
3594
+ const present::Rect dst = present::rectFromBox(cmd.x, cmd.y, cmd.w, cmd.h);
3595
+ const bool outside = dst.x1 < region.x0 || dst.x0 > region.x1 || dst.y1 < region.y0 || dst.y0 > region.y1;
3596
+ const bool inside = dst.x0 >= region.x0 && dst.y0 >= region.y0 && dst.x1 <= region.x1 && dst.y1 <= region.y1;
3597
+ if (!outside && !inside) return false;
3598
+ const float sx = static_cast<float>(cmd.w) / cmd.srcWidth;
3599
+ const float sy = static_cast<float>(cmd.h) / cmd.srcHeight;
3600
+ // PPA SRM scale range is [1/16, 256); stay comfortably inside.
3601
+ if (sx < 0.07f || sy < 0.07f || sx >= 250.0f || sy >= 250.0f) return false;
3602
+ }
3603
+
3604
+ // 1. CPU: opaque base fill across the region (Clear or full-screen fill).
3605
+ const std::uint16_t fillColor = frame.commands.front().color;
3606
+ const int rowWidth = region.x1 - region.x0 + 1;
3607
+ for (int y = region.y0; y <= region.y1; ++y) {
3608
+ std::uint16_t *row = frameBuffer_ + static_cast<std::size_t>(y) * logicalStride_ + region.x0;
3609
+ std::fill_n(row, rowWidth, fillColor);
3610
+ }
3611
+ // 2. Write the fill back to PSRAM so the PPA's writes compose on top.
3612
+ if (!syncFrameBufferRectToMemory(region)) return false;
3613
+
3614
+ // 3. The blits, in painter's order (ancestor fallbacks before exact tiles).
3615
+ for (std::size_t i = 1; i < frame.commands.size(); ++i) {
3616
+ const present::Command &cmd = frame.commands[i];
3617
+ const int dstW = cmd.type == Type::DrawImageScaled ? cmd.w : cmd.srcWidth;
3618
+ const int dstH = cmd.type == Type::DrawImageScaled ? cmd.h : cmd.srcHeight;
3619
+ const bool scaled = dstW != cmd.srcWidth || dstH != cmd.srcHeight;
3620
+ const present::Rect dst = present::rectFromBox(cmd.x, cmd.y, dstW, dstH);
3621
+ const present::Rect inter{std::max(dst.x0, region.x0), std::max(dst.y0, region.y0),
3622
+ std::min(dst.x1, region.x1), std::min(dst.y1, region.y1)};
3623
+ if (!present::valid(inter)) continue;
3624
+
3625
+ ppa_srm_oper_config_t config{};
3626
+ config.in.buffer = const_cast<void *>(static_cast<const void *>(cmd.pixels));
3627
+ config.in.pic_w = static_cast<std::uint32_t>(cmd.srcWidth);
3628
+ config.in.pic_h = static_cast<std::uint32_t>(cmd.srcHeight);
3629
+ if (scaled) {
3630
+ config.in.block_w = static_cast<std::uint32_t>(cmd.srcWidth);
3631
+ config.in.block_h = static_cast<std::uint32_t>(cmd.srcHeight);
3632
+ config.out.block_offset_x = static_cast<std::uint32_t>(dst.x0);
3633
+ config.out.block_offset_y = static_cast<std::uint32_t>(dst.y0);
3634
+ config.scale_x = static_cast<float>(dstW) / cmd.srcWidth;
3635
+ config.scale_y = static_cast<float>(dstH) / cmd.srcHeight;
3636
+ } else {
3637
+ config.in.block_w = static_cast<std::uint32_t>(inter.x1 - inter.x0 + 1);
3638
+ config.in.block_h = static_cast<std::uint32_t>(inter.y1 - inter.y0 + 1);
3639
+ config.in.block_offset_x = static_cast<std::uint32_t>(inter.x0 - dst.x0);
3640
+ config.in.block_offset_y = static_cast<std::uint32_t>(inter.y0 - dst.y0);
3641
+ config.out.block_offset_x = static_cast<std::uint32_t>(inter.x0);
3642
+ config.out.block_offset_y = static_cast<std::uint32_t>(inter.y0);
3643
+ config.scale_x = 1.0f;
3644
+ config.scale_y = 1.0f;
3645
+ }
3646
+ config.in.srm_cm = PPA_SRM_COLOR_MODE_RGB565;
3647
+ config.out.buffer = frameBuffer_;
3648
+ config.out.buffer_size = static_cast<std::uint32_t>(kMaxPixels * sizeof(std::uint16_t));
3649
+ config.out.pic_w = static_cast<std::uint32_t>(logicalStride_);
3650
+ config.out.pic_h = static_cast<std::uint32_t>(logicalHeight());
3651
+ config.out.srm_cm = PPA_SRM_COLOR_MODE_RGB565;
3652
+ config.rotation_angle = PPA_SRM_ROTATION_ANGLE_0;
3653
+ config.mode = PPA_TRANS_MODE_BLOCKING;
3654
+ if (ppa_do_scale_rotate_mirror(ppaSrmClient_, &config) != ESP_OK) return false;
3655
+ }
3656
+
3657
+ // 4. Drop the CPU's now-stale cached copy of the PPA-written rows.
3658
+ // Writeback-then-invalidate over a cache-line-aligned span so neighbor
3659
+ // lines never lose dirty data (M2C demands aligned ranges).
3660
+ {
3661
+ std::uint8_t *start = reinterpret_cast<std::uint8_t *>(frameBuffer_ + static_cast<std::size_t>(region.y0) * logicalStride_);
3662
+ const std::size_t len = static_cast<std::size_t>(region.y1 - region.y0 + 1) * logicalStride_ * sizeof(std::uint16_t);
3663
+ const std::uintptr_t spanStart = reinterpret_cast<std::uintptr_t>(start) & ~static_cast<std::uintptr_t>(127);
3664
+ const std::uintptr_t spanEnd = (reinterpret_cast<std::uintptr_t>(start) + len + 127) & ~static_cast<std::uintptr_t>(127);
3665
+ esp_cache_msync(reinterpret_cast<void *>(spanStart), spanEnd - spanStart,
3666
+ ESP_CACHE_MSYNC_FLAG_DIR_C2M | ESP_CACHE_MSYNC_FLAG_TYPE_DATA);
3667
+ esp_cache_msync(reinterpret_cast<void *>(spanStart), spanEnd - spanStart,
3668
+ ESP_CACHE_MSYNC_FLAG_DIR_M2C | ESP_CACHE_MSYNC_FLAG_TYPE_DATA);
3669
+ }
3670
+ return true;
3671
+ }
3672
+
3673
+ void rasterPresentRegion(const present::Frame &frame, const present::Rect &region)
3674
+ {
3675
+ if (!present::valid(region)) return;
3676
+ // Torus-aware: raster the LOGICAL region into its (possibly wrapped)
3677
+ // framebuffer location(s). With origin (0,0) this is exactly one part at
3678
+ // the identity position — the historical behavior.
3679
+ TorusPart parts[4];
3680
+ const int count = splitLogicalRectToTorus(region, parts);
3681
+ const int height = logicalHeight();
3682
+ const int maxRows = std::max(1, flushRows_);
3683
+ for (int p = 0; p < count; ++p) {
3684
+ const TorusPart &part = parts[p];
3685
+ const int width = part.torus.x1 - part.torus.x0 + 1;
3686
+ const int partRows = part.torus.y1 - part.torus.y0 + 1;
3687
+ PresentRasterBand job{
3688
+ frameBuffer_ + static_cast<std::size_t>(part.torus.y0) * logicalStride_ + part.torus.x0,
3689
+ logicalStride_,
3690
+ part.logicalX,
3691
+ width,
3692
+ part.logicalY,
3693
+ height,
3694
+ maxRows,
3695
+ &frame,
3696
+ };
3697
+ const std::int64_t rasterStartUs = esp_timer_get_time();
3698
+ bool parallel = false;
3699
+ if (!onAsyncPresentWorker() &&
3700
+ partRows >= kPresentParallelMinRows &&
3701
+ width * partRows >= kPresentParallelMinPixels) {
3702
+ const int mainRows = partRows / 2;
3703
+ if (mainRows > 0 && mainRows < partRows &&
3704
+ gea_render_parallel_submit(rasterPresentBandThunk, &job, mainRows, partRows - 1)) {
3705
+ rasterPresentBandRows(job, 0, mainRows - 1);
3706
+ gea_render_parallel_wait();
3707
+ parallel = true;
3708
+ }
3709
+ }
3710
+ if (!parallel) rasterPresentBandRows(job, 0, partRows - 1);
3711
+ flushStats_.rasterUs += esp_timer_get_time() - rasterStartUs;
3712
+ }
3713
+ }
3714
+
3715
+ void take()
3716
+ {
3717
+ if (mutex_) xSemaphoreTake(mutex_, portMAX_DELAY);
3718
+ }
3719
+
3720
+ void give()
3721
+ {
3722
+ if (mutex_) xSemaphoreGive(mutex_);
3723
+ }
3724
+
3725
+ SemaphoreHandle_t mutex_ = nullptr;
3726
+ esp_lcd_panel_handle_t panel_ = nullptr;
3727
+ esp_lcd_panel_io_handle_t io_ = nullptr;
3728
+ esp_lcd_dsi_bus_handle_t mipiDsiBus_ = nullptr;
3729
+ esp_ldo_channel_handle_t dsiPhyPower_ = nullptr;
3730
+ ppa_client_handle_t ppaSrmClient_ = nullptr;
3731
+ std::uint16_t *frameBuffer_ = nullptr;
3732
+ std::uint16_t *ownedFrameBuffer_ = nullptr;
3733
+ std::uint16_t *panelFrameBuffer_ = nullptr; // the buffer the DSI is currently scanning
3734
+ std::uint16_t *panelFrameBuffers_[kDpiFrameBufferCount] = {}; // DPI scanout buffers (num_fbs)
3735
+ int pendingReleasedFbIndex_ = -1;
3736
+ int scannedFbIndex_ = 0; // which of panelFrameBuffers_ the DSI scans now (driver default 0)
3737
+ present::Rect panelBufferStaleRects_[kDpiFrameBufferCount][kMaxFlushRects] = {};
3738
+ int panelBufferStaleCount_[kDpiFrameBufferCount] = {};
3739
+ bool panelBufferStaleFull_[kDpiFrameBufferCount] = {};
3740
+ present::Rect pendingPanelBackSyncRects_[kMaxFlushRects] = {};
3741
+ int pendingPanelBackSyncCount_ = 0;
3742
+ std::uint16_t *backgroundCache_ = nullptr;
3743
+ std::uint16_t *backdropCache_ = nullptr;
3744
+ // Scroll origin of the logical framebuffer when it acts as a wrapping
3745
+ // (torus) scroll surface for tile-grid pans; (0,0) = plain linear layout.
3746
+ int scrollOriginX_ = 0;
3747
+ int scrollOriginY_ = 0;
3748
+ // Refresh-boundary semaphore (given at 60Hz by the DPI on_refresh_done ISR)
3749
+ // + the moment of the last double-buffer flip, for scan-aligned writes.
3750
+ SemaphoreHandle_t refreshDoneSem_ = nullptr;
3751
+ std::int64_t lastFlipUs_ = 0;
3752
+ // Landscape pipelined present: the CPU rasters frame N+1 into a compose
3753
+ // ping-pong while the PPA rotates frame N into the panel back buffer —
3754
+ // throughput becomes the rotate alone (~43ms) instead of raster+rotate.
3755
+ std::uint16_t *composeBuffers_[2] = {nullptr, nullptr};
3756
+ int composeIndex_ = 0;
3757
+ SemaphoreHandle_t ppaDoneSem_ = nullptr;
3758
+ bool ppaInFlight_ = false;
3759
+ bool ppaCallbackRegistered_ = false;
3760
+ // The panel buffer is only ever DMA-written in torus mode; one defensive
3761
+ // writeback when entering the mode, then skipped.
3762
+ bool panelSyncedForTorus_ = false;
3763
+ // Panel-direct tile mode: full-frame flips own the scanout; the composed
3764
+ // logical canvas is stale, so its flush is suppressed until transition out.
3765
+ bool panelDirectActive_ = false;
3766
+ // Present-path diagnostics.
3767
+ int presentCalls_ = 0;
3768
+ int pathDirect_ = 0;
3769
+ int pathGeneral_ = 0;
3770
+ int pathExternalFlush_ = 0;
3771
+ int pathRejected_ = 0;
3772
+ int circleSpanCacheRadius_ = -1;
3773
+ int circleSpanHalfWidths_[kCircleSpanCacheMaxRadius + 1] = {};
3774
+ gea::framework::graphics::Canvas canvas_;
3775
+ gea::framework::graphics::Canvas workerCanvas_;
3776
+ TaskHandle_t asyncPresentTask_ = nullptr;
3777
+ SemaphoreHandle_t asyncPresentDoneSem_ = nullptr;
3778
+ std::atomic<bool> asyncPresentInFlight_{false};
3779
+ present::Frame asyncPresentFrame_{};
3780
+ bool asyncPresentOk_ = true;
3781
+ int logicalStride_ = kMaxLogicalWidth;
3782
+ int renderCoreId_ = -1;
3783
+ int flushRows_ = kFlushRowsDefault;
3784
+ int flushDepth_ = 1;
3785
+ int brightness_ = 100;
3786
+ bool brightnessInitialized_ = false;
3787
+ bool initialized_ = false;
3788
+ bool frameBufferCoherent_ = true;
3789
+ bool cacheSyncWarned_ = false;
3790
+ bool ppaWarned_ = false;
3791
+ bool backgroundCacheAttempted_ = false;
3792
+ bool backdropCacheAttempted_ = false;
3793
+ platform_display::DisplayFlushPerfStats flushStats_{};
3794
+ present::Frame previousPresentFrame_{};
3795
+ present::Frame panelCirclePrevFrame_[kDpiFrameBufferCount]{};
3796
+ bool panelCirclePrevValid_[kDpiFrameBufferCount] = {};
3797
+ bool previousPresentValid_ = false;
3798
+ bool needsFullPhysicalFlush_ = true;
3799
+ };
3800
+
3801
+ } // namespace gea::platform::esp32_p4_m5stack_tab5::display
3802
+
3803
+ extern "C" std::uint16_t *gea_bg_cache(int *cap_px)
3804
+ {
3805
+ return gea::platform::esp32_p4_m5stack_tab5::display::DisplayBackend::instance().backgroundCache(cap_px);
3806
+ }
3807
+
3808
+ extern "C" std::uint16_t *gea_backdrop_cache(int *cap_px)
3809
+ {
3810
+ return gea::platform::esp32_p4_m5stack_tab5::display::DisplayBackend::instance().backdropCache(cap_px);
3811
+ }
3812
+
3813
+ namespace {
3814
+
3815
+ struct P4RenderWorker {
3816
+ TaskHandle_t task = nullptr;
3817
+ void (*volatile fn)(void *, int, int) = nullptr;
3818
+ void *volatile ctx = nullptr;
3819
+ volatile int y0 = 0;
3820
+ volatile int y1 = 0;
3821
+ std::atomic<std::uint32_t> jobSeq{0};
3822
+ std::atomic<bool> done{true};
3823
+ bool attempted = false;
3824
+ };
3825
+
3826
+ P4RenderWorker gRenderWorker;
3827
+ constexpr std::uint32_t kRenderWorkerStackBytes = 12288;
3828
+
3829
+ void renderWorkerTask(void *)
3830
+ {
3831
+ // MUST start at 0 (jobSeq's initial value), NOT jobSeq.load(): submit() creates
3832
+ // this task and increments jobSeq immediately after, so loading here usually
3833
+ // reads 1 and swallows job 1 (the caller times out and the first parallel band
3834
+ // is silently dropped). Same race fixed on the elecrow in d22bfc5f9.
3835
+ std::uint32_t seen = 0;
3836
+ std::int64_t idleSince = esp_timer_get_time();
3837
+ for (;;) {
3838
+ while (gRenderWorker.jobSeq.load(std::memory_order_acquire) == seen) {
3839
+ if (esp_timer_get_time() - idleSince > 4000) {
3840
+ ulTaskNotifyTake(pdTRUE, pdMS_TO_TICKS(100));
3841
+ idleSince = esp_timer_get_time();
3842
+ }
3843
+ }
3844
+ seen = gRenderWorker.jobSeq.load(std::memory_order_acquire);
3845
+ void (*fn)(void *, int, int) = gRenderWorker.fn;
3846
+ if (fn) fn(gRenderWorker.ctx, gRenderWorker.y0, gRenderWorker.y1);
3847
+ gRenderWorker.done.store(true, std::memory_order_release);
3848
+ idleSince = esp_timer_get_time();
3849
+ }
3850
+ }
3851
+
3852
+ } // namespace
3853
+
3854
+ extern "C" bool gea_render_parallel_submit(void (*fn)(void *, int, int), void *ctx, int y0, int y1)
3855
+ {
3856
+ if (!gRenderWorker.attempted) {
3857
+ gRenderWorker.attempted = true;
3858
+ const BaseType_t renderCore = xPortGetCoreID();
3859
+ const BaseType_t workerCore = (renderCore == 0) ? 1 : 0;
3860
+ const UBaseType_t priority = uxTaskPriorityGet(nullptr);
3861
+ const BaseType_t created = xTaskCreatePinnedToCore(renderWorkerTask,
3862
+ "gea_rwrk",
3863
+ kRenderWorkerStackBytes,
3864
+ nullptr,
3865
+ priority,
3866
+ &gRenderWorker.task,
3867
+ workerCore);
3868
+ if (created != pdPASS || !gRenderWorker.task) {
3869
+ multi_heap_info_t info{};
3870
+ heap_caps_get_info(&info, MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT);
3871
+ ESP_LOGE("m5stack_tab5_display",
3872
+ "render worker creation failed: create=%d stack=%u internal_free=%u internal_largest=%u",
3873
+ static_cast<int>(created),
3874
+ static_cast<unsigned>(kRenderWorkerStackBytes),
3875
+ static_cast<unsigned>(info.total_free_bytes),
3876
+ static_cast<unsigned>(info.largest_free_block));
3877
+ }
3878
+ }
3879
+ if (!gRenderWorker.task) return false;
3880
+ gea::platform::esp32_p4_m5stack_tab5::display::DisplayBackend::instance().setRenderCore(static_cast<int>(xPortGetCoreID()));
3881
+ gRenderWorker.fn = fn;
3882
+ gRenderWorker.ctx = ctx;
3883
+ gRenderWorker.y0 = y0;
3884
+ gRenderWorker.y1 = y1;
3885
+ gRenderWorker.done.store(false, std::memory_order_release);
3886
+ gRenderWorker.jobSeq.fetch_add(1, std::memory_order_release);
3887
+ xTaskNotifyGive(gRenderWorker.task);
3888
+ return true;
3889
+ }
3890
+
3891
+ extern "C" void gea_render_parallel_wait()
3892
+ {
3893
+ if (!gRenderWorker.task) return;
3894
+ const std::int64_t deadline = esp_timer_get_time() + 100000;
3895
+ while (!gRenderWorker.done.load(std::memory_order_acquire)) {
3896
+ if (esp_timer_get_time() > deadline) {
3897
+ ESP_LOGW("m5stack_tab5_display", "render worker wait timed out");
3898
+ break;
3899
+ }
3900
+ }
3901
+ }
3902
+
3903
+ extern "C" void gea_render_parallel_merge_dirty()
3904
+ {
3905
+ gea::platform::esp32_p4_m5stack_tab5::display::DisplayBackend::instance().absorbWorkerDirty();
3906
+ }
3907
+
3908
+ extern "C" int gea_current_render_core()
3909
+ {
3910
+ return static_cast<int>(xPortGetCoreID());
3911
+ }
3912
+
3913
+ namespace gea::platform::display {
3914
+
3915
+ namespace {
3916
+
3917
+ gea::framework::graphics::Canvas *drawingCanvas()
3918
+ {
3919
+ return gea::platform::esp32_p4_m5stack_tab5::display::DisplayBackend::instance().drawingCanvas();
3920
+ }
3921
+
3922
+ } // namespace
3923
+
3924
+ bool Display::init() { return gea::platform::esp32_p4_m5stack_tab5::display::DisplayBackend::instance().init(); }
3925
+ bool Display::start() { return gea::platform::esp32_p4_m5stack_tab5::display::DisplayBackend::instance().start(); }
3926
+ gea::framework::graphics::Canvas *Display::canvas() { return gea::platform::esp32_p4_m5stack_tab5::display::DisplayBackend::instance().canvas(); }
3927
+ bool Display::framebufferIsPanelDirect() { return gea::platform::esp32_p4_m5stack_tab5::display::DisplayBackend::instance().framebufferIsPanelDirect(); }
3928
+ bool Display::panelScanoutSurface(uint16_t **outBuffer, int *outW, int *outH) { return gea::platform::esp32_p4_m5stack_tab5::display::DisplayBackend::instance().panelScanoutSurface(outBuffer, outW, outH); }
3929
+ bool Display::panelDirectTarget(int logicalX, int logicalY, int logicalW, int logicalH,
3930
+ uint16_t **outBuf, int *outBufW, int *outBufH,
3931
+ int *outPanelX, int *outPanelY, int *outPanelW, int *outPanelH,
3932
+ int *outRotSteps, int *outFlip) {
3933
+ return gea::platform::esp32_p4_m5stack_tab5::display::DisplayBackend::instance().panelDirectTarget(
3934
+ logicalX, logicalY, logicalW, logicalH, outBuf, outBufW, outBufH, outPanelX, outPanelY, outPanelW, outPanelH, outRotSteps, outFlip);
3935
+ }
3936
+ void Display::flipPanelToBack() { gea::platform::esp32_p4_m5stack_tab5::display::DisplayBackend::instance().flipPanelToBack(); }
3937
+ void Display::flipPanelToBack(uint16_t *buffer) { gea::platform::esp32_p4_m5stack_tab5::display::DisplayBackend::instance().flipPanelToBack(buffer); }
3938
+ void Display::clear() { gea::platform::esp32_p4_m5stack_tab5::display::DisplayBackend::instance().clear(); }
3939
+ void Display::clearNoFlush() { gea::platform::esp32_p4_m5stack_tab5::display::DisplayBackend::instance().clearNoFlush(); }
3940
+ void Display::print(const char *) {}
3941
+ void Display::flush() { gea::platform::esp32_p4_m5stack_tab5::display::DisplayBackend::instance().flush(); }
3942
+ void Display::rebindCanvasToFramebuffer() { gea::platform::esp32_p4_m5stack_tab5::display::DisplayBackend::instance().rebindCanvasToFramebuffer(); }
3943
+ void Display::flushRects(const DisplayFlushRect *rects, int count, bool) { gea::platform::esp32_p4_m5stack_tab5::display::DisplayBackend::instance().flushRects(rects, count); }
3944
+ bool Display::streamRect(int x, int y, int w, int h, DisplayStreamRasterFn raster, void *user) { return gea::platform::esp32_p4_m5stack_tab5::display::DisplayBackend::instance().streamRect(x, y, w, h, raster, user); }
3945
+ bool Display::present(const DisplayPresentCommand *commands, int command_count) { return gea::platform::esp32_p4_m5stack_tab5::display::DisplayBackend::instance().presentCommands(commands, command_count); }
3946
+ void Display::presentPathDebug(int *calls, int *direct, int *general, int *rejected, int *tileShapeFailKind, int *tileShapeFailType, int *tileShapeFailCount)
3947
+ {
3948
+ gea::platform::esp32_p4_m5stack_tab5::display::DisplayBackend::instance().presentPathDebug(
3949
+ calls, direct, general, rejected, tileShapeFailKind, tileShapeFailType, tileShapeFailCount);
3950
+ }
3951
+ void Display::landFrameDebug(int *total, int *align, int *raster, int *text, int *flip)
3952
+ {
3953
+ gea::platform::esp32_p4_m5stack_tab5::display::DisplayBackend::instance().landFrameDebug(total, align, raster, text, flip);
3954
+ }
3955
+ void Display::landPanDebug(int *detect, int *kick, int *strips, int *wait, int *interior)
3956
+ {
3957
+ gea::platform::esp32_p4_m5stack_tab5::display::DisplayBackend::instance().landPanDebug(detect, kick, strips, wait, interior);
3958
+ }
3959
+ void Display::setFlushConfig(int chunk_rows, int queue_depth) { gea::platform::esp32_p4_m5stack_tab5::display::DisplayBackend::instance().setFlushConfig(chunk_rows, queue_depth); }
3960
+ void Display::reserveInternal(std::size_t) {}
3961
+ bool Display::setHighBrightnessMode(bool) { return false; }
3962
+ bool Display::highBrightnessMode() { return false; }
3963
+ void Display::applyPendingInternalReserve() {}
3964
+ int Display::flushChunkRows() { return gea::platform::esp32_p4_m5stack_tab5::display::DisplayBackend::instance().flushChunkRows(); }
3965
+ int Display::flushQueueDepth() { return gea::platform::esp32_p4_m5stack_tab5::display::DisplayBackend::instance().flushQueueDepth(); }
3966
+ int Display::flushBufferBytes() { return gea::platform::esp32_p4_m5stack_tab5::display::DisplayBackend::instance().flushBufferBytes(); }
3967
+ void Display::pushClip(int x, int y, int w, int h) { if (auto *c = drawingCanvas()) c->pushClip(x, y, w, h); }
3968
+ void Display::popClip() { if (auto *c = drawingCanvas()) c->popClip(); }
3969
+ void Display::resetClip() { if (auto *c = drawingCanvas()) c->resetClip(); }
3970
+ void Display::setAlpha(std::uint8_t alpha) { if (auto *c = drawingCanvas()) c->setGlobalAlpha(alpha); }
3971
+ std::uint8_t Display::alpha() { return drawingCanvas() ? drawingCanvas()->globalAlpha() : 255; }
3972
+ int Display::brightness() { return gea::platform::esp32_p4_m5stack_tab5::display::DisplayBackend::instance().brightness(); }
3973
+ void Display::setBrightness(int brightness_percent) { gea::platform::esp32_p4_m5stack_tab5::display::DisplayBackend::instance().setBrightness(brightness_percent); }
3974
+ // Tearing sync (TE/VBlank): not implemented on this target.
3975
+ void Display::setVSync(bool) {}
3976
+ void Display::invalidate() {}
3977
+ bool Display::vsyncEnabled() { return false; }
3978
+ void Display::vsyncWaitForFrame() {}
3979
+ void Display::clip(int *x0, int *y0, int *x1, int *y1)
3980
+ {
3981
+ if (auto *c = drawingCanvas()) c->currentClip(x0, y0, x1, y1);
3982
+ }
3983
+ void Display::fillRect(int x, int y, int w, int h, std::uint16_t color) { if (auto *c = drawingCanvas()) c->fillRect(x, y, w, h, color); }
3984
+ void Display::scrollRect(int x, int y, int w, int h, int dx, int dy) { if (auto *c = drawingCanvas()) c->scrollRect(x, y, w, h, dx, dy); }
3985
+ void Display::resetScrollRegion() {}
3986
+ void Display::strokeRect(int x, int y, int w, int h, std::uint16_t color) { if (auto *c = drawingCanvas()) c->strokeRect(x, y, w, h, color); }
3987
+ void Display::fillCircle(int cx, int cy, int r, std::uint16_t color) { if (auto *c = drawingCanvas()) c->fillCircle(cx, cy, r, color); }
3988
+ void Display::strokeCircle(int cx, int cy, int r, std::uint16_t color) { if (auto *c = drawingCanvas()) c->strokeCircle(cx, cy, r, color); }
3989
+ void Display::drawLine(int x0, int y0, int x1, int y1, std::uint16_t color) { if (auto *c = drawingCanvas()) c->drawLine(x0, y0, x1, y1, color); }
3990
+ void Display::drawArc(int cx, int cy, int r, int start_deg, int end_deg, std::uint16_t color) { if (auto *c = drawingCanvas()) c->drawArc(cx, cy, r, start_deg, end_deg, color); }
3991
+ void Display::fillTriangle(int x0, int y0, int x1, int y1, int x2, int y2, std::uint16_t color) { if (auto *c = drawingCanvas()) c->fillTriangle(x0, y0, x1, y1, x2, y2, color); }
3992
+ void Display::drawText(const char *text, int x, int y, std::uint16_t color, float scale) { if (auto *c = drawingCanvas()) c->drawText(text, x, y, color, scale); }
3993
+ void Display::drawTextFont(const char *text, int x, int y, std::uint16_t color, int font_id) { if (auto *c = drawingCanvas()) c->drawTextFont(text, x, y, color, font_id); }
3994
+ void Display::drawTextFontFamily(const char *text, int x, int y, std::uint16_t color, int family_id, int size_px) { if (auto *c = drawingCanvas()) c->drawTextFontFamily(text, x, y, color, family_id, size_px); }
3995
+ void Display::setPixel(int x, int y, std::uint16_t color) { if (auto *c = drawingCanvas()) c->fillRect(x, y, 1, 1, color); }
3996
+ void Display::fillRoundedRect(int x, int y, int w, int h, int tl, int tr, int br, int bl, std::uint16_t color) { if (auto *c = drawingCanvas()) c->fillRoundedRect(x, y, w, h, tl, tr, br, bl, color); }
3997
+ void Display::fillRoundedRectBoxesRgb565(const std::int16_t *xs, const std::int16_t *ys, int count, int w, int h, int tl, int tr, int br, int bl, const std::uint16_t *colors) { if (auto *c = drawingCanvas()) c->fillRoundedRectBoxesRgb565(xs, ys, count, w, h, tl, tr, br, bl, colors); }
3998
+ void Display::strokeRoundedRect(int x, int y, int w, int h, int tl, int tr, int br, int bl, int lw, std::uint16_t color) { if (auto *c = drawingCanvas()) c->strokeRoundedRect(x, y, w, h, tl, tr, br, bl, lw, color); }
3999
+ void Display::blitImage(const gea::framework::graphics::pixel::native_t *src, const std::uint8_t *alpha, int src_w, int src_h, int dx, int dy) { if (auto *c = drawingCanvas()) c->drawImage(src, alpha, src_w, src_h, dx, dy); }
4000
+ void Display::blitImageScaled(const gea::framework::graphics::pixel::native_t *src, const std::uint8_t *alpha, int src_w, int src_h, int dx, int dy, int dst_w, int dst_h) { if (auto *c = drawingCanvas()) c->drawImage(src, alpha, src_w, src_h, dx, dy, dst_w, dst_h); }
4001
+ void Display::setWorldOverlay(const std::uint16_t *, int, int, int, int) {}
4002
+ void Display::setWorldScroll(int) {}
4003
+ void Display::flushStatsRead(std::int64_t *total_us, int *call_count, int *pixel_count)
4004
+ {
4005
+ const auto stats = gea::platform::esp32_p4_m5stack_tab5::display::DisplayBackend::instance().flushStats();
4006
+ if (total_us) *total_us = stats.totalUs;
4007
+ if (call_count) *call_count = stats.callCount;
4008
+ if (pixel_count) *pixel_count = stats.pixelCount;
4009
+ }
4010
+ DisplayFlushPerfStats Display::flushPerfStatsRead() { return gea::platform::esp32_p4_m5stack_tab5::display::DisplayBackend::instance().flushStats(); }
4011
+ void Display::flushStatsReset() { gea::platform::esp32_p4_m5stack_tab5::display::DisplayBackend::instance().flushStatsReset(); }
4012
+ const char *Display::flushStageName() { return gea::platform::esp32_p4_m5stack_tab5::display::DisplayBackend::instance().flushStageName(); }
4013
+ int Display::flushStageChunk() { return gea::platform::esp32_p4_m5stack_tab5::display::DisplayBackend::instance().flushStageChunk(); }
4014
+ DisplayFlushStageDetail Display::flushStageDetail() { return gea::platform::esp32_p4_m5stack_tab5::display::DisplayBackend::instance().flushStageDetail(); }
4015
+ bool Display::copySnapshotRgb565(std::uint16_t *dst, int pixel_capacity, int *width, int *height, bool) { return gea::platform::esp32_p4_m5stack_tab5::display::DisplayBackend::instance().copySnapshotRgb565(dst, pixel_capacity, width, height); }
4016
+ int Display::countNonBlackPixels(bool) { return gea::platform::esp32_p4_m5stack_tab5::display::DisplayBackend::instance().countNonBlackPixels(); }
4017
+
4018
+ extern "C" bool geaDisplaySnapshotPrefersPresented()
4019
+ {
4020
+ return gea::platform::esp32_p4_m5stack_tab5::display::DisplayBackend::instance().snapshotPrefersPresented();
4021
+ }
4022
+
4023
+ void applyOrientation(gea::framework::display::DisplayOrientation)
4024
+ {
4025
+ gea::platform::esp32_p4_m5stack_tab5::display::DisplayBackend::instance().applyOrientation();
4026
+ }
4027
+
4028
+ bool autoRotateAllowed()
4029
+ {
4030
+ return false;
4031
+ }
4032
+
4033
+ } // namespace gea::platform::display