swr: [rasterizer core] static analysis fixes for conservative rast
[mesa.git] / src / gallium / drivers / swr / rasterizer / core / rasterizer.cpp
1 /****************************************************************************
2 * Copyright (C) 2014-2015 Intel Corporation. All Rights Reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining a
5 * copy of this software and associated documentation files (the "Software"),
6 * to deal in the Software without restriction, including without limitation
7 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8 * and/or sell copies of the Software, and to permit persons to whom the
9 * Software is furnished to do so, subject to the following conditions:
10 *
11 * The above copyright notice and this permission notice (including the next
12 * paragraph) shall be included in all copies or substantial portions of the
13 * Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
18 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21 * IN THE SOFTWARE.
22 *
23 * @file rasterizer.cpp
24 *
25 * @brief Implementation for the rasterizer.
26 *
27 ******************************************************************************/
28
29 #include <vector>
30 #include <algorithm>
31
32 #include "rasterizer.h"
33 #include "rdtsc_core.h"
34 #include "backend.h"
35 #include "utils.h"
36 #include "frontend.h"
37 #include "tilemgr.h"
38 #include "memory/tilingtraits.h"
39
40 template <uint32_t numSamples = 1>
41 void GetRenderHotTiles(DRAW_CONTEXT *pDC, uint32_t macroID, uint32_t x, uint32_t y, RenderOutputBuffers &renderBuffers, uint32_t renderTargetArrayIndex);
42 template <typename RT>
43 void StepRasterTileX(uint32_t MaxRT, RenderOutputBuffers &buffers);
44 template <typename RT>
45 void StepRasterTileY(uint32_t MaxRT, RenderOutputBuffers &buffers, RenderOutputBuffers &startBufferRow);
46
47 #define MASKTOVEC(i3,i2,i1,i0) {-i0,-i1,-i2,-i3}
48 const __m256d gMaskToVecpd[] =
49 {
50 MASKTOVEC(0, 0, 0, 0),
51 MASKTOVEC(0, 0, 0, 1),
52 MASKTOVEC(0, 0, 1, 0),
53 MASKTOVEC(0, 0, 1, 1),
54 MASKTOVEC(0, 1, 0, 0),
55 MASKTOVEC(0, 1, 0, 1),
56 MASKTOVEC(0, 1, 1, 0),
57 MASKTOVEC(0, 1, 1, 1),
58 MASKTOVEC(1, 0, 0, 0),
59 MASKTOVEC(1, 0, 0, 1),
60 MASKTOVEC(1, 0, 1, 0),
61 MASKTOVEC(1, 0, 1, 1),
62 MASKTOVEC(1, 1, 0, 0),
63 MASKTOVEC(1, 1, 0, 1),
64 MASKTOVEC(1, 1, 1, 0),
65 MASKTOVEC(1, 1, 1, 1),
66 };
67
68 struct POS
69 {
70 int32_t x, y;
71 };
72
73 struct EDGE
74 {
75 double a, b; // a, b edge coefficients in fix8
76 double stepQuadX; // step to adjacent horizontal quad in fix16
77 double stepQuadY; // step to adjacent vertical quad in fix16
78 double stepRasterTileX; // step to adjacent horizontal raster tile in fix16
79 double stepRasterTileY; // step to adjacent vertical raster tile in fix16
80
81 __m256d vQuadOffsets; // offsets for 4 samples of a quad
82 __m256d vRasterTileOffsets; // offsets for the 4 corners of a raster tile
83 };
84
85 //////////////////////////////////////////////////////////////////////////
86 /// @brief rasterize a raster tile partially covered by the triangle
87 /// @param vEdge0-2 - edge equations evaluated at sample pos at each of the 4 corners of a raster tile
88 /// @param vA, vB - A & B coefs for each edge of the triangle (Ax + Bx + C)
89 /// @param vStepQuad0-2 - edge equations evaluated at the UL corners of the 2x2 pixel quad.
90 /// Used to step between quads when sweeping over the raster tile.
91 template<uint32_t NumEdges, typename EdgeMaskT>
92 INLINE uint64_t rasterizePartialTile(DRAW_CONTEXT *pDC, double startEdges[NumEdges], EDGE *pRastEdges)
93 {
94 uint64_t coverageMask = 0;
95
96 __m256d vEdges[NumEdges];
97 __m256d vStepX[NumEdges];
98 __m256d vStepY[NumEdges];
99
100 for (uint32_t e = 0; e < NumEdges; ++e)
101 {
102 // Step to the pixel sample locations of the 1st quad
103 vEdges[e] = _mm256_add_pd(_mm256_set1_pd(startEdges[e]), pRastEdges[e].vQuadOffsets);
104
105 // compute step to next quad (mul by 2 in x and y direction)
106 vStepX[e] = _mm256_set1_pd(pRastEdges[e].stepQuadX);
107 vStepY[e] = _mm256_set1_pd(pRastEdges[e].stepQuadY);
108 }
109
110 // fast unrolled version for 8x8 tile
111 #if KNOB_TILE_X_DIM == 8 && KNOB_TILE_Y_DIM == 8
112 int edgeMask[NumEdges];
113 uint64_t mask;
114
115 auto eval_lambda = [&](int e){edgeMask[e] = _mm256_movemask_pd(vEdges[e]);};
116 auto update_lambda = [&](int e){mask &= edgeMask[e];};
117 auto incx_lambda = [&](int e){vEdges[e] = _mm256_add_pd(vEdges[e], vStepX[e]);};
118 auto incy_lambda = [&](int e){vEdges[e] = _mm256_add_pd(vEdges[e], vStepY[e]);};
119 auto decx_lambda = [&](int e){vEdges[e] = _mm256_sub_pd(vEdges[e], vStepX[e]);};
120
121 // evaluate which pixels in the quad are covered
122 #define EVAL \
123 UnrollerLMask<0, NumEdges, 1, EdgeMaskT::value>::step(eval_lambda);
124
125 // update coverage mask
126 // if edge 0 is degenerate and will be skipped; init the mask
127 #define UPDATE_MASK(bit) \
128 if(std::is_same<EdgeMaskT, E1E2ValidT>::value || std::is_same<EdgeMaskT, NoEdgesValidT>::value){\
129 mask = 0xf;\
130 }\
131 else{\
132 mask = edgeMask[0]; \
133 }\
134 UnrollerLMask<1, NumEdges, 1, EdgeMaskT::value>::step(update_lambda); \
135 coverageMask |= (mask << bit);
136
137 // step in the +x direction to the next quad
138 #define INCX \
139 UnrollerLMask<0, NumEdges, 1, EdgeMaskT::value>::step(incx_lambda);
140
141 // step in the +y direction to the next quad
142 #define INCY \
143 UnrollerLMask<0, NumEdges, 1, EdgeMaskT::value>::step(incy_lambda);
144
145 // step in the -x direction to the next quad
146 #define DECX \
147 UnrollerLMask<0, NumEdges, 1, EdgeMaskT::value>::step(decx_lambda);
148
149 // sweep 2x2 quad back and forth through the raster tile,
150 // computing coverage masks for the entire tile
151
152 // raster tile
153 // 0 1 2 3 4 5 6 7
154 // x x
155 // x x ------------------>
156 // x x |
157 // <-----------------x x V
158 // ..
159
160 // row 0
161 EVAL;
162 UPDATE_MASK(0);
163 INCX;
164 EVAL;
165 UPDATE_MASK(4);
166 INCX;
167 EVAL;
168 UPDATE_MASK(8);
169 INCX;
170 EVAL;
171 UPDATE_MASK(12);
172 INCY;
173
174 //row 1
175 EVAL;
176 UPDATE_MASK(28);
177 DECX;
178 EVAL;
179 UPDATE_MASK(24);
180 DECX;
181 EVAL;
182 UPDATE_MASK(20);
183 DECX;
184 EVAL;
185 UPDATE_MASK(16);
186 INCY;
187
188 // row 2
189 EVAL;
190 UPDATE_MASK(32);
191 INCX;
192 EVAL;
193 UPDATE_MASK(36);
194 INCX;
195 EVAL;
196 UPDATE_MASK(40);
197 INCX;
198 EVAL;
199 UPDATE_MASK(44);
200 INCY;
201
202 // row 3
203 EVAL;
204 UPDATE_MASK(60);
205 DECX;
206 EVAL;
207 UPDATE_MASK(56);
208 DECX;
209 EVAL;
210 UPDATE_MASK(52);
211 DECX;
212 EVAL;
213 UPDATE_MASK(48);
214 #else
215 uint32_t bit = 0;
216 for (uint32_t y = 0; y < KNOB_TILE_Y_DIM/2; ++y)
217 {
218 __m256d vStartOfRowEdge[NumEdges];
219 for (uint32_t e = 0; e < NumEdges; ++e)
220 {
221 vStartOfRowEdge[e] = vEdges[e];
222 }
223
224 for (uint32_t x = 0; x < KNOB_TILE_X_DIM/2; ++x)
225 {
226 int edgeMask[NumEdges];
227 for (uint32_t e = 0; e < NumEdges; ++e)
228 {
229 edgeMask[e] = _mm256_movemask_pd(vEdges[e]);
230 }
231
232 uint64_t mask = edgeMask[0];
233 for (uint32_t e = 1; e < NumEdges; ++e)
234 {
235 mask &= edgeMask[e];
236 }
237 coverageMask |= (mask << bit);
238
239 // step to the next pixel in the x
240 for (uint32_t e = 0; e < NumEdges; ++e)
241 {
242 vEdges[e] = _mm256_add_pd(vEdges[e], vStepX[e]);
243 }
244 bit+=4;
245 }
246
247 // step to the next row
248 for (uint32_t e = 0; e < NumEdges; ++e)
249 {
250 vEdges[e] = _mm256_add_pd(vStartOfRowEdge[e], vStepY[e]);
251 }
252 }
253 #endif
254 return coverageMask;
255
256 }
257 // Top left rule:
258 // Top: if an edge is horizontal, and it is above other edges in tri pixel space, it is a 'top' edge
259 // Left: if an edge is not horizontal, and it is on the left side of the triangle in pixel space, it is a 'left' edge
260 // Top left: a sample is in if it is a top or left edge.
261 // Out: !(horizontal && above) = !horizontal && below
262 // Out: !horizontal && left = !(!horizontal && left) = horizontal and right
263 INLINE void adjustTopLeftRuleIntFix16(const __m128i vA, const __m128i vB, __m256d &vEdge)
264 {
265 // if vA < 0, vC--
266 // if vA == 0 && vB < 0, vC--
267
268 __m256d vEdgeOut = vEdge;
269 __m256d vEdgeAdjust = _mm256_sub_pd(vEdge, _mm256_set1_pd(1.0));
270
271 // if vA < 0 (line is not horizontal and below)
272 int msk = _mm_movemask_ps(_mm_castsi128_ps(vA));
273
274 // if vA == 0 && vB < 0 (line is horizontal and we're on the left edge of a tri)
275 __m128i vCmp = _mm_cmpeq_epi32(vA, _mm_setzero_si128());
276 int msk2 = _mm_movemask_ps(_mm_castsi128_ps(vCmp));
277 msk2 &= _mm_movemask_ps(_mm_castsi128_ps(vB));
278
279 // if either of these are true and we're on the line (edge == 0), bump it outside the line
280 vEdge = _mm256_blendv_pd(vEdgeOut, vEdgeAdjust, gMaskToVecpd[msk | msk2]);
281 }
282
283 //////////////////////////////////////////////////////////////////////////
284 /// @brief calculates difference in precision between the result of manh
285 /// calculation and the edge precision, based on compile time trait values
286 template<typename RT>
287 constexpr int64_t ManhToEdgePrecisionAdjust()
288 {
289 static_assert(RT::PrecisionT::BitsT::value + RT::ConservativePrecisionT::BitsT::value >= RT::EdgePrecisionT::BitsT::value,
290 "Inadequate precision of result of manh calculation ");
291 return ((RT::PrecisionT::BitsT::value + RT::ConservativePrecisionT::BitsT::value) - RT::EdgePrecisionT::BitsT::value);
292 }
293
294 //////////////////////////////////////////////////////////////////////////
295 /// @struct adjustEdgeConservative
296 /// @brief Primary template definition used for partially specializing
297 /// the adjustEdgeConservative function. This struct should never
298 /// be instantiated.
299 /// @tparam RT: rasterizer traits
300 /// @tparam ConservativeEdgeOffsetT: does the edge need offsetting?
301 template <typename RT, typename ConservativeEdgeOffsetT>
302 struct adjustEdgeConservative
303 {
304 //////////////////////////////////////////////////////////////////////////
305 /// @brief Performs calculations to adjust each edge of a triangle away
306 /// from the pixel center by 1/2 pixel + uncertainty region in both the x and y
307 /// direction.
308 ///
309 /// Uncertainty regions arise from fixed point rounding, which
310 /// can snap a vertex +/- by min fixed point value.
311 /// Adding 1/2 pixel in x/y bumps the edge equation tests out towards the pixel corners.
312 /// This allows the rasterizer to test for coverage only at the pixel center,
313 /// instead of having to test individual pixel corners for conservative coverage
314 INLINE adjustEdgeConservative(const __m128i &vAi, const __m128i &vBi, __m256d &vEdge)
315 {
316 // Assumes CCW winding order. Subtracting from the evaluated edge equation moves the edge away
317 // from the pixel center (in the direction of the edge normal A/B)
318
319 // edge = Ax + Bx + C - (manh/e)
320 // manh = manhattan distance = abs(A) + abs(B)
321 // e = absolute rounding error from snapping from float to fixed point precision
322
323 // 'fixed point' multiply (in double to be avx1 friendly)
324 // need doubles to hold result of a fixed multiply: 16.8 * 16.9 = 32.17, for example
325 __m256d vAai = _mm256_cvtepi32_pd(_mm_abs_epi32(vAi)), vBai = _mm256_cvtepi32_pd(_mm_abs_epi32(vBi));
326 __m256d manh = _mm256_add_pd(_mm256_mul_pd(vAai, _mm256_set1_pd(ConservativeEdgeOffsetT::value)),
327 _mm256_mul_pd(vBai, _mm256_set1_pd(ConservativeEdgeOffsetT::value)));
328
329 static_assert(RT::PrecisionT::BitsT::value + RT::ConservativePrecisionT::BitsT::value >= RT::EdgePrecisionT::BitsT::value,
330 "Inadequate precision of result of manh calculation ");
331
332 // rasterizer incoming edge precision is x.16, so we need to get our edge offset into the same precision
333 // since we're doing fixed math in double format, multiply by multiples of 1/2 instead of a bit shift right
334 manh = _mm256_mul_pd(manh, _mm256_set1_pd(ManhToEdgePrecisionAdjust<RT>() * 0.5));
335
336 // move the edge away from the pixel center by the required conservative precision + 1/2 pixel
337 // this allows the rasterizer to do a single conservative coverage test to see if the primitive
338 // intersects the pixel at all
339 vEdge = _mm256_sub_pd(vEdge, manh);
340 };
341 };
342
343 //////////////////////////////////////////////////////////////////////////
344 /// @brief adjustEdgeConservative specialization where no edge offset is needed
345 template <typename RT>
346 struct adjustEdgeConservative<RT, std::integral_constant<int32_t, 0>>
347 {
348 INLINE adjustEdgeConservative(const __m128i &vAi, const __m128i &vBi, __m256d &vEdge) {};
349 };
350
351 //////////////////////////////////////////////////////////////////////////
352 /// @brief calculates the distance a degenerate BBox needs to be adjusted
353 /// for conservative rast based on compile time trait values
354 template<typename RT>
355 constexpr int64_t ConservativeScissorOffset()
356 {
357 static_assert(RT::ConservativePrecisionT::BitsT::value - RT::PrecisionT::BitsT::value >= 0, "Rasterizer precision > conservative precision");
358 // if we have a degenerate triangle, we need to compensate for adjusting the degenerate BBox when calculating scissor edges
359 typedef std::integral_constant<int32_t, (RT::ValidEdgeMaskT::value == ALL_EDGES_VALID) ? 0 : 1> DegenerateEdgeOffsetT;
360 // 1/2 pixel edge offset + conservative offset - degenerateTriangle
361 return RT::ConservativeEdgeOffsetT::value - (DegenerateEdgeOffsetT::value << (RT::ConservativePrecisionT::BitsT::value - RT::PrecisionT::BitsT::value));
362 }
363
364 //////////////////////////////////////////////////////////////////////////
365 /// @brief Performs calculations to adjust each a vector of evaluated edges out
366 /// from the pixel center by 1/2 pixel + uncertainty region in both the x and y
367 /// direction.
368 template <typename RT>
369 INLINE void adjustScissorEdge(const double a, const double b, __m256d &vEdge)
370 {
371 int64_t aabs = std::abs(static_cast<int64_t>(a)), babs = std::abs(static_cast<int64_t>(b));
372 int64_t manh = ((aabs * ConservativeScissorOffset<RT>()) + (babs * ConservativeScissorOffset<RT>())) >> ManhToEdgePrecisionAdjust<RT>();
373 vEdge = _mm256_sub_pd(vEdge, _mm256_set1_pd(manh));
374 };
375
376 //////////////////////////////////////////////////////////////////////////
377 /// @brief Performs calculations to adjust each a scalar evaluated edge out
378 /// from the pixel center by 1/2 pixel + uncertainty region in both the x and y
379 /// direction.
380 template <typename RT, typename OffsetT>
381 INLINE double adjustScalarEdge(const double a, const double b, const double Edge)
382 {
383 int64_t aabs = std::abs(static_cast<int64_t>(a)), babs = std::abs(static_cast<int64_t>(b));
384 int64_t manh = ((aabs * OffsetT::value) + (babs * OffsetT::value)) >> ManhToEdgePrecisionAdjust<RT>();
385 return (Edge - manh);
386 };
387
388 //////////////////////////////////////////////////////////////////////////
389 /// @brief Perform any needed adjustments to evaluated triangle edges
390 template <typename RT, typename EdgeOffsetT>
391 struct adjustEdgesFix16
392 {
393 INLINE adjustEdgesFix16(const __m128i &vAi, const __m128i &vBi, __m256d &vEdge)
394 {
395 static_assert(std::is_same<typename RT::EdgePrecisionT, FixedPointTraits<Fixed_X_16>>::value,
396 "Edge equation expected to be in x.16 fixed point");
397
398 static_assert(RT::IsConservativeT::value, "Edge offset assumes conservative rasterization is enabled");
399
400 // need to apply any edge offsets before applying the top-left rule
401 adjustEdgeConservative<RT, EdgeOffsetT>(vAi, vBi, vEdge);
402
403 adjustTopLeftRuleIntFix16(vAi, vBi, vEdge);
404 }
405 };
406
407 //////////////////////////////////////////////////////////////////////////
408 /// @brief Perform top left adjustments to evaluated triangle edges
409 template <typename RT>
410 struct adjustEdgesFix16<RT, std::integral_constant<int32_t, 0>>
411 {
412 INLINE adjustEdgesFix16(const __m128i &vAi, const __m128i &vBi, __m256d &vEdge)
413 {
414 adjustTopLeftRuleIntFix16(vAi, vBi, vEdge);
415 }
416 };
417
418 // max(abs(dz/dx), abs(dz,dy)
419 INLINE float ComputeMaxDepthSlope(const SWR_TRIANGLE_DESC* pDesc)
420 {
421 /*
422 // evaluate i,j at (0,0)
423 float i00 = pDesc->I[0] * 0.0f + pDesc->I[1] * 0.0f + pDesc->I[2];
424 float j00 = pDesc->J[0] * 0.0f + pDesc->J[1] * 0.0f + pDesc->J[2];
425
426 // evaluate i,j at (1,0)
427 float i10 = pDesc->I[0] * 1.0f + pDesc->I[1] * 0.0f + pDesc->I[2];
428 float j10 = pDesc->J[0] * 1.0f + pDesc->J[1] * 0.0f + pDesc->J[2];
429
430 // compute dz/dx
431 float d00 = pDesc->Z[0] * i00 + pDesc->Z[1] * j00 + pDesc->Z[2];
432 float d10 = pDesc->Z[0] * i10 + pDesc->Z[1] * j10 + pDesc->Z[2];
433 float dzdx = abs(d10 - d00);
434
435 // evaluate i,j at (0,1)
436 float i01 = pDesc->I[0] * 0.0f + pDesc->I[1] * 1.0f + pDesc->I[2];
437 float j01 = pDesc->J[0] * 0.0f + pDesc->J[1] * 1.0f + pDesc->J[2];
438
439 float d01 = pDesc->Z[0] * i01 + pDesc->Z[1] * j01 + pDesc->Z[2];
440 float dzdy = abs(d01 - d00);
441 */
442
443 // optimized version of above
444 float dzdx = fabsf(pDesc->recipDet * (pDesc->Z[0] * pDesc->I[0] + pDesc->Z[1] * pDesc->J[0]));
445 float dzdy = fabsf(pDesc->recipDet * (pDesc->Z[0] * pDesc->I[1] + pDesc->Z[1] * pDesc->J[1]));
446
447 return std::max(dzdx, dzdy);
448 }
449
450 INLINE float ComputeBiasFactor(const SWR_RASTSTATE* pState, const SWR_TRIANGLE_DESC* pDesc, const float* z)
451 {
452 if (pState->depthFormat == R24_UNORM_X8_TYPELESS)
453 {
454 return (1.0f / (1 << 24));
455 }
456 else if (pState->depthFormat == R16_UNORM)
457 {
458 return (1.0f / (1 << 16));
459 }
460 else
461 {
462 SWR_ASSERT(pState->depthFormat == R32_FLOAT);
463
464 // for f32 depth, factor = 2^(exponent(max(abs(z) - 23)
465 float zMax = std::max(fabsf(z[0]), std::max(fabsf(z[1]), fabsf(z[2])));
466 uint32_t zMaxInt = *(uint32_t*)&zMax;
467 zMaxInt &= 0x7f800000;
468 zMax = *(float*)&zMaxInt;
469
470 return zMax * (1.0f / (1 << 23));
471 }
472 }
473
474 INLINE float ComputeDepthBias(const SWR_RASTSTATE* pState, const SWR_TRIANGLE_DESC* pTri, const float* z)
475 {
476 if (pState->depthBias == 0 && pState->slopeScaledDepthBias == 0)
477 {
478 return 0.0f;
479 }
480
481 float scale = pState->slopeScaledDepthBias;
482 if (scale != 0.0f)
483 {
484 scale *= ComputeMaxDepthSlope(pTri);
485 }
486
487 float bias = pState->depthBias;
488 if (!pState->depthBiasPreAdjusted)
489 {
490 bias *= ComputeBiasFactor(pState, pTri, z);
491 }
492 bias += scale;
493
494 if (pState->depthBiasClamp > 0.0f)
495 {
496 bias = std::min(bias, pState->depthBiasClamp);
497 }
498 else if (pState->depthBiasClamp < 0.0f)
499 {
500 bias = std::max(bias, pState->depthBiasClamp);
501 }
502
503 return bias;
504 }
505
506 // Prevent DCE by writing coverage mask from rasterizer to volatile
507 #if KNOB_ENABLE_TOSS_POINTS
508 __declspec(thread) volatile uint64_t gToss;
509 #endif
510
511 static const uint32_t vertsPerTri = 3, componentsPerAttrib = 4;
512 // try to avoid _chkstk insertions; make this thread local
513 static THREAD OSALIGNLINE(float) perspAttribsTLS[vertsPerTri * KNOB_NUM_ATTRIBUTES * componentsPerAttrib];
514
515 INLINE
516 void ComputeEdgeData(int32_t a, int32_t b, EDGE& edge)
517 {
518 edge.a = a;
519 edge.b = b;
520
521 // compute constant steps to adjacent quads
522 edge.stepQuadX = (double)((int64_t)a * (int64_t)(2 * FIXED_POINT_SCALE));
523 edge.stepQuadY = (double)((int64_t)b * (int64_t)(2 * FIXED_POINT_SCALE));
524
525 // compute constant steps to adjacent raster tiles
526 edge.stepRasterTileX = (double)((int64_t)a * (int64_t)(KNOB_TILE_X_DIM * FIXED_POINT_SCALE));
527 edge.stepRasterTileY = (double)((int64_t)b * (int64_t)(KNOB_TILE_Y_DIM * FIXED_POINT_SCALE));
528
529 // compute quad offsets
530 const __m256d vQuadOffsetsXIntFix8 = _mm256_set_pd(FIXED_POINT_SCALE, 0, FIXED_POINT_SCALE, 0);
531 const __m256d vQuadOffsetsYIntFix8 = _mm256_set_pd(FIXED_POINT_SCALE, FIXED_POINT_SCALE, 0, 0);
532
533 __m256d vQuadStepXFix16 = _mm256_mul_pd(_mm256_set1_pd(edge.a), vQuadOffsetsXIntFix8);
534 __m256d vQuadStepYFix16 = _mm256_mul_pd(_mm256_set1_pd(edge.b), vQuadOffsetsYIntFix8);
535 edge.vQuadOffsets = _mm256_add_pd(vQuadStepXFix16, vQuadStepYFix16);
536
537 // compute raster tile offsets
538 const __m256d vTileOffsetsXIntFix8 = _mm256_set_pd((KNOB_TILE_X_DIM - 1)*FIXED_POINT_SCALE, 0, (KNOB_TILE_X_DIM - 1)*FIXED_POINT_SCALE, 0);
539 const __m256d vTileOffsetsYIntFix8 = _mm256_set_pd((KNOB_TILE_Y_DIM - 1)*FIXED_POINT_SCALE, (KNOB_TILE_Y_DIM - 1)*FIXED_POINT_SCALE, 0, 0);
540
541 __m256d vTileStepXFix16 = _mm256_mul_pd(_mm256_set1_pd(edge.a), vTileOffsetsXIntFix8);
542 __m256d vTileStepYFix16 = _mm256_mul_pd(_mm256_set1_pd(edge.b), vTileOffsetsYIntFix8);
543 edge.vRasterTileOffsets = _mm256_add_pd(vTileStepXFix16, vTileStepYFix16);
544 }
545
546 INLINE
547 void ComputeEdgeData(const POS& p0, const POS& p1, EDGE& edge)
548 {
549 ComputeEdgeData(p0.y - p1.y, p1.x - p0.x, edge);
550 }
551
552 //////////////////////////////////////////////////////////////////////////
553 /// @brief Primary template definition used for partially specializing
554 /// the UpdateEdgeMasks function. Offset evaluated edges from UL pixel
555 /// corner to sample position, and test for coverage
556 /// @tparam sampleCount: multisample count
557 template <typename NumSamplesT>
558 INLINE void UpdateEdgeMasks(const __m256d (&vEdgeTileBbox)[3], const __m256d* vEdgeFix16,
559 int32_t &mask0, int32_t &mask1, int32_t &mask2)
560 {
561 __m256d vSampleBboxTest0, vSampleBboxTest1, vSampleBboxTest2;
562 // evaluate edge equations at the tile multisample bounding box
563 vSampleBboxTest0 = _mm256_add_pd(vEdgeTileBbox[0], vEdgeFix16[0]);
564 vSampleBboxTest1 = _mm256_add_pd(vEdgeTileBbox[1], vEdgeFix16[1]);
565 vSampleBboxTest2 = _mm256_add_pd(vEdgeTileBbox[2], vEdgeFix16[2]);
566 mask0 = _mm256_movemask_pd(vSampleBboxTest0);
567 mask1 = _mm256_movemask_pd(vSampleBboxTest1);
568 mask2 = _mm256_movemask_pd(vSampleBboxTest2);
569 }
570
571 //////////////////////////////////////////////////////////////////////////
572 /// @brief UpdateEdgeMasks<SingleSampleT> specialization, instantiated
573 /// when only rasterizing a single coverage test point
574 template <>
575 INLINE void UpdateEdgeMasks<SingleSampleT>(const __m256d(&)[3], const __m256d* vEdgeFix16,
576 int32_t &mask0, int32_t &mask1, int32_t &mask2)
577 {
578 mask0 = _mm256_movemask_pd(vEdgeFix16[0]);
579 mask1 = _mm256_movemask_pd(vEdgeFix16[1]);
580 mask2 = _mm256_movemask_pd(vEdgeFix16[2]);
581 }
582
583 //////////////////////////////////////////////////////////////////////////
584 /// @struct ComputeScissorEdges
585 /// @brief Primary template definition. Allows the function to be generically
586 /// called. When paired with below specializations, will result in an empty
587 /// inlined function if scissor is not enabled
588 /// @tparam RasterScissorEdgesT: is scissor enabled?
589 /// @tparam IsConservativeT: is conservative rast enabled?
590 /// @tparam RT: rasterizer traits
591 template <typename RasterScissorEdgesT, typename IsConservativeT, typename RT>
592 struct ComputeScissorEdges
593 {
594 INLINE ComputeScissorEdges(const BBOX &triBBox, const BBOX &scissorBBox, const int32_t x, const int32_t y,
595 EDGE (&rastEdges)[RT::NumEdgesT::value], __m256d (&vEdgeFix16)[7]){};
596 };
597
598 //////////////////////////////////////////////////////////////////////////
599 /// @brief ComputeScissorEdges<std::true_type, std::true_type, RT> partial
600 /// specialization. Instantiated when conservative rast and scissor are enabled
601 template <typename RT>
602 struct ComputeScissorEdges<std::true_type, std::true_type, RT>
603 {
604 //////////////////////////////////////////////////////////////////////////
605 /// @brief Intersect tri bbox with scissor, compute scissor edge vectors,
606 /// evaluate edge equations and offset them away from pixel center.
607 INLINE ComputeScissorEdges(const BBOX &triBBox, const BBOX &scissorBBox, const int32_t x, const int32_t y,
608 EDGE (&rastEdges)[RT::NumEdgesT::value], __m256d (&vEdgeFix16)[7])
609 {
610 // if conservative rasterizing, triangle bbox intersected with scissor bbox is used
611 BBOX scissor;
612 scissor.left = std::max(triBBox.left, scissorBBox.left);
613 scissor.right = std::min(triBBox.right, scissorBBox.right);
614 scissor.top = std::max(triBBox.top, scissorBBox.top);
615 scissor.bottom = std::min(triBBox.bottom, scissorBBox.bottom);
616
617 POS topLeft{scissor.left, scissor.top};
618 POS bottomLeft{scissor.left, scissor.bottom};
619 POS topRight{scissor.right, scissor.top};
620 POS bottomRight{scissor.right, scissor.bottom};
621
622 // construct 4 scissor edges in ccw direction
623 ComputeEdgeData(topLeft, bottomLeft, rastEdges[3]);
624 ComputeEdgeData(bottomLeft, bottomRight, rastEdges[4]);
625 ComputeEdgeData(bottomRight, topRight, rastEdges[5]);
626 ComputeEdgeData(topRight, topLeft, rastEdges[6]);
627
628 vEdgeFix16[3] = _mm256_set1_pd((rastEdges[3].a * (x - scissor.left)) + (rastEdges[3].b * (y - scissor.top)));
629 vEdgeFix16[4] = _mm256_set1_pd((rastEdges[4].a * (x - scissor.left)) + (rastEdges[4].b * (y - scissor.bottom)));
630 vEdgeFix16[5] = _mm256_set1_pd((rastEdges[5].a * (x - scissor.right)) + (rastEdges[5].b * (y - scissor.bottom)));
631 vEdgeFix16[6] = _mm256_set1_pd((rastEdges[6].a * (x - scissor.right)) + (rastEdges[6].b * (y - scissor.top)));
632
633 // if conservative rasterizing, need to bump the scissor edges out by the conservative uncertainty distance, else do nothing
634 adjustScissorEdge<RT>(rastEdges[3].a, rastEdges[3].b, vEdgeFix16[3]);
635 adjustScissorEdge<RT>(rastEdges[4].a, rastEdges[4].b, vEdgeFix16[4]);
636 adjustScissorEdge<RT>(rastEdges[5].a, rastEdges[5].b, vEdgeFix16[5]);
637 adjustScissorEdge<RT>(rastEdges[6].a, rastEdges[6].b, vEdgeFix16[6]);
638 }
639 };
640
641 //////////////////////////////////////////////////////////////////////////
642 /// @brief ComputeScissorEdges<std::true_type, std::false_type, RT> partial
643 /// specialization. Instantiated when scissor is enabled and conservative rast
644 /// is disabled.
645 template <typename RT>
646 struct ComputeScissorEdges<std::true_type, std::false_type, RT>
647 {
648 //////////////////////////////////////////////////////////////////////////
649 /// @brief Compute scissor edge vectors and evaluate edge equations
650 INLINE ComputeScissorEdges(const BBOX &, const BBOX &scissorBBox, const int32_t x, const int32_t y,
651 EDGE (&rastEdges)[RT::NumEdgesT::value], __m256d (&vEdgeFix16)[7])
652 {
653 const BBOX &scissor = scissorBBox;
654 POS topLeft{scissor.left, scissor.top};
655 POS bottomLeft{scissor.left, scissor.bottom};
656 POS topRight{scissor.right, scissor.top};
657 POS bottomRight{scissor.right, scissor.bottom};
658
659 // construct 4 scissor edges in ccw direction
660 ComputeEdgeData(topLeft, bottomLeft, rastEdges[3]);
661 ComputeEdgeData(bottomLeft, bottomRight, rastEdges[4]);
662 ComputeEdgeData(bottomRight, topRight, rastEdges[5]);
663 ComputeEdgeData(topRight, topLeft, rastEdges[6]);
664
665 vEdgeFix16[3] = _mm256_set1_pd((rastEdges[3].a * (x - scissor.left)) + (rastEdges[3].b * (y - scissor.top)));
666 vEdgeFix16[4] = _mm256_set1_pd((rastEdges[4].a * (x - scissor.left)) + (rastEdges[4].b * (y - scissor.bottom)));
667 vEdgeFix16[5] = _mm256_set1_pd((rastEdges[5].a * (x - scissor.right)) + (rastEdges[5].b * (y - scissor.bottom)));
668 vEdgeFix16[6] = _mm256_set1_pd((rastEdges[6].a * (x - scissor.right)) + (rastEdges[6].b * (y - scissor.top)));
669 }
670 };
671
672 //////////////////////////////////////////////////////////////////////////
673 /// @brief Primary function template for TrivialRejectTest. Should
674 /// never be called, but TemplateUnroller instantiates a few unused values,
675 /// so it calls a runtime assert instead of a static_assert.
676 template <typename ValidEdgeMaskT>
677 INLINE bool TrivialRejectTest(const int, const int, const int)
678 {
679 SWR_ASSERT(0, "Primary templated function should never be called");
680 return false;
681 };
682
683 //////////////////////////////////////////////////////////////////////////
684 /// @brief E0E1ValidT specialization of TrivialRejectTest. Tests edge 0
685 /// and edge 1 for trivial coverage reject
686 template <>
687 INLINE bool TrivialRejectTest<E0E1ValidT>(const int mask0, const int mask1, const int)
688 {
689 return (!(mask0 && mask1)) ? true : false;
690 };
691
692 //////////////////////////////////////////////////////////////////////////
693 /// @brief E0E2ValidT specialization of TrivialRejectTest. Tests edge 0
694 /// and edge 2 for trivial coverage reject
695 template <>
696 INLINE bool TrivialRejectTest<E0E2ValidT>(const int mask0, const int, const int mask2)
697 {
698 return (!(mask0 && mask2)) ? true : false;
699 };
700
701 //////////////////////////////////////////////////////////////////////////
702 /// @brief E1E2ValidT specialization of TrivialRejectTest. Tests edge 1
703 /// and edge 2 for trivial coverage reject
704 template <>
705 INLINE bool TrivialRejectTest<E1E2ValidT>(const int, const int mask1, const int mask2)
706 {
707 return (!(mask1 && mask2)) ? true : false;
708 };
709
710 //////////////////////////////////////////////////////////////////////////
711 /// @brief AllEdgesValidT specialization of TrivialRejectTest. Tests all
712 /// primitive edges for trivial coverage reject
713 template <>
714 INLINE bool TrivialRejectTest<AllEdgesValidT>(const int mask0, const int mask1, const int mask2)
715 {
716 return (!(mask0 && mask1 && mask2)) ? true : false;;
717 };
718
719 //////////////////////////////////////////////////////////////////////////
720 /// @brief NoEdgesValidT specialization of TrivialRejectTest. Degenerate
721 /// point, so return false and rasterize against conservative BBox
722 template <>
723 INLINE bool TrivialRejectTest<NoEdgesValidT>(const int, const int, const int)
724 {
725 return false;
726 };
727
728 //////////////////////////////////////////////////////////////////////////
729 /// @brief Primary function template for TrivialAcceptTest. Always returns
730 /// false, since it will only be called for degenerate tris, and as such
731 /// will never cover the entire raster tile
732 template <typename ValidEdgeMaskT>
733 INLINE bool TrivialAcceptTest(const int, const int, const int)
734 {
735 return false;
736 };
737
738 //////////////////////////////////////////////////////////////////////////
739 /// @brief AllEdgesValidT specialization for TrivialAcceptTest. Test all
740 /// edge masks for a fully covered raster tile
741 template <>
742 INLINE bool TrivialAcceptTest<AllEdgesValidT>(const int mask0, const int mask1, const int mask2)
743 {
744 return ((mask0 & mask1 & mask2) == 0xf);
745 };
746
747 //////////////////////////////////////////////////////////////////////////
748 /// @brief Primary function template for GenerateSVInnerCoverage. Results
749 /// in an empty function call if SVInnerCoverage isn't requested
750 template <typename RT, typename ValidEdgeMaskT, typename InputCoverageT>
751 struct GenerateSVInnerCoverage
752 {
753 INLINE GenerateSVInnerCoverage(DRAW_CONTEXT*, EDGE*, double*, uint64_t &){};
754 };
755
756 //////////////////////////////////////////////////////////////////////////
757 /// @brief Specialization of GenerateSVInnerCoverage where all edges
758 /// are non-degenerate and SVInnerCoverage is requested. Offsets the evaluated
759 /// edge values from OuterConservative to InnerConservative and rasterizes.
760 template <typename RT>
761 struct GenerateSVInnerCoverage<RT, AllEdgesValidT, InnerConservativeCoverageT>
762 {
763 INLINE GenerateSVInnerCoverage(DRAW_CONTEXT* pDC, EDGE* pRastEdges, double* pStartQuadEdges, uint64_t &innerCoverageMask)
764 {
765 double startQuadEdgesAdj[RT::NumEdgesT::value];
766 for(uint32_t e = 0; e < RT::NumEdgesT::value; ++e)
767 {
768 startQuadEdgesAdj[e] = adjustScalarEdge<RT, typename RT::InnerConservativeEdgeOffsetT>(pRastEdges[e].a, pRastEdges[e].b, pStartQuadEdges[e]);
769 }
770
771 // not trivial accept or reject, must rasterize full tile
772 RDTSC_START(BERasterizePartial);
773 innerCoverageMask = rasterizePartialTile<RT::NumEdgesT::value, typename RT::ValidEdgeMaskT>(pDC, startQuadEdgesAdj, pRastEdges);
774 RDTSC_STOP(BERasterizePartial, 0, 0);
775 }
776 };
777
778 //////////////////////////////////////////////////////////////////////////
779 /// @brief Primary function template for UpdateEdgeMasksInnerConservative. Results
780 /// in an empty function call if SVInnerCoverage isn't requested
781 template <typename RT, typename ValidEdgeMaskT, typename InputCoverageT>
782 struct UpdateEdgeMasksInnerConservative
783 {
784 INLINE UpdateEdgeMasksInnerConservative(const __m256d (&vEdgeTileBbox)[3], const __m256d*,
785 const __m128i, const __m128i, int32_t &, int32_t &, int32_t &){};
786 };
787
788 //////////////////////////////////////////////////////////////////////////
789 /// @brief Specialization of UpdateEdgeMasksInnerConservative where all edges
790 /// are non-degenerate and SVInnerCoverage is requested. Offsets the edges
791 /// evaluated at raster tile corners to inner conservative position and
792 /// updates edge masks
793 template <typename RT>
794 struct UpdateEdgeMasksInnerConservative<RT, AllEdgesValidT, InnerConservativeCoverageT>
795 {
796 INLINE UpdateEdgeMasksInnerConservative(const __m256d (&vEdgeTileBbox)[3], const __m256d* vEdgeFix16,
797 const __m128i vAi, const __m128i vBi, int32_t &mask0, int32_t &mask1, int32_t &mask2)
798 {
799 __m256d vTempEdge[3]{vEdgeFix16[0], vEdgeFix16[1], vEdgeFix16[2]};
800
801 // instead of keeping 2 copies of evaluated edges around, just compensate for the outer
802 // conservative evaluated edge when adjusting the edge in for inner conservative tests
803 adjustEdgeConservative<RT, typename RT::InnerConservativeEdgeOffsetT>(vAi, vBi, vTempEdge[0]);
804 adjustEdgeConservative<RT, typename RT::InnerConservativeEdgeOffsetT>(vAi, vBi, vTempEdge[1]);
805 adjustEdgeConservative<RT, typename RT::InnerConservativeEdgeOffsetT>(vAi, vBi, vTempEdge[2]);
806
807 UpdateEdgeMasks<typename RT::NumRasterSamplesT>(vEdgeTileBbox, vTempEdge, mask0, mask1, mask2);
808 }
809 };
810
811 //////////////////////////////////////////////////////////////////////////
812 /// @brief Specialization of UpdateEdgeMasksInnerConservative where SVInnerCoverage
813 /// is requested but at least one edge is degenerate. Since a degenerate triangle cannot
814 /// cover an entire raster tile, set mask0 to 0 to force it down the
815 /// rastierizePartialTile path
816 template <typename RT, typename ValidEdgeMaskT>
817 struct UpdateEdgeMasksInnerConservative<RT, ValidEdgeMaskT, InnerConservativeCoverageT>
818 {
819 INLINE UpdateEdgeMasksInnerConservative(const __m256d (&)[3], const __m256d*,
820 const __m128i, const __m128i, int32_t &mask0, int32_t &, int32_t &)
821 {
822 // set one mask to zero to force the triangle down the rastierizePartialTile path
823 mask0 = 0;
824 }
825 };
826
827 template <typename RT>
828 void RasterizeTriangle(DRAW_CONTEXT* pDC, uint32_t workerId, uint32_t macroTile, void* pDesc)
829 {
830 const TRIANGLE_WORK_DESC &workDesc = *((TRIANGLE_WORK_DESC*)pDesc);
831 #if KNOB_ENABLE_TOSS_POINTS
832 if (KNOB_TOSS_BIN_TRIS)
833 {
834 return;
835 }
836 #endif
837 RDTSC_START(BERasterizeTriangle);
838
839 RDTSC_START(BETriangleSetup);
840 const API_STATE &state = GetApiState(pDC);
841 const SWR_RASTSTATE &rastState = state.rastState;
842 const BACKEND_FUNCS& backendFuncs = pDC->pState->backendFuncs;
843
844 OSALIGNSIMD(SWR_TRIANGLE_DESC) triDesc;
845 triDesc.pUserClipBuffer = workDesc.pUserClipBuffer;
846
847 __m128 vX, vY, vZ, vRecipW;
848
849 // pTriBuffer data layout: grouped components of the 3 triangle points and 1 don't care
850 // eg: vX = [x0 x1 x2 dc]
851 vX = _mm_load_ps(workDesc.pTriBuffer);
852 vY = _mm_load_ps(workDesc.pTriBuffer + 4);
853 vZ = _mm_load_ps(workDesc.pTriBuffer + 8);
854 vRecipW = _mm_load_ps(workDesc.pTriBuffer + 12);
855
856 // convert to fixed point
857 static_assert(std::is_same<typename RT::PrecisionT, FixedPointTraits<Fixed_16_8>>::value, "Rasterizer expects 16.8 fixed point precision");
858 __m128i vXi = fpToFixedPoint(vX);
859 __m128i vYi = fpToFixedPoint(vY);
860
861 // quantize floating point position to fixed point precision
862 // to prevent attribute creep around the triangle vertices
863 vX = _mm_mul_ps(_mm_cvtepi32_ps(vXi), _mm_set1_ps(1.0f / FIXED_POINT_SCALE));
864 vY = _mm_mul_ps(_mm_cvtepi32_ps(vYi), _mm_set1_ps(1.0f / FIXED_POINT_SCALE));
865
866 // triangle setup - A and B edge equation coefs
867 __m128 vA, vB;
868 triangleSetupAB(vX, vY, vA, vB);
869
870 __m128i vAi, vBi;
871 triangleSetupABInt(vXi, vYi, vAi, vBi);
872
873 // determinant
874 float det = calcDeterminantInt(vAi, vBi);
875
876 // Verts in Pixel Coordinate Space at this point
877 // Det > 0 = CW winding order
878 // Convert CW triangles to CCW
879 if (det > 0.0)
880 {
881 vA = _mm_mul_ps(vA, _mm_set1_ps(-1));
882 vB = _mm_mul_ps(vB, _mm_set1_ps(-1));
883 vAi = _mm_mullo_epi32(vAi, _mm_set1_epi32(-1));
884 vBi = _mm_mullo_epi32(vBi, _mm_set1_epi32(-1));
885 det = -det;
886 }
887
888 __m128 vC;
889 // Finish triangle setup - C edge coef
890 triangleSetupC(vX, vY, vA, vB, vC);
891
892 if(RT::ValidEdgeMaskT::value != ALL_EDGES_VALID)
893 {
894 // If we have degenerate edge(s) to rasterize, set I and J coefs
895 // to 0 for constant interpolation of attributes
896 triDesc.I[0] = 0.0f;
897 triDesc.I[1] = 0.0f;
898 triDesc.I[2] = 0.0f;
899 triDesc.J[0] = 0.0f;
900 triDesc.J[1] = 0.0f;
901 triDesc.J[2] = 0.0f;
902
903 // Degenerate triangles have no area
904 triDesc.recipDet = 0.0f;
905 }
906 else
907 {
908 // only extract coefs for 2 of the barycentrics; the 3rd can be
909 // determined from the barycentric equation:
910 // i + j + k = 1 <=> k = 1 - j - i
911 _MM_EXTRACT_FLOAT(triDesc.I[0], vA, 1);
912 _MM_EXTRACT_FLOAT(triDesc.I[1], vB, 1);
913 _MM_EXTRACT_FLOAT(triDesc.I[2], vC, 1);
914 _MM_EXTRACT_FLOAT(triDesc.J[0], vA, 2);
915 _MM_EXTRACT_FLOAT(triDesc.J[1], vB, 2);
916 _MM_EXTRACT_FLOAT(triDesc.J[2], vC, 2);
917
918 // compute recipDet, used to calculate barycentric i and j in the backend
919 triDesc.recipDet = 1.0f/det;
920 }
921
922 OSALIGNSIMD(float) oneOverW[4];
923 _mm_store_ps(oneOverW, vRecipW);
924 triDesc.OneOverW[0] = oneOverW[0] - oneOverW[2];
925 triDesc.OneOverW[1] = oneOverW[1] - oneOverW[2];
926 triDesc.OneOverW[2] = oneOverW[2];
927
928 // calculate perspective correct coefs per vertex attrib
929 float* pPerspAttribs = perspAttribsTLS;
930 float* pAttribs = workDesc.pAttribs;
931 triDesc.pPerspAttribs = pPerspAttribs;
932 triDesc.pAttribs = pAttribs;
933 float *pRecipW = workDesc.pTriBuffer + 12;
934 triDesc.pRecipW = pRecipW;
935 __m128 vOneOverWV0 = _mm_broadcast_ss(pRecipW);
936 __m128 vOneOverWV1 = _mm_broadcast_ss(pRecipW+=1);
937 __m128 vOneOverWV2 = _mm_broadcast_ss(pRecipW+=1);
938 for(uint32_t i = 0; i < workDesc.numAttribs; i++)
939 {
940 __m128 attribA = _mm_load_ps(pAttribs);
941 __m128 attribB = _mm_load_ps(pAttribs+=4);
942 __m128 attribC = _mm_load_ps(pAttribs+=4);
943 pAttribs+=4;
944
945 attribA = _mm_mul_ps(attribA, vOneOverWV0);
946 attribB = _mm_mul_ps(attribB, vOneOverWV1);
947 attribC = _mm_mul_ps(attribC, vOneOverWV2);
948
949 _mm_store_ps(pPerspAttribs, attribA);
950 _mm_store_ps(pPerspAttribs+=4, attribB);
951 _mm_store_ps(pPerspAttribs+=4, attribC);
952 pPerspAttribs+=4;
953 }
954
955 // compute bary Z
956 // zInterp = zVert0 + i(zVert1-zVert0) + j (zVert2 - zVert0)
957 OSALIGNSIMD(float) a[4];
958 _mm_store_ps(a, vZ);
959 triDesc.Z[0] = a[0] - a[2];
960 triDesc.Z[1] = a[1] - a[2];
961 triDesc.Z[2] = a[2];
962
963 // add depth bias
964 triDesc.Z[2] += ComputeDepthBias(&rastState, &triDesc, workDesc.pTriBuffer + 8);
965
966 // Calc bounding box of triangle
967 OSALIGNSIMD(BBOX) bbox;
968 calcBoundingBoxInt(vXi, vYi, bbox);
969
970 if(RT::ValidEdgeMaskT::value != ALL_EDGES_VALID)
971 {
972 // If we're rasterizing a degenerate triangle, expand bounding box to guarantee the BBox is valid
973 bbox.left--; bbox.right++; bbox.top--; bbox.bottom++;
974 SWR_ASSERT(state.scissorInFixedPoint.left >= 0 && state.scissorInFixedPoint.top >= 0,
975 "Conservative rast degenerate handling requires a valid scissor rect");
976 }
977
978 // Intersect with scissor/viewport
979 OSALIGNSIMD(BBOX) intersect;
980 intersect.left = std::max(bbox.left, state.scissorInFixedPoint.left);
981 intersect.right = std::min(bbox.right - 1, state.scissorInFixedPoint.right);
982 intersect.top = std::max(bbox.top, state.scissorInFixedPoint.top);
983 intersect.bottom = std::min(bbox.bottom - 1, state.scissorInFixedPoint.bottom);
984
985 triDesc.triFlags = workDesc.triFlags;
986
987 // further constrain backend to intersecting bounding box of macro tile and scissored triangle bbox
988 uint32_t macroX, macroY;
989 MacroTileMgr::getTileIndices(macroTile, macroX, macroY);
990 int32_t macroBoxLeft = macroX * KNOB_MACROTILE_X_DIM_FIXED;
991 int32_t macroBoxRight = macroBoxLeft + KNOB_MACROTILE_X_DIM_FIXED - 1;
992 int32_t macroBoxTop = macroY * KNOB_MACROTILE_Y_DIM_FIXED;
993 int32_t macroBoxBottom = macroBoxTop + KNOB_MACROTILE_Y_DIM_FIXED - 1;
994
995 intersect.left = std::max(intersect.left, macroBoxLeft);
996 intersect.top = std::max(intersect.top, macroBoxTop);
997 intersect.right = std::min(intersect.right, macroBoxRight);
998 intersect.bottom = std::min(intersect.bottom, macroBoxBottom);
999
1000 SWR_ASSERT(intersect.left <= intersect.right && intersect.top <= intersect.bottom && intersect.left >= 0 && intersect.right >= 0 && intersect.top >= 0 && intersect.bottom >= 0);
1001
1002 RDTSC_STOP(BETriangleSetup, 0, pDC->drawId);
1003
1004 // update triangle desc
1005 uint32_t minTileX = intersect.left >> (KNOB_TILE_X_DIM_SHIFT + FIXED_POINT_SHIFT);
1006 uint32_t minTileY = intersect.top >> (KNOB_TILE_Y_DIM_SHIFT + FIXED_POINT_SHIFT);
1007 uint32_t maxTileX = intersect.right >> (KNOB_TILE_X_DIM_SHIFT + FIXED_POINT_SHIFT);
1008 uint32_t maxTileY = intersect.bottom >> (KNOB_TILE_Y_DIM_SHIFT + FIXED_POINT_SHIFT);
1009 uint32_t numTilesX = maxTileX - minTileX + 1;
1010 uint32_t numTilesY = maxTileY - minTileY + 1;
1011
1012 if (numTilesX == 0 || numTilesY == 0)
1013 {
1014 RDTSC_EVENT(BEEmptyTriangle, 1, 0);
1015 RDTSC_STOP(BERasterizeTriangle, 1, 0);
1016 return;
1017 }
1018
1019 RDTSC_START(BEStepSetup);
1020
1021 // Step to pixel center of top-left pixel of the triangle bbox
1022 // Align intersect bbox (top/left) to raster tile's (top/left).
1023 int32_t x = AlignDown(intersect.left, (FIXED_POINT_SCALE * KNOB_TILE_X_DIM));
1024 int32_t y = AlignDown(intersect.top, (FIXED_POINT_SCALE * KNOB_TILE_Y_DIM));
1025
1026 // convenience typedef
1027 typedef typename RT::NumRasterSamplesT NumRasterSamplesT;
1028
1029 // single sample rasterization evaluates edges at pixel center,
1030 // multisample evaluates edges UL pixel corner and steps to each sample position
1031 if(std::is_same<NumRasterSamplesT, SingleSampleT>::value)
1032 {
1033 // Add 0.5, in fixed point, to offset to pixel center
1034 x += (FIXED_POINT_SCALE / 2);
1035 y += (FIXED_POINT_SCALE / 2);
1036 }
1037
1038 __m128i vTopLeftX = _mm_set1_epi32(x);
1039 __m128i vTopLeftY = _mm_set1_epi32(y);
1040
1041 // evaluate edge equations at top-left pixel using 64bit math
1042 //
1043 // line = Ax + By + C
1044 // solving for C:
1045 // C = -Ax - By
1046 // we know x0 and y0 are on the line; plug them in:
1047 // C = -Ax0 - By0
1048 // plug C back into line equation:
1049 // line = Ax - By - Ax0 - By0
1050 // line = A(x - x0) + B(y - y0)
1051 // dX = (x-x0), dY = (y-y0)
1052 // so all this simplifies to
1053 // edge = A(dX) + B(dY), our first test at the top left of the bbox we're rasterizing within
1054
1055 __m128i vDeltaX = _mm_sub_epi32(vTopLeftX, vXi);
1056 __m128i vDeltaY = _mm_sub_epi32(vTopLeftY, vYi);
1057
1058 // evaluate A(dx) and B(dY) for all points
1059 __m256d vAipd = _mm256_cvtepi32_pd(vAi);
1060 __m256d vBipd = _mm256_cvtepi32_pd(vBi);
1061 __m256d vDeltaXpd = _mm256_cvtepi32_pd(vDeltaX);
1062 __m256d vDeltaYpd = _mm256_cvtepi32_pd(vDeltaY);
1063
1064 __m256d vAiDeltaXFix16 = _mm256_mul_pd(vAipd, vDeltaXpd);
1065 __m256d vBiDeltaYFix16 = _mm256_mul_pd(vBipd, vDeltaYpd);
1066 __m256d vEdge = _mm256_add_pd(vAiDeltaXFix16, vBiDeltaYFix16);
1067
1068 // apply any edge adjustments(top-left, crast, etc)
1069 adjustEdgesFix16<RT, typename RT::ConservativeEdgeOffsetT>(vAi, vBi, vEdge);
1070
1071 // broadcast respective edge results to all lanes
1072 double* pEdge = (double*)&vEdge;
1073 __m256d vEdgeFix16[7];
1074 vEdgeFix16[0] = _mm256_set1_pd(pEdge[0]);
1075 vEdgeFix16[1] = _mm256_set1_pd(pEdge[1]);
1076 vEdgeFix16[2] = _mm256_set1_pd(pEdge[2]);
1077
1078 OSALIGNSIMD(int32_t) aAi[4], aBi[4];
1079 _mm_store_si128((__m128i*)aAi, vAi);
1080 _mm_store_si128((__m128i*)aBi, vBi);
1081 EDGE rastEdges[RT::NumEdgesT::value];
1082
1083 // Compute and store triangle edge data
1084 ComputeEdgeData(aAi[0], aBi[0], rastEdges[0]);
1085 ComputeEdgeData(aAi[1], aBi[1], rastEdges[1]);
1086 ComputeEdgeData(aAi[2], aBi[2], rastEdges[2]);
1087
1088 // Compute and store triangle edge data if scissor needs to rasterized
1089 ComputeScissorEdges<typename RT::RasterizeScissorEdgesT, typename RT::IsConservativeT, RT>
1090 (bbox, state.scissorInFixedPoint, x, y, rastEdges, vEdgeFix16);
1091
1092 // Evaluate edge equations at sample positions of each of the 4 corners of a raster tile
1093 // used to for testing if entire raster tile is inside a triangle
1094 for (uint32_t e = 0; e < RT::NumEdgesT::value; ++e)
1095 {
1096 vEdgeFix16[e] = _mm256_add_pd(vEdgeFix16[e], rastEdges[e].vRasterTileOffsets);
1097 }
1098
1099 // at this point vEdge has been evaluated at the UL pixel corners of raster tile bbox
1100 // step sample positions to the raster tile bbox of multisample points
1101 // min(xSamples),min(ySamples) ------ max(xSamples),min(ySamples)
1102 // | |
1103 // | |
1104 // min(xSamples),max(ySamples) ------ max(xSamples),max(ySamples)
1105 __m256d vEdgeTileBbox[3];
1106 if (NumRasterSamplesT::value > 1)
1107 {
1108 __m128i vTileSampleBBoxXh = RT::MT::TileSampleOffsetsX();
1109 __m128i vTileSampleBBoxYh = RT::MT::TileSampleOffsetsY();
1110
1111 __m256d vTileSampleBBoxXFix8 = _mm256_cvtepi32_pd(vTileSampleBBoxXh);
1112 __m256d vTileSampleBBoxYFix8 = _mm256_cvtepi32_pd(vTileSampleBBoxYh);
1113
1114 // step edge equation tests from Tile
1115 // used to for testing if entire raster tile is inside a triangle
1116 for (uint32_t e = 0; e < 3; ++e)
1117 {
1118 __m256d vResultAxFix16 = _mm256_mul_pd(_mm256_set1_pd(rastEdges[e].a), vTileSampleBBoxXFix8);
1119 __m256d vResultByFix16 = _mm256_mul_pd(_mm256_set1_pd(rastEdges[e].b), vTileSampleBBoxYFix8);
1120 vEdgeTileBbox[e] = _mm256_add_pd(vResultAxFix16, vResultByFix16);
1121
1122 // adjust for msaa tile bbox edges outward for conservative rast, if enabled
1123 adjustEdgeConservative<RT, typename RT::ConservativeEdgeOffsetT>(vAi, vBi, vEdgeTileBbox[e]);
1124 }
1125 }
1126
1127 RDTSC_STOP(BEStepSetup, 0, pDC->drawId);
1128
1129 uint32_t tY = minTileY;
1130 uint32_t tX = minTileX;
1131 uint32_t maxY = maxTileY;
1132 uint32_t maxX = maxTileX;
1133
1134 RenderOutputBuffers renderBuffers, currentRenderBufferRow;
1135 GetRenderHotTiles<RT::MT::numSamples>(pDC, macroTile, minTileX, minTileY, renderBuffers, triDesc.triFlags.renderTargetArrayIndex);
1136 currentRenderBufferRow = renderBuffers;
1137
1138 // rasterize and generate coverage masks per sample
1139 for (uint32_t tileY = tY; tileY <= maxY; ++tileY)
1140 {
1141 __m256d vStartOfRowEdge[RT::NumEdgesT::value];
1142 for (uint32_t e = 0; e < RT::NumEdgesT::value; ++e)
1143 {
1144 vStartOfRowEdge[e] = vEdgeFix16[e];
1145 }
1146
1147 for (uint32_t tileX = tX; tileX <= maxX; ++tileX)
1148 {
1149 triDesc.anyCoveredSamples = 0;
1150
1151 // is the corner of the edge outside of the raster tile? (vEdge < 0)
1152 int mask0, mask1, mask2;
1153 UpdateEdgeMasks<NumRasterSamplesT>(vEdgeTileBbox, vEdgeFix16, mask0, mask1, mask2);
1154
1155 for (uint32_t sampleNum = 0; sampleNum < NumRasterSamplesT::value; sampleNum++)
1156 {
1157 // trivial reject, at least one edge has all 4 corners of raster tile outside
1158 bool trivialReject = TrivialRejectTest<typename RT::ValidEdgeMaskT>(mask0, mask1, mask2);
1159
1160 if (!trivialReject)
1161 {
1162 // trivial accept mask
1163 triDesc.coverageMask[sampleNum] = 0xffffffffffffffffULL;
1164
1165 // Update the raster tile edge masks based on inner conservative edge offsets, if enabled
1166 UpdateEdgeMasksInnerConservative<RT, typename RT::ValidEdgeMaskT, typename RT::InputCoverageT>
1167 (vEdgeTileBbox, vEdgeFix16, vAi, vBi, mask0, mask1, mask2);
1168
1169 if (TrivialAcceptTest<typename RT::ValidEdgeMaskT>(mask0, mask1, mask2))
1170 {
1171 // trivial accept, all 4 corners of all 3 edges are negative
1172 // i.e. raster tile completely inside triangle
1173 triDesc.anyCoveredSamples = triDesc.coverageMask[sampleNum];
1174 if(std::is_same<typename RT::InputCoverageT, InnerConservativeCoverageT>::value)
1175 {
1176 triDesc.innerCoverageMask = 0xffffffffffffffffULL;
1177 }
1178 RDTSC_EVENT(BETrivialAccept, 1, 0);
1179 }
1180 else
1181 {
1182 __m256d vEdgeAtSample[RT::NumEdgesT::value];
1183 if(std::is_same<NumRasterSamplesT, SingleSampleT>::value)
1184 {
1185 // should get optimized out for single sample case (global value numbering or copy propagation)
1186 for (uint32_t e = 0; e < RT::NumEdgesT::value; ++e)
1187 {
1188 vEdgeAtSample[e] = vEdgeFix16[e];
1189 }
1190 }
1191 else
1192 {
1193 __m128i vSampleOffsetXh = RT::MT::vXi(sampleNum);
1194 __m128i vSampleOffsetYh = RT::MT::vYi(sampleNum);
1195 __m256d vSampleOffsetX = _mm256_cvtepi32_pd(vSampleOffsetXh);
1196 __m256d vSampleOffsetY = _mm256_cvtepi32_pd(vSampleOffsetYh);
1197
1198 // step edge equation tests from UL tile corner to pixel sample position
1199 for (uint32_t e = 0; e < RT::NumEdgesT::value; ++e)
1200 {
1201 __m256d vResultAxFix16 = _mm256_mul_pd(_mm256_set1_pd(rastEdges[e].a), vSampleOffsetX);
1202 __m256d vResultByFix16 = _mm256_mul_pd(_mm256_set1_pd(rastEdges[e].b), vSampleOffsetY);
1203 vEdgeAtSample[e] = _mm256_add_pd(vResultAxFix16, vResultByFix16);
1204 vEdgeAtSample[e] = _mm256_add_pd(vEdgeFix16[e], vEdgeAtSample[e]);
1205 }
1206 }
1207
1208 double startQuadEdges[RT::NumEdgesT::value];
1209 const __m256i vLane0Mask = _mm256_set_epi32(0, 0, 0, 0, 0, 0, -1, -1);
1210 for (uint32_t e = 0; e < RT::NumEdgesT::value; ++e)
1211 {
1212 _mm256_maskstore_pd(&startQuadEdges[e], vLane0Mask, vEdgeAtSample[e]);
1213 }
1214
1215 // not trivial accept or reject, must rasterize full tile
1216 RDTSC_START(BERasterizePartial);
1217 triDesc.coverageMask[sampleNum] = rasterizePartialTile<RT::NumEdgesT::value, typename RT::ValidEdgeMaskT>(pDC, startQuadEdges, rastEdges);
1218 RDTSC_STOP(BERasterizePartial, 0, 0);
1219
1220 triDesc.anyCoveredSamples |= triDesc.coverageMask[sampleNum];
1221
1222 // Output SV InnerCoverage, if needed
1223 GenerateSVInnerCoverage<RT, typename RT::ValidEdgeMaskT, typename RT::InputCoverageT>(pDC, rastEdges, startQuadEdges, triDesc.innerCoverageMask);
1224 }
1225 }
1226 else
1227 {
1228 // if we're calculating coverage per sample, need to store it off. otherwise no covered samples, don't need to do anything
1229 if(NumRasterSamplesT::value > 1)
1230 {
1231 triDesc.coverageMask[sampleNum] = 0;
1232 }
1233 RDTSC_EVENT(BETrivialReject, 1, 0);
1234 }
1235 }
1236
1237 #if KNOB_ENABLE_TOSS_POINTS
1238 if(KNOB_TOSS_RS)
1239 {
1240 gToss = triDesc.coverageMask[0];
1241 }
1242 else
1243 #endif
1244 if(triDesc.anyCoveredSamples)
1245 {
1246 // if conservative rast and MSAA are enabled, conservative coverage for a pixel means all samples in that pixel are covered
1247 // copy conservative coverage result to all samples
1248 if(RT::IsConservativeT::value)
1249 {
1250 auto copyCoverage = [&](int sample){triDesc.coverageMask[sample] = triDesc.coverageMask[0]; };
1251 UnrollerL<1, RT::MT::numSamples, 1>::step(copyCoverage);
1252 }
1253
1254 RDTSC_START(BEPixelBackend);
1255 backendFuncs.pfnBackend(pDC, workerId, tileX << KNOB_TILE_X_DIM_SHIFT, tileY << KNOB_TILE_Y_DIM_SHIFT, triDesc, renderBuffers);
1256 RDTSC_STOP(BEPixelBackend, 0, 0);
1257 }
1258
1259 // step to the next tile in X
1260 for (uint32_t e = 0; e < RT::NumEdgesT::value; ++e)
1261 {
1262 vEdgeFix16[e] = _mm256_add_pd(vEdgeFix16[e], _mm256_set1_pd(rastEdges[e].stepRasterTileX));
1263 }
1264 StepRasterTileX<RT>(state.psState.numRenderTargets, renderBuffers);
1265 }
1266
1267 // step to the next tile in Y
1268 for (uint32_t e = 0; e < RT::NumEdgesT::value; ++e)
1269 {
1270 vEdgeFix16[e] = _mm256_add_pd(vStartOfRowEdge[e], _mm256_set1_pd(rastEdges[e].stepRasterTileY));
1271 }
1272 StepRasterTileY<RT>(state.psState.numRenderTargets, renderBuffers, currentRenderBufferRow);
1273 }
1274
1275 RDTSC_STOP(BERasterizeTriangle, 1, 0);
1276 }
1277
1278 void RasterizeTriPoint(DRAW_CONTEXT *pDC, uint32_t workerId, uint32_t macroTile, void* pData)
1279 {
1280 const TRIANGLE_WORK_DESC& workDesc = *(const TRIANGLE_WORK_DESC*)pData;
1281 const SWR_RASTSTATE& rastState = pDC->pState->state.rastState;
1282 const SWR_BACKEND_STATE& backendState = pDC->pState->state.backendState;
1283
1284 bool isPointSpriteTexCoordEnabled = backendState.pointSpriteTexCoordMask != 0;
1285
1286 // load point vertex
1287 float x = *workDesc.pTriBuffer;
1288 float y = *(workDesc.pTriBuffer + 1);
1289 float z = *(workDesc.pTriBuffer + 2);
1290
1291 // create a copy of the triangle buffer to write our adjusted vertices to
1292 OSALIGNSIMD(float) newTriBuffer[4 * 4];
1293 TRIANGLE_WORK_DESC newWorkDesc = workDesc;
1294 newWorkDesc.pTriBuffer = &newTriBuffer[0];
1295
1296 // create a copy of the attrib buffer to write our adjusted attribs to
1297 OSALIGNSIMD(float) newAttribBuffer[4 * 3 * KNOB_NUM_ATTRIBUTES];
1298 newWorkDesc.pAttribs = &newAttribBuffer[0];
1299
1300 newWorkDesc.pUserClipBuffer = workDesc.pUserClipBuffer;
1301 newWorkDesc.numAttribs = workDesc.numAttribs;
1302 newWorkDesc.triFlags = workDesc.triFlags;
1303
1304 // construct two tris by bloating point by point size
1305 float halfPointSize = workDesc.triFlags.pointSize * 0.5f;
1306 float lowerX = x - halfPointSize;
1307 float upperX = x + halfPointSize;
1308 float lowerY = y - halfPointSize;
1309 float upperY = y + halfPointSize;
1310
1311 // tri 0
1312 float *pBuf = &newTriBuffer[0];
1313 *pBuf++ = lowerX;
1314 *pBuf++ = lowerX;
1315 *pBuf++ = upperX;
1316 pBuf++;
1317 *pBuf++ = lowerY;
1318 *pBuf++ = upperY;
1319 *pBuf++ = upperY;
1320 pBuf++;
1321 _mm_store_ps(pBuf, _mm_set1_ps(z));
1322 _mm_store_ps(pBuf+=4, _mm_set1_ps(1.0f));
1323
1324 // setup triangle rasterizer function
1325 PFN_WORK_FUNC pfnTriRast;
1326 // for center sample pattern, all samples are at pixel center; calculate coverage
1327 // once at center and broadcast the results in the backend
1328 uint32_t sampleCount = (rastState.samplePattern == SWR_MSAA_STANDARD_PATTERN) ? rastState.sampleCount : SWR_MULTISAMPLE_1X;
1329 // conservative rast not supported for points/lines
1330 pfnTriRast = GetRasterizerFunc(sampleCount, false, SWR_INPUT_COVERAGE_NONE, ALL_EDGES_VALID, (rastState.scissorEnable > 0));
1331
1332 // overwrite texcoords for point sprites
1333 if (isPointSpriteTexCoordEnabled)
1334 {
1335 // copy original attribs
1336 memcpy(&newAttribBuffer[0], workDesc.pAttribs, 4 * 3 * workDesc.numAttribs * sizeof(float));
1337 newWorkDesc.pAttribs = &newAttribBuffer[0];
1338
1339 // overwrite texcoord for point sprites
1340 uint32_t texCoordMask = backendState.pointSpriteTexCoordMask;
1341 DWORD texCoordAttrib = 0;
1342
1343 while (_BitScanForward(&texCoordAttrib, texCoordMask))
1344 {
1345 texCoordMask &= ~(1 << texCoordAttrib);
1346 __m128* pTexAttrib = (__m128*)&newAttribBuffer[0] + 3 * texCoordAttrib;
1347 if (rastState.pointSpriteTopOrigin)
1348 {
1349 pTexAttrib[0] = _mm_set_ps(1, 0, 0, 0);
1350 pTexAttrib[1] = _mm_set_ps(1, 0, 1, 0);
1351 pTexAttrib[2] = _mm_set_ps(1, 0, 1, 1);
1352 }
1353 else
1354 {
1355 pTexAttrib[0] = _mm_set_ps(1, 0, 1, 0);
1356 pTexAttrib[1] = _mm_set_ps(1, 0, 0, 0);
1357 pTexAttrib[2] = _mm_set_ps(1, 0, 0, 1);
1358 }
1359 }
1360 }
1361 else
1362 {
1363 // no texcoord overwrite, can reuse the attrib buffer from frontend
1364 newWorkDesc.pAttribs = workDesc.pAttribs;
1365 }
1366
1367 pfnTriRast(pDC, workerId, macroTile, (void*)&newWorkDesc);
1368
1369 // tri 1
1370 pBuf = &newTriBuffer[0];
1371 *pBuf++ = lowerX;
1372 *pBuf++ = upperX;
1373 *pBuf++ = upperX;
1374 pBuf++;
1375 *pBuf++ = lowerY;
1376 *pBuf++ = upperY;
1377 *pBuf++ = lowerY;
1378 // z, w unchanged
1379
1380 if (isPointSpriteTexCoordEnabled)
1381 {
1382 uint32_t texCoordMask = backendState.pointSpriteTexCoordMask;
1383 DWORD texCoordAttrib = 0;
1384
1385 while (_BitScanForward(&texCoordAttrib, texCoordMask))
1386 {
1387 texCoordMask &= ~(1 << texCoordAttrib);
1388 __m128* pTexAttrib = (__m128*)&newAttribBuffer[0] + 3 * texCoordAttrib;
1389 if (rastState.pointSpriteTopOrigin)
1390 {
1391 pTexAttrib[0] = _mm_set_ps(1, 0, 0, 0);
1392 pTexAttrib[1] = _mm_set_ps(1, 0, 1, 1);
1393 pTexAttrib[2] = _mm_set_ps(1, 0, 0, 1);
1394
1395 }
1396 else
1397 {
1398 pTexAttrib[0] = _mm_set_ps(1, 0, 1, 0);
1399 pTexAttrib[1] = _mm_set_ps(1, 0, 0, 1);
1400 pTexAttrib[2] = _mm_set_ps(1, 0, 1, 1);
1401 }
1402 }
1403 }
1404
1405 pfnTriRast(pDC, workerId, macroTile, (void*)&newWorkDesc);
1406 }
1407
1408 void RasterizeSimplePoint(DRAW_CONTEXT *pDC, uint32_t workerId, uint32_t macroTile, void* pData)
1409 {
1410 #if KNOB_ENABLE_TOSS_POINTS
1411 if (KNOB_TOSS_BIN_TRIS)
1412 {
1413 return;
1414 }
1415 #endif
1416
1417 const TRIANGLE_WORK_DESC& workDesc = *(const TRIANGLE_WORK_DESC*)pData;
1418 const BACKEND_FUNCS& backendFuncs = pDC->pState->backendFuncs;
1419
1420 // map x,y relative offsets from start of raster tile to bit position in
1421 // coverage mask for the point
1422 static const uint32_t coverageMap[8][8] = {
1423 { 0, 1, 4, 5, 8, 9, 12, 13 },
1424 { 2, 3, 6, 7, 10, 11, 14, 15 },
1425 { 16, 17, 20, 21, 24, 25, 28, 29 },
1426 { 18, 19, 22, 23, 26, 27, 30, 31 },
1427 { 32, 33, 36, 37, 40, 41, 44, 45 },
1428 { 34, 35, 38, 39, 42, 43, 46, 47 },
1429 { 48, 49, 52, 53, 56, 57, 60, 61 },
1430 { 50, 51, 54, 55, 58, 59, 62, 63 }
1431 };
1432
1433 OSALIGNSIMD(SWR_TRIANGLE_DESC) triDesc;
1434
1435 // pull point information from triangle buffer
1436 // @todo use structs for readability
1437 uint32_t tileAlignedX = *(uint32_t*)workDesc.pTriBuffer;
1438 uint32_t tileAlignedY = *(uint32_t*)(workDesc.pTriBuffer + 1);
1439 float z = *(workDesc.pTriBuffer + 2);
1440
1441 // construct triangle descriptor for point
1442 // no interpolation, set up i,j for constant interpolation of z and attribs
1443 // @todo implement an optimized backend that doesn't require triangle information
1444
1445 // compute coverage mask from x,y packed into the coverageMask flag
1446 // mask indices by the maximum valid index for x/y of coveragemap.
1447 uint32_t tX = workDesc.triFlags.coverageMask & 0x7;
1448 uint32_t tY = (workDesc.triFlags.coverageMask >> 4) & 0x7;
1449 // todo: multisample points?
1450 triDesc.coverageMask[0] = 1ULL << coverageMap[tY][tX];
1451
1452 // no persp divide needed for points
1453 triDesc.pAttribs = triDesc.pPerspAttribs = workDesc.pAttribs;
1454 triDesc.triFlags = workDesc.triFlags;
1455 triDesc.recipDet = 1.0f;
1456 triDesc.OneOverW[0] = triDesc.OneOverW[1] = triDesc.OneOverW[2] = 1.0f;
1457 triDesc.I[0] = triDesc.I[1] = triDesc.I[2] = 0.0f;
1458 triDesc.J[0] = triDesc.J[1] = triDesc.J[2] = 0.0f;
1459 triDesc.Z[0] = triDesc.Z[1] = triDesc.Z[2] = z;
1460
1461 RenderOutputBuffers renderBuffers;
1462 GetRenderHotTiles(pDC, macroTile, tileAlignedX >> KNOB_TILE_X_DIM_SHIFT , tileAlignedY >> KNOB_TILE_Y_DIM_SHIFT,
1463 renderBuffers, triDesc.triFlags.renderTargetArrayIndex);
1464
1465 RDTSC_START(BEPixelBackend);
1466 backendFuncs.pfnBackend(pDC, workerId, tileAlignedX, tileAlignedY, triDesc, renderBuffers);
1467 RDTSC_STOP(BEPixelBackend, 0, 0);
1468 }
1469
1470 // Get pointers to hot tile memory for color RT, depth, stencil
1471 template <uint32_t numSamples>
1472 void GetRenderHotTiles(DRAW_CONTEXT *pDC, uint32_t macroID, uint32_t tileX, uint32_t tileY, RenderOutputBuffers &renderBuffers, uint32_t renderTargetArrayIndex)
1473 {
1474 const API_STATE& state = GetApiState(pDC);
1475 SWR_CONTEXT *pContext = pDC->pContext;
1476
1477 uint32_t mx, my;
1478 MacroTileMgr::getTileIndices(macroID, mx, my);
1479 tileX -= KNOB_MACROTILE_X_DIM_IN_TILES * mx;
1480 tileY -= KNOB_MACROTILE_Y_DIM_IN_TILES * my;
1481
1482 // compute tile offset for active hottile buffers
1483 const uint32_t pitch = KNOB_MACROTILE_X_DIM * FormatTraits<KNOB_COLOR_HOT_TILE_FORMAT>::bpp / 8;
1484 uint32_t offset = ComputeTileOffset2D<TilingTraits<SWR_TILE_SWRZ, FormatTraits<KNOB_COLOR_HOT_TILE_FORMAT>::bpp> >(pitch, tileX, tileY);
1485 offset*=numSamples;
1486
1487 unsigned long rtSlot = 0;
1488 uint32_t colorHottileEnableMask = state.colorHottileEnable;
1489 while(_BitScanForward(&rtSlot, colorHottileEnableMask))
1490 {
1491 HOTTILE *pColor = pContext->pHotTileMgr->GetHotTile(pContext, pDC, macroID, (SWR_RENDERTARGET_ATTACHMENT)(SWR_ATTACHMENT_COLOR0 + rtSlot), true,
1492 numSamples, renderTargetArrayIndex);
1493 pColor->state = HOTTILE_DIRTY;
1494 renderBuffers.pColor[rtSlot] = pColor->pBuffer + offset;
1495
1496 colorHottileEnableMask &= ~(1 << rtSlot);
1497 }
1498 if(state.depthHottileEnable)
1499 {
1500 const uint32_t pitch = KNOB_MACROTILE_X_DIM * FormatTraits<KNOB_DEPTH_HOT_TILE_FORMAT>::bpp / 8;
1501 uint32_t offset = ComputeTileOffset2D<TilingTraits<SWR_TILE_SWRZ, FormatTraits<KNOB_DEPTH_HOT_TILE_FORMAT>::bpp> >(pitch, tileX, tileY);
1502 offset*=numSamples;
1503 HOTTILE *pDepth = pContext->pHotTileMgr->GetHotTile(pContext, pDC, macroID, SWR_ATTACHMENT_DEPTH, true,
1504 numSamples, renderTargetArrayIndex);
1505 pDepth->state = HOTTILE_DIRTY;
1506 SWR_ASSERT(pDepth->pBuffer != nullptr);
1507 renderBuffers.pDepth = pDepth->pBuffer + offset;
1508 }
1509 if(state.stencilHottileEnable)
1510 {
1511 const uint32_t pitch = KNOB_MACROTILE_X_DIM * FormatTraits<KNOB_STENCIL_HOT_TILE_FORMAT>::bpp / 8;
1512 uint32_t offset = ComputeTileOffset2D<TilingTraits<SWR_TILE_SWRZ, FormatTraits<KNOB_STENCIL_HOT_TILE_FORMAT>::bpp> >(pitch, tileX, tileY);
1513 offset*=numSamples;
1514 HOTTILE* pStencil = pContext->pHotTileMgr->GetHotTile(pContext, pDC, macroID, SWR_ATTACHMENT_STENCIL, true,
1515 numSamples, renderTargetArrayIndex);
1516 pStencil->state = HOTTILE_DIRTY;
1517 SWR_ASSERT(pStencil->pBuffer != nullptr);
1518 renderBuffers.pStencil = pStencil->pBuffer + offset;
1519 }
1520 }
1521
1522 template <typename RT>
1523 INLINE void StepRasterTileX(uint32_t NumRT, RenderOutputBuffers &buffers)
1524 {
1525 for(uint32_t rt = 0; rt < NumRT; ++rt)
1526 {
1527 buffers.pColor[rt] += RT::colorRasterTileStep;
1528 }
1529
1530 buffers.pDepth += RT::depthRasterTileStep;
1531 buffers.pStencil += RT::stencilRasterTileStep;
1532 }
1533
1534 template <typename RT>
1535 INLINE void StepRasterTileY(uint32_t NumRT, RenderOutputBuffers &buffers, RenderOutputBuffers &startBufferRow)
1536 {
1537 for(uint32_t rt = 0; rt < NumRT; ++rt)
1538 {
1539 startBufferRow.pColor[rt] += RT::colorRasterTileRowStep;
1540 buffers.pColor[rt] = startBufferRow.pColor[rt];
1541 }
1542 startBufferRow.pDepth += RT::depthRasterTileRowStep;
1543 buffers.pDepth = startBufferRow.pDepth;
1544
1545 startBufferRow.pStencil += RT::stencilRasterTileRowStep;
1546 buffers.pStencil = startBufferRow.pStencil;
1547 }
1548
1549 void RasterizeLine(DRAW_CONTEXT *pDC, uint32_t workerId, uint32_t macroTile, void *pData)
1550 {
1551 const TRIANGLE_WORK_DESC &workDesc = *((TRIANGLE_WORK_DESC*)pData);
1552 #if KNOB_ENABLE_TOSS_POINTS
1553 if (KNOB_TOSS_BIN_TRIS)
1554 {
1555 return;
1556 }
1557 #endif
1558
1559 // bloat line to two tris and call the triangle rasterizer twice
1560 RDTSC_START(BERasterizeLine);
1561
1562 const API_STATE &state = GetApiState(pDC);
1563 const SWR_RASTSTATE &rastState = state.rastState;
1564
1565 // macrotile dimensioning
1566 uint32_t macroX, macroY;
1567 MacroTileMgr::getTileIndices(macroTile, macroX, macroY);
1568 int32_t macroBoxLeft = macroX * KNOB_MACROTILE_X_DIM_FIXED;
1569 int32_t macroBoxRight = macroBoxLeft + KNOB_MACROTILE_X_DIM_FIXED - 1;
1570 int32_t macroBoxTop = macroY * KNOB_MACROTILE_Y_DIM_FIXED;
1571 int32_t macroBoxBottom = macroBoxTop + KNOB_MACROTILE_Y_DIM_FIXED - 1;
1572
1573 // create a copy of the triangle buffer to write our adjusted vertices to
1574 OSALIGNSIMD(float) newTriBuffer[4 * 4];
1575 TRIANGLE_WORK_DESC newWorkDesc = workDesc;
1576 newWorkDesc.pTriBuffer = &newTriBuffer[0];
1577
1578 // create a copy of the attrib buffer to write our adjusted attribs to
1579 OSALIGNSIMD(float) newAttribBuffer[4 * 3 * KNOB_NUM_ATTRIBUTES];
1580 newWorkDesc.pAttribs = &newAttribBuffer[0];
1581
1582 const __m128 vBloat0 = _mm_set_ps(0.5f, -0.5f, -0.5f, 0.5f);
1583 const __m128 vBloat1 = _mm_set_ps(0.5f, 0.5f, 0.5f, -0.5f);
1584
1585 __m128 vX, vY, vZ, vRecipW;
1586
1587 vX = _mm_load_ps(workDesc.pTriBuffer);
1588 vY = _mm_load_ps(workDesc.pTriBuffer + 4);
1589 vZ = _mm_load_ps(workDesc.pTriBuffer + 8);
1590 vRecipW = _mm_load_ps(workDesc.pTriBuffer + 12);
1591
1592 // triangle 0
1593 // v0,v1 -> v0,v0,v1
1594 __m128 vXa = _mm_shuffle_ps(vX, vX, _MM_SHUFFLE(1, 1, 0, 0));
1595 __m128 vYa = _mm_shuffle_ps(vY, vY, _MM_SHUFFLE(1, 1, 0, 0));
1596 __m128 vZa = _mm_shuffle_ps(vZ, vZ, _MM_SHUFFLE(1, 1, 0, 0));
1597 __m128 vRecipWa = _mm_shuffle_ps(vRecipW, vRecipW, _MM_SHUFFLE(1, 1, 0, 0));
1598
1599 __m128 vLineWidth = _mm_set1_ps(pDC->pState->state.rastState.lineWidth);
1600 __m128 vAdjust = _mm_mul_ps(vLineWidth, vBloat0);
1601 if (workDesc.triFlags.yMajor)
1602 {
1603 vXa = _mm_add_ps(vAdjust, vXa);
1604 }
1605 else
1606 {
1607 vYa = _mm_add_ps(vAdjust, vYa);
1608 }
1609
1610 // Store triangle description for rasterizer
1611 _mm_store_ps((float*)&newTriBuffer[0], vXa);
1612 _mm_store_ps((float*)&newTriBuffer[4], vYa);
1613 _mm_store_ps((float*)&newTriBuffer[8], vZa);
1614 _mm_store_ps((float*)&newTriBuffer[12], vRecipWa);
1615
1616 // binner bins 3 edges for lines as v0, v1, v1
1617 // tri0 needs v0, v0, v1
1618 for (uint32_t a = 0; a < workDesc.numAttribs; ++a)
1619 {
1620 __m128 vAttrib0 = _mm_load_ps(&workDesc.pAttribs[a*12 + 0]);
1621 __m128 vAttrib1 = _mm_load_ps(&workDesc.pAttribs[a*12 + 4]);
1622
1623 _mm_store_ps((float*)&newAttribBuffer[a*12 + 0], vAttrib0);
1624 _mm_store_ps((float*)&newAttribBuffer[a*12 + 4], vAttrib0);
1625 _mm_store_ps((float*)&newAttribBuffer[a*12 + 8], vAttrib1);
1626 }
1627
1628 // Store user clip distances for triangle 0
1629 float newClipBuffer[3 * 8];
1630 uint32_t numClipDist = _mm_popcnt_u32(state.rastState.clipDistanceMask);
1631 if (numClipDist)
1632 {
1633 newWorkDesc.pUserClipBuffer = newClipBuffer;
1634
1635 float* pOldBuffer = workDesc.pUserClipBuffer;
1636 float* pNewBuffer = newClipBuffer;
1637 for (uint32_t i = 0; i < numClipDist; ++i)
1638 {
1639 // read barycentric coeffs from binner
1640 float a = *(pOldBuffer++);
1641 float b = *(pOldBuffer++);
1642
1643 // reconstruct original clip distance at vertices
1644 float c0 = a + b;
1645 float c1 = b;
1646
1647 // construct triangle barycentrics
1648 *(pNewBuffer++) = c0 - c1;
1649 *(pNewBuffer++) = c0 - c1;
1650 *(pNewBuffer++) = c1;
1651 }
1652 }
1653
1654 // setup triangle rasterizer function
1655 PFN_WORK_FUNC pfnTriRast;
1656 uint32_t sampleCount = (rastState.samplePattern == SWR_MSAA_STANDARD_PATTERN) ? rastState.sampleCount : SWR_MULTISAMPLE_1X;
1657 // conservative rast not supported for points/lines
1658 pfnTriRast = GetRasterizerFunc(sampleCount, false, SWR_INPUT_COVERAGE_NONE, ALL_EDGES_VALID, (rastState.scissorEnable > 0));
1659
1660 // make sure this macrotile intersects the triangle
1661 __m128i vXai = fpToFixedPoint(vXa);
1662 __m128i vYai = fpToFixedPoint(vYa);
1663 OSALIGNSIMD(BBOX) bboxA;
1664 calcBoundingBoxInt(vXai, vYai, bboxA);
1665
1666 if (!(bboxA.left > macroBoxRight ||
1667 bboxA.left > state.scissorInFixedPoint.right ||
1668 bboxA.right - 1 < macroBoxLeft ||
1669 bboxA.right - 1 < state.scissorInFixedPoint.left ||
1670 bboxA.top > macroBoxBottom ||
1671 bboxA.top > state.scissorInFixedPoint.bottom ||
1672 bboxA.bottom - 1 < macroBoxTop ||
1673 bboxA.bottom - 1 < state.scissorInFixedPoint.top)) {
1674 // rasterize triangle
1675 pfnTriRast(pDC, workerId, macroTile, (void*)&newWorkDesc);
1676 }
1677
1678 // triangle 1
1679 // v0,v1 -> v1,v1,v0
1680 vXa = _mm_shuffle_ps(vX, vX, _MM_SHUFFLE(1, 0, 1, 1));
1681 vYa = _mm_shuffle_ps(vY, vY, _MM_SHUFFLE(1, 0, 1, 1));
1682 vZa = _mm_shuffle_ps(vZ, vZ, _MM_SHUFFLE(1, 0, 1, 1));
1683 vRecipWa = _mm_shuffle_ps(vRecipW, vRecipW, _MM_SHUFFLE(1, 0, 1, 1));
1684
1685 vAdjust = _mm_mul_ps(vLineWidth, vBloat1);
1686 if (workDesc.triFlags.yMajor)
1687 {
1688 vXa = _mm_add_ps(vAdjust, vXa);
1689 }
1690 else
1691 {
1692 vYa = _mm_add_ps(vAdjust, vYa);
1693 }
1694
1695 // Store triangle description for rasterizer
1696 _mm_store_ps((float*)&newTriBuffer[0], vXa);
1697 _mm_store_ps((float*)&newTriBuffer[4], vYa);
1698 _mm_store_ps((float*)&newTriBuffer[8], vZa);
1699 _mm_store_ps((float*)&newTriBuffer[12], vRecipWa);
1700
1701 // binner bins 3 edges for lines as v0, v1, v1
1702 // tri1 needs v1, v1, v0
1703 for (uint32_t a = 0; a < workDesc.numAttribs; ++a)
1704 {
1705 __m128 vAttrib0 = _mm_load_ps(&workDesc.pAttribs[a * 12 + 0]);
1706 __m128 vAttrib1 = _mm_load_ps(&workDesc.pAttribs[a * 12 + 4]);
1707
1708 _mm_store_ps((float*)&newAttribBuffer[a * 12 + 0], vAttrib1);
1709 _mm_store_ps((float*)&newAttribBuffer[a * 12 + 4], vAttrib1);
1710 _mm_store_ps((float*)&newAttribBuffer[a * 12 + 8], vAttrib0);
1711 }
1712
1713 // store user clip distance for triangle 1
1714 if (numClipDist)
1715 {
1716 float* pOldBuffer = workDesc.pUserClipBuffer;
1717 float* pNewBuffer = newClipBuffer;
1718 for (uint32_t i = 0; i < numClipDist; ++i)
1719 {
1720 // read barycentric coeffs from binner
1721 float a = *(pOldBuffer++);
1722 float b = *(pOldBuffer++);
1723
1724 // reconstruct original clip distance at vertices
1725 float c0 = a + b;
1726 float c1 = b;
1727
1728 // construct triangle barycentrics
1729 *(pNewBuffer++) = c1 - c0;
1730 *(pNewBuffer++) = c1 - c0;
1731 *(pNewBuffer++) = c0;
1732 }
1733 }
1734
1735 vXai = fpToFixedPoint(vXa);
1736 vYai = fpToFixedPoint(vYa);
1737 calcBoundingBoxInt(vXai, vYai, bboxA);
1738
1739 if (!(bboxA.left > macroBoxRight ||
1740 bboxA.left > state.scissorInFixedPoint.right ||
1741 bboxA.right - 1 < macroBoxLeft ||
1742 bboxA.right - 1 < state.scissorInFixedPoint.left ||
1743 bboxA.top > macroBoxBottom ||
1744 bboxA.top > state.scissorInFixedPoint.bottom ||
1745 bboxA.bottom - 1 < macroBoxTop ||
1746 bboxA.bottom - 1 < state.scissorInFixedPoint.top)) {
1747 // rasterize triangle
1748 pfnTriRast(pDC, workerId, macroTile, (void*)&newWorkDesc);
1749 }
1750
1751 RDTSC_STOP(BERasterizeLine, 1, 0);
1752 }
1753
1754 struct RasterizerChooser
1755 {
1756 typedef PFN_WORK_FUNC FuncType;
1757
1758 template <typename... ArgsB>
1759 static FuncType GetFunc()
1760 {
1761 return RasterizeTriangle<RasterizerTraits<ArgsB...>>;
1762 }
1763 };
1764
1765 // Selector for correct templated RasterizeTriangle function
1766 PFN_WORK_FUNC GetRasterizerFunc(
1767 uint32_t numSamples,
1768 bool IsConservative,
1769 uint32_t InputCoverage,
1770 uint32_t EdgeEnable,
1771 bool RasterizeScissorEdges
1772 )
1773 {
1774 return TemplateArgUnroller<RasterizerChooser>::GetFunc(
1775 IntArg<SWR_MULTISAMPLE_1X,SWR_MULTISAMPLE_TYPE_COUNT-1>{numSamples},
1776 IsConservative,
1777 IntArg<SWR_INPUT_COVERAGE_NONE, SWR_INPUT_COVERAGE_COUNT-1>{InputCoverage},
1778 IntArg<0, VALID_TRI_EDGE_COUNT-1>{EdgeEnable},
1779 RasterizeScissorEdges);
1780 }