@geastack/gea3d 0.1.0 → 0.1.2

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.
@@ -16,6 +16,7 @@
16
16
  #include "pixel.h"
17
17
 
18
18
  #include <algorithm>
19
+ #include <atomic>
19
20
  #include <climits>
20
21
  #include <cmath>
21
22
  #include <cstring>
@@ -37,6 +38,9 @@
37
38
  #include "freertos/FreeRTOS.h"
38
39
  #include "freertos/semphr.h"
39
40
  #include "freertos/task.h"
41
+ #include "esp_memory_utils.h"
42
+ #include "esp_heap_caps.h"
43
+ #include "freertos/idf_additions.h"
40
44
  #define GEA3D_ASYNC_PRESENT 1
41
45
  #else
42
46
  #define GEA3D_ASYNC_PRESENT 0
@@ -406,6 +410,21 @@ struct Renderer {
406
410
  };
407
411
 
408
412
  Renderer g_renderer;
413
+ // Bumped each time a frame slot is rebuilt; keys the per-frame strip lists.
414
+ std::uint32_t g_frameSerial[2] = {0, 0};
415
+ // Per frame slot, a content hash of each kBandHashRows-row band: what its
416
+ // primitives draw there, in draw order. A composited frame marks dirty only
417
+ // the bands that differ from the frame on screen.
418
+ // The band height is the painter's strip height when it stages strips
419
+ // (g_stripRowsHint), so dirty runs start where strips do and every strip
420
+ // reads one prebuilt band list; 8 rows until it is known.
421
+ constexpr int kBandHashRows = 8;
422
+ std::atomic<int> g_stripRowsHint{0};
423
+ int g_bandHashRows[2] = {kBandHashRows, kBandHashRows};
424
+ int g_shownBandHashRows = kBandHashRows;
425
+ std::vector<std::uint64_t> g_bandHash[2];
426
+ std::vector<std::uint64_t> g_shownBandHash;
427
+ bool g_shownBandHashValid = false;
409
428
 
410
429
  // Fast memory for the raster. On the STM32F7 the heap and framebuffers are
411
430
  // SDRAM (framebuffers write-through), so two band buffers fill the zero-wait
@@ -482,8 +501,13 @@ RayHit g_rayHit;
482
501
 
483
502
  // ---------------------------------------------------------------- helpers
484
503
 
504
+ #if GEA3D_XTENSA_FPU
505
+ // No float max on Xtensa: the builtin is an fmaxf call.
506
+ GEA3D_INLINE float maxFloat(float a, float b) { return a > b || b != b ? a : b; }
507
+ #else
485
508
  // VMAXNM on FPv5: no float compare stalls the pipeline.
486
509
  GEA3D_INLINE float maxFloat(float a, float b) { return __builtin_fmaxf(a, b); }
510
+ #endif
487
511
 
488
512
  // 0..255 by truncation; clamped in integer registers (USAT), not with float
489
513
  // compares.
@@ -610,7 +634,7 @@ GEA3D_INLINE float fogFactor(float distance)
610
634
  const Environment &env = g_renderer.environment;
611
635
  if (env.fog == 1) {
612
636
  if (env.fogFar <= env.fogNear) return 1.0f;
613
- return clampFloat((env.fogFar - distance) / (env.fogFar - env.fogNear), 0.0f, 1.0f);
637
+ return clampFloat((env.fogFar - distance) * raster::detail::reciprocal(env.fogFar - env.fogNear), 0.0f, 1.0f);
614
638
  }
