/
rasterize.cpp
2269 lines (1933 loc) · 70.4 KB
/
rasterize.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) 2009-2016 DeSmuME team
This file 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, either version 2 of the License, or
(at your option) any later version.
This file 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 for more details.
You should have received a copy of the GNU General Public License
along with the this software. If not, see <http://www.gnu.org/licenses/>.
*/
//nothing in this file should be assumed to be accurate
//
//the shape rasterizers contained herein are based on code supplied by Chris Hecker from
//http://chrishecker.com/Miscellaneous_Technical_Articles
//TODO - due to a late change of a y-coord flipping, our winding order is wrong
//this causes us to have to flip the verts for every front-facing poly.
//a performance improvement would be to change the winding order logic
//so that this is done less frequently
#include "rasterize.h"
#include <algorithm>
#include <assert.h>
#include <math.h>
#include <string.h>
#if defined(_MSC_VER) && _MSC_VER == 1600
#define SLEEP_HACK_2011
#endif
#ifdef SLEEP_HACK_2011
#include <Windows.h>
#endif
#ifndef _MSC_VER
#include <stdint.h>
#endif
#ifdef ENABLE_SSE2
#include <emmintrin.h>
#endif
#include "matrix.h"
#include "render3D.h"
#include "MMU.h"
#include "NDSSystem.h"
#include "utils/task.h"
#include "filter/filter.h"
#include "filter/xbrz.h"
//#undef FORCEINLINE
//#define FORCEINLINE
//#undef INLINE
//#define INLINE
using std::min;
using std::max;
using std::swap;
template<typename T> T _min(T a, T b, T c) { return min(min(a,b),c); }
template<typename T> T _max(T a, T b, T c) { return max(max(a,b),c); }
template<typename T> T _min(T a, T b, T c, T d) { return min(_min(a,b,d),c); }
template<typename T> T _max(T a, T b, T c, T d) { return max(_max(a,b,d),c); }
static u8 modulate_table[64][64];
static u8 decal_table[32][64][64];
////optimized float floor useful in limited cases
////from http://www.stereopsis.com/FPU.html#convert
////(unfortunately, it relies on certain FPU register settings)
//int Real2Int(double val)
//{
// const double _double2fixmagic = 68719476736.0*1.5; //2^36 * 1.5, (52-_shiftamt=36) uses limited precisicion to floor
// const int _shiftamt = 16; //16.16 fixed point representation,
//
// #ifdef MSB_FIRST
// #define iman_ 1
// #else
// #define iman_ 0
// #endif
//
// val = val + _double2fixmagic;
// return ((int*)&val)[iman_] >> _shiftamt;
//}
//// this probably relies on rounding settings..
//int Real2Int(float val)
//{
// //val -= 0.5f;
// //int temp;
// //__asm {
// // fld val;
// // fistp temp;
// //}
// //return temp;
// return 0;
//}
//doesnt work yet
static FORCEINLINE int fastFloor(float f)
{
float temp = f + 1.f;
int ret = (*((u32*)&temp))&0x7FFFFF;
return ret;
}
//INLINE static void SubmitVertex(int vert_index, VERT& rawvert)
//{
// verts[vert_index] = &rawvert;
//}
static FORCEINLINE int iround(float f) {
return (int)f; //lol
}
typedef int fixed28_4;
// handle floor divides and mods correctly
static FORCEINLINE void FloorDivMod(long Numerator, long Denominator, long &Floor, long &Mod, bool& failure)
{
//These must be caused by invalid or degenerate shapes.. not sure yet.
//check it out in the mario face intro of SM64
//so, we have to take out the assert.
//I do know that we handle SOME invalid shapes without crashing,
//since I see them acting poppy in a way that doesnt happen in the HW.. so alas it is also incorrect.
//This particular incorrectness is not likely ever to get fixed!
//assert(Denominator > 0);
//but we have to bail out since our handling for these cases currently steps scanlines
//the wrong way and goes totally nuts (freezes)
if(Denominator<=0)
failure = true;
if(Numerator >= 0) {
// positive case, C is okay
Floor = Numerator / Denominator;
Mod = Numerator % Denominator;
} else {
// Numerator is negative, do the right thing
Floor = -((-Numerator) / Denominator);
Mod = (-Numerator) % Denominator;
if(Mod) {
// there is a remainder
Floor--; Mod = Denominator - Mod;
}
}
}
static FORCEINLINE fixed28_4 FloatToFixed28_4( float Value ) {
return (fixed28_4)(Value * 16);
}
static FORCEINLINE float Fixed28_4ToFloat( fixed28_4 Value ) {
return Value / 16.0f;
}
//inline fixed16_16 FloatToFixed16_16( float Value ) {
// return (fixed16_6)(Value * 65536);
//}
//inline float Fixed16_16ToFloat( fixed16_16 Value ) {
// return Value / 65536.0;
//}
static FORCEINLINE fixed28_4 Fixed28_4Mul( fixed28_4 A, fixed28_4 B ) {
// could make this asm to prevent overflow
return (A * B) / 16; // 28.4 * 28.4 = 24.8 / 16 = 28.4
}
static FORCEINLINE int Ceil28_4( fixed28_4 Value ) {
int ReturnValue;
int Numerator = Value - 1 + 16;
if(Numerator >= 0) {
ReturnValue = Numerator/16;
} else {
// deal with negative numerators correctly
ReturnValue = -((-Numerator)/16);
ReturnValue -= ((-Numerator) % 16) ? 1 : 0;
}
return ReturnValue;
}
struct edge_fx_fl {
edge_fx_fl() {}
edge_fx_fl(int Top, int Bottom, VERT** verts, bool& failure);
FORCEINLINE int Step();
VERT** verts;
long X, XStep, Numerator, Denominator; // DDA info for x
long ErrorTerm;
int Y, Height; // current y and vertical count
struct Interpolant {
float curr, step, stepExtra;
FORCEINLINE void doStep() { curr += step; }
FORCEINLINE void doStepExtra() { curr += stepExtra; }
FORCEINLINE void initialize(float value) {
curr = value;
step = 0;
stepExtra = 0;
}
FORCEINLINE void initialize(float top, float bottom, float dx, float dy, long XStep, float XPrestep, float YPrestep) {
dx = 0;
dy *= (bottom-top);
curr = top + YPrestep * dy + XPrestep * dx;
step = XStep * dx + dy;
stepExtra = dx;
}
};
static const int NUM_INTERPOLANTS = 7;
union {
struct {
Interpolant invw,z,u,v,color[3];
};
Interpolant interpolants[NUM_INTERPOLANTS];
};
void FORCEINLINE doStepInterpolants() { for(int i=0;i<NUM_INTERPOLANTS;i++) interpolants[i].doStep(); }
void FORCEINLINE doStepExtraInterpolants() { for(int i=0;i<NUM_INTERPOLANTS;i++) interpolants[i].doStepExtra(); }
};
FORCEINLINE edge_fx_fl::edge_fx_fl(int Top, int Bottom, VERT** verts, bool& failure) {
this->verts = verts;
Y = Ceil28_4((fixed28_4)verts[Top]->y);
int YEnd = Ceil28_4((fixed28_4)verts[Bottom]->y);
Height = YEnd - Y;
X = Ceil28_4((fixed28_4)verts[Top]->x);
int XEnd = Ceil28_4((fixed28_4)verts[Bottom]->x);
int Width = XEnd - X; // can be negative
// even if Height == 0, give some info for horizontal line poly
if(Height != 0 || Width != 0)
{
long dN = long(verts[Bottom]->y - verts[Top]->y);
long dM = long(verts[Bottom]->x - verts[Top]->x);
if (dN != 0)
{
long InitialNumerator = (long)(dM*16*Y - dM*verts[Top]->y + dN*verts[Top]->x - 1 + dN*16);
FloorDivMod(InitialNumerator,dN*16,X,ErrorTerm,failure);
FloorDivMod(dM*16,dN*16,XStep,Numerator,failure);
Denominator = dN*16;
}
else
{
XStep = Width;
Numerator = 0;
ErrorTerm = 0;
Denominator = 1;
dN = 1;
}
float YPrestep = Fixed28_4ToFloat((fixed28_4)(Y*16 - verts[Top]->y));
float XPrestep = Fixed28_4ToFloat((fixed28_4)(X*16 - verts[Top]->x));
float dy = 1/Fixed28_4ToFloat(dN);
float dx = 1/Fixed28_4ToFloat(dM);
invw.initialize(1/verts[Top]->w,1/verts[Bottom]->w,dx,dy,XStep,XPrestep,YPrestep);
u.initialize(verts[Top]->u,verts[Bottom]->u,dx,dy,XStep,XPrestep,YPrestep);
v.initialize(verts[Top]->v,verts[Bottom]->v,dx,dy,XStep,XPrestep,YPrestep);
z.initialize(verts[Top]->z,verts[Bottom]->z,dx,dy,XStep,XPrestep,YPrestep);
for(int i=0;i<3;i++)
color[i].initialize(verts[Top]->fcolor[i],verts[Bottom]->fcolor[i],dx,dy,XStep,XPrestep,YPrestep);
}
else
{
// even if Width == 0 && Height == 0, give some info for pixel poly
// example: Castlevania Portrait of Ruin, warp stone
XStep = 1;
Numerator = 0;
Denominator = 1;
ErrorTerm = 0;
invw.initialize(1/verts[Top]->w);
u.initialize(verts[Top]->u);
v.initialize(verts[Top]->v);
z.initialize(verts[Top]->z);
for(int i=0;i<3;i++)
color[i].initialize(verts[Top]->fcolor[i]);
}
}
FORCEINLINE int edge_fx_fl::Step() {
X += XStep; Y++; Height--;
doStepInterpolants();
ErrorTerm += Numerator;
if(ErrorTerm >= Denominator) {
X++;
ErrorTerm -= Denominator;
doStepExtraInterpolants();
}
return Height;
}
static FORCEINLINE void alphaBlend(FragmentColor &dst, const FragmentColor src)
{
if (src.a == 0)
{
return;
}
if (src.a == 31 || dst.a == 0 || !gfx3d.renderState.enableAlphaBlending)
{
dst = src;
}
else
{
const u8 alpha = src.a + 1;
const u8 invAlpha = 32 - alpha;
dst.r = (alpha*src.r + invAlpha*dst.r) >> 5;
dst.g = (alpha*src.g + invAlpha*dst.g) >> 5;
dst.b = (alpha*src.b + invAlpha*dst.b) >> 5;
dst.a = max(src.a, dst.a);
}
}
template<bool RENDERER>
class RasterizerUnit
{
protected:
SoftRasterizerRenderer *_softRender;
SoftRasterizerTexture *currentTexture;
VERT* verts[MAX_CLIPPED_VERTS];
int polynum;
u8 _textureWrapMode;
public:
bool _debug_thisPoly;
int SLI_MASK;
int SLI_VALUE;
void SetRenderer(SoftRasterizerRenderer *theRenderer)
{
this->_softRender = theRenderer;
}
Render3DError SetupTexture(const POLY &thePoly, size_t polyRenderIndex)
{
SoftRasterizerTexture *theTexture = (SoftRasterizerTexture *)this->_softRender->GetTextureByPolygonRenderIndex(polyRenderIndex);
this->currentTexture = theTexture;
if (!theTexture->IsSamplingEnabled())
{
return RENDER3DERROR_NOERR;
}
this->_textureWrapMode = (thePoly.texParam >> 16) & 0x0F;
theTexture->ResetCacheAge();
theTexture->IncreaseCacheUsageCount(1);
return RENDER3DERROR_NOERR;
}
FORCEINLINE FragmentColor sample(const float u, const float v)
{
//finally, we can use floor here. but, it is slower than we want.
//the best solution is probably to wait until the pipeline is full of fixed point
const float fu = u * (float)this->currentTexture->GetRenderWidth() / (float)this->currentTexture->GetWidth();
const float fv = v * (float)this->currentTexture->GetRenderHeight() / (float)this->currentTexture->GetHeight();
s32 iu = 0;
s32 iv = 0;
if (!CommonSettings.GFX3D_TXTHack)
{
iu = s32floor(fu);
iv = s32floor(fv);
}
else
{
iu = round_s(fu);
iv = round_s(fv);
}
const u32 *textureData = this->currentTexture->GetRenderData();
this->currentTexture->GetRenderSamplerCoordinates(this->_textureWrapMode, iu, iv);
FragmentColor color;
color.color = textureData[( iv << this->currentTexture->GetRenderWidthShift() ) + iu];
return color;
}
//round function - tkd3
float round_s(double val)
{
if (val > 0.0)
{
return floorf(val*256.0f+0.5f)/256.0f; //this value(256.0) is good result.(I think)
}
else
{
return -1.0*floorf(fabs(val)*256.0f+0.5f)/256.0f;
}
}
FORCEINLINE void shade(const PolygonMode polygonMode, const FragmentColor src, FragmentColor &dst, const float texCoordU, const float texCoordV)
{
static const FragmentColor colorWhite = MakeFragmentColor(0x3F, 0x3F, 0x3F, 0x1F);
const FragmentColor mainTexColor = (this->currentTexture->IsSamplingEnabled()) ? sample(texCoordU, texCoordV) : colorWhite;
switch (polygonMode)
{
case POLYGON_MODE_MODULATE:
dst.r = modulate_table[mainTexColor.r][src.r];
dst.g = modulate_table[mainTexColor.g][src.g];
dst.b = modulate_table[mainTexColor.b][src.b];
dst.a = modulate_table[GFX3D_5TO6_LOOKUP(mainTexColor.a)][GFX3D_5TO6_LOOKUP(src.a)]>>1;
//dst.a = 28;
//#ifdef _MSC_VER
//if(GetAsyncKeyState(VK_SHIFT)) {
// //debugging tricks
// dst = shader.materialColor;
// if(GetAsyncKeyState(VK_TAB)) {
// u8 alpha = dst.a;
// dst.color = polynum*8+8;
// dst.a = alpha;
// }
//}
//#endif
break;
case POLYGON_MODE_DECAL:
{
if (this->currentTexture->IsSamplingEnabled())
{
dst.r = decal_table[mainTexColor.a][mainTexColor.r][src.r];
dst.g = decal_table[mainTexColor.a][mainTexColor.g][src.g];
dst.b = decal_table[mainTexColor.a][mainTexColor.b][src.b];
dst.a = src.a;
}
else
{
dst = src;
}
}
break;
case POLYGON_MODE_TOONHIGHLIGHT:
{
const FragmentColor toonColor = this->_softRender->toonColor32LUT[src.r >> 1];
if (gfx3d.renderState.shading == PolygonShadingMode_Highlight)
{
// Tested in the "Shadows of Almia" logo in the Pokemon Ranger: Shadows of Almia title screen.
// Also tested in Advance Wars: Dual Strike and Advance Wars: Days of Ruin when tiles highlight
// during unit selection.
dst.r = modulate_table[mainTexColor.r][src.r];
dst.g = modulate_table[mainTexColor.g][src.r];
dst.b = modulate_table[mainTexColor.b][src.r];
dst.a = modulate_table[GFX3D_5TO6_LOOKUP(mainTexColor.a)][GFX3D_5TO6_LOOKUP(src.a)] >> 1;
dst.r = min<u8>(0x3F, (dst.r + toonColor.r));
dst.g = min<u8>(0x3F, (dst.g + toonColor.g));
dst.b = min<u8>(0x3F, (dst.b + toonColor.b));
}
else
{
dst.r = modulate_table[mainTexColor.r][toonColor.r];
dst.g = modulate_table[mainTexColor.g][toonColor.g];
dst.b = modulate_table[mainTexColor.b][toonColor.b];
dst.a = modulate_table[GFX3D_5TO6_LOOKUP(mainTexColor.a)][GFX3D_5TO6_LOOKUP(src.a)] >> 1;
}
}
break;
case POLYGON_MODE_SHADOW:
//is this right? only with the material color?
dst = src;
break;
}
}
template<bool ISSHADOWPOLYGON>
FORCEINLINE void pixel(const PolygonAttributes &polyAttr, const size_t fragmentIndex, FragmentColor &dstColor, float r, float g, float b, float invu, float invv, float w, float z)
{
FragmentColor srcColor;
FragmentColor shaderOutput;
bool isOpaquePixel;
u32 &dstAttributeDepth = this->_softRender->_framebufferAttributes->depth[fragmentIndex];
u8 &dstAttributeOpaquePolyID = this->_softRender->_framebufferAttributes->opaquePolyID[fragmentIndex];
u8 &dstAttributeTranslucentPolyID = this->_softRender->_framebufferAttributes->translucentPolyID[fragmentIndex];
u8 &dstAttributeStencil = this->_softRender->_framebufferAttributes->stencil[fragmentIndex];
u8 &dstAttributeIsFogged = this->_softRender->_framebufferAttributes->isFogged[fragmentIndex];
u8 &dstAttributeIsTranslucentPoly = this->_softRender->_framebufferAttributes->isTranslucentPoly[fragmentIndex];
// not sure about the w-buffer depth value: this value was chosen to make the skybox, castle window decals, and water level render correctly in SM64
//
// When using z-depth, be sure to test against the following test cases:
// - The drawing of the overworld map in Dragon Quest IV
// - The drawing of all units on the map in Advance Wars: Days of Ruin
const u32 newDepth = (gfx3d.renderState.wbuffer) ? u32floor(4096*w) : (u32floor(z*0x7FFF) << 9);
// run the depth test
if (polyAttr.enableDepthEqualTest)
{
const u32 minDepth = max<u32>(0x00000000, dstAttributeDepth - SOFTRASTERIZER_DEPTH_EQUAL_TEST_TOLERANCE);
const u32 maxDepth = min<u32>(0x00FFFFFF, dstAttributeDepth + SOFTRASTERIZER_DEPTH_EQUAL_TEST_TOLERANCE);
if (newDepth < minDepth || newDepth > maxDepth)
{
goto depth_fail;
}
}
else
{
if (newDepth >= dstAttributeDepth)
{
goto depth_fail;
}
}
//handle shadow polys
if (ISSHADOWPOLYGON)
{
if (polyAttr.polygonID == 0)
{
goto rejected_fragment;
}
else
{
if (dstAttributeStencil == 0)
{
goto rejected_fragment;
}
//shadow polys have a special check here to keep from self-shadowing when user
//has tried to prevent it from happening
//if this isnt here, then the vehicle select in mariokart will look terrible
if (dstAttributeOpaquePolyID == polyAttr.polygonID)
{
goto rejected_fragment;
}
}
}
//perspective-correct the colors
r = (r * w) + 0.5f;
g = (g * w) + 0.5f;
b = (b * w) + 0.5f;
//this is a HACK:
//we are being very sloppy with our interpolation precision right now
//and rather than fix it, i just want to clamp it
srcColor = MakeFragmentColor(max<u8>(0x00, min<u32>(0x3F,u32floor(r))),
max<u8>(0x00, min<u32>(0x3F,u32floor(g))),
max<u8>(0x00, min<u32>(0x3F,u32floor(b))),
polyAttr.alpha);
//pixel shader
shade(polyAttr.polygonMode, srcColor, shaderOutput, invu * w, invv * w);
// handle alpha test
if ( shaderOutput.a == 0 ||
(this->_softRender->currentRenderState->enableAlphaTest && shaderOutput.a < this->_softRender->currentRenderState->alphaTestRef) )
{
goto rejected_fragment;
}
// write pixel values to the framebuffer
isOpaquePixel = (shaderOutput.a == 0x1F);
if (isOpaquePixel)
{
dstAttributeOpaquePolyID = polyAttr.polygonID;
dstAttributeIsTranslucentPoly = polyAttr.isTranslucent;
dstAttributeIsFogged = polyAttr.enableRenderFog;
dstColor = shaderOutput;
}
else
{
//dont overwrite pixels on translucent polys with the same polyids
if (dstAttributeTranslucentPolyID == polyAttr.polygonID)
goto rejected_fragment;
//originally we were using a test case of shadows-behind-trees in sm64ds
//but, it looks bad in that game. this is actually correct
//if this isnt correct, then complex shape cart shadows in mario kart don't work right
dstAttributeTranslucentPolyID = polyAttr.polygonID;
//alpha blending and write color
alphaBlend(dstColor, shaderOutput);
dstAttributeIsFogged = (dstAttributeIsFogged && polyAttr.enableRenderFog);
}
//depth writing
if (isOpaquePixel || polyAttr.enableAlphaDepthWrite)
dstAttributeDepth = newDepth;
//shadow cases: (need multi-bit stencil buffer to cope with all of these, especially the mariokart complex shadows)
//1. sm64 (standing near signs and blocks)
//2. mariokart (no glitches in shadow shape in kart selector)
//3. mariokart (no junk beneath platform in kart selector / no shadow beneath grate floor in bowser stage)
//(specifically, the shadows in mario kart are complicated concave shapes)
goto done;
depth_fail:
if (ISSHADOWPOLYGON && polyAttr.polygonID == 0)
dstAttributeStencil++;
rejected_fragment:
done:
;
if (ISSHADOWPOLYGON && polyAttr.polygonID != 0 && dstAttributeStencil)
dstAttributeStencil--;
}
//draws a single scanline
template <bool ISSHADOWPOLYGON>
FORCEINLINE void drawscanline(const PolygonAttributes &polyAttr, FragmentColor *dstColor, const size_t framebufferWidth, const size_t framebufferHeight, edge_fx_fl *pLeft, edge_fx_fl *pRight, bool lineHack)
{
int XStart = pLeft->X;
int width = pRight->X - XStart;
// HACK: workaround for vertical/slant line poly
if (lineHack && width == 0)
{
int leftWidth = pLeft->XStep;
if (pLeft->ErrorTerm + pLeft->Numerator >= pLeft->Denominator)
leftWidth++;
int rightWidth = pRight->XStep;
if (pRight->ErrorTerm + pRight->Numerator >= pRight->Denominator)
rightWidth++;
width = max(1, max(abs(leftWidth), abs(rightWidth)));
}
//these are the starting values, taken from the left edge
float invw = pLeft->invw.curr;
float u = pLeft->u.curr;
float v = pLeft->v.curr;
float z = pLeft->z.curr;
float color[3] = {
pLeft->color[0].curr,
pLeft->color[1].curr,
pLeft->color[2].curr };
//our dx values are taken from the steps up until the right edge
float invWidth = 1.0f / width;
float dinvw_dx = (pRight->invw.curr - invw) * invWidth;
float du_dx = (pRight->u.curr - u) * invWidth;
float dv_dx = (pRight->v.curr - v) * invWidth;
float dz_dx = (pRight->z.curr - z) * invWidth;
float dc_dx[3] = {
(pRight->color[0].curr - color[0]) * invWidth,
(pRight->color[1].curr - color[1]) * invWidth,
(pRight->color[2].curr - color[2]) * invWidth };
size_t adr = (pLeft->Y*framebufferWidth)+XStart;
//CONSIDER: in case some other math is wrong (shouldve been clipped OK), we might go out of bounds here.
//better check the Y value.
if (RENDERER && (pLeft->Y < 0 || pLeft->Y > (framebufferHeight - 1)))
{
printf("rasterizer rendering at y=%d! oops!\n",pLeft->Y);
return;
}
if (!RENDERER && (pLeft->Y < 0 || pLeft->Y >= framebufferHeight))
{
printf("rasterizer rendering at y=%d! oops!\n",pLeft->Y);
return;
}
int x = XStart;
if (x < 0)
{
if (RENDERER && !lineHack)
{
printf("rasterizer rendering at x=%d! oops!\n",x);
return;
}
invw += dinvw_dx * -x;
u += du_dx * -x;
v += dv_dx * -x;
z += dz_dx * -x;
color[0] += dc_dx[0] * -x;
color[1] += dc_dx[1] * -x;
color[2] += dc_dx[2] * -x;
adr += -x;
width -= -x;
x = 0;
}
if (x+width > framebufferWidth)
{
if (RENDERER && !lineHack && framebufferWidth == GPU_FRAMEBUFFER_NATIVE_WIDTH)
{
printf("rasterizer rendering at x=%d! oops!\n",x+width-1);
return;
}
width = framebufferWidth - x;
}
while (width-- > 0)
{
pixel<ISSHADOWPOLYGON>(polyAttr, adr, dstColor[adr], color[0], color[1], color[2], u, v, 1.0f/invw, z);
adr++;
x++;
invw += dinvw_dx;
u += du_dx;
v += dv_dx;
z += dz_dx;
color[0] += dc_dx[0];
color[1] += dc_dx[1];
color[2] += dc_dx[2];
}
}
//runs several scanlines, until an edge is finished
template<bool SLI, bool ISSHADOWPOLYGON>
void runscanlines(const PolygonAttributes &polyAttr, FragmentColor *dstColor, const size_t framebufferWidth, const size_t framebufferHeight, edge_fx_fl *left, edge_fx_fl *right, bool horizontal, bool lineHack)
{
//oh lord, hack city for edge drawing
//do not overstep either of the edges
int Height = min(left->Height,right->Height);
bool first=true;
//HACK: special handling for horizontal line poly
if (lineHack && left->Height == 0 && right->Height == 0 && left->Y<framebufferHeight && left->Y>=0)
{
bool draw = (!SLI || (left->Y & SLI_MASK) == SLI_VALUE);
if(draw) drawscanline<ISSHADOWPOLYGON>(polyAttr, dstColor, framebufferWidth, framebufferHeight, left,right,lineHack);
}
while(Height--)
{
bool draw = (!SLI || (left->Y & SLI_MASK) == SLI_VALUE);
if(draw) drawscanline<ISSHADOWPOLYGON>(polyAttr, dstColor, framebufferWidth, framebufferHeight, left,right,lineHack);
const int xl = left->X;
const int xr = right->X;
const int y = left->Y;
left->Step();
right->Step();
if(!RENDERER && _debug_thisPoly)
{
//debug drawing
bool top = (horizontal&&first);
bool bottom = (!Height&&horizontal);
if(Height || top || bottom)
{
if(draw)
{
int nxl = left->X;
int nxr = right->X;
if(top)
{
int xs = min(xl,xr);
int xe = max(xl,xr);
for (int x = xs; x <= xe; x++)
{
int adr = (y*framebufferWidth)+x;
dstColor[adr].r = 63;
dstColor[adr].g = 0;
dstColor[adr].b = 0;
}
}
else if(bottom)
{
int xs = min(xl,xr);
int xe = max(xl,xr);
for (int x = xs; x <= xe; x++)
{
int adr = (y*framebufferWidth)+x;
dstColor[adr].r = 63;
dstColor[adr].g = 0;
dstColor[adr].b = 0;
}
}
else
{
int xs = min(xl,nxl);
int xe = max(xl,nxl);
for (int x = xs; x <= xe; x++)
{
int adr = (y*framebufferWidth)+x;
dstColor[adr].r = 63;
dstColor[adr].g = 0;
dstColor[adr].b = 0;
}
xs = min(xr,nxr);
xe = max(xr,nxr);
for (int x = xs; x <= xe; x++)
{
int adr = (y*framebufferWidth)+x;
dstColor[adr].r = 63;
dstColor[adr].g = 0;
dstColor[adr].b = 0;
}
}
}
}
first = false;
}
}
}
//rotates verts counterclockwise
template<int TYPE>
INLINE void rot_verts()
{
#define ROTSWAP(X) if(TYPE>X) swap(verts[X-1],verts[X]);
ROTSWAP(1); ROTSWAP(2); ROTSWAP(3); ROTSWAP(4);
ROTSWAP(5); ROTSWAP(6); ROTSWAP(7); ROTSWAP(8); ROTSWAP(9);
}
//rotate verts until vert0.y is minimum, and then vert0.x is minimum in case of ties
//this is a necessary precondition for our shape engine
template<int TYPE>
void sort_verts(bool backwards)
{
//if the verts are backwards, reorder them first
if (backwards)
for (size_t i = 0; i < TYPE/2; i++)
swap(verts[i],verts[TYPE-i-1]);
for (;;)
{
//this was the only way we could get this to unroll
#define CHECKY(X) if(TYPE>X) if(verts[0]->y > verts[X]->y) goto doswap;
CHECKY(1); CHECKY(2); CHECKY(3); CHECKY(4);
CHECKY(5); CHECKY(6); CHECKY(7); CHECKY(8); CHECKY(9);
break;
doswap:
rot_verts<TYPE>();
}
while (verts[0]->y == verts[1]->y && verts[0]->x > verts[1]->x)
{
rot_verts<TYPE>();
// hack for VC++ 2010 (bug in compiler optimization?)
// freeze on 3D
// TODO: study it
#ifdef SLEEP_HACK_2011
Sleep(0); // nop
#endif
}
}
//This function can handle any convex N-gon up to octagons
//verts must be clockwise.
//I didnt reference anything for this algorithm but it seems like I've seen it somewhere before.
//Maybe it is like crow's algorithm
template<bool SLI, bool ISSHADOWPOLYGON>
void shape_engine(const PolygonAttributes &polyAttr, FragmentColor *dstColor, const size_t framebufferWidth, const size_t framebufferHeight, int type, const bool backwards, bool lineHack)
{
bool failure = false;
switch(type)
{
case 3: sort_verts<3>(backwards); break;
case 4: sort_verts<4>(backwards); break;
case 5: sort_verts<5>(backwards); break;
case 6: sort_verts<6>(backwards); break;
case 7: sort_verts<7>(backwards); break;
case 8: sort_verts<8>(backwards); break;
case 9: sort_verts<9>(backwards); break;
case 10: sort_verts<10>(backwards); break;
default: printf("skipping type %d\n",type); return;
}
//we are going to step around the polygon in both directions starting from vert 0.
//right edges will be stepped over clockwise and left edges stepped over counterclockwise.
//these variables track that stepping, but in order to facilitate wrapping we start extra high
//for the counter we're decrementing.
int lv = type, rv = 0;
edge_fx_fl left, right;
bool step_left = true, step_right = true;
for (;;)
{
//generate new edges if necessary. we must avoid regenerating edges when they are incomplete
//so that they can be continued on down the shape
assert(rv != type);
int _lv = lv==type?0:lv; //make sure that we ask for vert 0 when the variable contains the starting value
if (step_left) left = edge_fx_fl(_lv,lv-1,(VERT**)&verts, failure);
if (step_right) right = edge_fx_fl(rv,rv+1,(VERT**)&verts, failure);
step_left = step_right = false;
//handle a failure in the edge setup due to nutty polys
if(failure)
return;
bool horizontal = left.Y == right.Y;
runscanlines<SLI, ISSHADOWPOLYGON>(polyAttr, dstColor, framebufferWidth, framebufferHeight, &left, &right, horizontal, lineHack);
//if we ran out of an edge, step to the next one
if (right.Height == 0)
{
step_right = true;
rv++;
}
if (left.Height == 0)
{
step_left = true;
lv--;
}
//this is our completion condition: when our stepped edges meet in the middle
if (lv<=rv+1) break;
}
}
template<bool SLI>
FORCEINLINE void mainLoop()
{
const size_t polyCount = this->_softRender->_clippedPolyCount;
if (polyCount == 0)
{
return;
}
FragmentColor *dstColor = this->_softRender->GetFramebuffer();
const size_t dstWidth = this->_softRender->GetFramebufferWidth();
const size_t dstHeight = this->_softRender->GetFramebufferHeight();
const GFX3D_Clipper::TClippedPoly &firstClippedPoly = this->_softRender->clippedPolys[0];
const POLY &firstPoly = *firstClippedPoly.poly;
PolygonAttributes polyAttr = firstPoly.getAttributes();
u32 lastPolyAttr = firstPoly.polyAttr;
u32 lastTexParams = firstPoly.texParam;
u32 lastTexPalette = firstPoly.texPalette;
this->SetupTexture(firstPoly, 0);
//iterate over polys
for (size_t i = 0; i < polyCount; i++)
{
if (!RENDERER) _debug_thisPoly = (i == this->_softRender->_debug_drawClippedUserPoly);
if (!this->_softRender->polyVisible[i]) continue;
polynum = i;
GFX3D_Clipper::TClippedPoly &clippedPoly = this->_softRender->clippedPolys[i];
const POLY &thePoly = *clippedPoly.poly;
const PolygonType type = clippedPoly.type;
if (lastPolyAttr != thePoly.polyAttr)
{
polyAttr = thePoly.getAttributes();
lastPolyAttr = thePoly.polyAttr;
}
if (lastTexParams != thePoly.texParam || lastTexPalette != thePoly.texPalette)
{
lastTexParams = thePoly.texParam;
lastTexPalette = thePoly.texPalette;
this->SetupTexture(thePoly, i);
}
for (int j = 0; j < type; j++)
this->verts[j] = &clippedPoly.clipVerts[j];
for (int j = type; j < MAX_CLIPPED_VERTS; j++)
this->verts[j] = NULL;
if (polyAttr.polygonMode == POLYGON_MODE_SHADOW)
{
shape_engine<SLI, true>(polyAttr, dstColor, dstWidth, dstHeight, type, !this->_softRender->polyBackfacing[i], (thePoly.vtxFormat & 4) && CommonSettings.GFX3D_LineHack);
}
else
{
shape_engine<SLI, false>(polyAttr, dstColor, dstWidth, dstHeight, type, !this->_softRender->polyBackfacing[i], (thePoly.vtxFormat & 4) && CommonSettings.GFX3D_LineHack);
}
}
}
}; //rasterizerUnit
#define _MAX_CORES 16
static Task rasterizerUnitTask[_MAX_CORES];
static RasterizerUnit<true> rasterizerUnit[_MAX_CORES];
static RasterizerUnit<false> _HACK_viewer_rasterizerUnit;
static size_t rasterizerCores = 0;
static bool rasterizerUnitTasksInited = false;
static void* execRasterizerUnit(void *arg)
{
intptr_t which = (intptr_t)arg;
rasterizerUnit[which].mainLoop<true>();
return 0;
}