-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
Rasterizer.cpp
1864 lines (1600 loc) · 68.2 KB
/
Rasterizer.cpp
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
// Copyright (c) 2013- PPSSPP Project.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, version 2.0 or later versions.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License 2.0 for more details.
// A copy of the GPL 2.0 should have been included with the program.
// If not, see http://www.gnu.org/licenses/
// Official git repository and contact information can be found at
// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/.
#include "ppsspp_config.h"
#include <cmath>
#include "Common/Common.h"
#include "Common/CPUDetect.h"
#include "Common/Data/Convert/ColorConv.h"
#include "Common/Profiler/Profiler.h"
#include "Common/StringUtils.h"
#include "Core/Config.h"
#include "Core/Debugger/MemBlockInfo.h"
#include "Core/MemMap.h"
#include "GPU/GPUState.h"
#include "GPU/Common/TextureDecoder.h"
#include "GPU/Software/BinManager.h"
#include "GPU/Software/DrawPixel.h"
#include "GPU/Software/Rasterizer.h"
#include "GPU/Software/Sampler.h"
#include "GPU/Software/SoftGpu.h"
#include "GPU/Software/TransformUnit.h"
#include "Common/Math/SIMDHeaders.h"
// For the SSE4 stuff
#if PPSSPP_ARCH(SSE2)
#include <smmintrin.h>
#endif
namespace Rasterizer {
// Only OK on x64 where our stack is aligned
#if defined(_M_SSE) && !PPSSPP_ARCH(X86)
static inline __m128 InterpolateF(const __m128 &c0, const __m128 &c1, const __m128 &c2, int w0, int w1, int w2, float wsum) {
__m128 v = _mm_mul_ps(c0, _mm_cvtepi32_ps(_mm_set1_epi32(w0)));
v = _mm_add_ps(v, _mm_mul_ps(c1, _mm_cvtepi32_ps(_mm_set1_epi32(w1))));
v = _mm_add_ps(v, _mm_mul_ps(c2, _mm_cvtepi32_ps(_mm_set1_epi32(w2))));
return _mm_mul_ps(v, _mm_set_ps1(wsum));
}
static inline __m128i InterpolateI(const __m128i &c0, const __m128i &c1, const __m128i &c2, int w0, int w1, int w2, float wsum) {
return _mm_cvtps_epi32(InterpolateF(_mm_cvtepi32_ps(c0), _mm_cvtepi32_ps(c1), _mm_cvtepi32_ps(c2), w0, w1, w2, wsum));
}
#elif PPSSPP_ARCH(ARM64_NEON)
static inline float32x4_t InterpolateF(const float32x4_t &c0, const float32x4_t &c1, const float32x4_t &c2, int w0, int w1, int w2, float wsum) {
float32x4_t v = vmulq_f32(c0, vcvtq_f32_s32(vdupq_n_s32(w0)));
v = vaddq_f32(v, vmulq_f32(c1, vcvtq_f32_s32(vdupq_n_s32(w1))));
v = vaddq_f32(v, vmulq_f32(c2, vcvtq_f32_s32(vdupq_n_s32(w2))));
return vmulq_f32(v, vdupq_n_f32(wsum));
}
static inline int32x4_t InterpolateI(const int32x4_t &c0, const int32x4_t &c1, const int32x4_t &c2, int w0, int w1, int w2, float wsum) {
return vcvtq_s32_f32(InterpolateF(vcvtq_f32_s32(c0), vcvtq_f32_s32(c1), vcvtq_f32_s32(c2), w0, w1, w2, wsum));
}
#endif
// NOTE: When not casting color0 and color1 to float vectors, this code suffers from severe overflow issues.
// Not sure if that should be regarded as a bug or if casting to float is a valid fix.
static inline Vec4<int> Interpolate(const Vec4<int> &c0, const Vec4<int> &c1, const Vec4<int> &c2, int w0, int w1, int w2, float wsum) {
#if (defined(_M_SSE) || PPSSPP_ARCH(ARM64_NEON)) && !PPSSPP_ARCH(X86)
return Vec4<int>(InterpolateI(c0.ivec, c1.ivec, c2.ivec, w0, w1, w2, wsum));
#else
return ((c0.Cast<float>() * w0 + c1.Cast<float>() * w1 + c2.Cast<float>() * w2) * wsum).Cast<int>();
#endif
}
static inline Vec3<int> Interpolate(const Vec3<int> &c0, const Vec3<int> &c1, const Vec3<int> &c2, int w0, int w1, int w2, float wsum) {
#if (defined(_M_SSE) || PPSSPP_ARCH(ARM64_NEON)) && !PPSSPP_ARCH(X86)
return Vec3<int>(InterpolateI(c0.ivec, c1.ivec, c2.ivec, w0, w1, w2, wsum));
#else
return ((c0.Cast<float>() * w0 + c1.Cast<float>() * w1 + c2.Cast<float>() * w2) * wsum).Cast<int>();
#endif
}
static inline Vec4<float> Interpolate(const float &c0, const float &c1, const float &c2, const Vec4<float> &w0, const Vec4<float> &w1, const Vec4<float> &w2, const Vec4<float> &wsum_recip) {
#if defined(_M_SSE) && !PPSSPP_ARCH(X86)
__m128 v = _mm_mul_ps(w0.vec, _mm_set1_ps(c0));
v = _mm_add_ps(v, _mm_mul_ps(w1.vec, _mm_set1_ps(c1)));
v = _mm_add_ps(v, _mm_mul_ps(w2.vec, _mm_set1_ps(c2)));
return _mm_mul_ps(v, wsum_recip.vec);
#elif PPSSPP_ARCH(ARM64_NEON)
float32x4_t v = vmulq_f32(w0.vec, vdupq_n_f32(c0));
v = vaddq_f32(v, vmulq_f32(w1.vec, vdupq_n_f32(c1)));
v = vaddq_f32(v, vmulq_f32(w2.vec, vdupq_n_f32(c2)));
return vmulq_f32(v, wsum_recip.vec);
#else
return (w0 * c0 + w1 * c1 + w2 * c2) * wsum_recip;
#endif
}
static inline Vec4<float> Interpolate(const float &c0, const float &c1, const float &c2, const Vec4<int> &w0, const Vec4<int> &w1, const Vec4<int> &w2, const Vec4<float> &wsum_recip) {
return Interpolate(c0, c1, c2, w0.Cast<float>(), w1.Cast<float>(), w2.Cast<float>(), wsum_recip);
}
void ComputeRasterizerState(RasterizerState *state, BinManager *binner) {
ComputePixelFuncID(&state->pixelID);
state->drawPixel = Rasterizer::GetSingleFunc(state->pixelID, binner);
state->enableTextures = gstate.isTextureMapEnabled() && !state->pixelID.clearMode;
if (state->enableTextures) {
ComputeSamplerID(&state->samplerID);
state->linear = Sampler::GetLinearFunc(state->samplerID, binner);
state->nearest = Sampler::GetNearestFunc(state->samplerID, binner);
// Since the definitions are the same, just force this setting using the func pointer.
if (g_Config.iTexFiltering == TEX_FILTER_FORCE_LINEAR) {
state->nearest = state->linear;
} else if (g_Config.iTexFiltering == TEX_FILTER_FORCE_NEAREST) {
state->linear = state->nearest;
}
state->maxTexLevel = state->samplerID.hasAnyMips ? gstate.getTextureMaxLevel() : 0;
GETextureFormat texfmt = state->samplerID.TexFmt();
for (uint8_t i = 0; i <= state->maxTexLevel; i++) {
u32 texaddr = gstate.getTextureAddress(i);
state->texaddr[i] = texaddr;
state->texbufw[i] = (uint16_t)GetTextureBufw(i, texaddr, texfmt);
if (Memory::IsValidAddress(texaddr))
state->texptr[i] = Memory::GetPointerUnchecked(texaddr);
else
state->texptr[i] = nullptr;
}
state->textureLodSlope = gstate.getTextureLodSlope();
state->texLevelMode = gstate.getTexLevelMode();
state->texLevelOffset = (int8_t)gstate.getTexLevelOffset16();
state->mipFilt = gstate.isMipmapFilteringEnabled();
state->minFilt = gstate.isMinifyFilteringEnabled();
state->magFilt = gstate.isMagnifyFilteringEnabled();
state->textureProj = gstate.getUVGenMode() == GE_TEXMAP_TEXTURE_MATRIX;
if (state->textureProj) {
// We may be able to optimize this off. This is actually kinda common.
const bool qZeroST = gstate.tgenMatrix[2] == 0.0f && gstate.tgenMatrix[5] == 0.0f;
const bool qZeroQ = gstate.tgenMatrix[8] == 0.0f;
// Two common cases: the source q factor is zero, OR source is UV.
const bool qFactorZero = gstate.getUVProjMode() == GE_PROJMAP_UV;
if (qZeroST && (qZeroQ || qFactorZero) && gstate.tgenMatrix[11] == 1.0f) {
state->textureProj = false;
}
}
}
state->shadeGouraud = !gstate.isModeClear() && gstate.getShadeMode() == GE_SHADE_GOURAUD;
state->throughMode = gstate.isModeThrough();
state->antialiasLines = gstate.isAntiAliasEnabled();
#if defined(SOFTGPU_MEMORY_TAGGING_DETAILED) || defined(SOFTGPU_MEMORY_TAGGING_BASIC)
DisplayList currentList{};
if (gpuDebug)
gpuDebug->GetCurrentDisplayList(currentList);
state->listPC = currentList.pc;
#endif
}
static inline void CalculateRasterStateFlags(RasterizerState *state, const VertexData &v0, bool useColor) {
if (useColor) {
if ((v0.color0 & 0x00FFFFFF) != 0x00FFFFFF)
state->flags |= RasterizerStateFlags::VERTEX_NON_FULL_WHITE;
uint8_t alpha = v0.color0 >> 24;
if (alpha != 0)
state->flags |= RasterizerStateFlags::VERTEX_ALPHA_NON_ZERO;
if (alpha != 0xFF)
state->flags |= RasterizerStateFlags::VERTEX_ALPHA_NON_FULL;
}
if (!(v0.fogdepth >= 1.0f))
state->flags |= RasterizerStateFlags::VERTEX_HAS_FOG;
}
void CalculateRasterStateFlags(RasterizerState *state, const VertexData &v0) {
CalculateRasterStateFlags(state, v0, true);
}
void CalculateRasterStateFlags(RasterizerState *state, const VertexData &v0, const VertexData &v1, bool forceFlat) {
CalculateRasterStateFlags(state, v0, !forceFlat && state->shadeGouraud);
CalculateRasterStateFlags(state, v1, true);
}
void CalculateRasterStateFlags(RasterizerState *state, const VertexData &v0, const VertexData &v1, const VertexData &v2) {
CalculateRasterStateFlags(state, v0, state->shadeGouraud);
CalculateRasterStateFlags(state, v1, state->shadeGouraud);
CalculateRasterStateFlags(state, v2, true);
}
static inline int OptimizePixelIDFlags(const RasterizerStateFlags &flags) {
return (int)flags & (int)RasterizerStateFlags::OPTIMIZED_PIXELID;
}
static inline int OptimizeSamplerIDFlags(const RasterizerStateFlags &flags) {
return (int)flags & (int)RasterizerStateFlags::OPTIMIZED_SAMPLERID;
}
static inline int OptimizeAllFlags(const RasterizerStateFlags &flags) {
return OptimizePixelIDFlags(flags) | OptimizeSamplerIDFlags(flags);
}
static inline RasterizerStateFlags ClearFlags(const RasterizerStateFlags &flags, const RasterizerStateFlags &mask) {
int clearBits = (int)flags & (int)mask;
return (RasterizerStateFlags)((int)flags & ~clearBits);
}
static inline RasterizerStateFlags ReplacePixelIDFlags(const RasterizerStateFlags &flags, const RasterizerStateFlags &replace) {
RasterizerStateFlags updated = ClearFlags(flags, RasterizerStateFlags::OPTIMIZED_PIXELID);
return updated | (RasterizerStateFlags)OptimizePixelIDFlags(replace);
}
static inline RasterizerStateFlags ReplaceSamplerIDFlags(const RasterizerStateFlags &flags, const RasterizerStateFlags &replace) {
RasterizerStateFlags updated = ClearFlags(flags, RasterizerStateFlags::OPTIMIZED_SAMPLERID);
return updated | (RasterizerStateFlags)OptimizeSamplerIDFlags(replace);
}
static bool CheckClutAlphaFull(RasterizerState *state) {
// We only need to check it once.
if (state->flags & RasterizerStateFlags::CLUT_ALPHA_CHECKED)
return !(state->flags & RasterizerStateFlags::CLUT_ALPHA_NON_FULL);
// For now, let's keep things simple.
const SamplerID &samplerID = state->samplerID;
if (samplerID.hasClutOffset || !samplerID.useSharedClut)
return false;
uint32_t count = samplerID.TexFmt() == GE_TFMT_CLUT4 ? 16 : 256;
if (samplerID.hasClutMask)
count = std::min(count, ((samplerID.cached.clutFormat >> 8) & 0xFF) + 1);
u32 alphaSum = 0xFFFFFFFF;
if (samplerID.ClutFmt() == GE_CMODE_32BIT_ABGR8888) {
CheckMask32((const uint32_t *)samplerID.cached.clut, count, &alphaSum);
} else {
CheckMask16((const uint16_t *)samplerID.cached.clut, count, &alphaSum);
}
bool onlyFull = true;
switch (samplerID.ClutFmt()) {
case GE_CMODE_16BIT_BGR5650:
break;
case GE_CMODE_16BIT_ABGR5551:
onlyFull = (alphaSum & 0x8000) != 0;
break;
case GE_CMODE_16BIT_ABGR4444:
onlyFull = (alphaSum & 0xF000) == 0xF000;
break;
case GE_CMODE_32BIT_ABGR8888:
onlyFull = (alphaSum & 0xFF000000) == 0xFF000000;
break;
}
// Might just be different patterns, but if alphaSum != 0, it can't contain zero.
if (alphaSum != 0)
state->flags |= RasterizerStateFlags::CLUT_ALPHA_NON_ZERO;
if (!onlyFull)
state->flags |= RasterizerStateFlags::CLUT_ALPHA_NON_FULL;
state->flags |= RasterizerStateFlags::CLUT_ALPHA_CHECKED;
return onlyFull;
}
static RasterizerStateFlags DetectStateOptimizations(RasterizerState *state) {
// Note: all optimizations must be undoable.
RasterizerStateFlags optimize = RasterizerStateFlags::NONE;
auto &pixelID = state->pixelID;
auto &samplerID = state->samplerID;
bool alphaZero = !(state->flags & RasterizerStateFlags::VERTEX_ALPHA_NON_ZERO);
bool alphaFull = !(state->flags & RasterizerStateFlags::VERTEX_ALPHA_NON_FULL);
bool needTextureAlpha = state->enableTextures && samplerID.useTextureAlpha;
if (!pixelID.clearMode) {
auto &cached = pixelID.cached;
bool alphaBlend = pixelID.alphaBlend || (state->flags & RasterizerStateFlags::OPTIMIZED_BLEND_OFF);
if (needTextureAlpha && alphaBlend && alphaFull) {
bool usesClut = (samplerID.texfmt & 4) != 0;
if (usesClut && CheckClutAlphaFull(state))
needTextureAlpha = false;
}
if (alphaBlend && !needTextureAlpha) {
PixelBlendFactor src = pixelID.AlphaBlendSrc();
PixelBlendFactor dst = pixelID.AlphaBlendDst();
if (state->flags & RasterizerStateFlags::OPTIMIZED_BLEND_SRC)
src = PixelBlendFactor::SRCALPHA;
if (state->flags & RasterizerStateFlags::OPTIMIZED_BLEND_DST)
dst = PixelBlendFactor::INVSRCALPHA;
// Okay, we may be able to convert this to a fixed value.
if (alphaZero || alphaFull) {
// If it was already set and we still can, set it again.
if (src == PixelBlendFactor::SRCALPHA)
optimize |= RasterizerStateFlags::OPTIMIZED_BLEND_SRC;
if (dst == PixelBlendFactor::INVSRCALPHA)
optimize |= RasterizerStateFlags::OPTIMIZED_BLEND_DST;
}
if (alphaFull && (src == PixelBlendFactor::SRCALPHA || src == PixelBlendFactor::ONE) && (dst == PixelBlendFactor::INVSRCALPHA || dst == PixelBlendFactor::ZERO)) {
optimize |= RasterizerStateFlags::OPTIMIZED_BLEND_OFF;
}
}
if (alphaBlend && (needTextureAlpha || !alphaFull)) {
// Okay, we're blending, and we need to. Are we alpha testing?
GEComparison alphaTestFunc = pixelID.AlphaTestFunc();
if (state->flags & RasterizerStateFlags::OPTIMIZED_ALPHATEST_OFF_NE)
alphaTestFunc = GE_COMP_NOTEQUAL;
if (state->flags & RasterizerStateFlags::OPTIMIZED_ALPHATEST_OFF_GT)
alphaTestFunc = GE_COMP_GREATER;
if (state->flags & RasterizerStateFlags::OPTIMIZED_ALPHATEST_ON)
alphaTestFunc = GE_COMP_ALWAYS;
PixelBlendFactor src = pixelID.AlphaBlendSrc();
PixelBlendFactor dst = pixelID.AlphaBlendDst();
if (state->flags & RasterizerStateFlags::OPTIMIZED_BLEND_SRC)
src = PixelBlendFactor::SRCALPHA;
if (state->flags & RasterizerStateFlags::OPTIMIZED_BLEND_DST)
dst = PixelBlendFactor::INVSRCALPHA;
if (alphaTestFunc == GE_COMP_ALWAYS && src == PixelBlendFactor::SRCALPHA && dst == PixelBlendFactor::INVSRCALPHA) {
bool usesClut = (samplerID.texfmt & 4) != 0;
bool couldHaveZeroTexAlpha = true;
if (usesClut && CheckClutAlphaFull(state))
couldHaveZeroTexAlpha = false;
if (state->flags & RasterizerStateFlags::CLUT_ALPHA_NON_ZERO)
couldHaveZeroTexAlpha = false;
// Blending is expensive, since we read the target. Force alpha testing on.
if (!pixelID.depthWrite && !pixelID.stencilTest && couldHaveZeroTexAlpha)
optimize |= RasterizerStateFlags::OPTIMIZED_ALPHATEST_ON;
}
}
bool applyFog = pixelID.applyFog || (state->flags & RasterizerStateFlags::OPTIMIZED_FOG_OFF);
if (applyFog) {
bool hasFog = state->flags & RasterizerStateFlags::VERTEX_HAS_FOG;
if (!hasFog)
optimize |= RasterizerStateFlags::OPTIMIZED_FOG_OFF;
}
}
if (state->enableTextures) {
bool colorFull = !(state->flags & RasterizerStateFlags::VERTEX_NON_FULL_WHITE);
if (colorFull && (!needTextureAlpha || alphaFull)) {
// Modulate is common, sometimes even with a fixed color. Replace is cheaper.
GETexFunc texFunc = samplerID.TexFunc();
if (state->flags & RasterizerStateFlags::OPTIMIZED_TEXREPLACE)
texFunc = GE_TEXFUNC_MODULATE;
if (texFunc == GE_TEXFUNC_MODULATE)
optimize |= RasterizerStateFlags::OPTIMIZED_TEXREPLACE;
}
bool usesClut = (samplerID.texfmt & 4) != 0;
if (usesClut && alphaFull && samplerID.useTextureAlpha) {
GEComparison alphaTestFunc = pixelID.AlphaTestFunc();
// We optimize > 0 to != 0, so this is especially common.
if (state->flags & RasterizerStateFlags::OPTIMIZED_ALPHATEST_OFF_NE)
alphaTestFunc = GE_COMP_NOTEQUAL;
// > 16, 8, or similar are also very common.
if (state->flags & RasterizerStateFlags::OPTIMIZED_ALPHATEST_OFF_GT)
alphaTestFunc = GE_COMP_GREATER;
if (state->flags & RasterizerStateFlags::OPTIMIZED_ALPHATEST_ON)
alphaTestFunc = GE_COMP_ALWAYS;
bool alphaTest = (alphaTestFunc == GE_COMP_NOTEQUAL || alphaTestFunc == GE_COMP_GREATER) && pixelID.alphaTestRef < 0xFF && !state->pixelID.hasAlphaTestMask;
if (alphaTest) {
bool canSkipAlphaTest = CheckClutAlphaFull(state);
if ((state->flags & RasterizerStateFlags::CLUT_ALPHA_NON_ZERO) && pixelID.alphaTestRef == 0)
canSkipAlphaTest = true;
if (canSkipAlphaTest)
optimize |= alphaTestFunc == GE_COMP_NOTEQUAL ? RasterizerStateFlags::OPTIMIZED_ALPHATEST_OFF_NE : RasterizerStateFlags::OPTIMIZED_ALPHATEST_OFF_GT;
}
}
}
return optimize;
}
static bool ApplyStateOptimizations(RasterizerState *state, const RasterizerStateFlags &optimize) {
bool changed = false;
// Check if we can compile the new funcs before replacing.
if (OptimizePixelIDFlags(state->flags) != OptimizePixelIDFlags(optimize)) {
bool canFull = !(state->flags & RasterizerStateFlags::VERTEX_ALPHA_NON_FULL);
PixelFuncID pixelID = state->pixelID;
if (optimize & RasterizerStateFlags::OPTIMIZED_BLEND_OFF)
pixelID.alphaBlend = false;
else if (state->flags & RasterizerStateFlags::OPTIMIZED_BLEND_OFF)
pixelID.alphaBlend = true;
if (optimize & RasterizerStateFlags::OPTIMIZED_BLEND_SRC)
pixelID.alphaBlendSrc = (uint8_t)(canFull ? PixelBlendFactor::ONE : PixelBlendFactor::ZERO);
else if (state->flags & RasterizerStateFlags::OPTIMIZED_BLEND_SRC)
pixelID.alphaBlendSrc = (uint8_t)PixelBlendFactor::SRCALPHA;
if (optimize & RasterizerStateFlags::OPTIMIZED_BLEND_DST)
pixelID.alphaBlendDst = (uint8_t)(canFull ? PixelBlendFactor::ZERO : PixelBlendFactor::ONE);
else if (state->flags & RasterizerStateFlags::OPTIMIZED_BLEND_DST)
pixelID.alphaBlendDst = (uint8_t)PixelBlendFactor::INVSRCALPHA;
if (optimize & RasterizerStateFlags::OPTIMIZED_FOG_OFF)
pixelID.applyFog = false;
else if (state->flags & RasterizerStateFlags::OPTIMIZED_FOG_OFF)
pixelID.applyFog = true;
if (optimize & (RasterizerStateFlags::OPTIMIZED_ALPHATEST_OFF_NE | RasterizerStateFlags::OPTIMIZED_ALPHATEST_OFF_GT))
pixelID.alphaTestFunc = GE_COMP_ALWAYS;
else if (state->flags & RasterizerStateFlags::OPTIMIZED_ALPHATEST_OFF_NE)
pixelID.alphaTestFunc = GE_COMP_NOTEQUAL;
else if (state->flags & RasterizerStateFlags::OPTIMIZED_ALPHATEST_OFF_GT)
pixelID.alphaTestFunc = GE_COMP_GREATER;
else if (optimize & RasterizerStateFlags::OPTIMIZED_ALPHATEST_ON) {
pixelID.alphaTestFunc = GE_COMP_NOTEQUAL;
pixelID.alphaTestRef = 0;
pixelID.hasAlphaTestMask = false;
} else if (state->flags & RasterizerStateFlags::OPTIMIZED_ALPHATEST_ON) {
pixelID.alphaTestFunc = GE_COMP_ALWAYS;
}
SingleFunc drawPixel = Rasterizer::GetSingleFunc(pixelID, nullptr);
// Can't compile during runtime. This failing is a bit of a problem when undoing...
if (drawPixel) {
state->drawPixel = drawPixel;
memcpy(&state->pixelID, &pixelID, sizeof(PixelFuncID));
state->flags = ReplacePixelIDFlags(state->flags, optimize) | RasterizerStateFlags::OPTIMIZED;
changed = true;
}
}
if (OptimizeSamplerIDFlags(state->flags) != OptimizeSamplerIDFlags(optimize)) {
SamplerID samplerID = state->samplerID;
if (optimize & RasterizerStateFlags::OPTIMIZED_TEXREPLACE)
samplerID.texFunc = (uint8_t)GE_TEXFUNC_REPLACE;
else if (state->flags & RasterizerStateFlags::OPTIMIZED_TEXREPLACE)
samplerID.texFunc = (uint8_t)GE_TEXFUNC_MODULATE;
Sampler::LinearFunc linear = Sampler::GetLinearFunc(samplerID, nullptr);
Sampler::LinearFunc nearest = Sampler::GetNearestFunc(samplerID, nullptr);
// Can't compile during runtime. This failing is a bit of a problem when undoing...
if (linear && nearest) {
// Since the definitions are the same, just force this setting using the func pointer.
if (g_Config.iTexFiltering == TEX_FILTER_FORCE_LINEAR) {
state->nearest = linear;
state->linear = linear;
} else if (g_Config.iTexFiltering == TEX_FILTER_FORCE_NEAREST) {
state->nearest = nearest;
state->linear = nearest;
} else {
state->nearest = nearest;
state->linear = linear;
}
memcpy(&state->samplerID, &samplerID, sizeof(SamplerID));
state->flags = ReplaceSamplerIDFlags(state->flags, optimize) | RasterizerStateFlags::OPTIMIZED;
changed = true;
}
}
state->lastFlags = state->flags;
return changed;
}
bool OptimizeRasterState(RasterizerState *state) {
if (state->flags == state->lastFlags)
return false;
RasterizerStateFlags optimize = DetectStateOptimizations(state);
// If it was optimized before, just revert and don't churn.
if ((state->flags & RasterizerStateFlags::OPTIMIZED) && OptimizeAllFlags(state->flags) != OptimizeAllFlags(optimize)) {
optimize = RasterizerStateFlags::NONE;
} else if (optimize == RasterizerStateFlags::NONE && !(state->flags & RasterizerStateFlags::OPTIMIZED)) {
state->lastFlags = state->flags;
return false;
}
return ApplyStateOptimizations(state, optimize);
}
RasterizerState OptimizeFlatRasterizerState(const RasterizerState &origState, const VertexData &v1) {
uint8_t alpha = v1.color0 >> 24;
RasterizerState state = origState;
// Sometimes, a particular draw can do better than the overall state.
state.flags = ClearFlags(state.flags, RasterizerStateFlags::VERTEX_FLAT_RESET);
CalculateRasterStateFlags(&state, v1, true);
RasterizerStateFlags optimize = DetectStateOptimizations(&state);
if (OptimizeAllFlags(state.flags) != OptimizeAllFlags(optimize)) {
ApplyStateOptimizations(&state, optimize);
return state;
}
return origState;
}
static inline u8 ClampFogDepth(float fogdepth) {
union FloatBits {
float f;
u32 u;
};
FloatBits f;
f.f = fogdepth;
u32 exp = f.u >> 23;
if ((f.u & 0x80000000) != 0 || exp <= 126 - 8)
return 0;
if (exp > 126)
return 255;
u32 mantissa = (f.u & 0x007FFFFF) | 0x00800000;
return mantissa >> (16 + 126 - exp);
}
static inline void GetTextureCoordinates(const VertexData& v0, const VertexData& v1, const float p, float &s, float &t) {
// Note that for environment mapping, texture coordinates have been calculated during lighting
float q0 = 1.f / v0.clipw;
float q1 = 1.f / v1.clipw;
float wq0 = p * q0;
float wq1 = (1.0f - p) * q1;
float q_recip = 1.0f / (wq0 + wq1);
s = (v0.texturecoords.s() * wq0 + v1.texturecoords.s() * wq1) * q_recip;
t = (v0.texturecoords.t() * wq0 + v1.texturecoords.t() * wq1) * q_recip;
}
static inline void GetTextureCoordinatesProj(const VertexData& v0, const VertexData& v1, const float p, float &s, float &t) {
// This is for texture matrix projection.
float q0 = 1.f / v0.clipw;
float q1 = 1.f / v1.clipw;
float wq0 = p * q0;
float wq1 = (1.0f - p) * q1;
float q_recip = 1.0f / (v0.texturecoords.q() * wq0 + v1.texturecoords.q() * wq1);
s = (v0.texturecoords.s() * wq0 + v1.texturecoords.s() * wq1) * q_recip;
t = (v0.texturecoords.t() * wq0 + v1.texturecoords.t() * wq1) * q_recip;
}
static inline void GetTextureCoordinates(const VertexData &v0, const VertexData &v1, const VertexData &v2, const Vec4<int> &w0, const Vec4<int> &w1, const Vec4<int> &w2, const Vec4<float> &wsum_recip, Vec4<float> &s, Vec4<float> &t) {
// Note that for environment mapping, texture coordinates have been calculated during lighting.
float q0 = 1.f / v0.clipw;
float q1 = 1.f / v1.clipw;
float q2 = 1.f / v2.clipw;
Vec4<float> wq0 = w0.Cast<float>() * q0;
Vec4<float> wq1 = w1.Cast<float>() * q1;
Vec4<float> wq2 = w2.Cast<float>() * q2;
Vec4<float> q_recip = (wq0 + wq1 + wq2).Reciprocal();
s = Interpolate(v0.texturecoords.s(), v1.texturecoords.s(), v2.texturecoords.s(), wq0, wq1, wq2, q_recip);
t = Interpolate(v0.texturecoords.t(), v1.texturecoords.t(), v2.texturecoords.t(), wq0, wq1, wq2, q_recip);
}
static inline void GetTextureCoordinatesProj(const VertexData &v0, const VertexData &v1, const VertexData &v2, const Vec4<int> &w0, const Vec4<int> &w1, const Vec4<int> &w2, const Vec4<float> &wsum_recip, Vec4<float> &s, Vec4<float> &t) {
// This is for texture matrix projection.
float q0 = 1.f / v0.clipw;
float q1 = 1.f / v1.clipw;
float q2 = 1.f / v2.clipw;
Vec4<float> wq0 = w0.Cast<float>() * q0;
Vec4<float> wq1 = w1.Cast<float>() * q1;
Vec4<float> wq2 = w2.Cast<float>() * q2;
// Here, Interpolate() is a bit suboptimal, since
// there's no need to multiply by 1.0f.
Vec4<float> q_recip = Interpolate(v0.texturecoords.q(), v1.texturecoords.q(), v2.texturecoords.q(), wq0, wq1, wq2, Vec4<float>::AssignToAll(1.0f)).Reciprocal();
s = Interpolate(v0.texturecoords.s(), v1.texturecoords.s(), v2.texturecoords.s(), wq0, wq1, wq2, q_recip);
t = Interpolate(v0.texturecoords.t(), v1.texturecoords.t(), v2.texturecoords.t(), wq0, wq1, wq2, q_recip);
}
static inline void SetPixelDepth(int x, int y, int stride, u16 value) {
depthbuf.Set16(x, y, stride, value);
}
static inline bool IsRightSideOrFlatBottomLine(const Vec2<int>& vertex, const Vec2<int>& line1, const Vec2<int>& line2)
{
if (line1.y == line2.y) {
// just check if vertex is above us => bottom line parallel to x-axis
return vertex.y < line1.y;
} else {
// check if vertex is on our left => right side
return vertex.x < line1.x + (line2.x - line1.x) * (vertex.y - line1.y) / (line2.y - line1.y);
}
}
static inline Vec4IntResult SOFTRAST_CALL ApplyTexturing(float s, float t, Vec4IntArg prim_color, int texlevel, int frac_texlevel, bool bilinear, const RasterizerState &state) {
const u8 **tptr0 = const_cast<const u8 **>(&state.texptr[texlevel]);
const uint16_t *bufw0 = &state.texbufw[texlevel];
if (!bilinear) {
return state.nearest(s, t, prim_color, tptr0, bufw0, texlevel, frac_texlevel, state.samplerID);
}
return state.linear(s, t, prim_color, tptr0, bufw0, texlevel, frac_texlevel, state.samplerID);
}
static inline Vec4IntResult SOFTRAST_CALL ApplyTexturingSingle(float s, float t, Vec4IntArg prim_color, int texlevel, int frac_texlevel, bool bilinear, const RasterizerState &state) {
return ApplyTexturing(s, t, prim_color, texlevel, frac_texlevel, bilinear, state);
}
// Produces a signed 1.27.4 value.
static int TexLog2(float delta) {
union FloatBits {
float f;
u32 u;
};
FloatBits f;
f.f = delta;
// Use the exponent as the tex level, and the top mantissa bits for a frac.
// We can't support more than 4 bits of frac, so truncate.
int useful = (f.u >> 19) & 0x0FFF;
// Now offset so the exponent aligns with log2f (exp=127 is 0.)
return useful - 127 * 16;
}
static inline void CalculateSamplingParams(const float ds, const float dt, float w, const RasterizerState &state, int &level, int &levelFrac, bool &filt) {
const int width = 1 << state.samplerID.width0Shift;
const int height = 1 << state.samplerID.height0Shift;
// With 8 bits of fraction (because texslope can be fairly precise.)
int detail;
switch (state.TexLevelMode()) {
case GE_TEXLEVEL_MODE_AUTO:
detail = TexLog2(std::max(std::abs(ds * width), std::abs(dt * height)));
break;
case GE_TEXLEVEL_MODE_SLOPE:
// This is always offset by an extra texlevel.
detail = TexLog2(2.0f * w * state.textureLodSlope);
break;
case GE_TEXLEVEL_MODE_CONST:
default:
// Unused value 3 operates the same as CONST.
detail = 0;
break;
}
// Add in the bias (used in all modes), with 4 bits of fraction.
detail += state.texLevelOffset;
if (detail > 0 && state.maxTexLevel > 0) {
bool mipFilt = state.mipFilt;
int level8 = std::min(detail, state.maxTexLevel * 16);
if (!mipFilt) {
// Round up at 1.5.
level8 += 8;
}
level = level8 >> 4;
levelFrac = mipFilt ? level8 & 0xF : 0;
} else {
level = 0;
levelFrac = 0;
}
if (detail > 0)
filt = state.minFilt;
else
filt = state.magFilt;
}
static inline void ApplyTexturing(const RasterizerState &state, Vec4<int> *prim_color, const Vec4<int> &mask, const Vec4<float> &s, const Vec4<float> &t, float w) {
float ds = s[1] - s[0];
float dt = t[2] - t[0];
int level;
int levelFrac;
bool bilinear;
CalculateSamplingParams(ds, dt, w, state, level, levelFrac, bilinear);
PROFILE_THIS_SCOPE("sampler");
for (int i = 0; i < 4; ++i) {
if (mask[i] >= 0)
prim_color[i] = ApplyTexturing(s[i], t[i], ToVec4IntArg(prim_color[i]), level, levelFrac, bilinear, state);
}
}
static inline Vec4<int> SOFTRAST_CALL CheckDepthTestPassed4(const Vec4<int> &mask, GEComparison func, int x, int y, int stride, Vec4<int> z) {
// Skip the depth buffer read if we're masked already.
#if defined(_M_SSE)
__m128i result = SAFE_M128I(mask.ivec);
int maskbits = _mm_movemask_epi8(result);
if (maskbits >= 0xFFFF)
return mask;
#else
Vec4<int> result = mask;
if (mask.x < 0 && mask.y < 0 && mask.z < 0 && mask.w < 0)
return result;
#endif
// Read in the existing depth values.
#if defined(_M_SSE)
// Tried using flags from maskbits to skip dwords... seemed neutral.
__m128i refz = _mm_cvtsi32_si128(*(u32 *)depthbuf.Get16Ptr(x, y, stride));
refz = _mm_unpacklo_epi32(refz, _mm_cvtsi32_si128(*(u32 *)depthbuf.Get16Ptr(x, y + 1, stride)));
refz = _mm_unpacklo_epi16(refz, _mm_setzero_si128());
#else
Vec4<int> refz(depthbuf.Get16(x, y, stride), depthbuf.Get16(x + 1, y, stride), depthbuf.Get16(x, y + 1, stride), depthbuf.Get16(x + 1, y + 1, stride));
#endif
switch (func) {
case GE_COMP_NEVER:
#if defined(_M_SSE)
result = _mm_set1_epi32(-1);
#else
result = Vec4<int>::AssignToAll(-1);
#endif
break;
case GE_COMP_ALWAYS:
break;
case GE_COMP_EQUAL:
#if defined(_M_SSE)
result = _mm_or_si128(result, _mm_xor_si128(_mm_cmpeq_epi32(z.ivec, refz), _mm_set1_epi32(-1)));
#else
for (int i = 0; i < 4; ++i)
result[i] |= z[i] != refz[i] ? -1 : 0;
#endif
break;
case GE_COMP_NOTEQUAL:
#if defined(_M_SSE)
result = _mm_or_si128(result, _mm_cmpeq_epi32(z.ivec, refz));
#else
for (int i = 0; i < 4; ++i)
result[i] |= z[i] == refz[i] ? -1 : 0;
#endif
break;
case GE_COMP_LESS:
#if defined(_M_SSE)
result = _mm_or_si128(result, _mm_cmpgt_epi32(z.ivec, refz));
result = _mm_or_si128(result, _mm_cmpeq_epi32(z.ivec, refz));
#else
for (int i = 0; i < 4; ++i)
result[i] |= z[i] >= refz[i] ? -1 : 0;
#endif
break;
case GE_COMP_LEQUAL:
#if defined(_M_SSE)
result = _mm_or_si128(result, _mm_cmpgt_epi32(z.ivec, refz));
#else
for (int i = 0; i < 4; ++i)
result[i] |= z[i] > refz[i] ? -1 : 0;
#endif
break;
case GE_COMP_GREATER:
#if defined(_M_SSE)
result = _mm_or_si128(result, _mm_cmplt_epi32(z.ivec, refz));
result = _mm_or_si128(result, _mm_cmpeq_epi32(z.ivec, refz));
#else
for (int i = 0; i < 4; ++i)
result[i] |= z[i] <= refz[i] ? -1 : 0;
#endif
break;
case GE_COMP_GEQUAL:
#if defined(_M_SSE)
result = _mm_or_si128(result, _mm_cmplt_epi32(z.ivec, refz));
#else
for (int i = 0; i < 4; ++i)
result[i] |= z[i] < refz[i] ? -1 : 0;
#endif
break;
}
return result;
}
template <bool useSSE4>
struct TriangleEdge {
Vec4<int> Start(const ScreenCoords &v0, const ScreenCoords &v1, const ScreenCoords &origin);
inline Vec4<int> StepX(const Vec4<int> &w);
inline Vec4<int> StepY(const Vec4<int> &w);
inline void NarrowMinMaxX(const Vec4<int> &w, int64_t minX, int64_t &rowMinX, int64_t &rowMaxX);
inline Vec4<int> StepXTimes(const Vec4<int> &w, int c);
Vec4<int> stepX;
Vec4<int> stepY;
};
#if defined(_M_SSE) && !PPSSPP_ARCH(X86)
#if defined(__GNUC__) || defined(__clang__) || defined(__INTEL_COMPILER)
[[gnu::target("sse4.1")]]
#endif
static inline __m128i SOFTRAST_CALL TriangleEdgeStartSSE4(__m128i initX, __m128i initY, int xf, int yf, int c) {
initX = _mm_mullo_epi32(initX, _mm_set1_epi32(xf));
initY = _mm_mullo_epi32(initY, _mm_set1_epi32(yf));
return _mm_add_epi32(_mm_add_epi32(initX, initY), _mm_set1_epi32(c));
}
#endif
template <bool useSSE4>
Vec4<int> TriangleEdge<useSSE4>::Start(const ScreenCoords &v0, const ScreenCoords &v1, const ScreenCoords &origin) {
// Start at pixel centers.
static constexpr int centerOff = (SCREEN_SCALE_FACTOR / 2) - 1;
static constexpr int centerPlus1 = SCREEN_SCALE_FACTOR + centerOff;
Vec4<int> initX = Vec4<int>::AssignToAll(origin.x) + Vec4<int>(centerOff, centerPlus1, centerOff, centerPlus1);
Vec4<int> initY = Vec4<int>::AssignToAll(origin.y) + Vec4<int>(centerOff, centerOff, centerPlus1, centerPlus1);
// orient2d refactored.
int xf = v0.y - v1.y;
int yf = v1.x - v0.x;
int c = v1.y * v0.x - v1.x * v0.y;
stepX = Vec4<int>::AssignToAll(xf * SCREEN_SCALE_FACTOR * 2);
stepY = Vec4<int>::AssignToAll(yf * SCREEN_SCALE_FACTOR * 2);
#if defined(_M_SSE) && !PPSSPP_ARCH(X86)
if constexpr (useSSE4)
return TriangleEdgeStartSSE4(initX.ivec, initY.ivec, xf, yf, c);
#endif
return Vec4<int>::AssignToAll(xf) * initX + Vec4<int>::AssignToAll(yf) * initY + Vec4<int>::AssignToAll(c);
}
template <bool useSSE4>
inline Vec4<int> TriangleEdge<useSSE4>::StepX(const Vec4<int> &w) {
#if defined(_M_SSE) && !PPSSPP_ARCH(X86)
return _mm_add_epi32(w.ivec, stepX.ivec);
#elif PPSSPP_ARCH(ARM64_NEON)
return vaddq_s32(w.ivec, stepX.ivec);
#else
return w + stepX;
#endif
}
template <bool useSSE4>
inline Vec4<int> TriangleEdge<useSSE4>::StepY(const Vec4<int> &w) {
#if defined(_M_SSE) && !PPSSPP_ARCH(X86)
return _mm_add_epi32(w.ivec, stepY.ivec);
#elif PPSSPP_ARCH(ARM64_NEON)
return vaddq_s32(w.ivec, stepY.ivec);
#else
return w + stepY;
#endif
}
#if defined(_M_SSE) && !PPSSPP_ARCH(X86)
#if defined(__GNUC__) || defined(__clang__) || defined(__INTEL_COMPILER)
[[gnu::target("sse4.1")]]
#endif
static inline int SOFTRAST_CALL MaxWeightSSE4(__m128i w) {
__m128i max2 = _mm_max_epi32(w, _mm_shuffle_epi32(w, _MM_SHUFFLE(3, 2, 3, 2)));
__m128i max1 = _mm_max_epi32(max2, _mm_shuffle_epi32(max2, _MM_SHUFFLE(1, 1, 1, 1)));
return _mm_cvtsi128_si32(max1);
}
#endif
template <bool useSSE4>
void TriangleEdge<useSSE4>::NarrowMinMaxX(const Vec4<int> &w, int64_t minX, int64_t &rowMinX, int64_t &rowMaxX) {
int wmax;
#if defined(_M_SSE) && !PPSSPP_ARCH(X86)
if constexpr (useSSE4) {
wmax = MaxWeightSSE4(w.ivec);
} else {
wmax = std::max(std::max(w.x, w.y), std::max(w.z, w.w));
}
#elif PPSSPP_ARCH(ARM64_NEON)
int32x2_t wmax_temp = vpmax_s32(vget_low_s32(w.ivec), vget_high_s32(w.ivec));
wmax = vget_lane_s32(vpmax_s32(wmax_temp, wmax_temp), 0);
#else
wmax = std::max(std::max(w.x, w.y), std::max(w.z, w.w));
#endif
if (wmax < 0) {
if (stepX.x > 0) {
int steps = -wmax / stepX.x;
rowMinX = std::max(rowMinX, minX + steps * SCREEN_SCALE_FACTOR * 2);
} else if (stepX.x <= 0) {
rowMinX = rowMaxX + 1;
}
}
if (wmax >= 0 && stepX.x < 0) {
int steps = (-wmax / stepX.x) + 1;
rowMaxX = std::min(rowMaxX, minX + steps * SCREEN_SCALE_FACTOR * 2);
}
}
#if defined(_M_SSE) && !PPSSPP_ARCH(X86)
#if defined(__GNUC__) || defined(__clang__) || defined(__INTEL_COMPILER)
[[gnu::target("sse4.1")]]
#endif
static inline __m128i SOFTRAST_CALL StepTimesSSE4(__m128i w, __m128i step, int c) {
return _mm_add_epi32(w, _mm_mullo_epi32(_mm_set1_epi32(c), step));
}
#endif
template <bool useSSE4>
inline Vec4<int> TriangleEdge<useSSE4>::StepXTimes(const Vec4<int> &w, int c) {
#if defined(_M_SSE) && !PPSSPP_ARCH(X86)
if constexpr (useSSE4)
return StepTimesSSE4(w.ivec, stepX.ivec, c);
#elif PPSSPP_ARCH(ARM64_NEON)
return vaddq_s32(w.ivec, vmulq_s32(vdupq_n_s32(c), stepX.ivec));
#endif
return w + stepX * c;
}
static inline Vec4<int> MakeMask(const Vec4<int> &w0, const Vec4<int> &w1, const Vec4<int> &w2, const Vec4<int> &bias0, const Vec4<int> &bias1, const Vec4<int> &bias2, const Vec4<int> &scissor) {
#if defined(_M_SSE) && !PPSSPP_ARCH(X86)
__m128i biased0 = _mm_add_epi32(w0.ivec, bias0.ivec);
__m128i biased1 = _mm_add_epi32(w1.ivec, bias1.ivec);
__m128i biased2 = _mm_add_epi32(w2.ivec, bias2.ivec);
return _mm_or_si128(_mm_or_si128(biased0, _mm_or_si128(biased1, biased2)), scissor.ivec);
#elif PPSSPP_ARCH(ARM64_NEON)
int32x4_t biased0 = vaddq_s32(w0.ivec, bias0.ivec);
int32x4_t biased1 = vaddq_s32(w1.ivec, bias1.ivec);
int32x4_t biased2 = vaddq_s32(w2.ivec, bias2.ivec);
return vorrq_s32(vorrq_s32(biased0, vorrq_s32(biased1, biased2)), scissor.ivec);
#else
return (w0 + bias0) | (w1 + bias1) | (w2 + bias2) | scissor;
#endif
}
#if defined(_M_SSE) && !PPSSPP_ARCH(X86)
#if defined(__GNUC__) || defined(__clang__) || defined(__INTEL_COMPILER)
[[gnu::target("sse4.1")]]
#endif
static inline bool SOFTRAST_CALL AnyMaskSSE4(__m128i mask) {
__m128i sig = _mm_srai_epi32(mask, 31);
return _mm_test_all_ones(sig) == 0;
}
#endif
template <bool useSSE4>
static inline bool AnyMask(const Vec4<int> &mask) {
#if defined(_M_SSE) && !PPSSPP_ARCH(X86)
if constexpr (useSSE4) {
return AnyMaskSSE4(mask.ivec);
}
// Source: https://fgiesen.wordpress.com/2013/02/10/optimizing-the-basic-rasterizer/#comment-6676
return _mm_movemask_ps(_mm_castsi128_ps(mask.ivec)) != 15;
#elif PPSSPP_ARCH(ARM64_NEON)
int64x2_t sig = vreinterpretq_s64_s32(vshrq_n_s32(mask.ivec, 31));
return vgetq_lane_s64(sig, 0) != -1 || vgetq_lane_s64(sig, 1) != -1;
#else
return mask.x >= 0 || mask.y >= 0 || mask.z >= 0 || mask.w >= 0;
#endif
}
static inline Vec4<float> EdgeRecip(const Vec4<int> &w0, const Vec4<int> &w1, const Vec4<int> &w2) {
#if defined(_M_SSE) && !PPSSPP_ARCH(X86)
__m128i wsum = _mm_add_epi32(w0.ivec, _mm_add_epi32(w1.ivec, w2.ivec));
// _mm_rcp_ps loses too much precision.
return _mm_div_ps(_mm_set1_ps(1.0f), _mm_cvtepi32_ps(wsum));
#elif PPSSPP_ARCH(ARM64_NEON)
int32x4_t wsum = vaddq_s32(w0.ivec, vaddq_s32(w1.ivec, w2.ivec));
return vdivq_f32(vdupq_n_f32(1.0f), vcvtq_f32_s32(wsum));
#else
return (w0 + w1 + w2).Cast<float>().Reciprocal();
#endif
}
template <bool clearMode, bool useSSE4>
void DrawTriangleSlice(
const VertexData& v0, const VertexData& v1, const VertexData& v2,
int x1, int y1, int x2, int y2,
const RasterizerState &state)
{
Vec4<int> bias0 = Vec4<int>::AssignToAll(IsRightSideOrFlatBottomLine(v0.screenpos.xy(), v1.screenpos.xy(), v2.screenpos.xy()) ? -1 : 0);
Vec4<int> bias1 = Vec4<int>::AssignToAll(IsRightSideOrFlatBottomLine(v1.screenpos.xy(), v2.screenpos.xy(), v0.screenpos.xy()) ? -1 : 0);
Vec4<int> bias2 = Vec4<int>::AssignToAll(IsRightSideOrFlatBottomLine(v2.screenpos.xy(), v0.screenpos.xy(), v1.screenpos.xy()) ? -1 : 0);
const PixelFuncID &pixelID = state.pixelID;
TriangleEdge<useSSE4> e0;
TriangleEdge<useSSE4> e1;
TriangleEdge<useSSE4> e2;
int64_t minX = x1, maxX = x2, minY = y1, maxY = y2;
ScreenCoords pprime(minX, minY, 0);
Vec4<int> w0_base = e0.Start(v1.screenpos, v2.screenpos, pprime);
Vec4<int> w1_base = e1.Start(v2.screenpos, v0.screenpos, pprime);
Vec4<int> w2_base = e2.Start(v0.screenpos, v1.screenpos, pprime);
// The sum of weights should remain constant as we move toward/away from the edges.
const Vec4<float> wsum_recip = EdgeRecip(w0_base, w1_base, w2_base);
// All the z values are the same, no interpolation required.
// This is common, and when we interpolate, we lose accuracy.
const bool flatZ = v0.screenpos.z == v1.screenpos.z && v0.screenpos.z == v2.screenpos.z;