@geastack/gea3d 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2261 @@
1
+ // SPDX-License-Identifier: GPL-3.0-only
2
+ // The per-vertex and per-pixel paths must be optimized even when the
3
+ // firmware is built for size.
4
+ #if defined(__GNUC__) && !defined(__clang__)
5
+ #pragma GCC optimize("O2")
6
+ #endif
7
+
8
+ #include "gea3d_native.h"
9
+
10
+ #include "gea3d_math.h"
11
+ #include "gea3d_raster.h"
12
+
13
+ #include "canvas.h"
14
+ #include "display.h"
15
+ #include "image.h"
16
+ #include "pixel.h"
17
+
18
+ #include <algorithm>
19
+ #include <climits>
20
+ #include <cmath>
21
+ #include <cstring>
22
+ #include <new>
23
+ #include <vector>
24
+
25
+ // Retained-UI compositing: with an engine that knows the underlay hook, a
26
+ // mounted UI tree repaints the 3D view under its own nodes in the same flush.
27
+ #if __has_include("display_underlay.h")
28
+ #include "display_underlay.h"
29
+ #define GEA3D_UNDERLAY 1
30
+ #else
31
+ #define GEA3D_UNDERLAY 0
32
+ #endif
33
+
34
+ // Async present on ESP32: the raster + panel stream of frame N runs on core 0
35
+ // while the app task builds frame N+1 (radios are off in the gea3d profile).
36
+ #if defined(ESP_PLATFORM) && __has_include("freertos/FreeRTOS.h")
37
+ #include "freertos/FreeRTOS.h"
38
+ #include "freertos/semphr.h"
39
+ #include "freertos/task.h"
40
+ #define GEA3D_ASYNC_PRESENT 1
41
+ #else
42
+ #define GEA3D_ASYNC_PRESENT 0
43
+ #endif
44
+
45
+ // Band copy-out by the STM32F7's DMA2D, overlapping the next band's raster.
46
+ #if defined(STM32F746xx) && __has_include("stm32f7xx.h")
47
+ #include "stm32f7xx.h"
48
+ #define GEA3D_DMA2D_COPY 1
49
+ #else
50
+ #define GEA3D_DMA2D_COPY 0
51
+ #endif
52
+
53
+ // Framebuffers the rasterizer cannot address directly (sub-byte packed gray,
54
+ // rotated panels) present flat triangles through the display's own command.
55
+ #if GEA_PIXEL_STORAGE_PACKED || (defined(GEA_EMBEDDED_DISPLAY_ROTATE_LANDSCAPE) && GEA_EMBEDDED_DISPLAY_ROTATE_LANDSCAPE)
56
+ #define GEA3D_PRESENT_COMMANDS 1
57
+ #else
58
+ #define GEA3D_PRESENT_COMMANDS 0
59
+ #endif
60
+
61
+ namespace gea::host::gea3d {
62
+
63
+ namespace {
64
+
65
+ namespace pixel = gea::framework::graphics::pixel;
66
+ namespace pd = gea::platform::display;
67
+ using raster::Pixel;
68
+ using raster::Prim;
69
+ using raster::detail::clampFloat;
70
+ using raster::detail::maxInt;
71
+ using raster::detail::minInt;
72
+ using raster::detail::roundToInt;
73
+
74
+ constexpr int kMaxLights = 4;
75
+ constexpr int kDepthBuckets = 1024;
76
+ // renderOrder spans up to this wide sort by counting; wider ones by stable_sort.
77
+ constexpr int kLayerCountingRange = 256;
78
+ // Screen coordinates stay within +-16000 px, so 16.16 edge positions fit int32.
79
+ constexpr float kCoordLimit = 16000.0f;
80
+ constexpr int kDefaultCapacity = 4096;
81
+
82
+ // ---------------------------------------------------------------- resources
83
+
84
+ struct Buffer {
85
+ bool live = false;
86
+ std::vector<float> f32;
87
+ std::vector<std::uint32_t> u32;
88
+ std::uint32_t version = 0;
89
+ };
90
+
91
+ struct Geometry {
92
+ bool live = false;
93
+ int position = -1;
94
+ int index = -1;
95
+ int color = -1;
96
+ int normal = -1;
97
+ // Bounding sphere of `position` at `boundsVersion`.
98
+ int boundsBuffer = -1;
99
+ std::uint32_t boundsVersion = 0;
100
+ float center[3] = {0, 0, 0};
101
+ float radius = -1.0f;
102
+ };
103
+
104
+ struct Material {
105
+ bool live = false;
106
+ int shade = 1;
107
+ float color[3] = {255, 255, 255}; // 0..255
108
+ float opacity = 1.0f;
109
+ int side = 0;
110
+ int flags = kMaterialVisible | kMaterialDepthTest | kMaterialDepthWrite | kMaterialFog;
111
+ float size = 1.0f;
112
+ };
113
+
114
+ struct Environment {
115
+ raster::Background background;
116
+ int fog = 0;
117
+ float fogColor[3] = {0, 0, 0};
118
+ float fogNear = 1.0f;
119
+ float fogFar = 1000.0f;
120
+ float fogDensity = 0.00025f;
121
+ };
122
+
123
+ struct Node {
124
+ bool live = false;
125
+ int kind = kNodeGroup;
126
+ int parent = -1;
127
+ int firstChild = -1;
128
+ int nextSibling = -1;
129
+ int prevSibling = -1;
130
+
131
+ float position[3] = {0, 0, 0};
132
+ float quaternion[4] = {0, 0, 0, 1};
133
+ float scale[3] = {1, 1, 1};
134
+ float local[16];
135
+ float world[16];
136
+ bool useMatrix = false;
137
+ bool localDirty = true;
138
+ std::uint32_t worldVersion = 1;
139
+ std::uint32_t parentWorldVersion = 0;
140
+
141
+ bool visible = true;
142
+ bool frustumCulled = true;
143
+ int renderOrder = 0;
144
+
145
+ int geometry = -1;
146
+ int material = -1;
147
+ // An InstancedMesh draws its instances only (none at a count of 0);
148
+ // any other mesh draws once at its own transform.
149
+ bool instanced = false;
150
+ int instanceMatrices = -1;
151
+ int instanceColors = -1;
152
+ int instanceCount = 0;
153
+
154
+ int lightKind = 0;
155
+ float lightColor[3] = {1, 1, 1};
156
+ float intensity = 1.0f;
157
+ float groundColor[3] = {1, 1, 1};
158
+ float distance = 0.0f;
159
+ float decay = 2.0f;
160
+ float target[3] = {0, 0, 0};
161
+
162
+ float projection[16];
163
+ float near = 0.1f;
164
+ float far = 2000.0f;
165
+
166
+ Environment environment;
167
+
168
+ Node()
169
+ {
170
+ math::identity(local);
171
+ math::identity(world);
172
+ math::identity(projection);
173
+ }
174
+ };
175
+
176
+ template <typename T>
177
+ int allocate(std::vector<T> &pool)
178
+ {
179
+ for (std::size_t i = 0; i < pool.size(); i++) {
180
+ if (!pool[i].live) {
181
+ pool[i] = T();
182
+ pool[i].live = true;
183
+ return static_cast<int>(i);
184
+ }
185
+ }
186
+ pool.emplace_back();
187
+ pool.back().live = true;
188
+ return static_cast<int>(pool.size() - 1);
189
+ }
190
+
191
+ template <typename T>
192
+ T *lookup(std::vector<T> &pool, double id)
193
+ {
194
+ const int index = static_cast<int>(id);
195
+ if (index < 0 || index >= static_cast<int>(pool.size()) || !pool[static_cast<std::size_t>(index)].live) return nullptr;
196
+ return &pool[static_cast<std::size_t>(index)];
197
+ }
198
+
199
+ std::vector<Buffer> g_buffers;
200
+ std::vector<Geometry> g_geometries;
201
+ std::vector<Material> g_materials;
202
+ std::vector<Node> g_nodes;
203
+
204
+ // ---------------------------------------------------------------- scene graph
205
+
206
+ void unlink(int id)
207
+ {
208
+ Node &node = g_nodes[static_cast<std::size_t>(id)];
209
+ if (node.parent < 0) return;
210
+
211
+ Node &parent = g_nodes[static_cast<std::size_t>(node.parent)];
212
+ if (node.prevSibling >= 0) g_nodes[static_cast<std::size_t>(node.prevSibling)].nextSibling = node.nextSibling;
213
+ else parent.firstChild = node.nextSibling;
214
+ if (node.nextSibling >= 0) g_nodes[static_cast<std::size_t>(node.nextSibling)].prevSibling = node.prevSibling;
215
+ node.parent = -1;
216
+ node.prevSibling = -1;
217
+ node.nextSibling = -1;
218
+ node.localDirty = true;
219
+ }
220
+
221
+ void link(int id, int parentId)
222
+ {
223
+ Node &node = g_nodes[static_cast<std::size_t>(id)];
224
+ Node &parent = g_nodes[static_cast<std::size_t>(parentId)];
225
+ node.parent = parentId;
226
+ node.prevSibling = -1;
227
+ node.nextSibling = parent.firstChild;
228
+ if (parent.firstChild >= 0) g_nodes[static_cast<std::size_t>(parent.firstChild)].prevSibling = id;
229
+ parent.firstChild = id;
230
+ node.localDirty = true;
231
+ }
232
+
233
+ bool isAncestor(int ancestor, int id)
234
+ {
235
+ for (int cursor = id; cursor >= 0; cursor = g_nodes[static_cast<std::size_t>(cursor)].parent) {
236
+ if (cursor == ancestor) return true;
237
+ }
238
+ return false;
239
+ }
240
+
241
+ // Recomputes the node's world matrix if it or its parent moved. The parent
242
+ // must already be current.
243
+ void refreshWorld(Node &node)
244
+ {
245
+ const Node *parent = node.parent >= 0 ? &g_nodes[static_cast<std::size_t>(node.parent)] : nullptr;
246
+ const std::uint32_t parentVersion = parent ? parent->worldVersion : 0;
247
+ if (!node.localDirty && node.parentWorldVersion == parentVersion) return;
248
+
249
+ if (node.localDirty && !node.useMatrix) math::compose(node.local, node.position, node.quaternion, node.scale);
250
+ if (parent) math::multiplyAffine(node.world, parent->world, node.local);
251
+ else std::memcpy(node.world, node.local, sizeof(node.world));
252
+ node.localDirty = false;
253
+ node.parentWorldVersion = parentVersion;
254
+ node.worldVersion++;
255
+ }
256
+
257
+ // World matrix of a node anywhere in a graph (walks the ancestor chain).
258
+ void ensureWorld(int id)
259
+ {
260
+ Node &node = g_nodes[static_cast<std::size_t>(id)];
261
+ if (node.parent >= 0) ensureWorld(node.parent);
262
+ refreshWorld(node);
263
+ }
264
+
265
+ // ---------------------------------------------------------------- frame state
266
+
267
+ struct Lights {
268
+ float ambient[3] = {0, 0, 0};
269
+ int directionalCount = 0;
270
+ float direction[kMaxLights][3];
271
+ float directionalColor[kMaxLights][3];
272
+ int pointCount = 0;
273
+ float pointPosition[kMaxLights][3];
274
+ float pointColor[kMaxLights][3];
275
+ float pointDistance[kMaxLights];
276
+ float pointDecay[kMaxLights];
277
+ int hemisphereCount = 0;
278
+ float hemisphereUp[kMaxLights][3];
279
+ float sky[kMaxLights][3];
280
+ float ground[kMaxLights][3];
281
+
282
+ void reset() { *this = Lights(); }
283
+ };
284
+
285
+ struct Stats {
286
+ int submitted = 0;
287
+ int nearRejected = 0;
288
+ int culled = 0;
289
+ int clipDropped = 0;
290
+ int dropped = 0;
291
+ int meshesDrawn = 0;
292
+ int meshesCulled = 0;
293
+ int primitives = 0;
294
+ int composited = 0;
295
+ };
296
+
297
+ struct View {
298
+ float view[16];
299
+ float projection[16];
300
+ float planes[6][4]; // view-space frustum
301
+ float near = 0.1f;
302
+ float far = 2000.0f;
303
+ bool orthographic = false;
304
+ float halfW = 0.0f;
305
+ float halfH = 0.0f;
306
+ int width = 0;
307
+ int height = 0;
308
+ };
309
+
310
+ // The material of one draw, resolved to what the vertex stage needs.
311
+ struct Surface {
312
+ int shade = 1;
313
+ float color[3] = {255, 255, 255}; // 0..255
314
+ int side = 0;
315
+ bool vertexColors = false;
316
+ bool blend = false;
317
+ bool additive = false;
318
+ std::uint8_t alpha = 255;
319
+ // The drawing object's renderOrder.
320
+ int layer = 0;
321
+ bool fog = true;
322
+ bool flat = false;
323
+ bool wireframe = false;
324
+ float size = 1.0f;
325
+ bool sizeAttenuation = true;
326
+ };
327
+
328
+ // Per-vertex results of the current draw, one record per vertex so a
329
+ // triangle's corners sit in few cache lines.
330
+ struct Vertex {
331
+ float view[3]; // view space
332
+ float color[3]; // final colour 0..255, or the unlit base where faces are shaded
333
+ float fog; // fog factor where faces are shaded (1 = no fog)
334
+ std::int32_t screen[2]; // 28.4
335
+ float depth; // near / w
336
+ std::uint8_t rgb[3]; // `color` as bytes, when shaded per vertex
337
+ std::uint8_t front; // in front of the near plane (screen and depth are set)
338
+ };
339
+
340
+ // `fixed` (optional) is a pool in faster memory used when a draw fits.
341
+ struct VertexScratch {
342
+ std::vector<Vertex> items;
343
+ Vertex *fixed = nullptr;
344
+ std::size_t fixedCount = 0;
345
+ Vertex *current = nullptr;
346
+
347
+ Vertex *prepare(std::size_t count)
348
+ {
349
+ if (count <= fixedCount) {
350
+ current = fixed;
351
+ return current;
352
+ }
353
+ if (items.size() < count) items.resize(count);
354
+ current = items.data();
355
+ return current;
356
+ }
357
+ };
358
+
359
+ // Band rendering: rows are rasterized into a small buffer in fast memory,
360
+ // then copied to the target in one sequential pass, so a framebuffer in slow
361
+ // (e.g. write-through SDRAM) memory takes each pixel once, in order.
362
+ struct Bands {
363
+ Pixel *pixels = nullptr;
364
+ // A second buffer where bands are copied out in the background: the
365
+ // raster fills one while the other drains.
366
+ Pixel *spare = nullptr;
367
+ int width = 0;
368
+ int rows = 0;
369
+ // Per band of the region being drawn, its primitives (buildBandLists).
370
+ std::vector<std::int32_t> items;
371
+ std::vector<int> starts;
372
+ std::vector<int> opaque;
373
+ std::vector<int> next;
374
+ std::vector<int> bandOfRow;
375
+ };
376
+
377
+ // A clipped polygon corner (view space + attributes).
378
+ struct Corner {
379
+ float x, y, z;
380
+ float r, g, b;
381
+ };
382
+
383
+ struct Renderer {
384
+ raster::Frame frames[2];
385
+ int building = 0;
386
+ raster::Scratch scratch;
387
+ int capacity = kDefaultCapacity;
388
+ bool depthBuffer = false;
389
+ int surface = -1;
390
+ View view;
391
+ Lights lights;
392
+ Environment environment;
393
+ Stats stats;
394
+ VertexScratch vertices;
395
+ Bands bands;
396
+ std::vector<int> stack;
397
+ std::vector<int> drawables;
398
+ std::vector<int> lightNodes;
399
+ std::vector<std::int32_t> keys;
400
+ std::vector<std::int32_t> bucketStarts;
401
+ std::vector<std::int32_t> layerCounts;
402
+ std::vector<std::int32_t> layerOrder;
403
+ bool legacyActive = false;
404
+
405
+ raster::Frame &frame() { return frames[building]; }
406
+ };
407
+
408
+ Renderer g_renderer;
409
+
410
+ // Fast memory for the raster. On the STM32F7 the heap and framebuffers are
411
+ // SDRAM (framebuffers write-through), so two band buffers fill the zero-wait
412
+ // DTCM beside the stack (never zeroed; the rasterizer initialises what it
413
+ // uses) while DMA2D drains the other, and the vertex scratch and primitive
414
+ // records live in internal SRAM. Bands draw painter's-order, so they need no
415
+ // coverage bookkeeping. GEA3D_BAND_ROWS lets host tests exercise bands.
416
+ #if defined(STM32F746xx) && !defined(GEA3D_BAND_ROWS)
417
+ #define GEA3D_BAND_ROWS 15
418
+ #define GEA3D_BAND_BUFFERS 2
419
+ #define GEA3D_FAST_MEMORY __attribute__((section(".dtcm.gea3d"), aligned(32)))
420
+ #define GEA3D_VERTEX_POOL 384
421
+ #define GEA3D_PRIM_POOL 1024
422
+ #elif defined(GEA3D_BAND_ROWS)
423
+ #define GEA3D_BAND_BUFFERS 1
424
+ #define GEA3D_FAST_MEMORY alignas(32)
425
+ #define GEA3D_VERTEX_POOL 384
426
+ #define GEA3D_PRIM_POOL 1024
427
+ #endif
428
+
429
+ #if defined(GEA3D_BAND_ROWS)
430
+ constexpr int kBandWidth = 480;
431
+ constexpr int kBandRows = GEA3D_BAND_ROWS;
432
+
433
+ GEA3D_FAST_MEMORY Pixel g_bandPixels[GEA3D_BAND_BUFFERS][kBandWidth * kBandRows];
434
+ Vertex g_vertexPool[GEA3D_VERTEX_POOL];
435
+ Prim g_primPool[GEA3D_PRIM_POOL];
436
+
437
+ struct FastMemoryBinding {
438
+ FastMemoryBinding()
439
+ {
440
+ Renderer &r = g_renderer;
441
+ r.bands.pixels = g_bandPixels[0];
442
+ r.bands.spare = GEA3D_BAND_BUFFERS > 1 && GEA3D_DMA2D_COPY ? g_bandPixels[GEA3D_BAND_BUFFERS - 1] : nullptr;
443
+ r.bands.width = kBandWidth;
444
+ r.bands.rows = kBandRows;
445
+ r.vertices.fixed = g_vertexPool;
446
+ r.vertices.fixedCount = GEA3D_VERTEX_POOL;
447
+ // Only frame 0: no asynchronous present where fast memory is bound.
448
+ r.frames[0].fixedPrims = g_primPool;
449
+ r.frames[0].fixedCapacity = GEA3D_PRIM_POOL;
450
+ }
451
+ };
452
+
453
+ FastMemoryBinding g_fastMemoryBinding;
454
+ #endif
455
+
456
+ struct Surfaces {
457
+ int ids[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
458
+ Pixel *pixels[8] = {};
459
+ int width[8] = {};
460
+ int height[8] = {};
461
+ int count = 0;
462
+
463
+ int find(int id) const
464
+ {
465
+ for (int i = 0; i < count; i++) {
466
+ if (ids[i] == id) return i;
467
+ }
468
+ return -1;
469
+ }
470
+ };
471
+
472
+ Surfaces g_surfaces;
473
+
474
+ struct RayHit {
475
+ float distance = 0.0f;
476
+ float point[3] = {0, 0, 0};
477
+ int face = -1;
478
+ int instance = -1;
479
+ };
480
+
481
+ RayHit g_rayHit;
482
+
483
+ // ---------------------------------------------------------------- helpers
484
+
485
+ // VMAXNM on FPv5: no float compare stalls the pipeline.
486
+ GEA3D_INLINE float maxFloat(float a, float b) { return __builtin_fmaxf(a, b); }
487
+
488
+ // 0..255 by truncation; clamped in integer registers (USAT), not with float
489
+ // compares.
490
+ GEA3D_INLINE std::uint8_t toByte(float value)
491
+ {
492
+ return static_cast<std::uint8_t>(raster::detail::clampInt(static_cast<int>(value), 0, 255));
493
+ }
494
+
495
+ void hexToRgb(double hex, std::uint8_t *out)
496
+ {
497
+ const std::uint32_t value = static_cast<std::uint32_t>(hex);
498
+ out[0] = static_cast<std::uint8_t>((value >> 16) & 0xFF);
499
+ out[1] = static_cast<std::uint8_t>((value >> 8) & 0xFF);
500
+ out[2] = static_cast<std::uint8_t>(value & 0xFF);
501
+ }
502
+
503
+ const Buffer *bufferAt(int id)
504
+ {
505
+ if (id < 0 || id >= static_cast<int>(g_buffers.size()) || !g_buffers[static_cast<std::size_t>(id)].live) return nullptr;
506
+ return &g_buffers[static_cast<std::size_t>(id)];
507
+ }
508
+
509
+ void updateBounds(Geometry &geometry)
510
+ {
511
+ const Buffer *positions = bufferAt(geometry.position);
512
+ if (!positions) {
513
+ geometry.radius = 0.0f;
514
+ return;
515
+ }
516
+ if (geometry.boundsBuffer == geometry.position && geometry.boundsVersion == positions->version && geometry.radius >= 0.0f) return;
517
+
518
+ const std::size_t count = positions->f32.size() / 3;
519
+ const float *p = positions->f32.data();
520
+ geometry.boundsBuffer = geometry.position;
521
+ geometry.boundsVersion = positions->version;
522
+ if (count == 0) {
523
+ geometry.center[0] = geometry.center[1] = geometry.center[2] = 0.0f;
524
+ geometry.radius = 0.0f;
525
+ return;
526
+ }
527
+
528
+ float lo[3] = {p[0], p[1], p[2]};
529
+ float hi[3] = {p[0], p[1], p[2]};
530
+ for (std::size_t i = 1; i < count; i++) {
531
+ for (int k = 0; k < 3; k++) {
532
+ lo[k] = std::min(lo[k], p[i * 3 + k]);
533
+ hi[k] = std::max(hi[k], p[i * 3 + k]);
534
+ }
535
+ }
536
+ for (int k = 0; k < 3; k++) geometry.center[k] = (lo[k] + hi[k]) * 0.5f;
537
+ float maxSq = 0.0f;
538
+ for (std::size_t i = 0; i < count; i++) {
539
+ const float dx = p[i * 3] - geometry.center[0];
540
+ const float dy = p[i * 3 + 1] - geometry.center[1];
541
+ const float dz = p[i * 3 + 2] - geometry.center[2];
542
+ maxSq = std::max(maxSq, dx * dx + dy * dy + dz * dz);
543
+ }
544
+ geometry.radius = std::sqrt(maxSq);
545
+ }
546
+
547
+ Surface resolveSurface(const Material &material)
548
+ {
549
+ Surface surface;
550
+ surface.shade = material.shade;
551
+ for (int k = 0; k < 3; k++) surface.color[k] = material.color[k];
552
+ surface.side = material.side;
553
+ surface.vertexColors = (material.flags & kMaterialVertexColors) != 0;
554
+ surface.additive = (material.flags & kMaterialAdditive) != 0;
555
+ surface.blend = surface.additive || ((material.flags & kMaterialTransparent) != 0 && material.opacity < 1.0f);
556
+ surface.alpha = toByte(material.opacity * 255.0f);
557
+ surface.fog = (material.flags & kMaterialFog) != 0;
558
+ surface.flat = (material.flags & kMaterialFlatShading) != 0;
559
+ surface.wireframe = (material.flags & kMaterialWireframe) != 0;
560
+ surface.size = material.size;
561
+ surface.sizeAttenuation = (material.flags & kMaterialSizeAttenuation) != 0;
562
+ return surface;
563
+ }
564
+
565
+ // ---------------------------------------------------------------- lighting
566
+
567
+ void lightNormal(const float *n, const float *p, float *out)
568
+ {
569
+ const Lights &lights = g_renderer.lights;
570
+ float r = lights.ambient[0], g = lights.ambient[1], b = lights.ambient[2];
571
+ for (int i = 0; i < lights.directionalCount; i++) {
572
+ const float *d = lights.direction[i];
573
+ const float dot = n[0] * d[0] + n[1] * d[1] + n[2] * d[2];
574
+ if (dot <= 0.0f) continue;
575
+ r += dot * lights.directionalColor[i][0];
576
+ g += dot * lights.directionalColor[i][1];
577
+ b += dot * lights.directionalColor[i][2];
578
+ }
579
+ for (int i = 0; i < lights.hemisphereCount; i++) {
580
+ const float *up = lights.hemisphereUp[i];
581
+ const float t = (n[0] * up[0] + n[1] * up[1] + n[2] * up[2]) * 0.5f + 0.5f;
582
+ r += lights.ground[i][0] + (lights.sky[i][0] - lights.ground[i][0]) * t;
583
+ g += lights.ground[i][1] + (lights.sky[i][1] - lights.ground[i][1]) * t;
584
+ b += lights.ground[i][2] + (lights.sky[i][2] - lights.ground[i][2]) * t;
585
+ }
586
+ for (int i = 0; i < lights.pointCount; i++) {
587
+ float l[3] = {lights.pointPosition[i][0] - p[0], lights.pointPosition[i][1] - p[1], lights.pointPosition[i][2] - p[2]};
588
+ const float distance = std::sqrt(l[0] * l[0] + l[1] * l[1] + l[2] * l[2]);
589
+ if (distance <= 0.0f) continue;
590
+ const float inv = 1.0f / distance;
591
+ const float dot = (n[0] * l[0] + n[1] * l[1] + n[2] * l[2]) * inv;
592
+ if (dot <= 0.0f) continue;
593
+ float falloff = lights.pointDecay[i] > 0.0f ? 1.0f / std::max(std::pow(distance, lights.pointDecay[i]), 0.01f) : 1.0f;
594
+ if (lights.pointDistance[i] > 0.0f) {
595
+ const float ratio = distance / lights.pointDistance[i];
596
+ const float window = std::clamp(1.0f - ratio * ratio * ratio * ratio, 0.0f, 1.0f);
597
+ falloff *= window * window;
598
+ }
599
+ r += dot * falloff * lights.pointColor[i][0];
600
+ g += dot * falloff * lights.pointColor[i][1];
601
+ b += dot * falloff * lights.pointColor[i][2];
602
+ }
603
+ out[0] = r;
604
+ out[1] = g;
605
+ out[2] = b;
606
+ }
607
+
608
+ GEA3D_INLINE float fogFactor(float distance)
609
+ {
610
+ const Environment &env = g_renderer.environment;
611
+ if (env.fog == 1) {
612
+ if (env.fogFar <= env.fogNear) return 1.0f;
613
+ return clampFloat((env.fogFar - distance) / (env.fogFar - env.fogNear), 0.0f, 1.0f);
614
+ }
615
+ if (env.fog == 2) {
616
+ const float d = env.fogDensity * distance;
617
+ return clampFloat(std::exp(-d * d), 0.0f, 1.0f);
618
+ }
619
+ return 1.0f;
620
+ }
621
+
622
+ // Final 0..255 colour of a lit, fogged corner.
623
+ GEA3D_INLINE void shadeCorner(const float *base, const float *light, float fog, float *out)
624
+ {
625
+ const Environment &env = g_renderer.environment;
626
+ for (int k = 0; k < 3; k++) out[k] = base[k] * light[k];
627
+ if (fog >= 1.0f) return;
628
+
629
+ for (int k = 0; k < 3; k++) out[k] = env.fogColor[k] + (out[k] - env.fogColor[k]) * fog;
630
+ }
631
+
632
+ // MeshNormalMaterial: the view-space normal as a colour.
633
+ void normalColor(const float *n, float *out)
634
+ {
635
+ for (int k = 0; k < 3; k++) out[k] = (n[k] * 0.5f + 0.5f) * 255.0f;
636
+ }
637
+
638
+ // ---------------------------------------------------------------- projection
639
+
640
+ GEA3D_INLINE void project(const View &v, float x, float y, float z, std::int32_t *sx, std::int32_t *sy, float *depth)
641
+ {
642
+ const float *p = v.projection;
643
+ const float cx = p[0] * x + p[4] * y + p[8] * z + p[12];
644
+ const float cy = p[1] * x + p[5] * y + p[9] * z + p[13];
645
+ float cw = p[3] * x + p[7] * y + p[11] * z + p[15];
646
+ if (cw < 0.000001f && cw > -0.000001f) cw = 0.000001f;
647
+ const float invW = 1.0f / cw;
648
+ const float fx = clampFloat((cx * invW + 1.0f) * v.halfW, -kCoordLimit, kCoordLimit);
649
+ const float fy = clampFloat((1.0f - cy * invW) * v.halfH, -kCoordLimit, kCoordLimit);
650
+ *sx = roundToInt(fx * 16.0f);
651
+ *sy = roundToInt(fy * 16.0f);
652
+ if (v.orthographic) {
653
+ 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;
655
+ } else {
656
+ *depth = clampFloat(v.near * invW, 0.0f, 1.0f);
657
+ }
658
+ }
659
+
660
+ // ---------------------------------------------------------------- emission
661
+
662
+ // Room for more primitives: the fixed pool first, then the heap (doubling;
663
+ // whatever the pool already holds moves along).
664
+ void growPrims(raster::Frame &frame)
665
+ {
666
+ int capacity = 0;
667
+ if (!frame.prims && frame.fixedPrims) {
668
+ frame.prims = frame.fixedPrims;
669
+ capacity = frame.fixedCapacity;
670
+ } else {
671
+ capacity = maxInt(256, frame.primCapacity * 2);
672
+ const bool fromPool = frame.prims == frame.fixedPrims;
673
+ frame.primStore.resize(static_cast<std::size_t>(capacity));
674
+ if (fromPool && frame.count > 0) std::memcpy(frame.primStore.data(), frame.prims, static_cast<std::size_t>(frame.count) * sizeof(Prim));
675
+ frame.prims = frame.primStore.data();
676
+ }
677
+ frame.primCapacity = capacity;
678
+ frame.sortKeys.resize(static_cast<std::size_t>(capacity));
679
+ frame.blended.resize(static_cast<std::size_t>(capacity));
680
+ frame.layers.resize(static_cast<std::size_t>(capacity));
681
+ frame.emittedRows.resize(static_cast<std::size_t>(capacity));
682
+ }
683
+
684
+ GEA3D_INLINE Prim *nextPrim()
685
+ {
686
+ raster::Frame &frame = g_renderer.frame();
687
+ if (frame.count >= g_renderer.capacity) {
688
+ g_renderer.stats.dropped++;
689
+ return nullptr;
690
+ }
691
+ if (frame.count >= frame.primCapacity) growPrims(frame);
692
+ return &frame.prims[frame.count++];
693
+ }
694
+
695
+ GEA3D_INLINE void finishPrim(Prim &prim, const Surface &surface, int corners)
696
+ {
697
+ prim.alpha = surface.alpha;
698
+ prim.flags = surface.blend ? raster::kBlend : 0;
699
+ if (surface.additive) prim.flags |= raster::kAdd;
700
+ // Corners that pack to one pixel colour make a flat primitive: every
701
+ // colour between them packs to that pixel too.
702
+ prim.color = raster::detail::packColor(prim.r[0], prim.g[0], prim.b[0]);
703
+ bool uniform = true;
704
+ for (int i = 1; i < corners; i++) uniform = uniform && raster::detail::packColor(prim.r[i], prim.g[i], prim.b[i]) == prim.color;
705
+ if (!uniform) prim.flags |= raster::kSmooth;
706
+
707
+ int lo = static_cast<int>(prim.y[0]), hi = lo;
708
+ for (int i = 1; i < corners; i++) {
709
+ lo = minInt(lo, static_cast<int>(prim.y[i]));
710
+ hi = maxInt(hi, static_cast<int>(prim.y[i]));
711
+ }
712
+ // A wide line reaches past its ends' rows.
713
+ const int margin = 1 + (prim.type == raster::kLine ? prim.width >> 1 : 0);
714
+ prim.rowY0 = static_cast<std::int16_t>((lo >> 4) - margin);
715
+ prim.rowY1 = static_cast<std::int16_t>((hi >> 4) + margin);
716
+
717
+ raster::Frame &frame = g_renderer.frame();
718
+ const std::size_t index = static_cast<std::size_t>(&prim - frame.prims);
719
+ frame.sortKeys[index] = prim.key;
720
+ frame.blended[index] = surface.blend ? 1 : 0;
721
+ frame.layers[index] = surface.layer;
722
+ frame.minLayer = minInt(frame.minLayer, surface.layer);
723
+ frame.maxLayer = maxInt(frame.maxLayer, surface.layer);
724
+ frame.emittedRows[index] = static_cast<std::uint16_t>(prim.rowY0) | (static_cast<std::uint32_t>(static_cast<std::uint16_t>(prim.rowY1)) << 16);
725
+ }
726
+
727
+ // Whether a primitive with these screen corners (28.4) may cover a pixel of
728
+ // the frame, give or take `margin` pixels.
729
+ GEA3D_INLINE bool onScreen(const std::int32_t *sx, const std::int32_t *sy, int corners, int margin)
730
+ {
731
+ int xl = sx[0], xh = xl, yl = sy[0], yh = yl;
732
+ for (int i = 1; i < corners; i++) {
733
+ xl = minInt(xl, sx[i]);
734
+ xh = maxInt(xh, sx[i]);
735
+ yl = minInt(yl, sy[i]);
736
+ yh = maxInt(yh, sy[i]);
737
+ }
738
+ const raster::Frame &frame = g_renderer.frame();
739
+ const int edge = margin * 16;
740
+ return xh >= -edge && yh >= -edge && xl <= (frame.width + margin) * 16 && yl <= (frame.height + margin) * 16;
741
+ }
742
+
743
+ void emitTriangle(const Surface &surface, const Corner *c, const std::int32_t *sx, const std::int32_t *sy, const float *depth, float key)
744
+ {
745
+ if (!onScreen(sx, sy, 3, 0)) {
746
+ g_renderer.stats.culled++;
747
+ return;
748
+ }
749
+
750
+ Prim *prim = nextPrim();
751
+ if (!prim) return;
752
+
753
+ prim->type = raster::kTriangle;
754
+ for (int i = 0; i < 3; i++) {
755
+ prim->x[i] = sx[i];
756
+ prim->y[i] = sy[i];
757
+ prim->depth[i] = depth[i];
758
+ prim->r[i] = toByte(c[i].r);
759
+ prim->g[i] = toByte(c[i].g);
760
+ prim->b[i] = toByte(c[i].b);
761
+ }
762
+ prim->key = key;
763
+ finishPrim(*prim, surface, 3);
764
+ }
765
+
766
+ void emitLine(const Surface &surface, const Corner &a, const Corner &b)
767
+ {
768
+ const float nearZ = -g_renderer.view.near;
769
+ Corner p = a, q = b;
770
+ if (p.z > nearZ && q.z > nearZ) {
771
+ g_renderer.stats.nearRejected++;
772
+ return;
773
+ }
774
+ if (p.z > nearZ || q.z > nearZ) {
775
+ Corner &out = p.z > nearZ ? p : q;
776
+ const Corner &in = p.z > nearZ ? q : p;
777
+ const float t = (nearZ - in.z) / (out.z - in.z);
778
+ out.x = in.x + (out.x - in.x) * t;
779
+ out.y = in.y + (out.y - in.y) * t;
780
+ out.z = nearZ;
781
+ out.r = in.r + (out.r - in.r) * t;
782
+ out.g = in.g + (out.g - in.g) * t;
783
+ out.b = in.b + (out.b - in.b) * t;
784
+ }
785
+
786
+ std::int32_t sx[2], sy[2];
787
+ float depth[2];
788
+ project(g_renderer.view, p.x, p.y, p.z, &sx[0], &sy[0], &depth[0]);
789
+ project(g_renderer.view, q.x, q.y, q.z, &sx[1], &sy[1], &depth[1]);
790
+ const int width = raster::detail::clampInt(roundToInt(surface.size), 1, 3);
791
+ if (!onScreen(sx, sy, 2, width)) {
792
+ g_renderer.stats.culled++;
793
+ return;
794
+ }
795
+
796
+ Prim *prim = nextPrim();
797
+ if (!prim) return;
798
+
799
+ prim->type = raster::kLine;
800
+ prim->width = static_cast<std::uint8_t>(width);
801
+ for (int i = 0; i < 2; i++) {
802
+ prim->x[i] = sx[i];
803
+ prim->y[i] = sy[i];
804
+ prim->depth[i] = depth[i];
805
+ }
806
+ prim->x[2] = prim->x[1];
807
+ prim->y[2] = prim->y[1];
808
+ prim->depth[2] = prim->depth[1];
809
+ prim->r[0] = toByte(p.r);
810
+ prim->g[0] = toByte(p.g);
811
+ prim->b[0] = toByte(p.b);
812
+ prim->r[1] = prim->r[2] = toByte(q.r);
813
+ prim->g[1] = prim->g[2] = toByte(q.g);
814
+ prim->b[1] = prim->b[2] = toByte(q.b);
815
+ prim->key = std::max(-p.z, -q.z);
816
+ finishPrim(*prim, surface, 2);
817
+ }
818
+
819
+ // Clips a triangle against the near plane (view space) and fans it out.
820
+ void emitClipped(const Surface &surface, const Corner *corners)
821
+ {
822
+ const float nearZ = -g_renderer.view.near;
823
+ Corner polygon[4];
824
+ int count = 0;
825
+ for (int e = 0; e < 3; e++) {
826
+ const Corner &a = corners[e];
827
+ const Corner &b = corners[(e + 1) % 3];
828
+ const bool aIn = a.z <= nearZ;
829
+ const bool bIn = b.z <= nearZ;
830
+ if (aIn) polygon[count++] = a;
831
+ if (aIn != bIn) {
832
+ const float t = (nearZ - a.z) / (b.z - a.z);
833
+ Corner &c = polygon[count++];
834
+ c.x = a.x + (b.x - a.x) * t;
835
+ c.y = a.y + (b.y - a.y) * t;
836
+ c.z = nearZ;
837
+ c.r = a.r + (b.r - a.r) * t;
838
+ c.g = a.g + (b.g - a.g) * t;
839
+ c.b = a.b + (b.b - a.b) * t;
840
+ }
841
+ }
842
+ if (count < 3) {
843
+ g_renderer.stats.clipDropped++;
844
+ return;
845
+ }
846
+
847
+ std::int32_t sx[4], sy[4];
848
+ float depth[4];
849
+ float key = 0.0f;
850
+ for (int i = 0; i < count; i++) {
851
+ project(g_renderer.view, polygon[i].x, polygon[i].y, polygon[i].z, &sx[i], &sy[i], &depth[i]);
852
+ key = maxFloat(key, -polygon[i].z);
853
+ }
854
+ for (int i = 2; i < count; i++) {
855
+ const Corner fan[3] = {polygon[0], polygon[i - 1], polygon[i]};
856
+ const std::int32_t fx[3] = {sx[0], sx[i - 1], sx[i]};
857
+ const std::int32_t fy[3] = {sy[0], sy[i - 1], sy[i]};
858
+ const float fd[3] = {depth[0], depth[i - 1], depth[i]};
859
+ emitTriangle(surface, fan, fx, fy, fd, key);
860
+ }
861
+ }
862
+
863
+ // Whether a mesh draw shades per face (flat shading, or lit without vertex
864
+ // normals); otherwise every corner takes its vertex's colour.
865
+ GEA3D_INLINE bool shadesPerFace(const Surface &surface, bool smoothLit)
866
+ {
867
+ return !surface.wireframe && !smoothLit && (surface.shade != 0 || surface.flat);
868
+ }
869
+
870
+ // Transforms, lights and projects every vertex of a draw once. Unless faces
871
+ // are shaded, each vertex also gets its final (lit, fogged) colour.
872
+ void transformVertices(const float *mv, const float *positions, std::size_t count, const float *colors, const float *normals, const Surface &surface, const float *tint, bool smoothLit, bool perVertex)
873
+ {
874
+ Vertex *vertices = g_renderer.vertices.prepare(count);
875
+ // Local copies: the compiler keeps them in registers, as vertex stores
876
+ // cannot alias them.
877
+ const View view = g_renderer.view;
878
+ float m[16];
879
+ std::memcpy(m, mv, sizeof(m));
880
+ const float nearZ = -view.near;
881
+ const bool fogged = surface.fog && g_renderer.environment.fog != 0;
882
+ const float tinted[3] = {surface.color[0] * tint[0], surface.color[1] * tint[1], surface.color[2] * tint[2]};
883
+
884
+ float normalMatrix[16];
885
+ if (normals) {
886
+ float inverse[16];
887
+ math::invertAffine(inverse, mv);
888
+ // Transpose of the inverse's 3x3.
889
+ normalMatrix[0] = inverse[0];
890
+ normalMatrix[4] = inverse[1];
891
+ normalMatrix[8] = inverse[2];
892
+ normalMatrix[1] = inverse[4];
893
+ normalMatrix[5] = inverse[5];
894
+ normalMatrix[9] = inverse[6];
895
+ normalMatrix[2] = inverse[8];
896
+ normalMatrix[6] = inverse[9];
897
+ normalMatrix[10] = inverse[10];
898
+ }
899
+
900
+ for (std::size_t i = 0; i < count; i++) {
901
+ // The attribute buffers live in slow memory: fetch a few vertices ahead.
902
+ __builtin_prefetch(positions + (i + 8) * 3);
903
+ if (colors) __builtin_prefetch(colors + (i + 8) * 3);
904
+ Vertex &vertex = vertices[i];
905
+ float *p = vertex.view;
906
+ math::transformPoint(m, positions[i * 3], positions[i * 3 + 1], positions[i * 3 + 2], p);
907
+ vertex.front = p[2] <= nearZ;
908
+ if (vertex.front) project(view, p[0], p[1], p[2], &vertex.screen[0], &vertex.screen[1], &vertex.depth);
909
+
910
+ float base[3] = {tinted[0], tinted[1], tinted[2]};
911
+ if (colors) {
912
+ base[0] *= colors[i * 3];
913
+ base[1] *= colors[i * 3 + 1];
914
+ base[2] *= colors[i * 3 + 2];
915
+ }
916
+ const float fog = fogged ? fogFactor(-p[2]) : 1.0f;
917
+ if (!perVertex) {
918
+ for (int k = 0; k < 3; k++) vertex.color[k] = base[k];
919
+ vertex.fog = fog;
920
+ continue;
921
+ }
922
+
923
+ float light[3] = {1.0f, 1.0f, 1.0f};
924
+ if (smoothLit) {
925
+ float n[3];
926
+ math::transformDirection(normalMatrix, normals[i * 3], normals[i * 3 + 1], normals[i * 3 + 2], n);
927
+ math::normalize3(n);
928
+ if (surface.shade == 2) normalColor(n, base);
929
+ else lightNormal(n, p, light);
930
+ }
931
+ shadeCorner(base, light, fog, vertex.color);
932
+ for (int k = 0; k < 3; k++) vertex.rgb[k] = toByte(vertex.color[k]);
933
+ vertex.fog = 1.0f;
934
+ }
935
+ }
936
+
937
+ // A triangle whose corners are all in front of the near plane and shaded
938
+ // per vertex: its record comes straight from the vertices.
939
+ void emitVertexTriangle(const Surface &surface, const Vertex &a, const Vertex &b, const Vertex &c)
940
+ {
941
+ Prim *prim = nextPrim();
942
+ if (!prim) return;
943
+
944
+ prim->type = raster::kTriangle;
945
+ const Vertex *corners[3] = {&a, &b, &c};
946
+ for (int i = 0; i < 3; i++) {
947
+ const Vertex &v = *corners[i];
948
+ prim->x[i] = v.screen[0];
949
+ prim->y[i] = v.screen[1];
950
+ prim->depth[i] = v.depth;
951
+ prim->r[i] = v.rgb[0];
952
+ prim->g[i] = v.rgb[1];
953
+ prim->b[i] = v.rgb[2];
954
+ }
955
+ prim->key = maxFloat(-a.view[2], maxFloat(-b.view[2], -c.view[2]));
956
+ finishPrim(*prim, surface, 3);
957
+ }
958
+
959
+ GEA3D_INLINE Corner cornerOf(const Vertex &vertex, const float *rgb)
960
+ {
961
+ const float *p = vertex.view;
962
+ return Corner{p[0], p[1], p[2], rgb[0], rgb[1], rgb[2]};
963
+ }
964
+
965
+ void emitTriangles(const Surface &surface, std::size_t vertexCount, const std::uint32_t *indices, std::size_t indexCount, bool smoothLit)
966
+ {
967
+ const Vertex *v = g_renderer.vertices.current;
968
+ Stats &stats = g_renderer.stats;
969
+ const bool orthographic = g_renderer.view.orthographic;
970
+ const std::size_t triangles = (indices ? indexCount : vertexCount) / 3;
971
+ const bool perFace = shadesPerFace(surface, smoothLit);
972
+ // Only culling and face lighting need to know which way a face points.
973
+ const bool needsFacing = surface.side != 2 || perFace || surface.wireframe;
974
+ stats.submitted += static_cast<int>(triangles);
975
+
976
+ for (std::size_t t = 0; t < triangles; t++) {
977
+ std::uint32_t id[3];
978
+ for (int k = 0; k < 3; k++) id[k] = indices ? indices[t * 3 + k] : static_cast<std::uint32_t>(t * 3 + k);
979
+ if (id[0] >= vertexCount || id[1] >= vertexCount || id[2] >= vertexCount) continue;
980
+
981
+ const Vertex &v0 = v[id[0]], &v1 = v[id[1]], &v2 = v[id[2]];
982
+ const float *p0 = v0.view;
983
+ const float *p1 = v1.view;
984
+ const float *p2 = v2.view;
985
+ if ((v0.front | v1.front | v2.front) == 0) {
986
+ stats.nearRejected++;
987
+ continue;
988
+ }
989
+
990
+ const bool inFront = (v0.front & v1.front & v2.front) != 0;
991
+ if (inFront && !surface.wireframe) {
992
+ const std::int32_t sx[3] = {v0.screen[0], v1.screen[0], v2.screen[0]};
993
+ const std::int32_t sy[3] = {v0.screen[1], v1.screen[1], v2.screen[1]};
994
+ if (!onScreen(sx, sy, 3, 0)) {
995
+ stats.culled++;
996
+ continue;
997
+ }
998
+ }
999
+
1000
+ float n[3] = {0, 0, 0};
1001
+ bool back = false;
1002
+ if (needsFacing) {
1003
+ const float e1[3] = {p1[0] - p0[0], p1[1] - p0[1], p1[2] - p0[2]};
1004
+ const float e2[3] = {p2[0] - p0[0], p2[1] - p0[1], p2[2] - p0[2]};
1005
+ n[0] = e1[1] * e2[2] - e1[2] * e2[1];
1006
+ n[1] = e1[2] * e2[0] - e1[0] * e2[2];
1007
+ n[2] = e1[0] * e2[1] - e1[1] * e2[0];
1008
+ const float facing = orthographic ? -n[2] : n[0] * p0[0] + n[1] * p0[1] + n[2] * p0[2];
1009
+ back = facing >= 0.0f;
1010
+ }
1011
+
1012
+ if (surface.wireframe) {
1013
+ const Corner c[3] = {cornerOf(v0, v0.color), cornerOf(v1, v1.color), cornerOf(v2, v2.color)};
1014
+ for (int k = 0; k < 3; k++) emitLine(surface, c[k], c[(k + 1) % 3]);
1015
+ continue;
1016
+ }
1017
+
1018
+ if ((surface.side == 0 && back) || (surface.side == 1 && !back)) {
1019
+ stats.culled++;
1020
+ continue;
1021
+ }
1022
+
1023
+ if (!perFace) {
1024
+ if (inFront) {
1025
+ emitVertexTriangle(surface, v0, v1, v2);
1026
+ continue;
1027
+ }
1028
+ const Corner c[3] = {cornerOf(v0, v0.color), cornerOf(v1, v1.color), cornerOf(v2, v2.color)};
1029
+ emitClipped(surface, c);
1030
+ continue;
1031
+ }
1032
+
1033
+ if (back) {
1034
+ n[0] = -n[0];
1035
+ n[1] = -n[1];
1036
+ n[2] = -n[2];
1037
+ }
1038
+
1039
+ float faceLight[3] = {1, 1, 1};
1040
+ float faceBase[3] = {0, 0, 0};
1041
+ const bool faceNormalColor = surface.shade == 2;
1042
+ if (surface.shade != 0 && math::normalize3(n)) {
1043
+ if (faceNormalColor) {
1044
+ normalColor(n, faceBase);
1045
+ } else {
1046
+ const float centroid[3] = {(p0[0] + p1[0] + p2[0]) / 3.0f, (p0[1] + p1[1] + p2[1]) / 3.0f, (p0[2] + p1[2] + p2[2]) / 3.0f};
1047
+ lightNormal(n, centroid, faceLight);
1048
+ }
1049
+ }
1050
+
1051
+ float faceBaseAverage[3] = {0, 0, 0};
1052
+ if (surface.flat && !faceNormalColor) {
1053
+ for (int j = 0; j < 3; j++) faceBaseAverage[j] = v0.color[j] * (1.0f / 3.0f);
1054
+ for (int j = 0; j < 3; j++) faceBaseAverage[j] += v1.color[j] * (1.0f / 3.0f);
1055
+ for (int j = 0; j < 3; j++) faceBaseAverage[j] += v2.color[j] * (1.0f / 3.0f);
1056
+ }
1057
+ Corner c[3];
1058
+ const Vertex *corners[3] = {&v0, &v1, &v2};
1059
+ for (int k = 0; k < 3; k++) {
1060
+ const Vertex &vertex = *corners[k];
1061
+ const float *base = faceNormalColor ? faceBase : (surface.flat ? faceBaseAverage : vertex.color);
1062
+ float rgb[3];
1063
+ shadeCorner(base, faceLight, vertex.fog, rgb);
1064
+ c[k] = cornerOf(vertex, rgb);
1065
+ }
1066
+
1067
+ if (inFront) {
1068
+ const std::int32_t sx[3] = {v0.screen[0], v1.screen[0], v2.screen[0]};
1069
+ const std::int32_t sy[3] = {v0.screen[1], v1.screen[1], v2.screen[1]};
1070
+ const float depth[3] = {v0.depth, v1.depth, v2.depth};
1071
+ const float key = maxFloat(-p0[2], maxFloat(-p1[2], -p2[2]));
1072
+ emitTriangle(surface, c, sx, sy, depth, key);
1073
+ } else {
1074
+ emitClipped(surface, c);
1075
+ }
1076
+ }
1077
+ }
1078
+
1079
+ void emitLines(const Surface &surface, std::size_t vertexCount, const std::uint32_t *indices, std::size_t indexCount, bool strip)
1080
+ {
1081
+ const Vertex *v = g_renderer.vertices.current;
1082
+ const std::size_t count = indices ? indexCount : vertexCount;
1083
+ const std::size_t segments = strip ? (count > 0 ? count - 1 : 0) : count / 2;
1084
+ for (std::size_t s = 0; s < segments; s++) {
1085
+ const std::size_t a = strip ? s : s * 2;
1086
+ const std::uint32_t ia = indices ? indices[a] : static_cast<std::uint32_t>(a);
1087
+ const std::uint32_t ib = indices ? indices[a + 1] : static_cast<std::uint32_t>(a + 1);
1088
+ if (ia >= vertexCount || ib >= vertexCount) continue;
1089
+
1090
+ emitLine(surface, cornerOf(v[ia], v[ia].color), cornerOf(v[ib], v[ib].color));
1091
+ }
1092
+ }
1093
+
1094
+ // A screen-aligned square of `sizePx` around a view-space point.
1095
+ void emitQuad(const Surface &surface, const float *p, float halfX, float halfY, const float *rgb, bool screenSpace)
1096
+ {
1097
+ const float nearZ = -g_renderer.view.near;
1098
+ if (p[2] > nearZ) {
1099
+ g_renderer.stats.nearRejected++;
1100
+ return;
1101
+ }
1102
+
1103
+ std::int32_t sx[4], sy[4];
1104
+ float depth[4];
1105
+ if (screenSpace) {
1106
+ std::int32_t cx = 0, cy = 0;
1107
+ float d = 0.0f;
1108
+ project(g_renderer.view, p[0], p[1], p[2], &cx, &cy, &d);
1109
+ const std::int32_t hx = static_cast<std::int32_t>(halfX * 16.0f);
1110
+ const std::int32_t hy = static_cast<std::int32_t>(halfY * 16.0f);
1111
+ const std::int32_t xs[4] = {cx - hx, cx + hx, cx + hx, cx - hx};
1112
+ const std::int32_t ys[4] = {cy - hy, cy - hy, cy + hy, cy + hy};
1113
+ for (int i = 0; i < 4; i++) {
1114
+ sx[i] = xs[i];
1115
+ sy[i] = ys[i];
1116
+ depth[i] = d;
1117
+ }
1118
+ } else {
1119
+ const float xs[4] = {p[0] - halfX, p[0] + halfX, p[0] + halfX, p[0] - halfX};
1120
+ const float ys[4] = {p[1] + halfY, p[1] + halfY, p[1] - halfY, p[1] - halfY};
1121
+ for (int i = 0; i < 4; i++) project(g_renderer.view, xs[i], ys[i], p[2], &sx[i], &sy[i], &depth[i]);
1122
+ }
1123
+
1124
+ const Corner c{p[0], p[1], p[2], rgb[0], rgb[1], rgb[2]};
1125
+ const Corner corners[3] = {c, c, c};
1126
+ const float key = -p[2];
1127
+ const std::int32_t ax[3] = {sx[0], sx[1], sx[2]}, ay[3] = {sy[0], sy[1], sy[2]};
1128
+ const float ad[3] = {depth[0], depth[1], depth[2]};
1129
+ emitTriangle(surface, corners, ax, ay, ad, key);
1130
+ const std::int32_t bx[3] = {sx[0], sx[2], sx[3]}, by[3] = {sy[0], sy[2], sy[3]};
1131
+ const float bd[3] = {depth[0], depth[2], depth[3]};
1132
+ emitTriangle(surface, corners, bx, by, bd, key);
1133
+ }
1134
+
1135
+ void emitPoints(const Surface &surface, std::size_t vertexCount)
1136
+ {
1137
+ const Vertex *v = g_renderer.vertices.current;
1138
+ const View &view = g_renderer.view;
1139
+ for (std::size_t i = 0; i < vertexCount; i++) {
1140
+ const float *p = v[i].view;
1141
+ float size = surface.size;
1142
+ if (surface.sizeAttenuation && !view.orthographic && p[2] < 0.0f) size = surface.size * view.halfH / -p[2];
1143
+ const float half = std::max(size * 0.5f, 0.5f);
1144
+ emitQuad(surface, p, half, half, v[i].color, true);
1145
+ }
1146
+ }
1147
+
1148
+ // ---------------------------------------------------------------- draws
1149
+
1150
+ // One draw of a node's geometry through modelView `mv` (instance `tint`).
1151
+ void drawGeometry(int kind, const Geometry &geometry, const Surface &surface, const float *mv, const float *tint)
1152
+ {
1153
+ const Buffer *positions = bufferAt(geometry.position);
1154
+ if (!positions || positions->f32.size() < 3) return;
1155
+
1156
+ const std::size_t vertexCount = positions->f32.size() / 3;
1157
+ const Buffer *indexBuffer = bufferAt(geometry.index);
1158
+ const std::uint32_t *indices = indexBuffer && !indexBuffer->u32.empty() ? indexBuffer->u32.data() : nullptr;
1159
+ const std::size_t indexCount = indices ? indexBuffer->u32.size() : 0;
1160
+ const Buffer *colorBuffer = surface.vertexColors ? bufferAt(geometry.color) : nullptr;
1161
+ const float *colors = colorBuffer && colorBuffer->f32.size() >= vertexCount * 3 ? colorBuffer->f32.data() : nullptr;
1162
+ const Buffer *normalBuffer = bufferAt(geometry.normal);
1163
+ const float *normals = normalBuffer && normalBuffer->f32.size() >= vertexCount * 3 ? normalBuffer->f32.data() : nullptr;
1164
+ const bool triangles = kind == kNodeMesh;
1165
+ const bool smoothLit = triangles && normals && !surface.flat && surface.shade != 0 && !surface.wireframe;
1166
+
1167
+ const bool perVertex = !triangles || !shadesPerFace(surface, smoothLit);
1168
+ transformVertices(mv, positions->f32.data(), vertexCount, colors, normals, surface, tint, smoothLit, perVertex);
1169
+ if (kind == kNodeMesh) emitTriangles(surface, vertexCount, indices, indexCount, smoothLit);
1170
+ else if (kind == kNodeLineSegments) emitLines(surface, vertexCount, indices, indexCount, false);
1171
+ else if (kind == kNodeLine) emitLines(surface, vertexCount, indices, indexCount, true);
1172
+ else if (kind == kNodePoints) emitPoints(surface, vertexCount);
1173
+ }
1174
+
1175
+ bool sphereVisible(const Geometry &geometry, const float *mv)
1176
+ {
1177
+ float center[3];
1178
+ math::transformPoint(mv, geometry.center[0], geometry.center[1], geometry.center[2], center);
1179
+ const float radius = geometry.radius * math::maxScaleOnAxis(mv);
1180
+ return math::sphereInFrustum(g_renderer.view.planes, center, radius);
1181
+ }
1182
+
1183
+ void drawSprite(const Surface &surface, const float *mv)
1184
+ {
1185
+ float center[3];
1186
+ math::transformPoint(mv, 0.0f, 0.0f, 0.0f, center);
1187
+ const float sx = std::sqrt(mv[0] * mv[0] + mv[1] * mv[1] + mv[2] * mv[2]);
1188
+ const float sy = std::sqrt(mv[4] * mv[4] + mv[5] * mv[5] + mv[6] * mv[6]);
1189
+ if (!math::sphereInFrustum(g_renderer.view.planes, center, std::max(sx, sy))) {
1190
+ g_renderer.stats.meshesCulled++;
1191
+ return;
1192
+ }
1193
+
1194
+ const float base[3] = {surface.color[0], surface.color[1], surface.color[2]};
1195
+ const float unlit[3] = {1, 1, 1};
1196
+ float rgb[3];
1197
+ shadeCorner(base, unlit, surface.fog && g_renderer.environment.fog != 0 ? fogFactor(-center[2]) : 1.0f, rgb);
1198
+ emitQuad(surface, center, sx * 0.5f, sy * 0.5f, rgb, false);
1199
+ g_renderer.stats.meshesDrawn++;
1200
+ }
1201
+
1202
+ void drawNode(const Node &node)
1203
+ {
1204
+ Material *material = lookup(g_materials, node.material);
1205
+ if (!material || !(material->flags & kMaterialVisible)) return;
1206
+
1207
+ Surface surface = resolveSurface(*material);
1208
+ surface.layer = node.renderOrder;
1209
+ float mv[16];
1210
+ if (node.kind == kNodeSprite) {
1211
+ math::multiplyAffine(mv, g_renderer.view.view, node.world);
1212
+ drawSprite(surface, mv);
1213
+ return;
1214
+ }
1215
+
1216
+ Geometry *geometry = lookup(g_geometries, node.geometry);
1217
+ if (!geometry) return;
1218
+
1219
+ updateBounds(*geometry);
1220
+ const float white[3] = {1, 1, 1};
1221
+ if (!node.instanced) {
1222
+ math::multiplyAffine(mv, g_renderer.view.view, node.world);
1223
+ if (node.frustumCulled && !sphereVisible(*geometry, mv)) {
1224
+ g_renderer.stats.meshesCulled++;
1225
+ return;
1226
+ }
1227
+ drawGeometry(node.kind, *geometry, surface, mv, white);
1228
+ g_renderer.stats.meshesDrawn++;
1229
+ return;
1230
+ }
1231
+
1232
+ const Buffer *instances = bufferAt(node.instanceMatrices);
1233
+ if (!instances) return;
1234
+
1235
+ const Buffer *tints = bufferAt(node.instanceColors);
1236
+ const int count = std::min(node.instanceCount, static_cast<int>(instances->f32.size() / 16));
1237
+ float viewWorld[16];
1238
+ math::multiplyAffine(viewWorld, g_renderer.view.view, node.world);
1239
+ for (int i = 0; i < count; i++) {
1240
+ math::multiplyAffine(mv, viewWorld, &instances->f32[static_cast<std::size_t>(i) * 16]);
1241
+ if (node.frustumCulled && !sphereVisible(*geometry, mv)) {
1242
+ g_renderer.stats.meshesCulled++;
1243
+ continue;
1244
+ }
1245
+ const float *tint = tints && tints->f32.size() >= static_cast<std::size_t>(i + 1) * 3 ? &tints->f32[static_cast<std::size_t>(i) * 3] : white;
1246
+ drawGeometry(node.kind, *geometry, surface, mv, tint);
1247
+ g_renderer.stats.meshesDrawn++;
1248
+ }
1249
+ }
1250
+
1251
+ // ---------------------------------------------------------------- frame setup
1252
+
1253
+ void beginFrameState(int width, int height)
1254
+ {
1255
+ Renderer &r = g_renderer;
1256
+ raster::Frame &frame = r.frame();
1257
+ frame.count = 0;
1258
+ frame.opaqueCount = 0;
1259
+ frame.blendCount = 0;
1260
+ frame.minLayer = INT_MAX;
1261
+ frame.maxLayer = INT_MIN;
1262
+ frame.width = width;
1263
+ frame.height = height;
1264
+ frame.depthBuffer = r.depthBuffer;
1265
+ r.stats = Stats();
1266
+ r.lights.reset();
1267
+ r.view.width = width;
1268
+ r.view.height = height;
1269
+ r.view.halfW = static_cast<float>(width) * 0.5f;
1270
+ r.view.halfH = static_cast<float>(height) * 0.5f;
1271
+ }
1272
+
1273
+ void setProjection(const float *projection, float near, float far)
1274
+ {
1275
+ View &v = g_renderer.view;
1276
+ std::memcpy(v.projection, projection, sizeof(v.projection));
1277
+ v.near = near < 0.0001f ? 0.0001f : near;
1278
+ v.far = far;
1279
+ v.orthographic = projection[15] == 1.0f && projection[11] == 0.0f;
1280
+ math::frustumPlanes(v.projection, v.planes);
1281
+ }
1282
+
1283
+ void addLight(const Node &node)
1284
+ {
1285
+ Lights &lights = g_renderer.lights;
1286
+ const float *view = g_renderer.view.view;
1287
+ const float color[3] = {node.lightColor[0] * node.intensity, node.lightColor[1] * node.intensity, node.lightColor[2] * node.intensity};
1288
+ const float *world = node.world;
1289
+
1290
+ if (node.lightKind == kLightDirectional && lights.directionalCount < kMaxLights) {
1291
+ float direction[3];
1292
+ math::transformDirection(view, world[12] - node.target[0], world[13] - node.target[1], world[14] - node.target[2], direction);
1293
+ if (!math::normalize3(direction)) return;
1294
+ const int i = lights.directionalCount++;
1295
+ std::memcpy(lights.direction[i], direction, sizeof(direction));
1296
+ std::memcpy(lights.directionalColor[i], color, sizeof(color));
1297
+ } else if (node.lightKind == kLightPoint && lights.pointCount < kMaxLights) {
1298
+ const int i = lights.pointCount++;
1299
+ math::transformPoint(view, world[12], world[13], world[14], lights.pointPosition[i]);
1300
+ std::memcpy(lights.pointColor[i], color, sizeof(color));
1301
+ lights.pointDistance[i] = node.distance;
1302
+ lights.pointDecay[i] = node.decay;
1303
+ } else if (node.lightKind == kLightHemisphere && lights.hemisphereCount < kMaxLights) {
1304
+ float up[3];
1305
+ math::transformDirection(view, world[12], world[13], world[14], up);
1306
+ if (!math::normalize3(up)) {
1307
+ math::transformDirection(view, 0.0f, 1.0f, 0.0f, up);
1308
+ math::normalize3(up);
1309
+ }
1310
+ const int i = lights.hemisphereCount++;
1311
+ std::memcpy(lights.hemisphereUp[i], up, sizeof(up));
1312
+ std::memcpy(lights.sky[i], color, sizeof(color));
1313
+ for (int k = 0; k < 3; k++) lights.ground[i][k] = node.groundColor[k] * node.intensity;
1314
+ } else if (node.lightKind == kLightAmbient) {
1315
+ for (int k = 0; k < 3; k++) lights.ambient[k] += color[k];
1316
+ }
1317
+ }
1318
+
1319
+ // Updates world matrices below `root` and collects what it draws and lights.
1320
+ void collect(int root)
1321
+ {
1322
+ std::vector<int> &stack = g_renderer.stack;
1323
+ std::vector<int> &drawables = g_renderer.drawables;
1324
+ std::vector<int> &lightNodes = g_renderer.lightNodes;
1325
+ stack.clear();
1326
+ drawables.clear();
1327
+ lightNodes.clear();
1328
+ stack.push_back(root);
1329
+ while (!stack.empty()) {
1330
+ const int id = stack.back();
1331
+ stack.pop_back();
1332
+ Node &node = g_nodes[static_cast<std::size_t>(id)];
1333
+ if (!node.visible) continue;
1334
+
1335
+ refreshWorld(node);
1336
+ if (node.kind == kNodeLight) lightNodes.push_back(id);
1337
+ else if (node.kind != kNodeGroup && node.kind != kNodeCamera) drawables.push_back(id);
1338
+ for (int child = node.firstChild; child >= 0; child = g_nodes[static_cast<std::size_t>(child)].nextSibling) stack.push_back(child);
1339
+ }
1340
+ }
1341
+
1342
+ // Frame::rows for the sorted order.
1343
+ void packRowRanges(raster::Frame &frame)
1344
+ {
1345
+ frame.rowStore.resize(static_cast<std::size_t>(frame.count));
1346
+ std::uint32_t *rows = frame.rowStore.data();
1347
+ for (int i = 0; i < frame.count; i++) rows[i] = frame.emittedRows[static_cast<std::size_t>(frame.order[static_cast<std::size_t>(i)])];
1348
+ frame.rows = rows;
1349
+ }
1350
+
1351
+ // Stably reorders frame.order[first, last) by renderOrder, keeping the depth
1352
+ // order within each layer: highest layer first for the nearest-first opaque
1353
+ // run, lowest first for the farthest-first blended run.
1354
+ void orderLayers(raster::Frame &frame, int first, int last, bool highestFirst)
1355
+ {
1356
+ const std::int32_t *layers = frame.layers.data();
1357
+ std::int32_t *order = frame.order.data() + first;
1358
+ const int count = last - first;
1359
+ const int minLayer = frame.minLayer;
1360
+ const int range = frame.maxLayer - minLayer;
1361
+ if (count < 2) return;
1362
+
1363
+ if (range >= kLayerCountingRange) {
1364
+ std::stable_sort(order, order + count, [layers, highestFirst](std::int32_t a, std::int32_t b) { return highestFirst ? layers[a] > layers[b] : layers[a] < layers[b]; });
1365
+ return;
1366
+ }
1367
+
1368
+ Renderer &r = g_renderer;
1369
+ std::vector<std::int32_t> &counts = r.layerCounts;
1370
+ counts.assign(static_cast<std::size_t>(range + 2), 0);
1371
+ for (int i = 0; i < count; i++) {
1372
+ const int rank = layers[order[i]] - minLayer;
1373
+ counts[static_cast<std::size_t>((highestFirst ? range - rank : rank) + 1)]++;
1374
+ }
1375
+ for (int b = 1; b <= range + 1; b++) counts[static_cast<std::size_t>(b)] += counts[static_cast<std::size_t>(b - 1)];
1376
+ std::vector<std::int32_t> &sorted = r.layerOrder;
1377
+ sorted.resize(static_cast<std::size_t>(count));
1378
+ for (int i = 0; i < count; i++) {
1379
+ const int rank = layers[order[i]] - minLayer;
1380
+ sorted[static_cast<std::size_t>(counts[static_cast<std::size_t>(highestFirst ? range - rank : rank)]++)] = order[i];
1381
+ }
1382
+ std::memcpy(order, sorted.data(), static_cast<std::size_t>(count) * sizeof(std::int32_t));
1383
+ }
1384
+
1385
+ // Nearest-first order for opaque primitives, farthest-first for blended;
1386
+ // by renderOrder first when the frame has several (three.js's order).
1387
+ // Reads only the dense key arrays, never the primitive records.
1388
+ void sortFrame()
1389
+ {
1390
+ Renderer &r = g_renderer;
1391
+ raster::Frame &frame = r.frame();
1392
+ const int n = frame.count;
1393
+ frame.order.resize(static_cast<std::size_t>(n));
1394
+ r.keys.resize(static_cast<std::size_t>(n));
1395
+ r.bucketStarts.assign(2 * (kDepthBuckets + 1), 0);
1396
+ frame.opaqueCount = 0;
1397
+ frame.blendCount = 0;
1398
+ if (n == 0) {
1399
+ packRowRanges(frame);
1400
+ return;
1401
+ }
1402
+
1403
+ const float *keys = frame.sortKeys.data();
1404
+ const std::uint8_t *blended = frame.blended.data();
1405
+ float lo = keys[0], hi = lo;
1406
+ for (int i = 1; i < n; i++) {
1407
+ lo = keys[i] < lo ? keys[i] : lo;
1408
+ hi = keys[i] > hi ? keys[i] : hi;
1409
+ }
1410
+ const float range = hi - lo;
1411
+ const float scale = range > 0.000001f ? static_cast<float>(kDepthBuckets - 1) / range : 0.0f;
1412
+
1413
+ // One counting sort over [opaque buckets | blended buckets]. Opaque is the
1414
+ // exact reverse of the painter's order, ties included (later primitives
1415
+ // win a tie, as they would painting back-to-front), so opaque keys count
1416
+ // down from the far end and are placed walking the store backwards.
1417
+ std::int32_t *counts = r.bucketStarts.data();
1418
+ int blendedCount = 0;
1419
+ for (int i = 0; i < n; i++) {
1420
+ const int painter = minInt(static_cast<int>((hi - keys[i]) * scale), kDepthBuckets - 1);
1421
+ const int bucket = blended[i] ? kDepthBuckets + 1 + painter : kDepthBuckets - 1 - painter;
1422
+ r.keys[static_cast<std::size_t>(i)] = bucket;
1423
+ counts[bucket + 1]++;
1424
+ blendedCount += blended[i];
1425
+ }
1426
+ frame.opaqueCount = n - blendedCount;
1427
+ frame.blendCount = blendedCount;
1428
+ for (int b = 1; b <= 2 * kDepthBuckets + 1; b++) counts[b] += counts[b - 1];
1429
+ for (int k = 0; k < n; k++) {
1430
+ const int i = n - 1 - k;
1431
+ if (blended[i]) continue;
1432
+ frame.order[static_cast<std::size_t>(counts[r.keys[static_cast<std::size_t>(i)]]++)] = i;
1433
+ }
1434
+ for (int i = 0; i < n; i++) {
1435
+ if (!blended[i]) continue;
1436
+ frame.order[static_cast<std::size_t>(counts[r.keys[static_cast<std::size_t>(i)]]++)] = i;
1437
+ }
1438
+ if (frame.minLayer < frame.maxLayer) {
1439
+ orderLayers(frame, 0, frame.opaqueCount, true);
1440
+ orderLayers(frame, frame.opaqueCount, n, false);
1441
+ }
1442
+ packRowRanges(frame);
1443
+ }
1444
+
1445
+ // ---------------------------------------------------------------- present
1446
+
1447
+ // One band row out to the target: 32-byte blocks (LDM/STM bursts on
1448
+ // Cortex-M) when both ends are word aligned, else memcpy.
1449
+ GEA3D_INLINE void copyRow(Pixel *dst, const Pixel *src, std::size_t bytes)
1450
+ {
1451
+ struct Block {
1452
+ std::uint32_t words[8];
1453
+ };
1454
+ if (((reinterpret_cast<std::uintptr_t>(dst) | reinterpret_cast<std::uintptr_t>(src)) & 3u) != 0) {
1455
+ std::memcpy(dst, src, bytes);
1456
+ return;
1457
+ }
1458
+ Block *to = reinterpret_cast<Block *>(dst);
1459
+ const Block *from = reinterpret_cast<const Block *>(src);
1460
+ const std::size_t blocks = bytes / sizeof(Block);
1461
+ for (std::size_t i = 0; i < blocks; i++) to[i] = from[i];
1462
+ const std::size_t done = blocks * sizeof(Block);
1463
+ std::memcpy(reinterpret_cast<std::uint8_t *>(dst) + done, reinterpret_cast<const std::uint8_t *>(src) + done, bytes - done);
1464
+ }
1465
+
1466
+ #if GEA3D_DMA2D_COPY
1467
+ // Band copy-out on DMA2D (RGB565, memory to memory). A copy starts once the
1468
+ // previous one (or the engine's own DMA2D work) is done. The data cache is
1469
+ // cleaned before the first copy (no dirty line may later overwrite what DMA2D
1470
+ // wrote) and dropped after the last (no stale line may be read): whole-cache
1471
+ // operations, since the 4 KB cache holds far fewer lines than the target.
1472
+ static_assert(sizeof(Pixel) == 2, "DMA2D band copies are RGB565");
1473
+
1474
+ void waitBandCopy()
1475
+ {
1476
+ while ((DMA2D->CR & DMA2D_CR_START) != 0) {}
1477
+ }
1478
+
1479
+ void startBandCopy(Pixel *dst, int stride, const Pixel *src, int width, int rows)
1480
+ {
1481
+ waitBandCopy();
1482
+ __DSB();
1483
+ constexpr std::uint32_t kRgb565 = 2;
1484
+ DMA2D->CR = 0;
1485
+ DMA2D->FGPFCCR = kRgb565;
1486
+ DMA2D->FGMAR = reinterpret_cast<std::uint32_t>(src);
1487
+ DMA2D->FGOR = 0;
1488
+ DMA2D->OPFCCR = kRgb565;
1489
+ DMA2D->OMAR = reinterpret_cast<std::uint32_t>(dst);
1490
+ DMA2D->OOR = static_cast<std::uint32_t>(stride - width);
1491
+ DMA2D->NLR = (static_cast<std::uint32_t>(width) << DMA2D_NLR_PL_Pos) | static_cast<std::uint32_t>(rows);
1492
+ DMA2D->CR |= DMA2D_CR_START;
1493
+ }
1494
+ #endif
1495
+
1496
+ // Each band's primitives in sorted order (Bands::items[starts[b]..starts[b+1]),
1497
+ // the first opaque[b] of them opaque), so a band never visits the primitives
1498
+ // that miss it and reads no sort order.
1499
+ void buildBandLists(const raster::Frame &frame, int y0, int y1, Bands &bands)
1500
+ {
1501
+ const int count = (y1 - y0) / bands.rows + 1;
1502
+ bands.bandOfRow.resize(static_cast<std::size_t>(y1 - y0 + 1));
1503
+ for (int y = y0; y <= y1; y++) bands.bandOfRow[static_cast<std::size_t>(y - y0)] = (y - y0) / bands.rows;
1504
+ bands.starts.assign(static_cast<std::size_t>(count + 1), 0);
1505
+ bands.opaque.assign(static_cast<std::size_t>(count), 0);
1506
+
1507
+ const int *bandOf = bands.bandOfRow.data();
1508
+ int *starts = bands.starts.data();
1509
+ for (int i = 0; i < frame.count; i++) {
1510
+ const int first = maxInt(static_cast<std::int16_t>(frame.rows[i] & 0xFFFFu), y0);
1511
+ const int last = minInt(static_cast<std::int16_t>(frame.rows[i] >> 16), y1);
1512
+ if (first > last) continue;
1513
+ for (int b = bandOf[first - y0]; b <= bandOf[last - y0]; b++) starts[b + 1]++;
1514
+ }
1515
+ for (int b = 0; b < count; b++) starts[b + 1] += starts[b];
1516
+
1517
+ bands.items.resize(static_cast<std::size_t>(starts[count]));
1518
+ bands.next.assign(bands.starts.begin(), bands.starts.end() - 1);
1519
+ int *next = bands.next.data();
1520
+ int *opaque = bands.opaque.data();
1521
+ std::int32_t *items = bands.items.data();
1522
+ for (int i = 0; i < frame.count; i++) {
1523
+ const int first = maxInt(static_cast<std::int16_t>(frame.rows[i] & 0xFFFFu), y0);
1524
+ const int last = minInt(static_cast<std::int16_t>(frame.rows[i] >> 16), y1);
1525
+ if (first > last) continue;
1526
+ const bool isOpaque = i < frame.opaqueCount;
1527
+ const std::int32_t prim = frame.order[static_cast<std::size_t>(i)];
1528
+ for (int b = bandOf[first - y0]; b <= bandOf[last - y0]; b++) {
1529
+ items[next[b]++] = prim;
1530
+ opaque[b] += isOpaque;
1531
+ }
1532
+ }
1533
+ }
1534
+
1535
+ raster::BandList bandList(const Bands &bands, int band)
1536
+ {
1537
+ const std::size_t at = static_cast<std::size_t>(band);
1538
+ const int start = bands.starts[at];
1539
+ return raster::BandList{bands.items.data() + start, bands.starts[at + 1] - start, bands.opaque[at]};
1540
+ }
1541
+
1542
+ // Rasterizes the frame's viewport part of [x0..x1] x [y0..y1].
1543
+ void rasterizeInto(const raster::Frame &frame, Pixel *base, int stride, int x0, int y0, int x1, int y1)
1544
+ {
1545
+ x1 = std::min(x1, frame.width - 1);
1546
+ y1 = std::min(y1, frame.height - 1);
1547
+ if (x0 > x1 || y0 > y1) return;
1548
+
1549
+ Bands &bands = g_renderer.bands;
1550
+ const int width = x1 - x0 + 1;
1551
+ if (!bands.pixels || width > bands.width) {
1552
+ raster::Rasterizer rasterizer(frame, g_renderer.scratch, base, stride, x0, y0, x1, y1);
1553
+ rasterizer.run();
1554
+ return;
1555
+ }
1556
+
1557
+ buildBandLists(frame, y0, y1, bands);
1558
+ const std::size_t rowBytes = static_cast<std::size_t>(width) * sizeof(Pixel);
1559
+ const bool keepUnder = frame.background.mode == raster::kBackgroundNone;
1560
+ #if GEA3D_DMA2D_COPY
1561
+ if (bands.spare) SCB_CleanInvalidateDCache();
1562
+ #endif
1563
+ int band = 0;
1564
+ for (int bandY = y0; bandY <= y1; bandY += bands.rows, band++) {
1565
+ const int bandLast = minInt(bandY + bands.rows - 1, y1);
1566
+ Pixel *buffer = (band & 1) != 0 && bands.spare ? bands.spare : bands.pixels;
1567
+ // The band buffer addressed in screen coordinates, stride = width.
1568
+ Pixel *bandBase = buffer - (static_cast<std::ptrdiff_t>(bandY) * width + x0);
1569
+ Pixel *target = base + static_cast<std::ptrdiff_t>(bandY) * stride + x0;
1570
+ const int rows = bandLast - bandY + 1;
1571
+ if (keepUnder) {
1572
+ for (int y = 0; y < rows; y++) std::memcpy(buffer + static_cast<std::ptrdiff_t>(y) * width, target + static_cast<std::ptrdiff_t>(y) * stride, rowBytes);
1573
+ }
1574
+ raster::Rasterizer rasterizer(frame, g_renderer.scratch, bandBase, width, x0, bandY, x1, bandLast, raster::Occlusion::kPainter);
1575
+ rasterizer.runPainter(bandList(bands, band));
1576
+ #if GEA3D_DMA2D_COPY
1577
+ if (bands.spare) {
1578
+ startBandCopy(target, stride, buffer, width, rows);
1579
+ continue;
1580
+ }
1581
+ #endif
1582
+ for (int y = 0; y < rows; y++) copyRow(target + static_cast<std::ptrdiff_t>(y) * stride, buffer + static_cast<std::ptrdiff_t>(y) * width, rowBytes);
1583
+ }
1584
+ #if GEA3D_DMA2D_COPY
1585
+ if (bands.spare) {
1586
+ waitBandCopy();
1587
+ SCB_CleanInvalidateDCache();
1588
+ }
1589
+ #endif
1590
+ }
1591
+
1592
+ // Display::flushRectsRasterized chunk: pixels hold rows [oy, oy + h) of a
1593
+ // full-width band, so the chunk width is its stride.
1594
+ void rasterChunk(Pixel *pixels, int width, int height, int ox, int oy, void *user)
1595
+ {
1596
+ const raster::Frame &frame = *static_cast<const raster::Frame *>(user);
1597
+ Pixel *base = pixels - (static_cast<std::ptrdiff_t>(oy) * width + ox);
1598
+ rasterizeInto(frame, base, width, ox, oy, ox + width - 1, oy + height - 1);
1599
+ }
1600
+
1601
+ int displayWidth(int fallback)
1602
+ {
1603
+ auto *canvas = pd::Display::canvas();
1604
+ const int width = canvas ? canvas->width() : 0;
1605
+ return width > 0 ? width : fallback;
1606
+ }
1607
+
1608
+ bool presentDirect(raster::Frame &frame)
1609
+ {
1610
+ if (frame.width <= 0 || frame.height <= 0) return false;
1611
+
1612
+ const pd::DisplayFlushRect rect{0, 0, displayWidth(frame.width) - 1, frame.height - 1};
1613
+ pd::Display::flushRectsRasterized(&rect, 1, rasterChunk, &frame, true);
1614
+ pd::Display::rebindCanvasToFramebuffer();
1615
+ return true;
1616
+ }
1617
+
1618
+ #if GEA3D_PRESENT_COMMANDS
1619
+ std::vector<gea::framework::graphics::TriangleEntry> g_entries;
1620
+
1621
+ bool presentCommands(raster::Frame &frame)
1622
+ {
1623
+ g_entries.clear();
1624
+ for (int i = frame.count - 1; i >= 0; i--) {
1625
+ const Prim &prim = frame.prims[frame.order[static_cast<std::size_t>(i)]];
1626
+ if (prim.type != raster::kTriangle) continue;
1627
+ gea::framework::graphics::TriangleEntry entry{};
1628
+ entry.x0 = static_cast<std::int16_t>(prim.x[0] >> 4);
1629
+ entry.y0 = static_cast<std::int16_t>(prim.y[0] >> 4);
1630
+ entry.x1 = static_cast<std::int16_t>(prim.x[1] >> 4);
1631
+ entry.y1 = static_cast<std::int16_t>(prim.y[1] >> 4);
1632
+ entry.x2 = static_cast<std::int16_t>(prim.x[2] >> 4);
1633
+ entry.y2 = static_cast<std::int16_t>(prim.y[2] >> 4);
1634
+ entry.color = prim.color;
1635
+ entry.rowY0 = prim.rowY0;
1636
+ entry.rowY1 = prim.rowY1;
1637
+ g_entries.push_back(entry);
1638
+ }
1639
+ pd::DisplayPresentCommand commands[2];
1640
+ int count = 0;
1641
+ const raster::Background &bg = frame.background;
1642
+ if (bg.mode != raster::kBackgroundNone) {
1643
+ commands[count] = {};
1644
+ commands[count].type = pd::DisplayPresentCommandType::FillRectRgb565;
1645
+ commands[count].fillRectRgb565 = {0, 0, frame.width, frame.height, raster::detail::packColor(bg.top[0], bg.top[1], bg.top[2]), 255};
1646
+ count++;
1647
+ }
1648
+ commands[count] = {};
1649
+ commands[count].type = pd::DisplayPresentCommandType::FillTrianglesRgb565;
1650
+ commands[count].fillTrianglesRgb565.entries = g_entries.data();
1651
+ commands[count].fillTrianglesRgb565.count = static_cast<int>(g_entries.size());
1652
+ commands[count].fillTrianglesRgb565.alpha = 255;
1653
+ count++;
1654
+ return pd::Display::present(commands, count);
1655
+ }
1656
+ #endif
1657
+
1658
+ #if GEA3D_UNDERLAY && !GEA3D_PRESENT_COMMANDS
1659
+ // Engine callback: paints the last frame into the display canvas, clipped to
1660
+ // the canvas's current clip (a dirty region or one flush band).
1661
+ void paintUnderlay(int x0, int y0, int x1, int y1, void *user)
1662
+ {
1663
+ auto *canvas = pd::Display::canvas();
1664
+ if (!canvas || !canvas->pixels()) return;
1665
+
1666
+ int cx0 = 0, cy0 = 0, cx1 = -1, cy1 = -1;
1667
+ canvas->currentClip(&cx0, &cy0, &cx1, &cy1);
1668
+ x0 = std::max({x0, cx0, 0});
1669
+ y0 = std::max({y0, cy0, 0});
1670
+ x1 = std::min({x1, cx1, canvas->width() - 1});
1671
+ y1 = std::min({y1, cy1, canvas->height() - 1});
1672
+ if (x0 > x1 || y0 > y1) return;
1673
+
1674
+ const int stride = canvas->strideBytes() / static_cast<int>(sizeof(Pixel));
1675
+ rasterizeInto(*static_cast<const raster::Frame *>(user), canvas->pixels(), stride, x0, y0, x1, y1);
1676
+ }
1677
+
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;
1684
+
1685
+ 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);
1687
+ return true;
1688
+ }
1689
+ #endif
1690
+
1691
+ bool presentSurface(raster::Frame &frame)
1692
+ {
1693
+ const int slot = g_surfaces.find(g_renderer.surface);
1694
+ if (slot < 0) return false;
1695
+
1696
+ const int width = g_surfaces.width[slot];
1697
+ const int height = g_surfaces.height[slot];
1698
+ rasterizeInto(frame, g_surfaces.pixels[slot], width, 0, 0, std::min(width, frame.width) - 1, std::min(height, frame.height) - 1);
1699
+ return true;
1700
+ }
1701
+
1702
+ #if GEA3D_ASYNC_PRESENT
1703
+ TaskHandle_t g_presentTask = nullptr;
1704
+ SemaphoreHandle_t g_presentWork = nullptr;
1705
+ SemaphoreHandle_t g_presentDone = nullptr;
1706
+ raster::Frame *g_presentFrame = nullptr;
1707
+ volatile bool g_presentOk = true;
1708
+
1709
+ void presentTaskMain(void *)
1710
+ {
1711
+ for (;;) {
1712
+ xSemaphoreTake(g_presentWork, portMAX_DELAY);
1713
+ g_presentOk = presentDirect(*g_presentFrame);
1714
+ xSemaphoreGive(g_presentDone);
1715
+ }
1716
+ }
1717
+
1718
+ bool ensurePresentTask()
1719
+ {
1720
+ if (g_presentTask) return true;
1721
+ g_presentWork = xSemaphoreCreateBinary();
1722
+ g_presentDone = xSemaphoreCreateBinary();
1723
+ if (!g_presentWork || !g_presentDone) return false;
1724
+ // "Done" starts available: the first frame must not wait.
1725
+ xSemaphoreGive(g_presentDone);
1726
+ const BaseType_t ok = xTaskCreatePinnedToCore(presentTaskMain, "gea3d_present", 12288, nullptr, 20, &g_presentTask, 0);
1727
+ return ok == pdPASS;
1728
+ }
1729
+
1730
+ // Blocks until the previous asynchronous present released its frame.
1731
+ void waitForPresent()
1732
+ {
1733
+ if (!g_presentTask) return;
1734
+ xSemaphoreTake(g_presentDone, portMAX_DELAY);
1735
+ xSemaphoreGive(g_presentDone);
1736
+ }
1737
+ #else
1738
+ void waitForPresent() {}
1739
+ #endif
1740
+
1741
+ // Hands the built frame to its destination. Returns false when rejected.
1742
+ bool present()
1743
+ {
1744
+ Renderer &r = g_renderer;
1745
+ raster::Frame &frame = r.frame();
1746
+ r.stats.primitives = frame.count;
1747
+
1748
+ if (r.surface >= 0) {
1749
+ waitForPresent();
1750
+ return presentSurface(frame);
1751
+ }
1752
+ #if GEA3D_PRESENT_COMMANDS
1753
+ return presentCommands(frame);
1754
+ #else
1755
+ #if GEA3D_UNDERLAY
1756
+ waitForPresent();
1757
+ if (presentUnderlay(frame)) {
1758
+ r.stats.composited = 1;
1759
+ return true;
1760
+ }
1761
+ gea::framework::display::Underlay::clear();
1762
+ #endif
1763
+ #if GEA3D_ASYNC_PRESENT
1764
+ if (ensurePresentTask()) {
1765
+ // Wait for frame N-1, hand frame N to core 0 and build N+1 in the
1766
+ // other slot while it streams.
1767
+ xSemaphoreTake(g_presentDone, portMAX_DELAY);
1768
+ const bool previousOk = g_presentOk;
1769
+ g_presentFrame = &frame;
1770
+ xSemaphoreGive(g_presentWork);
1771
+ r.building ^= 1;
1772
+ return previousOk;
1773
+ }
1774
+ #endif
1775
+ return presentDirect(frame);
1776
+ #endif
1777
+ }
1778
+
1779
+ void setBackground(raster::Background &background, double bgColor)
1780
+ {
1781
+ if (bgColor < 0) {
1782
+ background.mode = raster::kBackgroundNone;
1783
+ return;
1784
+ }
1785
+ background.mode = raster::kBackgroundFlat;
1786
+ hexToRgb(bgColor, background.top);
1787
+ std::memcpy(background.bottom, background.top, sizeof(background.top));
1788
+ }
1789
+
1790
+ } // namespace
1791
+
1792
+ // ================================================================ buffers
1793
+
1794
+ double createBuffer()
1795
+ {
1796
+ return allocate(g_buffers);
1797
+ }
1798
+
1799
+ void deleteBuffer(double buffer)
1800
+ {
1801
+ Buffer *slot = lookup(g_buffers, buffer);
1802
+ if (slot) *slot = Buffer();
1803
+ }
1804
+
1805
+ void bufferDataF32Raw(double buffer, const float *data, std::size_t count)
1806
+ {
1807
+ Buffer *slot = lookup(g_buffers, buffer);
1808
+ if (!slot) return;
1809
+ slot->f32.assign(data, data + count);
1810
+ slot->version++;
1811
+ }
1812
+
1813
+ void bufferDataU32Raw(double buffer, const std::uint32_t *data, std::size_t count)
1814
+ {
1815
+ Buffer *slot = lookup(g_buffers, buffer);
1816
+ if (!slot) return;
1817
+ slot->u32.assign(data, data + count);
1818
+ slot->version++;
1819
+ }
1820
+
1821
+ // ================================================================ geometry / material
1822
+
1823
+ double createGeometry()
1824
+ {
1825
+ return allocate(g_geometries);
1826
+ }
1827
+
1828
+ void deleteGeometry(double geometry)
1829
+ {
1830
+ Geometry *slot = lookup(g_geometries, geometry);
1831
+ if (slot) *slot = Geometry();
1832
+ }
1833
+
1834
+ void geometryBuffers(double geometry, double position, double index, double color, double normal)
1835
+ {
1836
+ Geometry *slot = lookup(g_geometries, geometry);
1837
+ if (!slot) return;
1838
+ slot->position = static_cast<int>(position);
1839
+ slot->index = static_cast<int>(index);
1840
+ slot->color = static_cast<int>(color);
1841
+ slot->normal = static_cast<int>(normal);
1842
+ slot->radius = -1.0f;
1843
+ }
1844
+
1845
+ double createMaterial()
1846
+ {
1847
+ return allocate(g_materials);
1848
+ }
1849
+
1850
+ void deleteMaterial(double material)
1851
+ {
1852
+ Material *slot = lookup(g_materials, material);
1853
+ if (slot) *slot = Material();
1854
+ }
1855
+
1856
+ void materialSet(double material, double shade, double r, double g, double b, double opacity, double side, double flags, double size)
1857
+ {
1858
+ Material *slot = lookup(g_materials, material);
1859
+ if (!slot) return;
1860
+ slot->shade = static_cast<int>(shade);
1861
+ const double rgb[3] = {r, g, b};
1862
+ for (int k = 0; k < 3; k++) slot->color[k] = clampFloat(static_cast<float>(rgb[k] * 255.0), 0.0f, 255.0f);
1863
+ slot->opacity = static_cast<float>(opacity);
1864
+ slot->side = static_cast<int>(side);
1865
+ slot->flags = static_cast<int>(flags);
1866
+ slot->size = static_cast<float>(size);
1867
+ }
1868
+
1869
+ // ================================================================ nodes
1870
+
1871
+ double createNode(double kind)
1872
+ {
1873
+ const int id = allocate(g_nodes);
1874
+ g_nodes[static_cast<std::size_t>(id)].kind = static_cast<int>(kind);
1875
+ return id;
1876
+ }
1877
+
1878
+ void deleteNode(double node)
1879
+ {
1880
+ Node *slot = lookup(g_nodes, node);
1881
+ if (!slot) return;
1882
+
1883
+ const int id = static_cast<int>(node);
1884
+ unlink(id);
1885
+ while (slot->firstChild >= 0) unlink(slot->firstChild);
1886
+ *slot = Node();
1887
+ }
1888
+
1889
+ void nodeParent(double node, double parent)
1890
+ {
1891
+ if (!lookup(g_nodes, node)) return;
1892
+
1893
+ const int id = static_cast<int>(node);
1894
+ const int parentId = static_cast<int>(parent);
1895
+ const bool attach = lookup(g_nodes, parent) != nullptr && !isAncestor(id, parentId);
1896
+ if (g_nodes[static_cast<std::size_t>(id)].parent == (attach ? parentId : -1)) return;
1897
+
1898
+ unlink(id);
1899
+ if (attach) link(id, parentId);
1900
+ }
1901
+
1902
+ 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
+ {
1904
+ Node *slot = lookup(g_nodes, node);
1905
+ if (!slot) return;
1906
+ const float position[3] = {static_cast<float>(px), static_cast<float>(py), static_cast<float>(pz)};
1907
+ const float quaternion[4] = {static_cast<float>(qx), static_cast<float>(qy), static_cast<float>(qz), static_cast<float>(qw)};
1908
+ const float scale[3] = {static_cast<float>(sx), static_cast<float>(sy), static_cast<float>(sz)};
1909
+ // An unchanged transform keeps the cached world matrices.
1910
+ const bool same = !slot->useMatrix && std::memcmp(slot->position, position, sizeof(position)) == 0 &&
1911
+ std::memcmp(slot->quaternion, quaternion, sizeof(quaternion)) == 0 && std::memcmp(slot->scale, scale, sizeof(scale)) == 0;
1912
+ if (same) return;
1913
+
1914
+ std::memcpy(slot->position, position, sizeof(position));
1915
+ std::memcpy(slot->quaternion, quaternion, sizeof(quaternion));
1916
+ std::memcpy(slot->scale, scale, sizeof(scale));
1917
+ slot->useMatrix = false;
1918
+ slot->localDirty = true;
1919
+ }
1920
+
1921
+ void nodeMatrixRaw(double node, const float *elements, std::size_t count)
1922
+ {
1923
+ Node *slot = lookup(g_nodes, node);
1924
+ if (!slot || count < 16) return;
1925
+ // An unchanged matrix keeps the cached world matrices.
1926
+ if (slot->useMatrix && std::memcmp(slot->local, elements, sizeof(slot->local)) == 0) return;
1927
+
1928
+ std::memcpy(slot->local, elements, sizeof(slot->local));
1929
+ slot->useMatrix = true;
1930
+ slot->localDirty = true;
1931
+ }
1932
+
1933
+ void nodeFlags(double node, double visible, double frustumCulled, double renderOrder)
1934
+ {
1935
+ Node *slot = lookup(g_nodes, node);
1936
+ if (!slot) return;
1937
+ slot->visible = visible != 0;
1938
+ slot->frustumCulled = frustumCulled != 0;
1939
+ slot->renderOrder = static_cast<int>(renderOrder);
1940
+ }
1941
+
1942
+ void nodeGeometry(double node, double geometry, double material)
1943
+ {
1944
+ Node *slot = lookup(g_nodes, node);
1945
+ if (!slot) return;
1946
+ slot->geometry = static_cast<int>(geometry);
1947
+ slot->material = static_cast<int>(material);
1948
+ }
1949
+
1950
+ void nodeInstances(double node, double matrices, double colors, double count)
1951
+ {
1952
+ Node *slot = lookup(g_nodes, node);
1953
+ if (!slot) return;
1954
+ slot->instanced = true;
1955
+ slot->instanceMatrices = static_cast<int>(matrices);
1956
+ slot->instanceColors = static_cast<int>(colors);
1957
+ slot->instanceCount = std::max(0, static_cast<int>(count));
1958
+ }
1959
+
1960
+ 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
+ {
1962
+ Node *slot = lookup(g_nodes, node);
1963
+ if (!slot) return;
1964
+ slot->lightKind = static_cast<int>(kind);
1965
+ slot->lightColor[0] = static_cast<float>(r);
1966
+ slot->lightColor[1] = static_cast<float>(g);
1967
+ slot->lightColor[2] = static_cast<float>(b);
1968
+ slot->intensity = static_cast<float>(intensity);
1969
+ slot->groundColor[0] = static_cast<float>(groundR);
1970
+ slot->groundColor[1] = static_cast<float>(groundG);
1971
+ slot->groundColor[2] = static_cast<float>(groundB);
1972
+ slot->distance = static_cast<float>(distance);
1973
+ slot->decay = static_cast<float>(decay);
1974
+ }
1975
+
1976
+ void nodeLightTarget(double node, double x, double y, double z)
1977
+ {
1978
+ Node *slot = lookup(g_nodes, node);
1979
+ if (!slot) return;
1980
+ slot->target[0] = static_cast<float>(x);
1981
+ slot->target[1] = static_cast<float>(y);
1982
+ slot->target[2] = static_cast<float>(z);
1983
+ }
1984
+
1985
+ void cameraProjectionRaw(double node, const float *elements, std::size_t count, double near, double far)
1986
+ {
1987
+ Node *slot = lookup(g_nodes, node);
1988
+ if (!slot || count < 16) return;
1989
+ std::memcpy(slot->projection, elements, sizeof(slot->projection));
1990
+ slot->near = static_cast<float>(near);
1991
+ slot->far = static_cast<float>(far);
1992
+ }
1993
+
1994
+ void sceneEnvironment(double scene, double background, double top, double bottom, double fog, double fogColor, double fogNear, double fogFar, double fogDensity)
1995
+ {
1996
+ Node *slot = lookup(g_nodes, scene);
1997
+ if (!slot) return;
1998
+
1999
+ Environment &env = slot->environment;
2000
+ const int mode = static_cast<int>(background);
2001
+ env.background.mode = static_cast<std::uint8_t>(std::clamp(mode, 0, 2));
2002
+ hexToRgb(top, env.background.top);
2003
+ if (mode == raster::kBackgroundGradient) hexToRgb(bottom, env.background.bottom);
2004
+ else std::memcpy(env.background.bottom, env.background.top, sizeof(env.background.top));
2005
+ env.fog = static_cast<int>(fog);
2006
+ std::uint8_t rgb[3];
2007
+ hexToRgb(fogColor, rgb);
2008
+ for (int k = 0; k < 3; k++) env.fogColor[k] = rgb[k];
2009
+ env.fogNear = static_cast<float>(fogNear);
2010
+ env.fogFar = static_cast<float>(fogFar);
2011
+ env.fogDensity = static_cast<float>(fogDensity);
2012
+ }
2013
+
2014
+ // ================================================================ frame
2015
+
2016
+ void renderOptions(double depthBuffer, double capacity)
2017
+ {
2018
+ g_renderer.depthBuffer = depthBuffer != 0;
2019
+ if (capacity >= 64) g_renderer.capacity = static_cast<int>(capacity);
2020
+ }
2021
+
2022
+ void renderTarget(double surface)
2023
+ {
2024
+ g_renderer.surface = static_cast<int>(surface);
2025
+ }
2026
+
2027
+ double createSurface(double width, double height)
2028
+ {
2029
+ const int w = static_cast<int>(width);
2030
+ const int h = static_cast<int>(height);
2031
+ if (w <= 0 || h <= 0 || g_surfaces.count >= 8) return -1;
2032
+
2033
+ auto *pixels = new (std::nothrow) Pixel[static_cast<std::size_t>(w) * static_cast<std::size_t>(h)]();
2034
+ if (!pixels) return -1;
2035
+ const int id = gea::framework::graphics::ImageStore::instance().registerBuffer(pixels, w, h);
2036
+ if (id < 0) {
2037
+ delete[] pixels;
2038
+ return -1;
2039
+ }
2040
+ const int slot = g_surfaces.count++;
2041
+ g_surfaces.ids[slot] = id;
2042
+ g_surfaces.pixels[slot] = pixels;
2043
+ g_surfaces.width[slot] = w;
2044
+ g_surfaces.height[slot] = h;
2045
+ return id;
2046
+ }
2047
+
2048
+ double drawScene(double scene, double camera, double width, double height)
2049
+ {
2050
+ Node *sceneNode = lookup(g_nodes, scene);
2051
+ Node *cameraNode = lookup(g_nodes, camera);
2052
+ if (!sceneNode || !cameraNode) return 0;
2053
+
2054
+ Renderer &r = g_renderer;
2055
+ beginFrameState(static_cast<int>(width), static_cast<int>(height));
2056
+ r.legacyActive = false;
2057
+ raster::Frame &frame = r.frame();
2058
+ r.environment = sceneNode->environment;
2059
+ frame.background = r.environment.background;
2060
+
2061
+ collect(static_cast<int>(scene));
2062
+
2063
+ ensureWorld(static_cast<int>(camera));
2064
+ math::invertAffine(r.view.view, cameraNode->world);
2065
+ setProjection(cameraNode->projection, cameraNode->near, cameraNode->far);
2066
+
2067
+ for (const int id : r.lightNodes) addLight(g_nodes[static_cast<std::size_t>(id)]);
2068
+ for (const int id : r.drawables) drawNode(g_nodes[static_cast<std::size_t>(id)]);
2069
+
2070
+ sortFrame();
2071
+ const int count = frame.count;
2072
+ return present() ? count : -1;
2073
+ }
2074
+
2075
+ double stat(double which)
2076
+ {
2077
+ const Stats &s = g_renderer.stats;
2078
+ switch (static_cast<int>(which)) {
2079
+ case 0: return s.submitted;
2080
+ case 1: return s.nearRejected;
2081
+ case 2: return s.culled;
2082
+ case 3: return s.clipDropped;
2083
+ case 4: return s.dropped;
2084
+ case 5: return s.meshesDrawn;
2085
+ case 6: return s.meshesCulled;
2086
+ case 7: return s.primitives;
2087
+ case 8: return s.composited;
2088
+ default: return 0;
2089
+ }
2090
+ }
2091
+
2092
+ // ================================================================ raycast
2093
+
2094
+ double raycast(double node, double ox, double oy, double oz, double dx, double dy, double dz, double near, double far)
2095
+ {
2096
+ Node *slot = lookup(g_nodes, node);
2097
+ if (!slot || slot->kind != kNodeMesh) return 0;
2098
+ Geometry *geometry = lookup(g_geometries, slot->geometry);
2099
+ Material *material = lookup(g_materials, slot->material);
2100
+ const Buffer *positions = geometry ? bufferAt(geometry->position) : nullptr;
2101
+ if (!positions || !material) return 0;
2102
+
2103
+ float direction[3] = {static_cast<float>(dx), static_cast<float>(dy), static_cast<float>(dz)};
2104
+ if (!math::normalize3(direction)) return 0;
2105
+ ensureWorld(static_cast<int>(node));
2106
+
2107
+ const Buffer *indexBuffer = bufferAt(geometry->index);
2108
+ const std::uint32_t *indices = indexBuffer && !indexBuffer->u32.empty() ? indexBuffer->u32.data() : nullptr;
2109
+ const std::size_t vertexCount = positions->f32.size() / 3;
2110
+ const std::size_t triangles = (indices ? indexBuffer->u32.size() : vertexCount) / 3;
2111
+ const float *p = positions->f32.data();
2112
+ const Buffer *instances = slot->instanced ? bufferAt(slot->instanceMatrices) : nullptr;
2113
+ const int instanceCount = slot->instanced ? (instances ? std::min(slot->instanceCount, static_cast<int>(instances->f32.size() / 16)) : 0) : 1;
2114
+
2115
+ float best = static_cast<float>(far);
2116
+ bool hit = false;
2117
+ for (int instance = 0; instance < instanceCount; instance++) {
2118
+ float world[16];
2119
+ if (instances) math::multiplyAffine(world, slot->world, &instances->f32[static_cast<std::size_t>(instance) * 16]);
2120
+ else std::memcpy(world, slot->world, sizeof(world));
2121
+ float inverse[16];
2122
+ if (!math::invertAffine(inverse, world)) continue;
2123
+
2124
+ float o[3], d[3];
2125
+ math::transformPoint(inverse, static_cast<float>(ox), static_cast<float>(oy), static_cast<float>(oz), o);
2126
+ math::transformDirection(inverse, direction[0], direction[1], direction[2], d);
2127
+
2128
+ for (std::size_t t = 0; t < triangles; t++) {
2129
+ std::uint32_t id[3];
2130
+ for (int k = 0; k < 3; k++) id[k] = indices ? indices[t * 3 + k] : static_cast<std::uint32_t>(t * 3 + k);
2131
+ if (id[0] >= vertexCount || id[1] >= vertexCount || id[2] >= vertexCount) continue;
2132
+
2133
+ const float *a = &p[id[0] * 3], *b = &p[id[1] * 3], *c = &p[id[2] * 3];
2134
+ const float e1[3] = {b[0] - a[0], b[1] - a[1], b[2] - a[2]};
2135
+ const float e2[3] = {c[0] - a[0], c[1] - a[1], c[2] - a[2]};
2136
+ const float h[3] = {d[1] * e2[2] - d[2] * e2[1], d[2] * e2[0] - d[0] * e2[2], d[0] * e2[1] - d[1] * e2[0]};
2137
+ const float det = e1[0] * h[0] + e1[1] * h[1] + e1[2] * h[2];
2138
+ if (det > -1e-9f && det < 1e-9f) continue;
2139
+ if ((material->side == 0 && det < 0.0f) || (material->side == 1 && det > 0.0f)) continue;
2140
+
2141
+ const float inv = 1.0f / det;
2142
+ const float s[3] = {o[0] - a[0], o[1] - a[1], o[2] - a[2]};
2143
+ const float u = (s[0] * h[0] + s[1] * h[1] + s[2] * h[2]) * inv;
2144
+ if (u < 0.0f || u > 1.0f) continue;
2145
+ const float q[3] = {s[1] * e1[2] - s[2] * e1[1], s[2] * e1[0] - s[0] * e1[2], s[0] * e1[1] - s[1] * e1[0]};
2146
+ const float v = (d[0] * q[0] + d[1] * q[1] + d[2] * q[2]) * inv;
2147
+ if (v < 0.0f || u + v > 1.0f) continue;
2148
+ const float t0 = (e2[0] * q[0] + e2[1] * q[1] + e2[2] * q[2]) * inv;
2149
+ if (t0 < static_cast<float>(near) || t0 >= best) continue;
2150
+
2151
+ best = t0;
2152
+ hit = true;
2153
+ g_rayHit.distance = t0;
2154
+ g_rayHit.point[0] = static_cast<float>(ox) + direction[0] * t0;
2155
+ g_rayHit.point[1] = static_cast<float>(oy) + direction[1] * t0;
2156
+ g_rayHit.point[2] = static_cast<float>(oz) + direction[2] * t0;
2157
+ g_rayHit.face = static_cast<int>(t);
2158
+ g_rayHit.instance = instances ? instance : -1;
2159
+ }
2160
+ }
2161
+ return hit ? 1 : 0;
2162
+ }
2163
+
2164
+ double rayResult(double which)
2165
+ {
2166
+ switch (static_cast<int>(which)) {
2167
+ case 0: return g_rayHit.distance;
2168
+ case 1: return g_rayHit.point[0];
2169
+ case 2: return g_rayHit.point[1];
2170
+ case 3: return g_rayHit.point[2];
2171
+ case 4: return g_rayHit.face;
2172
+ case 5: return g_rayHit.instance;
2173
+ default: return 0;
2174
+ }
2175
+ }
2176
+
2177
+ // ================================================================ immediate API
2178
+
2179
+ void beginFrameRaw(const float *projection, std::size_t count, double near, double bgColor, double viewportW, double viewportH)
2180
+ {
2181
+ Renderer &r = g_renderer;
2182
+ beginFrameState(static_cast<int>(viewportW), static_cast<int>(viewportH));
2183
+ r.legacyActive = true;
2184
+ r.environment = Environment();
2185
+ setBackground(r.frame().background, bgColor);
2186
+ math::identity(r.view.view);
2187
+ float matrix[16];
2188
+ for (int i = 0; i < 16; i++) matrix[i] = i < static_cast<int>(count) ? projection[i] : 0.0f;
2189
+ setProjection(matrix, static_cast<float>(near), 1e30f);
2190
+ }
2191
+
2192
+ void ambientLight(double r, double g, double b)
2193
+ {
2194
+ Lights &lights = g_renderer.lights;
2195
+ lights.ambient[0] += static_cast<float>(r);
2196
+ lights.ambient[1] += static_cast<float>(g);
2197
+ lights.ambient[2] += static_cast<float>(b);
2198
+ }
2199
+
2200
+ void directionalLight(double x, double y, double z, double r, double g, double b)
2201
+ {
2202
+ Lights &lights = g_renderer.lights;
2203
+ float direction[3] = {static_cast<float>(x), static_cast<float>(y), static_cast<float>(z)};
2204
+ if (lights.directionalCount >= kMaxLights || !math::normalize3(direction)) return;
2205
+ const int i = lights.directionalCount++;
2206
+ std::memcpy(lights.direction[i], direction, sizeof(direction));
2207
+ lights.directionalColor[i][0] = static_cast<float>(r);
2208
+ lights.directionalColor[i][1] = static_cast<float>(g);
2209
+ lights.directionalColor[i][2] = static_cast<float>(b);
2210
+ }
2211
+
2212
+ void drawElementsRaw(double positionBuffer,
2213
+ double indexBuffer,
2214
+ double colorBuffer,
2215
+ double triangleCount,
2216
+ const float *modelView,
2217
+ std::size_t modelViewCount,
2218
+ double shadeMode,
2219
+ double baseR,
2220
+ double baseG,
2221
+ double baseB,
2222
+ double doubleSide)
2223
+ {
2224
+ if (!g_renderer.legacyActive || modelViewCount < 16) return;
2225
+ const Buffer *positions = bufferAt(static_cast<int>(positionBuffer));
2226
+ if (!positions) return;
2227
+
2228
+ Surface surface;
2229
+ surface.shade = static_cast<int>(shadeMode);
2230
+ surface.color[0] = static_cast<float>(baseR);
2231
+ surface.color[1] = static_cast<float>(baseG);
2232
+ surface.color[2] = static_cast<float>(baseB);
2233
+ surface.side = doubleSide != 0 ? 2 : 0;
2234
+ surface.vertexColors = colorBuffer >= 0;
2235
+ surface.fog = false;
2236
+
2237
+ Geometry geometry;
2238
+ geometry.position = static_cast<int>(positionBuffer);
2239
+ geometry.index = static_cast<int>(indexBuffer);
2240
+ geometry.color = static_cast<int>(colorBuffer);
2241
+
2242
+ const std::size_t vertexCount = positions->f32.size() / 3;
2243
+ const Buffer *indices = bufferAt(geometry.index);
2244
+ const std::size_t available = indices ? indices->u32.size() : vertexCount;
2245
+ const std::size_t indexCount = std::min(available, static_cast<std::size_t>(std::max(0.0, triangleCount)) * 3);
2246
+ const Buffer *colors = bufferAt(geometry.color);
2247
+ const float white[3] = {1, 1, 1};
2248
+ transformVertices(modelView, positions->f32.data(), vertexCount, colors && colors->f32.size() >= vertexCount * 3 ? colors->f32.data() : nullptr, nullptr, surface, white, false, !shadesPerFace(surface, false));
2249
+ emitTriangles(surface, indices ? vertexCount : std::min(vertexCount, indexCount), indices && !indices->u32.empty() ? indices->u32.data() : nullptr, indexCount, false);
2250
+ }
2251
+
2252
+ double endFrame()
2253
+ {
2254
+ if (!g_renderer.legacyActive) return 0;
2255
+ g_renderer.legacyActive = false;
2256
+ sortFrame();
2257
+ const int count = g_renderer.frame().count;
2258
+ return present() ? count : -1;
2259
+ }
2260
+
2261
+ } // namespace gea::host::gea3d