615
639
  if (env.fog == 2) {
616
640
  const float d = env.fogDensity * distance;
@@ -644,14 +668,14 @@ GEA3D_INLINE void project(const View &v, float x, float y, float z, std::int32_t
644
668
  const float cy = p[1] * x + p[5] * y + p[9] * z + p[13];
645
669
  float cw = p[3] * x + p[7] * y + p[11] * z + p[15];
646
670
  if (cw < 0.000001f && cw > -0.000001f) cw = 0.000001f;
647
- const float invW = 1.0f / cw;
671
+ const float invW = raster::detail::reciprocal(cw);
648
672
  const float fx = clampFloat((cx * invW + 1.0f) * v.halfW, -kCoordLimit, kCoordLimit);
649
673
  const float fy = clampFloat((1.0f - cy * invW) * v.halfH, -kCoordLimit, kCoordLimit);
650
674
  *sx = roundToInt(fx * 16.0f);
651
675
  *sy = roundToInt(fy * 16.0f);
652
676
  if (v.orthographic) {
653
677
  const float range = v.far - v.near;
654
- *depth = range > 0.0f ? clampFloat(1.0f - (-z - v.near) / range, 0.0f, 1.0f) : 1.0f;
678
+ *depth = range > 0.0f ? clampFloat(1.0f - (-z - v.near) * raster::detail::reciprocal(range), 0.0f, 1.0f) : 1.0f;
655
679
  } else {
656
680
  *depth = clampFloat(v.near * invW, 0.0f, 1.0f);
657
681
  }
@@ -1390,6 +1414,7 @@ void sortFrame()
1390
1414
  Renderer &r = g_renderer;
1391
1415
  raster::Frame &frame = r.frame();
1392
1416
  const int n = frame.count;
1417
+ for (int i = 0; i < n; i++) raster::prepareTriangle(frame.prims[i]);
1393
1418
  frame.order.resize(static_cast<std::size_t>(n));
1394
1419
  r.keys.resize(static_cast<std::size_t>(n));
1395
1420
  r.bucketStarts.assign(2 * (kDepthBuckets + 1), 0);
@@ -1548,6 +1573,24 @@ void rasterizeInto(const raster::Frame &frame, Pixel *base, int stride, int x0,
1548
1573
 
1549
1574
  Bands &bands = g_renderer.bands;
1550
1575
  const int width = x1 - x0 + 1;
1576
+ #if GEA3D_ASYNC_PRESENT && !defined(GEA3D_BAND_ROWS)
1577
+ // A target in PSRAM (the ESP32-P4's swapped scanout buffers) takes the
1578
+ // raster in bands of internal RAM, painter's order, each copied out in one
1579
+ // sequential pass: coverage mode straight into PSRAM cost the CrowPanel 5.0
1580
+ // ~65 ms of a Lantern frame, the same figure painter's order in fast
1581
+ // memory cut to ~20 ms on the 7.0.
1582
+ if (width > bands.width && !esp_ptr_internal(base + static_cast<std::ptrdiff_t>(y0) * stride + x0)) {
1583
+ constexpr int kEspBandRows = 32;
1584
+ const int bandWidth = std::max(width, frame.width);
1585
+ Pixel *pixels = static_cast<Pixel *>(heap_caps_aligned_alloc(16, static_cast<std::size_t>(bandWidth) * kEspBandRows * sizeof(Pixel), MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT));
1586
+ if (pixels) {
1587
+ if (bands.pixels) heap_caps_free(bands.pixels);
1588
+ bands.pixels = pixels;
1589
+ bands.width = bandWidth;
1590
+ bands.rows = kEspBandRows;
1591
+ }
1592
+ }
1593
+ #endif
1551
1594
  if (!bands.pixels || width > bands.width) {
1552
1595
  raster::Rasterizer rasterizer(frame, g_renderer.scratch, base, stride, x0, y0, x1, y1);
1553
1596
  rasterizer.run();
@@ -1589,6 +1632,92 @@ void rasterizeInto(const raster::Frame &frame, Pixel *base, int stride, int x0,
1589
1632
  #endif
1590
1633
  }
1591
1634
 
1635
+ #if GEA3D_ASYNC_PRESENT
1636
+ // A target in internal RAM (the display's staged strip) takes painter's order
1637
+ // straight into it: the background, then the region's primitives back to
1638
+ // front. Coverage mode suits slow target memory only; in fast memory its
1639
+ // per-pixel coverage bits, and the depth scratch it zeroes for every region
1640
+ // once anything blends, cost more than the overdraw they save (Neon Drift on
1641
+ // the CrowPanel 7.0: 66 -> 19.5 ms of raster a frame).
1642
+ // The UI paints the underlay in strips of one height, top to bottom, every
1643
+ // frame: each strip's primitives come from bands of that height built once
1644
+ // per frame, not from a scan of every primitive per strip.
1645
+ struct StripLists {
1646
+ const raster::Frame *frame = nullptr;
1647
+ std::uint32_t serial = 0;
1648
+ int rows = 0;
1649
+ Bands bands;
1650
+ };
1651
+ // One per frame slot: the build core fills the building frame's lists for
1652
+ // the strip height the painter last used (g_stripRowsHint), so the painter
1653
+ // core no longer spends ~0.75 ms a frame on them.
1654
+ StripLists g_stripLists[2];
1655
+ void prebuildStripLists(const raster::Frame &frame, int slot)
1656
+ {
1657
+ const int rows = g_stripRowsHint.load(std::memory_order_relaxed);
1658
+ if (rows <= 0 || slot < 0 || slot > 1) return;
1659
+ StripLists &cache = g_stripLists[slot];
1660
+ cache.bands.rows = rows;
1661
+ buildBandLists(frame, 0, frame.height - 1, cache.bands);
1662
+ cache.frame = &frame;
1663
+ cache.serial = g_frameSerial[slot];
1664
+ cache.rows = rows;
1665
+ }
1666
+
1667
+ bool rasterizePainterInPlace(const raster::Frame &frame, Pixel *base, int stride, int x0, int y0, int x1, int y1)
1668
+ {
1669
+ if (!esp_ptr_internal(base + static_cast<std::ptrdiff_t>(y0) * stride + x0)) return false;
1670
+ x1 = std::min(x1, frame.width - 1);
1671
+ y1 = std::min(y1, frame.height - 1);
1672
+ if (x0 > x1 || y0 > y1) return true;
1673
+
1674
+ const int rows = y1 - y0 + 1;
1675
+ // The tallest full-width strip is the staging height (a run's first and
1676
+ // last strips can be shorter; narrower boxes stage taller strips): the
1677
+ // next builds hash bands and prebuild lists at it.
1678
+ if (x0 == 0 && x1 == frame.width - 1 && rows > g_stripRowsHint.load(std::memory_order_relaxed)) g_stripRowsHint.store(rows, std::memory_order_relaxed);
1679
+ const std::ptrdiff_t slot = &frame - g_renderer.frames;
1680
+ raster::BandList list{nullptr, 0, 0};
1681
+ bool listed = false;
1682
+ if (slot >= 0 && slot < 2) {
1683
+ StripLists &cache = g_stripLists[slot];
1684
+ const std::uint32_t serial = g_frameSerial[slot];
1685
+ bool fresh = cache.frame == &frame && cache.serial == serial && cache.rows > 0;
1686
+ if (!fresh && y0 % rows == 0) {
1687
+ cache.bands.rows = rows;
1688
+ buildBandLists(frame, 0, frame.height - 1, cache.bands);
1689
+ cache.frame = &frame;
1690
+ cache.serial = serial;
1691
+ cache.rows = rows;
1692
+ fresh = true;
1693
+ }
1694
+ // Any strip inside one band reads that band's list (the build core
1695
+ // made it, at the staging height); the extra primitives clip away. A
1696
+ // strip across two bands (a UI dirty box moved its start) scans.
1697
+ if (fresh && y0 / cache.rows == y1 / cache.rows) {
1698
+ list = bandList(cache.bands, y0 / cache.rows);
1699
+ listed = true;
1700
+ }
1701
+ }
1702
+ if (!listed) {
1703
+ std::vector<std::int32_t> &items = g_renderer.bands.items;
1704
+ items.clear();
1705
+ int opaque = 0;
1706
+ for (int i = 0; i < frame.count; i++) {
1707
+ const int first = static_cast<std::int16_t>(frame.rows[i] & 0xFFFFu);
1708
+ const int last = static_cast<std::int16_t>(frame.rows[i] >> 16);
1709
+ if (last < y0 || first > y1) continue;
1710
+ items.push_back(frame.order[static_cast<std::size_t>(i)]);
1711
+ opaque += i < frame.opaqueCount;
1712
+ }
1713
+ list = raster::BandList{items.data(), static_cast<int>(items.size()), opaque};
1714
+ }
1715
+ raster::Rasterizer rasterizer(frame, g_renderer.scratch, base, stride, x0, y0, x1, y1, raster::Occlusion::kPainter);
1716
+ rasterizer.runPainter(list);
1717
+ return true;
1718
+ }
1719
+ #endif
1720
+
1592
1721
  // Display::flushRectsRasterized chunk: pixels hold rows [oy, oy + h) of a
1593
1722
  // full-width band, so the chunk width is its stride.
1594
1723
  void rasterChunk(Pixel *pixels, int width, int height, int ox, int oy, void *user)
@@ -1672,18 +1801,78 @@ void paintUnderlay(int x0, int y0, int x1, int y1, void *user)
1672
1801
  if (x0 > x1 || y0 > y1) return;
1673
1802
 
1674
1803
  const int stride = canvas->strideBytes() / static_cast<int>(sizeof(Pixel));
1804
+ #if GEA3D_ASYNC_PRESENT
1805
+ if (rasterizePainterInPlace(*static_cast<const raster::Frame *>(user), canvas->pixels(), stride, x0, y0, x1, y1)) return;
1806
+ #endif
1675
1807
  rasterizeInto(*static_cast<const raster::Frame *>(user), canvas->pixels(), stride, x0, y0, x1, y1);
1676
1808
  }
1677
1809
 
1678
- bool presentUnderlay(raster::Frame &frame)
1679
- {
1680
- if (!gea::framework::display::Underlay::composited()) return false;
1681
-
1682
- auto *canvas = pd::Display::canvas();
1683
- if (!canvas || frame.width <= 0 || frame.height <= 0) return false;
1810
+ // The display's draw canvas for state only (the dirty box), where the target
1811
+ // splits it from pixel access. A double-buffered panel readies its back buffer
1812
+ // the first time Display::canvas() is asked for, copying every stale pixel in
1813
+ // from the front; asked here, before the UI's refresh can say it repaints the
1814
+ // whole frame, that was a full-screen PSRAM copy every frame.
1815
+ extern "C" gea::framework::graphics::Canvas *gea_display_state_canvas() __attribute__((weak));
1816
+
1817
+ // `hash` is the frame's band hashes, or null when it has none: then every
1818
+ // row is dirty. Rows whose bands match the frame on screen stay as they are,
1819
+ // so the UI repaints, recomposites and copies out only what moved.
1820
+ bool presentUnderlay(raster::Frame &frame, const std::vector<std::uint64_t> *hash = nullptr)
1821
+ {
1822
+ if (!gea::framework::display::Underlay::composited()) {
1823
+ g_shownBandHashValid = false;
1824
+ return false;
1825
+ }
1826
+
1827
+ auto *canvas = gea_display_state_canvas ? gea_display_state_canvas() : nullptr;
1828
+ if (!canvas) canvas = pd::Display::canvas();
1829
+ if (!canvas || frame.width <= 0 || frame.height <= 0) {
1830
+ g_shownBandHashValid = false;
1831
+ return false;
1832
+ }
1833
+
1834
+ // Changed bands as row runs; unchanged bands between them stay clean, so
1835
+ // a frame whose motion sits in a few separate bands repaints only those.
1836
+ constexpr int kMaxRuns = 8;
1837
+ int runFirst[kMaxRuns];
1838
+ int runLast[kMaxRuns];
1839
+ int runs = 0;
1840
+ const int hashRows = hash ? g_bandHashRows[hash == &g_bandHash[1] ? 1 : 0] : kBandHashRows;
1841
+ if (hash && g_shownBandHashValid && g_shownBandHashRows == hashRows && g_shownBandHash.size() == hash->size() && gea::framework::display::Underlay::active()) {
1842
+ const int bands = static_cast<int>(hash->size());
1843
+ for (int b = 0; b < bands; b++) {
1844
+ if ((*hash)[b] == g_shownBandHash[b]) continue;
1845
+ if (runs > 0 && runLast[runs - 1] == b - 1) {
1846
+ runLast[runs - 1] = b;
1847
+ } else if (runs < kMaxRuns) {
1848
+ runFirst[runs] = runLast[runs] = b;
1849
+ runs++;
1850
+ } else {
1851
+ runLast[runs - 1] = b; // out of runs: extend the last one
1852
+ }
1853
+ }
1854
+ for (int k = 0; k < runs; k++) {
1855
+ runFirst[k] *= hashRows;
1856
+ runLast[k] = std::min(frame.height - 1, (runLast[k] + 1) * hashRows - 1);
1857
+ }
1858
+ } else {
1859
+ runFirst[0] = 0;
1860
+ runLast[0] = frame.height - 1;
1861
+ runs = 1;
1862
+ }
1863
+ if (hash) {
1864
+ g_shownBandHash = *hash;
1865
+ g_shownBandHashRows = hashRows;
1866
+ g_shownBandHashValid = true;
1867
+ } else {
1868
+ g_shownBandHashValid = false;
1869
+ }
1684
1870
 
1685
1871
  gea::framework::display::Underlay::set(paintUnderlay, &frame, 0, 0, frame.width - 1, frame.height - 1);
1686
- canvas->markDirty(0, 0, frame.width - 1, frame.height - 1);
1872
+ // A background colour fills the frame before any triangle: every pixel of
1873
+ // it is written, so the UI's refresh need not restore what was there.
1874
+ gea::framework::display::Underlay::setOpaque(frame.background.mode != raster::kBackgroundNone);
1875
+ for (int k = 0; k < runs; k++) canvas->markDirty(0, runFirst[k], frame.width - 1, runLast[k]);
1687
1876
  return true;
1688
1877
  }
1689
1878
  #endif
@@ -1739,7 +1928,8 @@ void waitForPresent() {}
1739
1928
  #endif
1740
1929
 
1741
1930
  // Hands the built frame to its destination. Returns false when rejected.
1742
- bool present()
1931
+ // `hash`: the frame's band hashes, when it has them (drawScene builds).
1932
+ bool present(const std::vector<std::uint64_t> *hash = nullptr)
1743
1933
  {
1744
1934
  Renderer &r = g_renderer;
1745
1935
  raster::Frame &frame = r.frame();
@@ -1754,7 +1944,7 @@ bool present()
1754
1944
  #else
1755
1945
  #if GEA3D_UNDERLAY
1756
1946
  waitForPresent();
1757
- if (presentUnderlay(frame)) {
1947
+ if (presentUnderlay(frame, hash)) {
1758
1948
  r.stats.composited = 1;
1759
1949
  return true;
1760
1950
  }
@@ -1787,23 +1977,107 @@ void setBackground(raster::Background &background, double bgColor)
1787
1977
  std::memcpy(background.bottom, background.top, sizeof(background.top));
1788
1978
  }
1789
1979
 
1980
+
1981
+ #if GEA3D_ASYNC_PRESENT && GEA3D_UNDERLAY && !GEA3D_PRESENT_COMMANDS
1982
+ // Frame build on the other core. drawScene presents the frame built during
1983
+ // the previous call and hands this call's build to a task pinned beside the
1984
+ // display's row worker, below it in priority: the build (world matrices,
1985
+ // transform, clip, sort) overlaps the UI's strip loop instead of preceding it,
1986
+ // for one frame of latency. The build reads nodes, buffers, geometries and
1987
+ // materials and writes world matrices, so every other entry point waits for
1988
+ // it first; the painter reads only the shown frame, the band lists and the
1989
+ // raster scratch, none of which the build touches.
1990
+ #define GEA3D_ASYNC_BUILD 1
1991
+ extern "C" void gea_render_worker_block_when_idle(bool on) __attribute__((weak));
1992
+
1993
+ struct BuildJob {
1994
+ int scene = -1;
1995
+ int camera = -1;
1996
+ int width = 0;
1997
+ int height = 0;
1998
+ };
1999
+
2000
+ TaskHandle_t g_buildTask = nullptr;
2001
+ SemaphoreHandle_t g_buildWork = nullptr;
2002
+ SemaphoreHandle_t g_buildDone = nullptr;
2003
+ BuildJob g_buildJob;
2004
+ bool g_buildInFlight = false;
2005
+ // The presented frame's stats while the next build overwrites the live ones.
2006
+ Stats g_shownStats;
2007
+ bool g_buildFailed = false;
2008
+ // The slot holding a finished frame not yet presented, or -1.
2009
+ int g_readyFrame = -1;
2010
+
2011
+ void buildFrame(int scene, int camera, int width, int height);
2012
+
2013
+ void buildTaskMain(void *)
2014
+ {
2015
+ for (;;) {
2016
+ xSemaphoreTake(g_buildWork, portMAX_DELAY);
2017
+ buildFrame(g_buildJob.scene, g_buildJob.camera, g_buildJob.width, g_buildJob.height);
2018
+ g_renderer.stats.composited = 1;
2019
+ xSemaphoreGive(g_buildDone);
2020
+ }
2021
+ }
2022
+
2023
+ bool ensureBuildTask()
2024
+ {
2025
+ if (g_buildTask) return true;
2026
+ if (g_buildFailed) return false;
2027
+ g_buildFailed = true;
2028
+ g_buildWork = xSemaphoreCreateBinary();
2029
+ g_buildDone = xSemaphoreCreateBinary();
2030
+ if (!g_buildWork || !g_buildDone) return false;
2031
+ const BaseType_t core = xPortGetCoreID() == 0 ? 1 : 0;
2032
+ const UBaseType_t own = uxTaskPriorityGet(nullptr);
2033
+ const UBaseType_t priority = own > 1 ? own - 1 : 1;
2034
+ BaseType_t ok = xTaskCreatePinnedToCore(buildTaskMain, "gea3d_build", 8192, nullptr, priority, &g_buildTask, core);
2035
+ if (ok != pdPASS || !g_buildTask) {
2036
+ g_buildTask = nullptr;
2037
+ ok = xTaskCreatePinnedToCoreWithCaps(buildTaskMain, "gea3d_build", 8192, nullptr, priority, &g_buildTask, core, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
2038
+ }
2039
+ if (ok != pdPASS || !g_buildTask) {
2040
+ g_buildTask = nullptr;
2041
+ return false;
2042
+ }
2043
+ if (gea_render_worker_block_when_idle) gea_render_worker_block_when_idle(true);
2044
+ g_buildFailed = false;
2045
+ return true;
2046
+ }
2047
+
2048
+ void waitBuild()
2049
+ {
2050
+ if (!g_buildInFlight) return;
2051
+ xSemaphoreTake(g_buildDone, portMAX_DELAY);
2052
+ g_buildInFlight = false;
2053
+ }
2054
+
2055
+ #define GEA3D_SYNC_BUILD() waitBuild()
2056
+ #else
2057
+ #define GEA3D_ASYNC_BUILD 0
2058
+ #define GEA3D_SYNC_BUILD() ((void)0)
2059
+ #endif
2060
+
1790
2061
  } // namespace
1791
2062
 
1792
2063
  // ================================================================ buffers
1793
2064
 
1794
2065
  double createBuffer()
1795
2066
  {
2067
+ GEA3D_SYNC_BUILD();
1796
2068
  return allocate(g_buffers);
1797
2069
  }
1798
2070
 
1799
2071
  void deleteBuffer(double buffer)
1800
2072
  {
2073
+ GEA3D_SYNC_BUILD();
1801
2074
  Buffer *slot = lookup(g_buffers, buffer);
1802
2075
  if (slot) *slot = Buffer();
1803
2076
  }
1804
2077
 
1805
2078
  void bufferDataF32Raw(double buffer, const float *data, std::size_t count)
1806
2079
  {
2080
+ GEA3D_SYNC_BUILD();
1807
2081
  Buffer *slot = lookup(g_buffers, buffer);
1808
2082
  if (!slot) return;
1809
2083
  slot->f32.assign(data, data + count);
@@ -1812,6 +2086,7 @@ void bufferDataF32Raw(double buffer, const float *data, std::size_t count)
1812
2086
 
1813
2087
  void bufferDataU32Raw(double buffer, const std::uint32_t *data, std::size_t count)
1814
2088
  {
2089
+ GEA3D_SYNC_BUILD();
1815
2090
  Buffer *slot = lookup(g_buffers, buffer);
1816
2091
  if (!slot) return;
1817
2092
  slot->u32.assign(data, data + count);
@@ -1822,17 +2097,20 @@ void bufferDataU32Raw(double buffer, const std::uint32_t *data, std::size_t coun
1822
2097
 
1823
2098
  double createGeometry()
1824
2099
  {
2100
+ GEA3D_SYNC_BUILD();
1825
2101
  return allocate(g_geometries);
1826
2102
  }
1827
2103
 
1828
2104
  void deleteGeometry(double geometry)
1829
2105
  {
2106
+ GEA3D_SYNC_BUILD();
1830
2107
  Geometry *slot = lookup(g_geometries, geometry);
1831
2108
  if (slot) *slot = Geometry();
1832
2109
  }
1833
2110
 
1834
2111
  void geometryBuffers(double geometry, double position, double index, double color, double normal)
1835
2112
  {
2113
+ GEA3D_SYNC_BUILD();
1836
2114
  Geometry *slot = lookup(g_geometries, geometry);
1837
2115
  if (!slot) return;
1838
2116
  slot->position = static_cast<int>(position);
@@ -1844,17 +2122,20 @@ void geometryBuffers(double geometry, double position, double index, double colo
1844
2122
 
1845
2123
  double createMaterial()
1846
2124
  {
2125
+ GEA3D_SYNC_BUILD();
1847
2126
  return allocate(g_materials);
1848
2127
  }
1849
2128
 
1850
2129
  void deleteMaterial(double material)
1851
2130
  {
2131
+ GEA3D_SYNC_BUILD();
1852
2132
  Material *slot = lookup(g_materials, material);
1853
2133
  if (slot) *slot = Material();
1854
2134
  }
1855
2135
 
1856
2136
  void materialSet(double material, double shade, double r, double g, double b, double opacity, double side, double flags, double size)
1857
2137
  {
2138
+ GEA3D_SYNC_BUILD();
1858
2139
  Material *slot = lookup(g_materials, material);
1859
2140
  if (!slot) return;
1860
2141
  slot->shade = static_cast<int>(shade);
@@ -1870,6 +2151,7 @@ void materialSet(double material, double shade, double r, double g, double b, do
1870
2151
 
1871
2152
  double createNode(double kind)
1872
2153
  {
2154
+ GEA3D_SYNC_BUILD();
1873
2155
  const int id = allocate(g_nodes);
1874
2156
  g_nodes[static_cast<std::size_t>(id)].kind = static_cast<int>(kind);
1875
2157
  return id;
@@ -1877,6 +2159,7 @@ double createNode(double kind)
1877
2159
 
1878
2160
  void deleteNode(double node)
1879
2161
  {
2162
+ GEA3D_SYNC_BUILD();
1880
2163
  Node *slot = lookup(g_nodes, node);
1881
2164
  if (!slot) return;
1882
2165
 
@@ -1888,6 +2171,7 @@ void deleteNode(double node)
1888
2171
 
1889
2172
  void nodeParent(double node, double parent)
1890
2173
  {
2174
+ GEA3D_SYNC_BUILD();
1891
2175
  if (!lookup(g_nodes, node)) return;
1892
2176
 
1893
2177
  const int id = static_cast<int>(node);
@@ -1901,6 +2185,7 @@ void nodeParent(double node, double parent)
1901
2185
 
1902
2186
  void nodeTransform(double node, double px, double py, double pz, double qx, double qy, double qz, double qw, double sx, double sy, double sz)
1903
2187
  {
2188
+ GEA3D_SYNC_BUILD();
1904
2189
  Node *slot = lookup(g_nodes, node);
1905
2190
  if (!slot) return;
1906
2191
  const float position[3] = {static_cast<float>(px), static_cast<float>(py), static_cast<float>(pz)};
@@ -1920,6 +2205,7 @@ void nodeTransform(double node, double px, double py, double pz, double qx, doub
1920
2205
 
1921
2206
  void nodeMatrixRaw(double node, const float *elements, std::size_t count)
1922
2207
  {
2208
+ GEA3D_SYNC_BUILD();
1923
2209
  Node *slot = lookup(g_nodes, node);
1924
2210
  if (!slot || count < 16) return;
1925
2211
  // An unchanged matrix keeps the cached world matrices.
@@ -1932,6 +2218,7 @@ void nodeMatrixRaw(double node, const float *elements, std::size_t count)
1932
2218
 
1933
2219
  void nodeFlags(double node, double visible, double frustumCulled, double renderOrder)
1934
2220
  {
2221
+ GEA3D_SYNC_BUILD();
1935
2222
  Node *slot = lookup(g_nodes, node);
1936
2223
  if (!slot) return;
1937
2224
  slot->visible = visible != 0;
@@ -1941,6 +2228,7 @@ void nodeFlags(double node, double visible, double frustumCulled, double renderO
1941
2228
 
1942
2229
  void nodeGeometry(double node, double geometry, double material)
1943
2230
  {
2231
+ GEA3D_SYNC_BUILD();
1944
2232
  Node *slot = lookup(g_nodes, node);
1945
2233
  if (!slot) return;
1946
2234
  slot->geometry = static_cast<int>(geometry);
@@ -1949,6 +2237,7 @@ void nodeGeometry(double node, double geometry, double material)
1949
2237
 
1950
2238
  void nodeInstances(double node, double matrices, double colors, double count)
1951
2239
  {
2240
+ GEA3D_SYNC_BUILD();
1952
2241
  Node *slot = lookup(g_nodes, node);
1953
2242
  if (!slot) return;
1954
2243
  slot->instanced = true;
@@ -1959,6 +2248,7 @@ void nodeInstances(double node, double matrices, double colors, double count)
1959
2248
 
1960
2249
  void nodeLight(double node, double kind, double r, double g, double b, double intensity, double groundR, double groundG, double groundB, double distance, double decay)
1961
2250
  {
2251
+ GEA3D_SYNC_BUILD();
1962
2252
  Node *slot = lookup(g_nodes, node);
1963
2253
  if (!slot) return;
1964
2254
  slot->lightKind = static_cast<int>(kind);
@@ -1975,6 +2265,7 @@ void nodeLight(double node, double kind, double r, double g, double b, double in
1975
2265
 
1976
2266
  void nodeLightTarget(double node, double x, double y, double z)
1977
2267
  {
2268
+ GEA3D_SYNC_BUILD();
1978
2269
  Node *slot = lookup(g_nodes, node);
1979
2270
  if (!slot) return;
1980
2271
  slot->target[0] = static_cast<float>(x);
@@ -1984,6 +2275,7 @@ void nodeLightTarget(double node, double x, double y, double z)
1984
2275
 
1985
2276
  void cameraProjectionRaw(double node, const float *elements, std::size_t count, double near, double far)
1986
2277
  {
2278
+ GEA3D_SYNC_BUILD();
1987
2279
  Node *slot = lookup(g_nodes, node);
1988
2280
  if (!slot || count < 16) return;
1989
2281
  std::memcpy(slot->projection, elements, sizeof(slot->projection));
@@ -1993,6 +2285,7 @@ void cameraProjectionRaw(double node, const float *elements, std::size_t count,
1993
2285
 
1994
2286
  void sceneEnvironment(double scene, double background, double top, double bottom, double fog, double fogColor, double fogNear, double fogFar, double fogDensity)
1995
2287
  {
2288
+ GEA3D_SYNC_BUILD();
1996
2289
  Node *slot = lookup(g_nodes, scene);
1997
2290
  if (!slot) return;
1998
2291
 
@@ -2015,17 +2308,20 @@ void sceneEnvironment(double scene, double background, double top, double bottom
2015
2308
 
2016
2309
  void renderOptions(double depthBuffer, double capacity)
2017
2310
  {
2311
+ GEA3D_SYNC_BUILD();
2018
2312
  g_renderer.depthBuffer = depthBuffer != 0;
2019
2313
  if (capacity >= 64) g_renderer.capacity = static_cast<int>(capacity);
2020
2314
  }
2021
2315
 
2022
2316
  void renderTarget(double surface)
2023
2317
  {
2318
+ GEA3D_SYNC_BUILD();
2024
2319
  g_renderer.surface = static_cast<int>(surface);
2025
2320
  }
2026
2321
 
2027
2322
  double createSurface(double width, double height)
2028
2323
  {
2324
+ GEA3D_SYNC_BUILD();
2029
2325
  const int w = static_cast<int>(width);
2030
2326
  const int h = static_cast<int>(height);
2031
2327
  if (w <= 0 || h <= 0 || g_surfaces.count >= 8) return -1;
@@ -2045,36 +2341,145 @@ double createSurface(double width, double height)
2045
2341
  return id;
2046
2342
  }
2047
2343
 
2048
- double drawScene(double scene, double camera, double width, double height)
2344
+ namespace {
2345
+ GEA3D_INLINE std::uint64_t mixHash(std::uint64_t h, std::uint64_t v)
2346
+ {
2347
+ h ^= v + 0x9E3779B97F4A7C15ull + (h << 6) + (h >> 2);
2348
+ return h * 0xBF58476D1CE4E5B9ull;
2349
+ }
2350
+
2351
+ std::uint64_t primHash(const raster::Prim &p, bool opaque, bool withDepth, bool withKey)
2049
2352
  {
2050
- Node *sceneNode = lookup(g_nodes, scene);
2051
- Node *cameraNode = lookup(g_nodes, camera);
2052
- if (!sceneNode || !cameraNode) return 0;
2353
+ std::uint64_t h = 0xCBF29CE484222325ull;
2354
+ for (int k = 0; k < 3; k++) h = mixHash(h, (static_cast<std::uint64_t>(static_cast<std::uint32_t>(p.x[k])) << 32) | static_cast<std::uint32_t>(p.y[k]));
2355
+ h = mixHash(h, static_cast<std::uint64_t>(p.r[0]) | static_cast<std::uint64_t>(p.r[1]) << 8 | static_cast<std::uint64_t>(p.r[2]) << 16 |
2356
+ static_cast<std::uint64_t>(p.g[0]) << 24 | static_cast<std::uint64_t>(p.g[1]) << 32 | static_cast<std::uint64_t>(p.g[2]) << 40 |
2357
+ static_cast<std::uint64_t>(p.b[0]) << 48 | static_cast<std::uint64_t>(p.b[1]) << 56);
2358
+ h = mixHash(h, static_cast<std::uint64_t>(p.b[2]) | static_cast<std::uint64_t>(p.type) << 8 | static_cast<std::uint64_t>(p.flags) << 16 |
2359
+ static_cast<std::uint64_t>(p.alpha) << 24 | static_cast<std::uint64_t>(p.width) << 32 | static_cast<std::uint64_t>(p.color) << 40 |
2360
+ static_cast<std::uint64_t>(opaque) << 56);
2361
+ if (withDepth) {
2362
+ std::uint32_t d[3];
2363
+ std::memcpy(d, p.depth, sizeof(d));
2364
+ h = mixHash(h, (static_cast<std::uint64_t>(d[0]) << 32) | d[1]);
2365
+ h = mixHash(h, d[2]);
2366
+ }
2367
+ if (withKey) {
2368
+ std::uint32_t key;
2369
+ std::memcpy(&key, &p.key, sizeof(key));
2370
+ h = mixHash(h, key);
2371
+ }
2372
+ return h;
2373
+ }
2374
+
2375
+ // Band hashes of a sorted frame. Depth matters only to a depth-tested frame,
2376
+ // and the sort key only where blended primitives interleave by it.
2377
+ void hashBands(const raster::Frame &frame, std::vector<std::uint64_t> &out, int bandRows)
2378
+ {
2379
+ const int bands = frame.height > 0 ? (frame.height + bandRows - 1) / bandRows : 0;
2380
+ std::uint64_t seed = mixHash(0x84222325CBF29CE4ull, static_cast<std::uint64_t>(frame.width) << 32 | static_cast<std::uint32_t>(frame.height));
2381
+ const raster::Background &bg = frame.background;
2382
+ seed = mixHash(seed, static_cast<std::uint64_t>(bg.mode) | static_cast<std::uint64_t>(bg.top[0]) << 8 | static_cast<std::uint64_t>(bg.top[1]) << 16 |
2383
+ static_cast<std::uint64_t>(bg.top[2]) << 24 | static_cast<std::uint64_t>(bg.bottom[0]) << 32 |
2384
+ static_cast<std::uint64_t>(bg.bottom[1]) << 40 | static_cast<std::uint64_t>(bg.bottom[2]) << 48 |
2385
+ static_cast<std::uint64_t>(frame.depthBuffer) << 56);
2386
+ out.assign(static_cast<std::size_t>(bands), seed);
2387
+ const bool withDepth = frame.depthBuffer;
2388
+ const bool withKey = frame.blendCount > 0;
2389
+ for (int i = 0; i < frame.count; i++) {
2390
+ const int first = maxInt(static_cast<std::int16_t>(frame.rows[i] & 0xFFFFu), 0);
2391
+ const int last = minInt(static_cast<std::int16_t>(frame.rows[i] >> 16), frame.height - 1);
2392
+ if (first > last) continue;
2393
+ const std::uint64_t h = primHash(frame.prims[frame.order[static_cast<std::size_t>(i)]], i < frame.opaqueCount, withDepth, withKey);
2394
+ for (int b = first / bandRows; b <= last / bandRows; b++) out[static_cast<std::size_t>(b)] = mixHash(out[static_cast<std::size_t>(b)], h);
2395
+ }
2396
+ }
2053
2397
 
2398
+ // Builds the scene into frames[building] (no present).
2399
+ void buildFrame(int scene, int camera, int width, int height)
2400
+ {
2401
+ Node &sceneNode = g_nodes[static_cast<std::size_t>(scene)];
2402
+ Node &cameraNode = g_nodes[static_cast<std::size_t>(camera)];
2054
2403
  Renderer &r = g_renderer;
2055
- beginFrameState(static_cast<int>(width), static_cast<int>(height));
2404
+ beginFrameState(width, height);
2056
2405
  r.legacyActive = false;
2057
2406
  raster::Frame &frame = r.frame();
2058
- r.environment = sceneNode->environment;
2407
+ r.environment = sceneNode.environment;
2059
2408
  frame.background = r.environment.background;
2060
2409
 
2061
- collect(static_cast<int>(scene));
2410
+ collect(scene);
2062
2411
 
2063
- ensureWorld(static_cast<int>(camera));
2064
- math::invertAffine(r.view.view, cameraNode->world);
2065
- setProjection(cameraNode->projection, cameraNode->near, cameraNode->far);
2412
+ ensureWorld(camera);
2413
+ math::invertAffine(r.view.view, cameraNode.world);
2414
+ setProjection(cameraNode.projection, cameraNode.near, cameraNode.far);
2066
2415
 
2067
2416
  for (const int id : r.lightNodes) addLight(g_nodes[static_cast<std::size_t>(id)]);
2068
2417
  for (const int id : r.drawables) drawNode(g_nodes[static_cast<std::size_t>(id)]);
2069
2418
 
2070
2419
  sortFrame();
2071
- const int count = frame.count;
2072
- return present() ? count : -1;
2420
+ r.stats.primitives = frame.count;
2421
+ {
2422
+ const int hint = g_stripRowsHint.load(std::memory_order_relaxed);
2423
+ g_bandHashRows[r.building] = hint >= 4 && hint <= 32 ? hint : kBandHashRows;
2424
+ }
2425
+ hashBands(frame, g_bandHash[r.building], g_bandHashRows[r.building]);
2426
+ g_frameSerial[r.building]++;
2427
+ #if GEA3D_ASYNC_PRESENT
2428
+ prebuildStripLists(frame, r.building);
2429
+ #endif
2430
+ }
2431
+ } // namespace
2432
+
2433
+ double drawScene(double scene, double camera, double width, double height)
2434
+ {
2435
+ GEA3D_SYNC_BUILD();
2436
+ if (!lookup(g_nodes, scene) || !lookup(g_nodes, camera)) return 0;
2437
+ const int sceneId = static_cast<int>(scene);
2438
+ const int cameraId = static_cast<int>(camera);
2439
+ const int w = static_cast<int>(width);
2440
+ const int h = static_cast<int>(height);
2441
+ Renderer &r = g_renderer;
2442
+
2443
+ #if GEA3D_ASYNC_BUILD
2444
+ if (r.surface < 0 && gea::framework::display::Underlay::composited() && ensureBuildTask()) {
2445
+ if (g_readyFrame < 0) {
2446
+ // First frame (or after a synchronous one): nothing built ahead.
2447
+ waitForPresent();
2448
+ buildFrame(sceneId, cameraId, w, h);
2449
+ g_readyFrame = r.building;
2450
+ }
2451
+ raster::Frame &shown = r.frames[g_readyFrame];
2452
+ if (shown.width != w || shown.height != h || !presentUnderlay(shown, &g_bandHash[g_readyFrame])) {
2453
+ g_readyFrame = -1;
2454
+ } else {
2455
+ const int count = shown.count;
2456
+ g_shownStats = r.stats;
2457
+ g_shownStats.composited = 1;
2458
+ r.building = g_readyFrame ^ 1;
2459
+ g_buildJob = BuildJob{sceneId, cameraId, w, h};
2460
+ g_buildInFlight = true;
2461
+ g_readyFrame = r.building;
2462
+ xSemaphoreGive(g_buildWork);
2463
+ return count;
2464
+ }
2465
+ } else {
2466
+ g_readyFrame = -1;
2467
+ }
2468
+ #endif
2469
+
2470
+ buildFrame(sceneId, cameraId, w, h);
2471
+ const int count = r.frame().count;
2472
+ return present(&g_bandHash[r.building]) ? count : -1;
2073
2473
  }
2074
2474
 
2075
2475
  double stat(double which)
2076
2476
  {
2477
+ // The shown frame's counts: no wait for the build running ahead.
2478
+ #if GEA3D_ASYNC_BUILD
2479
+ const Stats &s = g_buildInFlight ? g_shownStats : g_renderer.stats;
2480
+ #else
2077
2481
  const Stats &s = g_renderer.stats;
2482
+ #endif
2078
2483
  switch (static_cast<int>(which)) {
2079
2484
  case 0: return s.submitted;
2080
2485
  case 1: return s.nearRejected;
@@ -2093,6 +2498,7 @@ double stat(double which)
2093
2498
 
2094
2499
  double raycast(double node, double ox, double oy, double oz, double dx, double dy, double dz, double near, double far)
2095
2500
  {
2501
+ GEA3D_SYNC_BUILD();
2096
2502
  Node *slot = lookup(g_nodes, node);
2097
2503
  if (!slot || slot->kind != kNodeMesh) return 0;
2098
2504
  Geometry *geometry = lookup(g_geometries, slot->geometry);
@@ -2163,6 +2569,7 @@ double raycast(double node, double ox, double oy, double oz, double dx, double d
2163
2569
 
2164
2570
  double rayResult(double which)
2165
2571
  {
2572
+ GEA3D_SYNC_BUILD();
2166
2573
  switch (static_cast<int>(which)) {
2167
2574
  case 0: return g_rayHit.distance;
2168
2575
  case 1: return g_rayHit.point[0];
@@ -2178,6 +2585,7 @@ double rayResult(double which)
2178
2585
 
2179
2586
  void beginFrameRaw(const float *projection, std::size_t count, double near, double bgColor, double viewportW, double viewportH)
2180
2587
  {
2588
+ GEA3D_SYNC_BUILD();
2181
2589
  Renderer &r = g_renderer;
2182
2590
  beginFrameState(static_cast<int>(viewportW), static_cast<int>(viewportH));
2183
2591
  r.legacyActive = true;
@@ -2191,6 +2599,7 @@ void beginFrameRaw(const float *projection, std::size_t count, double near, doub
2191
2599
 
2192
2600
  void ambientLight(double r, double g, double b)
2193
2601
  {
2602
+ GEA3D_SYNC_BUILD();
2194
2603
  Lights &lights = g_renderer.lights;
2195
2604
  lights.ambient[0] += static_cast<float>(r);
2196
2605
  lights.ambient[1] += static_cast<float>(g);
@@ -2199,6 +2608,7 @@ void ambientLight(double r, double g, double b)
2199
2608
 
2200
2609
  void directionalLight(double x, double y, double z, double r, double g, double b)
2201
2610
  {
2611
+ GEA3D_SYNC_BUILD();
2202
2612
  Lights &lights = g_renderer.lights;
2203
2613
  float direction[3] = {static_cast<float>(x), static_cast<float>(y), static_cast<float>(z)};
2204
2614
  if (lights.directionalCount >= kMaxLights || !math::normalize3(direction)) return;
@@ -2221,6 +2631,7 @@ void drawElementsRaw(double positionBuffer,
2221
2631
  double baseB,
2222
2632
  double doubleSide)
2223
2633
  {
2634
+ GEA3D_SYNC_BUILD();
2224
2635
  if (!g_renderer.legacyActive || modelViewCount < 16) return;
2225
2636
  const Buffer *positions = bufferAt(static_cast<int>(positionBuffer));
2226
2637
  if (!positions) return;
@@ -2251,6 +2662,7 @@ void drawElementsRaw(double positionBuffer,
2251
2662
 
2252
2663
  double endFrame()
2253
2664
  {
2665
+ GEA3D_SYNC_BUILD();
2254
2666
  if (!g_renderer.legacyActive) return 0;
2255
2667
  g_renderer.legacyActive = false;
2256
2668
  sortFrame();