Repository navigation
Expand file tree
/
Copy pathQuadBlit.cpp
More file actions
2458 lines (2286 loc) · 90.3 KB
/
Copy pathQuadBlit.cpp
File metadata and controls
2458 lines (2286 loc) · 90.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "QuadBlit.h"
#include "DekiRenderer.h"
#include "PixelFormat.h"
#include "DirtyRegion.h"
#include "RenderProfiler.h"
#include <cmath>
#include <algorithm>
#include <atomic>
#include <cstring>
#include <vector>
// Deki::ColorFormat comes from the engine header. Never re-declare it here: a
// second definition is a redefinition error once a unity build puts this file
// in a translation unit that includes DekiEngine.h.
#include <deki/Engine.h>
#include <deki/LogSystem.h>
#include <deki/providers/Memory.h>
// ============================================================================
// How this file is organised
// ============================================================================
//
// Every blit - scaled or rotated, any of the five source layouts onto any of
// the four target formats - runs one pixel pipeline, CompositePixel<SK, F>:
// read the source pixel, drop it if transparent or chroma-keyed, tint, apply
// the alpha tint, then dither / write opaque / blend with the destination.
// The source layout (SrcKind) and the target format are template parameters,
// so each blit resolves them once. The per-blit flags (tint, alpha tint, key,
// dither, flips) are runtime booleans hoisted out of the loops, and a separate
// "Plain" instantiation (none of them set) keeps the common
// sprite-onto-framebuffer loop tight.
//
// One pipeline keeps every format pair behaving the same way; do not add
// per-pair kernels that compute pixels differently. tests/GoldenBlitTests.cpp
// pins the output of every path.
//
// The 1:1 fast paths that matter on the ESP32 sit beside it and produce the
// same pixels: whole-row copies and the registered SIMD row kernels, the
// per-row opaque-span split for RGB565A8 sprites, and the chroma-key span copy
// for RGB565 sprites.
using DekiPixel::AlphaUnion;
using DekiPixel::BayerThreshold;
using DekiPixel::Div255;
using DekiPixel::FromMemory565;
using DekiPixel::Load565;
using DekiPixel::LoadU16;
using DekiPixel::PackRGB565;
using DekiPixel::StoreU16;
using DekiPixel::ToMemory565;
using DekiPixel::UnpackRGB565;
using DekiPixel::SrcKind;
using DekiPixel::ReadSrcPixel;
using DekiPixel::ReadDstPixel;
using DekiPixel::WriteDstPixel;
namespace QuadBlit
{
// ============================================================================
// Kernel dispatch table
// ============================================================================
// Null by default. Platform packages call RegisterKernel(op, fn) at init to
// plug in SIMD implementations. The blit dispatcher looks for an entry only
// when all preconditions hold (format, no scale, no rotation, alignment, and
// no tint where it applies).
static RowKernelFn s_Kernels[(int)KernelOp::Count] = {};
// KernelOp is uint8_t, so only the upper bound is checked. A `(int)op < 0`
// test is always false, which GCC 15 warns about and ESP-IDF 6 makes an error.
void RegisterKernel(KernelOp op, RowKernelFn fn)
{
if ((int)op >= (int)KernelOp::Count)
{
return;
}
s_Kernels[(int)op] = fn;
}
RowKernelFn GetKernel(KernelOp op)
{
if ((int)op >= (int)KernelOp::Count)
{
return nullptr;
}
return s_Kernels[(int)op];
}
// ============================================================================
// Path timing, for the render profiler
// ============================================================================
// Which loop drew a blit, and what it cost per destination pixel inside the
// clip: the fast paths, and the generic pipeline they fall back to. One test
// per blit when the profiler is off.
enum class BlitPath : uint32_t
{
CopyRows,
ChromaSpans,
BlendSpans,
TintRows,
TintScaledRows,
ExpandRows,
Rows565A8,
GenericScaledPlain,
GenericScaled,
GenericRotated,
AlphaRows,
StretchRows,
TintRotatedRows,
None
};
// One word each, so a report line splits on spaces.
constexpr const char* kBlitPathNames[] = {
"CopyRows", "ChromaSpans", "BlendSpans", "TintRows", "TintScaledRows",
"ExpandRows", "Rows565A8", "GenericScaledPlain", "GenericScaled", "GenericRotated",
"AlphaRows", "StretchRows", "TintRotatedRows",
};
struct PathScope
{
BlitPath path = BlitPath::None;
const uint64_t pixels;
const bool on;
const uint64_t start;
explicit PathScope(uint64_t destPixels)
: pixels(destPixels),
on(DekiRendering::RenderProfiler::IsEnabled()),
start(on ? DekiRendering::RenderProfiler::Now() : 0)
{
}
~PathScope()
{
if (on && path != BlitPath::None)
{
DekiRendering::RenderProfiler::AddPath(static_cast<uint32_t>(path),
kBlitPathNames[static_cast<uint32_t>(path)],
DekiRendering::RenderProfiler::Now() - start, pixels);
}
}
};
// True when both pointers are 16-byte aligned, as the SIMD (PIE) kernels need.
static inline bool Aligned16(const void* a, const void* b)
{
return ((uintptr_t)a & 0xF) == 0 && ((uintptr_t)b & 0xF) == 0;
}
// ============================================================================
// Clip rect stack
// ============================================================================
// Grows with the nesting depth of the scene, with no fixed limit. Capacity
// persists across frames (ClearClipStack only clears).
static std::vector<ClipRect> s_ClipStack;
static bool s_ClipEnabled = true;
void PushClipRect(int32_t left, int32_t top, int32_t right, int32_t bottom)
{
ClipRect rect = { left, top, right, bottom };
// Intersect with the parent clip rect.
if (!s_ClipStack.empty())
{
const ClipRect& parent = s_ClipStack.back();
rect.left = std::max(rect.left, parent.left);
rect.top = std::max(rect.top, parent.top);
rect.right = std::min(rect.right, parent.right);
rect.bottom = std::min(rect.bottom, parent.bottom);
}
s_ClipStack.push_back(rect);
}
void PopClipRect()
{
if (!s_ClipStack.empty())
{
s_ClipStack.pop_back();
}
}
static ClipRect s_Limit; // SetTargetLimit; not set (IsSet false) when none
ClipRect GetCurrentClipRect()
{
ClipRect clip = (!s_ClipEnabled || s_ClipStack.empty()) ? ClipRect{} : s_ClipStack.back();
if (s_Limit.IsSet())
{
clip.left = std::max(clip.left, s_Limit.left);
clip.top = std::max(clip.top, s_Limit.top);
clip.right = std::min(clip.right, s_Limit.right);
clip.bottom = std::min(clip.bottom, s_Limit.bottom);
}
return clip;
}
void ClearClipStack()
{
s_ClipStack.clear();
s_ClipEnabled = true;
s_Limit = ClipRect{};
}
void SetTargetLimit(int32_t left, int32_t top, int32_t right, int32_t bottom)
{
s_Limit = ClipRect{ left, top, right, bottom };
}
void ClearTargetLimit()
{
s_Limit = ClipRect{};
}
void SetClipEnabled(bool enabled)
{
s_ClipEnabled = enabled;
}
bool IsClipEnabled()
{
return s_ClipEnabled;
}
int GetClipStackDepth()
{
return static_cast<int>(s_ClipStack.size());
}
// ============================================================================
// Blit sink
// ============================================================================
// s_SinkTarget is null outside a sink frame, and a blit's target never is, so
// a blit tests one pointer and costs nothing more without a sink.
static BlitSink* s_Sink = nullptr;
static const uint8_t* s_SinkTarget = nullptr;
static std::atomic<uint32_t> s_SourceRevision{ 0 };
uint32_t NextRevision()
{
uint32_t revision = s_SourceRevision.fetch_add(1) + 1;
// Zero means untracked. A wrap after four billion bakes is far away, but
// skip it rather than hand out the one value that disables caching.
if (revision == 0)
{
revision = s_SourceRevision.fetch_add(1) + 1;
}
return revision;
}
void SetBlitSink(BlitSink* sink)
{
s_Sink = sink;
s_SinkTarget = nullptr;
}
BlitSink* GetBlitSink()
{
return s_Sink;
}
bool BeginSinkFrame(uint8_t* target, int32_t width, int32_t height, Deki::ColorFormat format, uint8_t clearR,
uint8_t clearG, uint8_t clearB)
{
s_SinkTarget = nullptr;
if (!s_Sink || !target || !s_Sink->BeginFrame(target, width, height, format, clearR, clearG, clearB))
{
return false;
}
s_SinkTarget = target;
return true;
}
void EndSinkFrame()
{
if (s_Sink && s_SinkTarget)
{
s_Sink->EndFrame();
}
s_SinkTarget = nullptr;
}
const uint8_t* SinkTarget()
{
return s_SinkTarget;
}
// The frame's clear while nothing has written its buffer: a blit tests one
// pointer for it.
static const uint8_t* s_ClearTarget = nullptr;
static const DekiRendering::DeferredClear* s_PendingClear = nullptr;
void SetPendingClear(const uint8_t* buffer, const DekiRendering::DeferredClear* clear)
{
s_PendingClear = buffer ? clear : nullptr;
s_ClearTarget = s_PendingClear ? buffer : nullptr;
}
const DekiRendering::DeferredClear* PendingClear()
{
return s_PendingClear;
}
void RunPendingClear()
{
const DekiRendering::DeferredClear* clear = s_PendingClear;
s_PendingClear = nullptr;
s_ClearTarget = nullptr;
if (clear && clear->run)
{
clear->run(clear->owner);
}
}
void DropPendingClear()
{
s_PendingClear = nullptr;
s_ClearTarget = nullptr;
}
bool TakePendingClear(const uint8_t* buffer, uint8_t* pixel)
{
if (!buffer || buffer != s_ClearTarget || !s_PendingClear->pixel ||
!s_PendingClear->pixel(s_PendingClear->owner, pixel))
{
return false;
}
DropPendingClear();
return true;
}
void BeforeWriting(const uint8_t* buffer)
{
if (buffer && buffer == s_ClearTarget)
{
RunPendingClear();
}
}
void NoteWritten(const uint8_t* buffer)
{
if (buffer && buffer == s_SinkTarget)
{
s_Sink->TargetWritten();
}
}
bool LightSinkFrame(const DekiRendering::Lighting2D& lighting)
{
return s_Sink && s_SinkTarget && s_Sink->Light(lighting);
}
// Hands a blit to the sink; true when it drew it. When it cannot, the CPU
// draws it into the target, so the sink is told the target was written.
static bool DrawOnSink(const SinkBlit& blit)
{
if (s_Sink->Draw(blit))
{
return true;
}
s_Sink->TargetWritten();
return false;
}
// ============================================================================
// Source creation
// ============================================================================
Source MakeSource(const uint8_t* pixels, int32_t width, int32_t height, PixelLayout layout, bool ownsPixels,
const int16_t* alphaRowSpans)
{
Source src;
src.pixels = pixels;
src.width = width;
src.height = height;
src.bytesPerPixel = layout.bytesPerPixel;
src.hasAlpha = layout.hasAlpha;
src.isRGB565 = layout.isRGB565;
src.ownsPixels = ownsPixels;
src.alphaRowSpans = alphaRowSpans;
src.stride = 0;
src.hasChromaKey = false;
src.keyR = 0;
src.keyG = 0;
src.keyB = 0;
src.chromaRowSpans = nullptr;
if (layout.hasAlpha)
{
src.alphaOffset = layout.isRGB565 ? 2 : 3;
}
else
{
src.alphaOffset = 0;
}
return src;
}
void FindUniformRuns(const uint8_t* pixels, int32_t width, int32_t height, int32_t stride, UniformRun* runs)
{
constexpr int32_t kMinRun = 8;
for (int32_t y = 0; y < height; y++)
{
const uint8_t* row = pixels + static_cast<size_t>(y) * stride;
UniformRun best;
for (int32_t x = 0; x < width;)
{
if (row[x * 3 + 2] != 255)
{
x++;
continue;
}
const uint16_t color = LoadU16(row + x * 3);
const int32_t start = x;
while (x < width && row[x * 3 + 2] == 255 && LoadU16(row + x * 3) == color)
{
x++;
}
if (x - start >= kMinRun && x - start > best.end - best.start)
{
best.start = static_cast<int16_t>(start);
best.end = static_cast<int16_t>(x);
best.color = color;
}
}
runs[y] = best;
}
}
// Bytes per row of a Source buffer. Source::stride 0 means tightly packed
// (each row right after the previous); a non-zero stride lets a Source point
// at a sub-rect of a larger buffer (e.g. a tile in an atlas) without a copy.
static inline int32_t SourceStride(const Source& s)
{
return s.stride ? s.stride : s.width * s.bytesPerPixel;
}
// Maps a sampled source coordinate through the Source's flip flags. This is
// the inverse of Tiled's order (transpose, then H, then V), so it applies V,
// then H, then D.
static inline void ApplyFlips(const Source& s, int32_t& x, int32_t& y)
{
if (s.flipV)
{
y = s.height - 1 - y;
}
if (s.flipH)
{
x = s.width - 1 - x;
}
if (s.flipD)
{
// A transpose only makes sense for a square source; Tiled sets it only
// on tiles, which are square. Anything else keeps its orientation.
if (s.width == s.height)
{
const int32_t t = x;
x = y;
y = t;
}
}
}
static inline bool HasFlips(const Source& s)
{
return s.flipH || s.flipV || s.flipD;
}
// ============================================================================
// Clipping bounds, shared by BlitScaled and Blit
// ============================================================================
struct BlitBounds
{
int32_t startX, startY, endX, endY;
};
static inline bool ComputeClipBounds(int32_t destX, int32_t destY, int32_t destWidth, int32_t destHeight,
int32_t targetWidth, int32_t targetHeight, BlitBounds& out)
{
ClipRect clip = GetCurrentClipRect();
out.startX = std::max<int32_t>(0, std::max(destX, clip.left));
out.startY = std::max<int32_t>(0, std::max(destY, clip.top));
out.endX = std::min<int32_t>(targetWidth, std::min(destX + destWidth, clip.right));
out.endY = std::min<int32_t>(targetHeight, std::min(destY + destHeight, clip.bottom));
return out.startX < out.endX && out.startY < out.endY;
}
// ============================================================================
// Pixel formats
// ============================================================================
// The SrcKind of a Source; see SrcKind in PixelFormat.h for the layouts.
static inline SrcKind KindOf(const Source& s)
{
if (s.isRGB565)
{
return s.bytesPerPixel >= 3 ? SrcKind::RGB565A8 : SrcKind::RGB565;
}
if (s.bytesPerPixel == 4)
{
return SrcKind::RGBA8888;
}
if (s.bytesPerPixel == 3)
{
return SrcKind::RGB888;
}
return SrcKind::ALPHA8;
}
// ============================================================================
// The pixel pipeline
// ============================================================================
struct BlitParams
{
bool hasTint = false;
bool hasAlphaTint = false;
bool hasKey = false;
bool dither = false; // ordered dither instead of alpha blend (alpha sources only)
bool flips = false;
uint8_t tintR = 255, tintG = 255, tintB = 255, tintA = 255;
uint8_t keyR = 0, keyG = 0, keyB = 0;
};
// Composites the source pixel at `sp` onto destination pixel `idx`; px, py
// pick the dither threshold. Plain means no tint, alpha tint, key or dither:
// the tight loop for the common sprite blit.
template <SrcKind SK, Deki::ColorFormat F, bool Plain>
static inline void CompositePixel(const Source& source, const uint8_t* sp, uint8_t* target, size_t idx, int32_t px,
int32_t py, const BlitParams& p)
{
uint8_t r, g, b, a;
ReadSrcPixel<SK>(sp, source.hasAlpha, r, g, b, a);
if (a == 0)
{
return;
}
if constexpr (Plain)
{
if (a == 255)
{
WriteDstPixel<F>(target, idx, r, g, b, 255);
return;
}
uint8_t bgR, bgG, bgB, bgA;
ReadDstPixel<F>(target, idx, bgR, bgG, bgB, bgA);
const uint32_t invA = 255u - a;
WriteDstPixel<F>(target, idx, Div255(r * a + bgR * invA), Div255(g * a + bgG * invA),
Div255(b * a + bgB * invA), AlphaUnion(a, bgA));
return;
}
else
{
// The key is compared against the untinted colour.
if (p.hasKey && r == p.keyR && g == p.keyG && b == p.keyB)
{
return;
}
if (p.hasTint)
{
r = Div255(r * p.tintR);
g = Div255(g * p.tintG);
b = Div255(b * p.tintB);
}
const uint8_t effA = p.hasAlphaTint ? Div255(a * p.tintA) : a;
if (effA == 0)
{
return;
}
if (p.dither)
{
// 255 always passes, since the matrix tops out at 252.
if (effA <= BayerThreshold(px, py))
{
return;
}
WriteDstPixel<F>(target, idx, r, g, b, 255);
return;
}
if (effA == 255)
{
WriteDstPixel<F>(target, idx, r, g, b, 255);
return;
}
uint8_t bgR, bgG, bgB, bgA;
ReadDstPixel<F>(target, idx, bgR, bgG, bgB, bgA);
const uint32_t invA = 255u - effA;
WriteDstPixel<F>(target, idx, Div255(r * effA + bgR * invA), Div255(g * effA + bgG * invA),
Div255(b * effA + bgB * invA), AlphaUnion(effA, bgA));
}
}
// ============================================================================
// 1:1 row fast paths: opaque copies, span splits, SIMD hooks
// ============================================================================
// Each returns true when it handled the whole blit. They exist only for
// speed: the pipeline above produces the same pixels.
// A tint as lookup tables over the RGB565 channel values: an RGB565 source
// has only 32 reds, 64 greens and 32 blues, so the pipeline's tinted channel,
// Div255(channel8 * tint), is one of those, worked out once per blit instead
// of per pixel. The packed tables are the same values already shifted into
// place and in memory's byte order, so an opaque pixel is three lookups and a
// store. An untinted blit uses tint 255, which gives the channel back
// unchanged.
struct TintTables
{
uint8_t r[32], g[64], b[32]; // the tinted 8-bit channel
uint16_t pr[32], pg[64], pb[32]; // the same, packed into RGB565 as stored
};
static void MakeTintTables(TintTables& t, uint8_t tintR, uint8_t tintG, uint8_t tintB)
{
for (uint32_t i = 0; i < 32; i++)
{
t.r[i] = Div255((i << 3) * tintR);
t.b[i] = Div255((i << 3) * tintB);
t.pr[i] = ToMemory565(static_cast<uint16_t>((t.r[i] >> 3) << 11));
t.pb[i] = ToMemory565(static_cast<uint16_t>(t.b[i] >> 3));
}
for (uint32_t i = 0; i < 64; i++)
{
t.g[i] = Div255((i << 2) * tintG);
t.pg[i] = ToMemory565(static_cast<uint16_t>((t.g[i] >> 2) << 5));
}
}
// The tables for the last few tints asked for, kept between blits: the same
// tints are usually drawn many times a frame (a row of cards, each with its
// coloured badge and white label; a particle emitter's colour while only its
// alpha fades), and building the tables costs about as much as tinting a
// hundred pixels. QuadBlit runs on one thread (its clip stack is shared too),
// so static entries are enough.
static const TintTables& TintTablesFor(uint8_t tintR, uint8_t tintG, uint8_t tintB)
{
constexpr uint32_t kEntries = 8;
static TintTables s_Tables[kEntries];
// No RGB tint packs to 0xFFFFFFFF.
static uint32_t s_Keys[kEntries] = { 0xFFFFFFFFu, 0xFFFFFFFFu, 0xFFFFFFFFu, 0xFFFFFFFFu,
0xFFFFFFFFu, 0xFFFFFFFFu, 0xFFFFFFFFu, 0xFFFFFFFFu };
static uint32_t s_Next = 0;
const uint32_t key = (static_cast<uint32_t>(tintR) << 16) | (static_cast<uint32_t>(tintG) << 8) | tintB;
for (uint32_t i = 0; i < kEntries; i++)
{
if (s_Keys[i] == key)
{
return s_Tables[i];
}
}
const uint32_t i = s_Next;
s_Next = (s_Next + 1) % kEntries;
MakeTintTables(s_Tables[i], tintR, tintG, tintB);
s_Keys[i] = key;
return s_Tables[i];
}
// The row loops below but BlitRows run from IRAM (DEKI_FAST_ATTR), and each
// one Blit or BlitScaled calls is [[gnu::noinline]]: those run from flash,
// and a loop inlined into one runs from flash with it, its IRAM copy dropped.
// Which ones the compiler inlined changed with any edit near a caller, and
// with it how fast a blit was and how much IRAM the build took.
// Fills n RGB565 pixels with one stored value, two at a time. Inlined where
// it may be: every caller is a row loop in IRAM.
static DEKI_FAST_ATTR void FillRow565(uint16_t* dst, int32_t n, uint16_t value)
{
if (n <= 0)
{
return;
}
if (reinterpret_cast<uintptr_t>(dst) & 2)
{
*dst++ = value;
--n;
}
const uint32_t pair = static_cast<uint32_t>(value) | (static_cast<uint32_t>(value) << 16);
uint32_t* dst32 = reinterpret_cast<uint32_t*>(dst);
for (int32_t i = 0; i < n / 2; ++i)
{
dst32[i] = pair;
}
if (n & 1)
{
dst[n - 1] = value;
}
}
// A source colour of 8-bit channels (r, g, b) at alpha a (not 0 or 255) over
// the destination pixel bg16 as stored, as the pipeline composites it: each
// channel Div255(source * a + destination * (255 - a)). Red and blue are mixed
// together, in the two halves of one word: each mix is under 65536, so the
// halves never carry into each other, nor does Div255's rounding. Two
// multiplies fewer a pixel, the same result.
[[gnu::always_inline]] static inline uint16_t Blend565(uint32_t r, uint32_t g, uint32_t b, uint32_t a, uint16_t bg16)
{
const uint32_t bg = FromMemory565(bg16);
const uint32_t invA = 255u - a;
uint32_t rb = ((r << 16) | b) * a + ((((bg >> 11) << 19) | ((bg & 0x1Fu) << 3)) * invA);
rb = ((rb + 0x00010001u + ((rb >> 8) & 0x00FF00FFu)) >> 8) & 0x00FF00FFu;
const uint32_t g8 = Div255(g * a + (((bg >> 5) & 0x3Fu) << 2) * invA);
return ToMemory565(static_cast<uint16_t>(((rb >> 19) << 11) | ((g8 >> 2) << 5) | ((rb & 0xFFu) >> 3)));
}
// A tinted source pixel v of alpha a (not 0 or 255) over the destination
// pixel bg16 as stored, as the pipeline composites it.
[[gnu::always_inline]] static inline uint16_t TintBlend565(const TintTables& t, uint32_t v, uint32_t a, uint16_t bg16)
{
return Blend565(t.r[v >> 11], t.g[(v >> 5) & 0x3F], t.b[v & 0x1F], a, bg16);
}
// One tinted source pixel of alpha `a` (already multiplied by any alpha tint,
// not 0) onto an RGB565 destination pixel, as the pipeline composites it.
// Always inlined: it runs per pixel, and a call (into flash, from the IRAM
// loops that use it) cost more than the work.
[[gnu::always_inline]] static inline void TintPixel565(const TintTables& t, uint32_t v, uint32_t a, uint16_t* dp)
{
if (a == 255)
{
*dp = static_cast<uint16_t>(t.pr[v >> 11] | t.pg[(v >> 5) & 0x3F] | t.pb[v & 0x1F]);
return;
}
*dp = TintBlend565(t, v, a, *dp);
}
// Destination columns [x0, x1) of one row of a 1:1 tinted blit, each pixel
// with its own alpha. Inlined: its loop is the blit's inner loop. The source's
// bytes per pixel and whether there is an alpha tint are constants, so the
// loop keeps what it needs in registers: an Xtensa core has few, and each one
// spilled was a load per pixel.
template <bool SourceAlpha, bool AlphaTint, int32_t Bpp>
[[gnu::always_inline]] static inline void TintRun(const TintTables& t, const uint8_t* srcRow, uint16_t* dstRow,
int32_t destX, int32_t x0, int32_t x1, uint32_t tintA)
{
const uint8_t* sp = srcRow + (x0 - destX) * Bpp;
uint16_t* dp = dstRow + x0;
if constexpr (AlphaTint)
{
// Every pixel blends: an alpha tint is below 255, and so is any alpha
// it scales. The last blend is remembered: a translucent shape over a
// flat background (a card's tinted glow, a faded panel) blends the
// same source pixel over the same destination pixel after pixel.
uint32_t lastIn = 0xFFFFFFFFu; // source alpha << 16 | pixel as stored; nothing packs to this
uint16_t lastBg = 0;
uint16_t lastOut = 0;
for (int32_t px = x0; px < x1; px++, sp += Bpp, dp++)
{
uint32_t a8 = 255;
if constexpr (SourceAlpha)
{
a8 = sp[2];
if (a8 == 0)
{
continue;
}
}
const uint32_t in = (a8 << 16) | LoadU16(sp);
const uint16_t bg = *dp;
if (in != lastIn || bg != lastBg)
{
lastIn = in;
lastBg = bg;
const uint32_t a = Div255(a8 * tintA);
lastOut = a == 0 ? bg : TintBlend565(t, FromMemory565(static_cast<uint16_t>(in)), a, bg);
}
*dp = lastOut;
}
}
else
{
for (int32_t px = x0; px < x1; px++, sp += Bpp, dp++)
{
uint32_t a = 255;
if constexpr (SourceAlpha)
{
a = sp[2];
if (a == 0)
{
continue;
}
}
TintPixel565(t, Load565(sp), a, dp);
}
}
}
// RGB565 or RGB565A8 -> RGB565, 1:1, any tint and alpha tint; no key, dither or
// flips. The pipeline's arithmetic in one tight loop per row: CompositePixel
// per pixel cost several times as much, most of it for opaque pixels that
// need no blending at all. (Splitting rows at their opaque run, as
// BlendRows_RGB565A8_to_RGB565 does, was measured slower here on an
// ESP32-S3: 100 ns a pixel against 80.)
template <bool SourceAlpha, bool AlphaTint, int32_t Bpp>
[[gnu::noinline]] static DEKI_FAST_ATTR void TintRows_RGB565(const Source& source, uint16_t* target16,
int32_t targetWidth, int32_t destX, int32_t destY,
const BlitBounds& b, const BlitParams& p)
{
const TintTables& t = TintTablesFor(p.tintR, p.tintG, p.tintB);
const int32_t stride = SourceStride(source);
const uint32_t tintA = p.tintA;
const int16_t* clear = SourceAlpha ? source.clearRowSpans : nullptr;
const UniformRun* runs = SourceAlpha ? source.uniformRuns : nullptr;
for (int32_t py = b.startY; py < b.endY; py++)
{
const int32_t srcY = py - destY;
const uint8_t* srcRow = source.pixels + srcY * stride;
uint16_t* dstRow = target16 + py * targetWidth;
// The row's transparent run (alpha 0 everywhere in it) is not read,
// and its run of one opaque colour is drawn without reading the
// source: only the columns either side of them, inside the clip, go
// pixel by pixel. The two runs never overlap.
int32_t cs = b.endX, ce = b.endX, us = b.endX, ue = b.endX;
if (clear)
{
cs = std::clamp<int32_t>(destX + clear[srcY * 2], b.startX, b.endX);
ce = std::clamp<int32_t>(destX + clear[srcY * 2 + 1], cs, b.endX);
}
if (runs)
{
us = std::clamp<int32_t>(destX + runs[srcY].start, b.startX, b.endX);
ue = std::clamp<int32_t>(destX + runs[srcY].end, us, b.endX);
}
// An empty run goes to the row's end, out of the other's way.
if (ce == cs)
{
cs = ce = b.endX;
}
if (ue == us)
{
us = ue = b.endX;
}
const bool clearFirst = cs < us;
const int32_t parts[6] = {
b.startX, clearFirst ? cs : us, clearFirst ? ce : ue, clearFirst ? us : cs, clearFirst ? ue : ce, b.endX
};
#pragma GCC unroll 1
for (int32_t i = 0; i < 6; i += 2)
{
TintRun<SourceAlpha, AlphaTint, Bpp>(t, srcRow, dstRow, destX, parts[i], parts[i + 1], tintA);
}
if (ue > us)
{
// Alpha 255 throughout: the tinted colour, or with an alpha tint
// that colour at the tint's alpha (Div255(255 * a) is a) over
// each destination pixel, worked out again only when it changes.
const uint32_t v = FromMemory565(runs[srcY].color);
uint16_t* dp = dstRow + us;
if constexpr (AlphaTint)
{
uint16_t lastBg = static_cast<uint16_t>(~dp[0]);
uint16_t lastOut = 0;
for (int32_t i = 0; i < ue - us; i++)
{
const uint16_t bg = dp[i];
if (bg != lastBg)
{
lastBg = bg;
lastOut = TintBlend565(t, v, tintA, bg);
}
dp[i] = lastOut;
}
}
else
{
FillRow565(dp, ue - us, static_cast<uint16_t>(t.pr[v >> 11] | t.pg[(v >> 5) & 0x3F] | t.pb[v & 0x1F]));
}
}
}
}
// An alpha-only source (ALPHA8: text in one colour) onto RGB565, 1:1, any tint
// and alpha tint; no key, dither or flips. The source is white, so the colour
// is the tint itself (Div255(255 * t) is t): one colour, each pixel at its own
// alpha. A byte a pixel read where an RGB565A8 source reads three. Not
// inlined: its one caller runs from flash, and the loop must stay in IRAM.
template <bool AlphaTint>
[[gnu::noinline]] static DEKI_FAST_ATTR void AlphaRows_RGB565(const Source& source, uint16_t* target16,
int32_t targetWidth, int32_t destX, int32_t destY,
const BlitBounds& b, const BlitParams& p)
{
const uint32_t r = p.tintR, g = p.tintG, bl = p.tintB;
const uint16_t opaque =
ToMemory565(PackRGB565(static_cast<uint8_t>(r), static_cast<uint8_t>(g), static_cast<uint8_t>(bl)));
const uint32_t tintA = p.tintA;
const int32_t stride = SourceStride(source);
for (int32_t py = b.startY; py < b.endY; py++)
{
const uint8_t* sp = source.pixels + (py - destY) * stride + (b.startX - destX);
uint16_t* dp = target16 + py * targetWidth + b.startX;
for (int32_t px = b.startX; px < b.endX; px++, sp++, dp++)
{
uint32_t a = *sp;
if (a == 0)
{
continue;
}
if constexpr (AlphaTint)
{
a = Div255(a * tintA);
if (a == 0)
{
continue;
}
}
if (a == 255)
{
*dp = opaque;
continue;
}
*dp = Blend565(r, g, bl, a, *dp);
}
}
}
// TintRows_RGB565 for a source of Bpp bytes a pixel, with or without an alpha tint.
template <bool SourceAlpha, int32_t Bpp>
static inline void TintRowsFor(const Source& source, uint16_t* target16, int32_t targetWidth, int32_t destX,
int32_t destY, const BlitBounds& b, const BlitParams& p)
{
if (p.hasAlphaTint)
{
TintRows_RGB565<SourceAlpha, true, Bpp>(source, target16, targetWidth, destX, destY, b, p);
}
else
{
TintRows_RGB565<SourceAlpha, false, Bpp>(source, target16, targetWidth, destX, destY, b, p);
}
}
// RGB565 or RGB565A8 -> RGB565A8, at any scale, any tint and alpha tint; no
// key, dither or flips. The scaled pipeline's stepping and arithmetic in one
// tight loop per row: a particle emitter draws each particle this way into
// its composite, dozens a frame.
template <bool SourceAlpha>
[[gnu::noinline]] static DEKI_FAST_ATTR void
TintScaledRows_RGB565A8(const Source& source, uint8_t* target, int32_t targetWidth, int32_t destX, int32_t destY,
int32_t destWidth, int32_t destHeight, const BlitBounds& b, const BlitParams& p)
{
const TintTables& t = TintTablesFor(p.tintR, p.tintG, p.tintB);
const int32_t stride = SourceStride(source);
const int32_t bpp = source.bytesPerPixel;
const bool alphaTint = p.hasAlphaTint;
const uint32_t tintA = p.tintA;
const uint32_t xStep = ((uint32_t)source.width << 16) / (uint32_t)destWidth;
const uint32_t yStep = ((uint32_t)source.height << 16) / (uint32_t)destHeight;
for (int32_t py = b.startY; py < b.endY; py++)
{
const int32_t srcY = (int32_t)(((uint32_t)(py - destY) * yStep) >> 16);
const uint8_t* srcRow = source.pixels + srcY * stride;
uint8_t* dp = target + ((size_t)py * (size_t)targetWidth + b.startX) * 3;
uint32_t acc = (uint32_t)(b.startX - destX) * xStep;
for (int32_t px = b.startX; px < b.endX; px++, dp += 3)
{
const uint8_t* sp = srcRow + (int32_t)(acc >> 16) * bpp;
acc += xStep;
uint32_t a = 255;
if constexpr (SourceAlpha)
{
a = sp[2];
if (a == 0)
{
continue;
}
}
if (alphaTint)
{
a = Div255(a * tintA);
if (a == 0)
{
continue;
}
}
const uint32_t v = Load565(sp);
const uint32_t r5 = v >> 11;
const uint32_t g6 = (v >> 5) & 0x3F;
const uint32_t b5 = v & 0x1F;
uint32_t out; // as stored
if (a == 255)
{
out = t.pr[r5] | t.pg[g6] | t.pb[b5];
dp[2] = 255;
}